import fs from 'node:fs'; import path from 'node:path'; import { spawn, execFileSync } from 'node:child_process'; import { randomBytes, randomUUID } from 'node:crypto'; import { setTimeout as delay } from 'node:timers/promises'; import { HOST_PROTOCOL, HOST_REGISTRATION_FILE, hostError, verifyHostProof } from '../../shared/contracts/desktop-host.mjs'; import { projectEnvironment } from '../process-environment.mjs'; import { observeWindowsProcess, binaryIdentity } from './process-identity.mjs'; import { inspectHostInstallation } from './app-installation.mjs'; import { ownedChild, readState, writeState, samePath, assertLocalTree } from './file-state.mjs'; export const HOST_ENVIRONMENT = Object.freeze(['AGENT_WORKBENCH_DEEPSEEK_ROOT', 'AGENT_WORKBENCH_PURGE_ROOT', 'AGENT_WORKBENCH_PYTHON_PATH', 'AGENT_WORKBENCH_TEST_PYTHON']); async function jsonResponse(response) { if (!response.ok) throw hostError('本机宿主接口拒绝操作(HTTP ' + response.status + ')。', 'HOST_API_REJECTED', response.status); const chunks = []; for await (const chunk of response.body) chunks.push(chunk); try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { throw hostError('端口未返回有效的宿主协议。'); } } export class HostController { constructor({ appRoot, dataRoot, port = 4318, nodePath = null, timeoutMs = 45000, environment = {} }) { if (!Number.isInteger(port) || port < 1 || port > 65535 || typeof dataRoot !== 'string' || !path.isAbsolute(dataRoot)) throw hostError('桌面宿主目录或端口无效。'); this.installation = inspectHostInstallation(appRoot); this.appRoot = this.installation.root; assertLocalTree(dataRoot, { missing: true }); fs.mkdirSync(dataRoot, { recursive: true }); this.dataRoot = fs.realpathSync.native(dataRoot); const bundled = path.join(this.appRoot, 'runtime/node.exe'); const executable = nodePath ?? (fs.existsSync(bundled) ? bundled : !process.versions.electron ? process.execPath : null); if (!executable) throw hostError('桌面安装缺少独立Node宿主。'); this.node = binaryIdentity(executable); const version = execFileSync(this.node.path, ['--version'], { encoding: 'utf8', windowsHide: true, timeout: 10000, env: projectEnvironment() }).trim(); if (!/^v24\./.test(version)) throw hostError('桌面宿主需要已经核验的Node24运行器。'); this.node.version = version; this.port = port; this.url = 'http://127.0.0.1:' + port; this.timeoutMs = Math.min(60000, Math.max(1000, timeoutMs)); const allowed = new Set(HOST_ENVIRONMENT); if (Object.keys(environment).some(key => !allowed.has(key) || typeof environment[key] !== 'string' || !path.isAbsolute(environment[key]))) throw hostError('宿主启动只接受已声明的本机运行器路径。'); this.environment = environment; } async api(route, { method = 'GET', input = null, timeoutMs = 15000 } = {}) { if (typeof route !== 'string' || !route.startsWith('/') || route.startsWith('//')) throw hostError('宿主接口路径无效。'); return jsonResponse(await fetch(this.url + '/api' + route, { method, headers: { Connection: 'close', ...(this.token ? { 'X-Workbench-Token': this.token } : {}), ...(input ? { 'Content-Type': 'application/json' } : {}) }, body: input ? JSON.stringify(input) : undefined, signal: AbortSignal.timeout(timeoutMs) })); } async health() { try { return await this.api('/health', { timeoutMs: 1500 }); } catch (cause) { if (cause.cause?.code === 'ECONNREFUSED' || cause.cause?.errors?.every(value => value.code === 'ECONNREFUSED')) return null; throw hostError('端口被占用或响应无法核对;不会启动另一套宿主。', 'HOST_PORT_UNVERIFIED'); } } async connect() { const health = await this.health(); if (!health) return null; if (health.app !== 'agent-workbench' || health.ready !== true || !Number.isInteger(health.pid)) throw hostError('端口属于未知服务。'); const bootstrap = await this.api('/bootstrap'); if (bootstrap.version !== this.installation.version || typeof bootstrap.token !== 'string') throw hostError('运行版本不匹配,请使用明确的升级流程。', 'HOST_VERSION_MISMATCH'); this.token = bootstrap.token; const challenge = randomBytes(32).toString('hex'), reply = await this.api('/host/identity?challenge=' + challenge); ownedChild(this.dataRoot, '.secrets'); const registration = readState(ownedChild(this.dataRoot, '.secrets/' + HOST_REGISTRATION_FILE), 16384); if (registration.schema !== 1 || registration.protocol !== HOST_PROTOCOL || !/^[A-Za-z0-9+/]{43}=$/.test(registration.secret ?? '')) throw hostError('本机原注册格式无法核对。'); const identity = verifyHostProof(reply, challenge, Buffer.from(registration.secret, 'base64')); const actual = observeWindowsProcess(identity.pid), caller = observeWindowsProcess(process.pid); if (!actual || !caller || identity.pid !== health.pid || identity.pid !== registration.pid || identity.createdAt !== actual.createdAt || identity.createdAt !== registration.createdAt || identity.instanceId !== registration.instanceId || identity.ownerId !== registration.ownerId || identity.userSid !== actual.userSid || identity.userSid !== registration.userSid || identity.userSid !== caller.userSid || identity.protocol !== HOST_PROTOCOL || identity.version !== this.installation.version || identity.port !== this.port || !samePath(identity.dataRoot, this.dataRoot) || !samePath(identity.runtimeRoot, this.appRoot) || identity.runtimeIdentity !== this.installation.identitySha256 || !samePath(identity.executable.path, actual.executable) || identity.executable.sha256 !== this.node.sha256 || binaryIdentity(actual.executable).sha256 !== this.node.sha256) throw hostError('实际PID创建、用户、程序、安装或数据目录与原宿主登记不一致。'); const info = readState(ownedChild(this.dataRoot, 'service-info.json')); if (info.pid !== identity.pid || info.instanceId !== identity.instanceId || info.createdAt !== identity.createdAt || info.port !== this.port || info.userSid !== identity.userSid || info.ownerId !== identity.ownerId || info.runtimeIdentity !== identity.runtimeIdentity || !samePath(info.appRoot, identity.appRoot) || !samePath(info.dataRoot, this.dataRoot) || !samePath(info.runtimeRoot, this.appRoot)) throw hostError('本机宿主索引与实际实例不一致。'); this.identity = identity; return { url: this.url, identity }; } async lock(action) { const lockDirectory = ownedChild(this.dataRoot, '.desktop-launch.lock', { missing: true }), nonce = randomUUID(), observed = observeWindowsProcess(process.pid); const deadline = Date.now() + this.timeoutMs; while (true) { try { fs.mkdirSync(lockDirectory, { mode: 0o700 }); break; } catch (cause) { if (cause.code !== 'EEXIST') throw cause; ownedChild(this.dataRoot, '.desktop-launch.lock'); const ownerFile = path.join(lockDirectory, 'owner.json'); if (fs.existsSync(ownerFile)) { ownedChild(this.dataRoot, '.desktop-launch.lock/owner.json'); const owner = readState(ownerFile, 16384); if (!Number.isInteger(owner.pid) || typeof owner.createdAt !== 'string' || typeof owner.nonce !== 'string') throw hostError('启动锁的原身份无法核对。'); const active = observeWindowsProcess(owner.pid); if (active && active.createdAt === owner.createdAt && (owner.userSid !== active.userSid || owner.userSid !== observed.userSid)) throw hostError('启动锁不属于当前Windows用户。'); if (!active || active.createdAt !== owner.createdAt) { if (readState(ownerFile).nonce !== owner.nonce) continue; const archive = ownedChild(this.dataRoot, '.desktop-launch-stale-' + randomUUID(), { missing: true }); try { fs.renameSync(lockDirectory, archive); } catch (error) { if (!['ENOENT', 'EEXIST'].includes(error.code)) throw error; } continue; } } else if (Date.now() - fs.statSync(lockDirectory).mtimeMs > 10000) throw hostError('启动锁缺少原记录,请核对该目录。'); if (Date.now() >= deadline) throw hostError('正在等待原启动操作,请核对当前宿主。', 'HOST_START_PENDING'); await delay(100); } } const ownerFile = path.join(lockDirectory, 'owner.json'); try { writeState(ownerFile, { schema: 1, pid: process.pid, createdAt: observed.createdAt, userSid: observed.userSid, nonce }); return await action(); } finally { if (fs.existsSync(ownerFile) && readState(ownerFile).nonce === nonce) { fs.unlinkSync(ownerFile); fs.rmdirSync(lockDirectory); } } } async start() { return this.lock(async () => { const existing = await this.connect(); if (existing) return { ...existing, reused: true }; const intentFile = ownedChild(this.dataRoot, 'desktop-launch-state.json', { missing: true }); if (fs.existsSync(intentFile)) { const intent = readState(intentFile); if (intent.pid && !['exited', 'failed'].includes(intent.state)) { const actual = observeWindowsProcess(intent.pid); if (actual && actual.createdAt === intent.createdAt) throw hostError('原启动进程仍活动但没有可核验接口,请核对原日志;不会再启动另一进程。', 'HOST_START_UNVERIFIED'); } } const logs = ownedChild(this.dataRoot, 'logs', { missing: true }); if (!fs.existsSync(logs)) fs.mkdirSync(logs); const id = randomUUID(), stdoutPath = path.join(logs, 'desktop-host-' + id + '-stdout.log'), stderrPath = path.join(logs, 'desktop-host-' + id + '-stderr.log'); let output, errors, child; try { output = fs.openSync(stdoutPath, 'wx', 0o600); errors = fs.openSync(stderrPath, 'wx', 0o600); child = spawn(this.node.path, [ownedChild(this.appRoot, 'dist-server/server.mjs')], { cwd: this.appRoot, windowsHide: true, detached: true, env: projectEnvironment({ ...this.environment, AGENT_WORKBENCH_APP_DIR: this.appRoot, AGENT_WORKBENCH_DATA_DIR: this.dataRoot, AGENT_WORKBENCH_PORT: String(this.port) }), stdio: ['ignore', output, errors] }); } finally { if (output !== undefined) fs.closeSync(output); if (errors !== undefined) fs.closeSync(errors); } let failure = null; child.on('error', cause => { failure = cause; }); child.unref(); const observedChild = child.pid ? observeWindowsProcess(child.pid) : null; writeState(intentFile, { schema: 1, state: observedChild ? 'starting' : 'failed', id, pid: child.pid ?? null, createdAt: observedChild?.createdAt ?? null, appRoot: this.appRoot, dataRoot: this.dataRoot, port: this.port, stdoutPath, stderrPath }); const deadline = Date.now() + this.timeoutMs; while (Date.now() < deadline) { if (failure || child.exitCode !== null) throw hostError('所属宿主启动失败,请查看本机启动记录。', 'HOST_START_FAILED'); await delay(100); let health; try { health = await this.health(); } catch (cause) { if (cause.code !== 'HOST_PORT_UNVERIFIED') throw cause; const waiting = observeWindowsProcess(child.pid); if (!waiting || !observedChild || waiting.createdAt !== observedChild.createdAt || waiting.userSid !== observedChild.userSid || !samePath(waiting.executable, this.node.path)) throw hostError('所属宿主启动进程已结束或身份变化,请核对原日志。', 'HOST_START_FAILED'); // Registration can still occupy this owned process after listen(). // Retry only observation, within the original deadline; never launch // another host or accept a connection without the complete proof. continue; } if (!health) continue; if (health.pid !== child.pid) throw hostError('启动期间端口被其他进程占用。'); const connected = await this.connect(); if (connected) { writeState(intentFile, { ...readState(intentFile), state: 'ready', instanceId: connected.identity.instanceId }); return { ...connected, reused: false, logs: { stdoutPath, stderrPath } }; } } throw hostError('所属宿主尚未完成注册;不会重新启动或结束未知进程。', 'HOST_START_UNVERIFIED'); }); } async status() { if (!await this.connect()) return { state: 'not-running', url: this.url }; return this.api('/host/status'); } async stop() { return this.lock(async () => { const connection = await this.connect(); if (!connection) return { state: 'not-running', url: this.url }; const original = connection.identity; await this.api('/host/stop', { method: 'POST', input: { instanceId: original.instanceId, createdAt: original.createdAt, runtimeIdentity: original.runtimeIdentity, confirmation: 'stop-owned-host' }, timeoutMs: this.timeoutMs }); const deadline = Date.now() + this.timeoutMs; while (Date.now() < deadline) { await delay(200); const observed = observeWindowsProcess(original.pid); if (!observed) { if (await this.health()) throw hostError('原宿主已结束,但端口存在其他服务。'); return { state: 'stopped', identity: original, processExited: true }; } if (observed.createdAt !== original.createdAt) throw hostError('原PID已被复用,不会结束新的进程。'); } throw hostError('所属宿主退出仍待核对,请保留原实例记录。', 'HOST_STOP_UNVERIFIED'); }); } }