import fs from 'node:fs'; import path from 'node:path'; import { randomBytes, randomUUID } from 'node:crypto'; import { APP_VERSION } from '../../server/diagnostics.mjs'; import { HOST_PROTOCOL, HOST_REGISTRATION_FILE, hostError, hostProof, assertHostStop } from '../../shared/contracts/desktop-host.mjs'; import { observeWindowsProcess, binaryIdentity, protectUserDirectory } from './process-identity.mjs'; import { ownedChild, readState, writeState, samePath } from './file-state.mjs'; import { inspectHostInstallation } from './app-installation.mjs'; export class HostAuthority { constructor(context) { this.context = context; this.stopping = false; } initialize() { if (this.registration) return; const { store, server, appDirectory } = this.context, observed = observeWindowsProcess(process.pid); if (!observed || !samePath(observed.executable, process.execPath)) throw hostError('当前宿主程序无法核对。'); const dataRoot = fs.realpathSync.native(store.directory), secretDirectory = ownedChild(dataRoot, '.secrets', { missing: true }); if (!fs.existsSync(secretDirectory)) fs.mkdirSync(secretDirectory, { mode: 0o700 }); protectUserDirectory(secretDirectory); const file = ownedChild(dataRoot, '.secrets/' + HOST_REGISTRATION_FILE, { missing: true }); let previous = fs.existsSync(file) ? readState(file, 16384) : null; if (previous && (previous.pid !== process.pid || previous.createdAt !== observed.createdAt)) { const active = observeWindowsProcess(previous.pid); if (active && active.createdAt === previous.createdAt) throw hostError('本机注册仍属于另一个活动进程,请核对原宿主。'); writeState(ownedChild(dataRoot, '.secrets/host-authority-stale-' + randomUUID() + '.json', { missing: true }), previous); previous = null; } const matches = previous?.schema === 1 && previous.protocol === HOST_PROTOCOL && previous.pid === process.pid && previous.createdAt === observed.createdAt && previous.userSid === observed.userSid && previous.ownerId === store.ownerId && /^[a-f0-9-]{36}$/.test(previous.instanceId ?? '') && /^[A-Za-z0-9+/]{43}=$/.test(previous.secret ?? ''); if (previous && !matches) throw hostError('当前宿主的原注册记录已变化,请核对本机状态。'); const registration = previous ?? { schema: 1, protocol: HOST_PROTOCOL, pid: process.pid, createdAt: observed.createdAt, userSid: observed.userSid, ownerId: store.ownerId, instanceId: randomUUID(), secret: randomBytes(32).toString('base64') }; const originalInfoFile = ownedChild(dataRoot, 'service-info.json', { missing: true }); const originalInfo = fs.existsSync(originalInfoFile) ? readState(originalInfoFile) : {}; const sameInstance = originalInfo.pid === process.pid && (!originalInfo.createdAt || originalInfo.createdAt === observed.createdAt); const bootRoot = sameInstance && originalInfo.appRoot ? fs.realpathSync.native(originalInfo.appRoot) : fs.realpathSync.native(appDirectory); const boundRoot = fs.realpathSync.native(this.context.runtime.appDirectory ?? appDirectory), boundInstallation = inspectHostInstallation(boundRoot); const executable = binaryIdentity(observed.executable); const info = { ...originalInfo, app: 'agent-workbench', protocol: HOST_PROTOCOL, pid: process.pid, createdAt: observed.createdAt, port: server.address().port, appRoot: bootRoot, runtimeRoot: boundRoot, dataRoot, version: APP_VERSION, instanceId: registration.instanceId, userSid: observed.userSid, ownerId: store.ownerId, runtimeIdentity: boundInstallation.identitySha256, startedAt: sameInstance && originalInfo.startedAt ? originalInfo.startedAt : observed.createdAt }; // Do all validation and durable writes before publishing initialized memory. if (!previous) writeState(file, registration); writeState(originalInfoFile, info); Object.assign(this, { registration, secret: Buffer.from(registration.secret, 'base64'), observed, bootRoot, boundRoot, boundInstallation, executable }); } refreshInstallation() { const current = fs.realpathSync.native(this.context.runtime.appDirectory ?? this.context.appDirectory); // Bind once to the actual loaded directory. Mutating that directory later // never silently changes the claimed running-code identity. if (!this.boundInstallation || !samePath(current, this.boundRoot)) { const installation = inspectHostInstallation(current); if (this.registration) { const file = ownedChild(this.context.store.directory, 'service-info.json'), info = readState(file); if (info.instanceId !== this.registration.instanceId || info.createdAt !== this.observed.createdAt) throw hostError('宿主索引已变化。'); writeState(file, { ...info, runtimeRoot: current, runtimeIdentity: installation.identitySha256, version: APP_VERSION, upgradedAt: new Date().toISOString() }); } this.boundInstallation = installation; this.boundRoot = current; } } identity() { if (!this.registration) this.initialize(); this.refreshInstallation(); return { schema: 1, protocol: HOST_PROTOCOL, app: 'agent-workbench', version: APP_VERSION, instanceId: this.registration.instanceId, pid: this.observed.pid, createdAt: this.observed.createdAt, userSid: this.observed.userSid, ownerId: this.registration.ownerId, executable: this.executable, appRoot: this.bootRoot, runtimeRoot: this.boundRoot, runtimeIdentity: this.boundInstallation.identitySha256, dataRoot: fs.realpathSync.native(this.context.store.directory), port: this.context.server.address().port }; } attest(challenge) { const identity = this.identity(); return { identity, challenge, proof: hostProof(identity, challenge, this.secret) }; } activity() { const { runtime, provider, store } = this.context; const counts = { tasks: runtime.active.size, approvals: runtime.waiters.size, workers: runtime.workers?.active.size ?? 0, controlledEngines: runtime.controlledEngines?.drivers.size ?? 0, mcp: runtime.mcp?.active.size ?? 0, checks: runtime.checks?.active.size ?? 0, deliveries: runtime.deliveries?.active.size ?? 0, fileBatches: runtime.changeSets?.projects.size ?? 0, workspaces: (runtime.workspaces?.projects.size ?? 0) + (runtime.workspaces?.pending.size ?? 0), research: runtime.research?.active.size ?? 0, engines: runtime.engines?.active.size ?? 0, browsers: runtime.browser?.active.size ?? 0, plans: runtime.taskPlans?.active.size ?? 0, modelRequests: provider.activeRequests ?? 0, modelQueue: provider.hub?.waiting ?? 0, modelLeases: [...(provider.hub?.leases.values() ?? [])].reduce((sum, value) => sum + value, 0) }; const unresolved = [...store.core.tool.values()].filter(value => value.requiresVerification).map(value => ({ id: value.id, sessionId: value.sessionId, taskId: value.taskId, runId: value.runId })); return { counts, active: Object.values(counts).some(value => value > 0), unresolvedTools: unresolved.length, unknownResults: unresolved.slice(0, 50), scope: 'Current host-owned active managers and saved tool verification flags; no tool/model/repair is executed.' }; } status() { return { identity: this.identity(), state: this.stopping ? 'stopping' : 'ready', activity: this.activity(), windowClose: 'keep-host-running' }; } async stop(input) { assertHostStop(input, this.identity()); if (this.stopping) throw hostError('宿主已经在停止,请等待原操作。', 'HOST_STOP_PENDING'); this.stopping = true; try { await Promise.all([this.context.provider.abortRequests?.(), this.context.runtime.stopAll()]); if (this.activity().active) throw hostError('所属任务或进程尚未结束,宿主保持运行以便核对。', 'HOST_STOP_UNVERIFIED'); return { closing: true, instanceId: this.registration.instanceId, pid: process.pid, stoppedActivity: this.activity() }; } catch (cause) { this.stopping = false; this.context.provider.resumeRequests?.(); throw cause; } } } export function hostAuthority(context) { const { server } = context; server.workbenchHostAuthority ??= new HostAuthority(context); Object.setPrototypeOf(server.workbenchHostAuthority, HostAuthority.prototype); server.workbenchHostAuthority.context = context; return server.workbenchHostAuthority; }