feat(desktop): attest and manage the owned Windows host lifecycle
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { binaryIdentity } from './process-identity.mjs';
|
||||
import { ownedChild, readState, assertLocalTree } from './file-state.mjs';
|
||||
import { canonicalHost, hostError } from '../../shared/contracts/desktop-host.mjs';
|
||||
|
||||
export function inspectHostInstallation(directory, { full = false } = {}) {
|
||||
assertLocalTree(directory);
|
||||
const root = fs.realpathSync.native(path.resolve(directory));
|
||||
if (!fs.statSync(root).isDirectory()) throw hostError('宿主安装目录无效。');
|
||||
const digest = value => createHash('sha256').update(value).digest('hex');
|
||||
const manifestFile = path.join(root, 'MANIFEST.json'), manifest = fs.existsSync(manifestFile) ? readState(manifestFile, 16 * 1024 * 1024) : null;
|
||||
if (manifest && (manifest.app !== 'agent-workbench' || !Array.isArray(manifest.files) || manifest.files.length > 60000)) throw hostError('宿主发行清单无效。');
|
||||
const version = manifest?.version ?? (fs.existsSync(path.join(root, 'package.json')) ? readState(path.join(root, 'package.json')).version : null);
|
||||
if (typeof version !== 'string' || !/^\d+\.\d+\.\d+$/.test(version)) throw hostError('宿主安装版本无效。');
|
||||
const files = new Set(['dist-server/server.mjs', 'dist-server/hot-upgrade.mjs', 'dist-client/index.html']);
|
||||
if (!manifest || fs.existsSync(path.join(root, 'dist-server/host-launcher.mjs'))) files.add('dist-server/host-launcher.mjs');
|
||||
const names = new Map();
|
||||
for (const row of manifest?.files ?? []) {
|
||||
if (!row || typeof row.path !== 'string' || row.path.includes('\\') || row.path.split('/').includes('..') || names.has(row.path)
|
||||
|| !/^[a-f0-9]{64}$/.test(row.sha256 ?? '') || !Number.isSafeInteger(row.bytes) || row.bytes < 0) throw hostError('宿主清单包含重复或越界输入。');
|
||||
names.set(row.path, row);
|
||||
if (full || row.path.startsWith('dist-client/') || row.path.startsWith('dist-server/')) files.add(row.path);
|
||||
}
|
||||
if (!manifest) for (const entry of fs.readdirSync(path.join(root, 'dist-client/assets'))) files.add('dist-client/assets/' + entry);
|
||||
const inputs = [...files].sort().map(relative => {
|
||||
const file = ownedChild(root, relative), identity = binaryIdentity(file), declared = names.get(relative);
|
||||
if (manifest?.kind === 'portable' && !declared) throw hostError('实际宿主程序不在原发行清单中。');
|
||||
if (declared && (identity.bytes !== declared.bytes || identity.sha256 !== declared.sha256)) throw hostError('实际宿主程序与原发行清单不一致。');
|
||||
return { path: relative, bytes: identity.bytes, sha256: identity.sha256 };
|
||||
});
|
||||
const result = { root, version, kind: manifest?.kind ?? 'development-build', manifestSha256: manifest ? digest(fs.readFileSync(manifestFile)) : null,
|
||||
inputs, verification: full ? 'full-manifest' : 'loaded-host-and-client-inputs' };
|
||||
return { ...result, identitySha256: digest(JSON.stringify(canonicalHost(result))) };
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { hostError } from '../../shared/contracts/desktop-host.mjs';
|
||||
|
||||
const normalized = value => process.platform === 'win32' ? value.toLowerCase() : value;
|
||||
export const samePath = (a, b) => normalized(path.resolve(a)) === normalized(path.resolve(b));
|
||||
export function assertLocalTree(absolute, { missing = false } = {}) {
|
||||
const resolved = path.resolve(absolute), parsed = path.parse(resolved);
|
||||
let current = parsed.root;
|
||||
const components = resolved.slice(parsed.root.length).split(path.sep).filter(Boolean);
|
||||
for (const component of components) {
|
||||
if (component.includes(':') || component.includes('\0')) throw hostError('本机状态路径格式无效。');
|
||||
current = path.join(current, component);
|
||||
let stat;
|
||||
try { stat = fs.lstatSync(current); }
|
||||
catch (cause) { if (missing && cause.code === 'ENOENT') return resolved; throw cause; }
|
||||
if (stat.isSymbolicLink() || !samePath(current, fs.realpathSync.native(current))) throw hostError('本机状态不接受链接或重解析目录。');
|
||||
if (stat.isFile() && stat.nlink !== 1) throw hostError('本机状态文件具有多个路径。');
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
export function ownedChild(root, relative, { missing = false } = {}) {
|
||||
if (typeof relative !== 'string') throw hostError('本机状态路径无效。');
|
||||
assertLocalTree(root);
|
||||
const base = fs.realpathSync.native(root), target = path.resolve(base, relative);
|
||||
if (path.isAbsolute(relative) || path.win32.isAbsolute(relative) || relative.includes('\0')
|
||||
|| !normalized(target).startsWith(normalized(base + path.sep))) throw hostError('本机状态路径超出所属目录。');
|
||||
let existing = target;
|
||||
while (!fs.existsSync(existing)) {
|
||||
if (!missing) throw hostError('本机状态文件不存在。', 'HOST_REGISTRATION_MISSING');
|
||||
const parent = path.dirname(existing); if (parent === existing) throw hostError('本机状态路径无法核对。'); existing = parent;
|
||||
}
|
||||
const real = fs.realpathSync.native(existing);
|
||||
if (!samePath(base, real) && !normalized(real).startsWith(normalized(base + path.sep))) throw hostError('本机状态链接超出所属目录。');
|
||||
if (fs.lstatSync(existing).isSymbolicLink()) throw hostError('本机状态不接受链接或重解析目录。');
|
||||
const stat = fs.statSync(existing); if (stat.isFile() && stat.nlink !== 1) throw hostError('本机状态文件具有多个路径。');
|
||||
return assertLocalTree(target, { missing });
|
||||
}
|
||||
export function readState(file, maximum = 4 * 1024 * 1024) {
|
||||
assertLocalTree(file);
|
||||
const stat = fs.lstatSync(file);
|
||||
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > maximum) throw hostError('本机状态文件格式或作用范围无效。');
|
||||
try { return JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '')); }
|
||||
catch { throw hostError('本机状态文件损坏,请核对原记录。'); }
|
||||
}
|
||||
export function writeState(file, value) {
|
||||
assertLocalTree(file, { missing: true });
|
||||
const directory = path.dirname(file), temporary = path.join(directory, '.' + path.basename(file) + '-' + randomUUID() + '.tmp');
|
||||
if (fs.existsSync(file)) readState(file);
|
||||
try {
|
||||
const descriptor = fs.openSync(temporary, 'wx', 0o600);
|
||||
try { fs.writeFileSync(descriptor, JSON.stringify(value, null, 2) + '\n'); fs.fsyncSync(descriptor); } finally { fs.closeSync(descriptor); }
|
||||
assertLocalTree(file, { missing: true }); fs.renameSync(temporary, file);
|
||||
}
|
||||
finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); }
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
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';
|
||||
|
||||
async function jsonResponse(response) {
|
||||
if (!response.ok) throw hostError('本机宿主接口拒绝操作(HTTP ' + response.status + ')。', 'HOST_API_REJECTED', response.status);
|
||||
const chunks = []; let length = 0;
|
||||
for await (const chunk of response.body) { length += chunk.length; if (length > 4 * 1024 * 1024) throw hostError('本机宿主响应过大。'); 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(['AGENT_WORKBENCH_ENGINE_ROOT', 'AGENT_WORKBENCH_PURGE_ROOT', 'AWB_QA_PYTHON']);
|
||||
if (Object.keys(environment).some(key => !allowed.has(key) || typeof environment[key] !== 'string')) 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);
|
||||
const health = await this.health();
|
||||
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');
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { projectEnvironment } from '../process-environment.mjs';
|
||||
import { hostError } from '../../shared/contracts/desktop-host.mjs';
|
||||
import { assertLocalTree } from './file-state.mjs';
|
||||
|
||||
export function protectUserDirectory(directory) {
|
||||
assertLocalTree(directory);
|
||||
if (process.platform !== 'win32') throw hostError('本机秘密目录需要Windows用户权限。');
|
||||
const script = "$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue';$awbPath=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String([Console]::In.ReadToEnd()));"
|
||||
+ '$awbSid=[Security.Principal.WindowsIdentity]::GetCurrent().User;'
|
||||
+ '$awbAcl=[IO.Directory]::GetAccessControl($awbPath,[Security.AccessControl.AccessControlSections]::Access);'
|
||||
+ '$awbAcl.SetAccessRuleProtection($true,$false);'
|
||||
+ 'foreach($awbExisting in $awbAcl.GetAccessRules($true,$false,[Security.Principal.SecurityIdentifier])){$awbAcl.RemoveAccessRuleSpecific($awbExisting)};'
|
||||
+ '$awbRule=New-Object Security.AccessControl.FileSystemAccessRule($awbSid,"FullControl","ContainerInherit,ObjectInherit","None","Allow");'
|
||||
+ '$awbAcl.AddAccessRule($awbRule);[IO.Directory]::SetAccessControl($awbPath,$awbAcl)';
|
||||
try { execFileSync(path.join(process.env.SystemRoot || 'C:\\Windows', 'System32/WindowsPowerShell/v1.0/powershell.exe'),
|
||||
['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')],
|
||||
{ input: Buffer.from(directory, 'utf8').toString('base64'), encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, timeout: 15000, maxBuffer: 65536, env: projectEnvironment() }); }
|
||||
catch { throw hostError('无法为本机秘密目录设置当前Windows用户权限。', 'HOST_DIRECTORY_UNPROTECTED'); }
|
||||
}
|
||||
|
||||
export function observeWindowsProcess(pid) {
|
||||
if (process.platform !== 'win32') throw hostError('此桌面宿主核验需要Windows。', 'HOST_PLATFORM_UNSUPPORTED');
|
||||
if (!Number.isInteger(pid) || pid < 1 || pid > 2147483647) throw hostError('宿主PID无效。');
|
||||
const script = "$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue';[Console]::OutputEncoding=New-Object System.Text.UTF8Encoding($false);"
|
||||
+ '$awbProcess=Get-CimInstance Win32_Process -Filter "ProcessId=' + pid + '";'
|
||||
+ 'if($null -eq $awbProcess){Write-Output "null";exit 0};'
|
||||
+ '$awbOwner=Invoke-CimMethod -InputObject $awbProcess -MethodName GetOwnerSid;'
|
||||
+ 'if($awbOwner.ReturnValue -ne 0 -or -not $awbOwner.Sid){throw "Owner identity unavailable"};'
|
||||
+ '[pscustomobject]@{pid=[int]$awbProcess.ProcessId;parentPid=[int]$awbProcess.ParentProcessId;'
|
||||
+ 'createdAt=$awbProcess.CreationDate.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ");'
|
||||
+ 'executable=$awbProcess.ExecutablePath;userSid=$awbOwner.Sid}|ConvertTo-Json -Compress';
|
||||
try {
|
||||
const shell = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32/WindowsPowerShell/v1.0/powershell.exe');
|
||||
const output = execFileSync(shell, ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')],
|
||||
{ windowsHide: true, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 15000, maxBuffer: 65536, env: projectEnvironment() });
|
||||
const value = JSON.parse(output.trim().replace(/^\uFEFF/, ''));
|
||||
if (value === null) return null;
|
||||
if (value.pid !== pid || !Number.isFinite(Date.parse(value.createdAt)) || !/^S-1-\d+(?:-\d+)+$/.test(value.userSid)
|
||||
|| !value.executable || !fs.existsSync(value.executable)) throw new Error('Invalid observation');
|
||||
return { ...value, executable: fs.realpathSync.native(value.executable) };
|
||||
} catch { throw hostError('无法核对Windows宿主创建、用户或可执行身份;不会复用或停止未知进程。', 'HOST_PROCESS_UNVERIFIED'); }
|
||||
}
|
||||
export function binaryIdentity(file) {
|
||||
assertLocalTree(file);
|
||||
const absolute = fs.realpathSync.native(file), stat = fs.lstatSync(absolute);
|
||||
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 256 * 1024 * 1024) throw hostError('宿主可执行文件身份无效。');
|
||||
return { path: absolute, bytes: stat.size, sha256: createHash('sha256').update(fs.readFileSync(absolute)).digest('hex') };
|
||||
}
|
||||
@@ -58,6 +58,16 @@ export class EngineRunner {
|
||||
}
|
||||
return driver.job;
|
||||
}
|
||||
async stopAll() {
|
||||
for (const driver of this.drivers.values()) driver.run.controller.abort(new Error('用户停止执行宿主。'));
|
||||
for (const [id, driver] of [...this.drivers]) {
|
||||
await driver.close();
|
||||
if (driver.native && (!driver.job.native?.cleanup?.rootExited || driver.job.native?.cleanup?.treeConfirmed === false)) {
|
||||
throw engineError('所属原生引擎进程结束仍待核对,宿主保持运行。');
|
||||
}
|
||||
this.drivers.delete(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class EngineRunDriver {
|
||||
|
||||
@@ -179,6 +179,11 @@ export class ModelHub {
|
||||
} finally { this.waiting--; }
|
||||
}
|
||||
async complete(config, body, signal, onProgress, plan, execute) {
|
||||
const operation = this.provider.requestOperation?.(signal);
|
||||
try { return await this.completeOwned(config, body, operation?.signal ?? signal, onProgress, plan, execute); }
|
||||
finally { operation?.finish(); }
|
||||
}
|
||||
async completeOwned(config, body, signal, onProgress, plan, execute) {
|
||||
const routing = config.modelRouting, excluded = new Set(), deadline = Date.now() + Math.min(routing.queueTimeoutMs, 60000);
|
||||
const requestId = plan?.id ?? randomUUID(), runId = plan?.runId ?? requestId;
|
||||
let lastError;
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { HostController } from '../core/desktop/host-controller.mjs';
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
if (args.includes('--help')) { console.log('node host-launcher.mjs <start|status|stop> [--app-root <absolute>] [--data-root <absolute>] [--node <absolute>] [--port <1..65535>]'); process.exit(0); }
|
||||
const command = args.shift(); if (!['start', 'status', 'stop'].includes(command)) throw new Error('Use --help for a supported desktop host operation.');
|
||||
const options = {};
|
||||
while (args.length) {
|
||||
const flag = args.shift(), value = args.shift();
|
||||
if (!['--app-root', '--data-root', '--node', '--port'].includes(flag) || !value || options[flag] !== undefined) throw new Error('Invalid or repeated host option.');
|
||||
options[flag] = value;
|
||||
}
|
||||
const defaultRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const appRoot = options['--app-root'] || process.env.AGENT_WORKBENCH_APP_DIR || defaultRoot;
|
||||
const dataRoot = options['--data-root'] || process.env.AGENT_WORKBENCH_DATA_DIR || path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), '.local/share'), 'AgentWorkbench');
|
||||
const nodePath = options['--node'] || (fs.existsSync(path.join(appRoot, 'runtime/node.exe')) ? path.join(appRoot, 'runtime/node.exe') : process.execPath);
|
||||
try {
|
||||
const controller = new HostController({ appRoot, dataRoot, nodePath, port: Number(options['--port'] || process.env.AGENT_WORKBENCH_PORT || 4318),
|
||||
environment: Object.fromEntries(['AGENT_WORKBENCH_ENGINE_ROOT', 'AGENT_WORKBENCH_PURGE_ROOT', 'AWB_QA_PYTHON'].filter(key => process.env[key]).map(key => [key, process.env[key]])) });
|
||||
console.log(JSON.stringify(await controller[command]()));
|
||||
} catch (cause) { console.error(JSON.stringify({ success: false, code: cause.code || 'HOST_FAILED', message: cause.message })); process.exitCode = 1; }
|
||||
+12
-2
@@ -13,6 +13,7 @@ import { verifyBrowserJob } from '../core/browser/browser-manager.mjs';
|
||||
import { ConfigImporter } from '../core/models/config-import.mjs';
|
||||
import { ProjectMemoryManager } from '../core/memory/project-memory.mjs';
|
||||
import { workerForProject, workerConflict, assertWorkersResolved } from '../shared/contracts/workers.mjs';
|
||||
import { hostAuthority } from '../core/desktop/host-authority.mjs';
|
||||
|
||||
export function createSessionPublisher(clients) {
|
||||
return session => {
|
||||
@@ -31,6 +32,7 @@ function cursorNumber(value) {
|
||||
}
|
||||
|
||||
export function createRequestHandler({ appDirectory, server, store, provider, runtime, token, clients, started, getPort, exampleProject, shutdown }) {
|
||||
const host = () => hostAuthority({ appDirectory, server, store, provider, runtime });
|
||||
const research = [
|
||||
{ id: 'overview', title: '统一机制报告', file: 'RESEARCH.md', description: '研究结论、证据与本产品采用的独立设计。' },
|
||||
{ id: 'cursor', title: 'Cursor:执行与编辑', file: 'research/CURSOR-MECHANISMS.md', description: '工具能力、执行事件、取消、恢复与文本改动。' },
|
||||
@@ -81,7 +83,13 @@ return async (request, response) => {
|
||||
allowRequest(request, url);
|
||||
const method = request.method;
|
||||
const route = url.pathname;
|
||||
if (method === 'GET' && route === '/api/health') return json(response, { app: 'agent-workbench', version: APP_VERSION, pid: process.pid, ready: true, uptimeMs: Date.now() - started });
|
||||
if (method === 'GET' && route === '/api/health') return json(response, { app: 'agent-workbench', version: APP_VERSION, pid: process.pid, ready: server?.workbenchReady !== false, uptimeMs: Date.now() - started });
|
||||
if (method === 'GET' && route === '/api/host/identity') return json(response, host().attest(url.searchParams.get('challenge')));
|
||||
if (method === 'GET' && route === '/api/host/status') return json(response, host().status());
|
||||
if (method === 'POST' && route === '/api/host/stop') {
|
||||
const result = await host().stop(await body(request)); json(response, result); setTimeout(shutdown, 100); return;
|
||||
}
|
||||
if (!['GET', 'HEAD'].includes(method) && server?.workbenchHostAuthority?.stopping) throw Object.assign(new Error('执行宿主正在停止,请等待所属操作结束。'), { status: 409 });
|
||||
const skillsMatch = route.match(/^\/api\/projects\/([a-f0-9-]+)\/skills(?:\/(toggle|refresh|content))?$/i);
|
||||
if (skillsMatch) {
|
||||
const registry = runtime.skillRegistry(), projectId = skillsMatch[1], action = skillsMatch[2];
|
||||
@@ -655,7 +663,9 @@ return async (request, response) => {
|
||||
return json(response, { title: document.title, content: fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '这份报告正在整理,完成后会保存在产品的 docs 目录。' });
|
||||
}
|
||||
if (method === 'POST' && route === '/api/shutdown') {
|
||||
await body(request); json(response, { closing: true });
|
||||
await body(request);
|
||||
const authority = host(), identity = authority.identity();
|
||||
const result = await authority.stop({ ...identity, confirmation: 'stop-owned-host' }); json(response, result);
|
||||
setTimeout(shutdown, 100); return;
|
||||
}
|
||||
if (route.startsWith('/api/')) return json(response, { error: '接口不存在。' }, 404);
|
||||
|
||||
@@ -8,17 +8,21 @@ import { ModelHub } from '../core/models/model-hub.mjs';
|
||||
import { ConfigImporter } from '../core/models/config-import.mjs';
|
||||
import { createRequestHandler, createSessionPublisher } from './app.mjs';
|
||||
import { APP_VERSION } from './diagnostics.mjs';
|
||||
import { hostAuthority } from '../core/desktop/host-authority.mjs';
|
||||
|
||||
// Keep the existing objects and their in-memory connection. No credential is
|
||||
// extracted, transferred, returned, or persisted by this operation.
|
||||
export function installUpgrade(context, { appDirectory, updateServiceInfo = true }) {
|
||||
const { server, store, provider, runtime, token, clients, started, exampleProject, shutdown } = context;
|
||||
if (!server?.listening || !store || !provider || !runtime || !clients || !token) throw new Error('The existing Workbench context is incomplete.');
|
||||
if (server.workbenchHostAuthority?.stopping) throw new Error('Wait for the original host stop operation before upgrading.');
|
||||
if (runtime.active.size || runtime.waiters.size || runtime.workers?.active.size || runtime.controlledEngines?.drivers.size || runtime.mcp?.active.size || runtime.checks?.active.size || runtime.deliveries?.active.size || runtime.changeSets?.projects.size || runtime.workspaces?.projects.size || runtime.workspaces?.pending.size || runtime.research?.active.size || runtime.engines?.active.size || runtime.browser?.active.size || runtime.taskPlans?.active.size) throw new Error('Wait for active tasks, workers, controlled engines, MCP operations, checks, Git deliveries, file batches, workspaces, research, engines, browsers, task plans and approvals to finish before upgrading.');
|
||||
if (provider.activeRequests || provider.hub?.waiting || [...(provider.hub?.leases.values() ?? [])].some(count => count > 0)) throw new Error('Wait for active model requests and probes before upgrading.');
|
||||
const root = fs.realpathSync.native(path.resolve(appDirectory));
|
||||
if (!fs.existsSync(path.join(root, 'dist-client', 'index.html'))) throw new Error('The new client bundle is missing.');
|
||||
const oldHandlers = server.listeners('request');
|
||||
const oldAuthority = server.workbenchHostAuthority, oldAuthorityProperties = oldAuthority ? { ...oldAuthority } : null;
|
||||
const oldAuthorityPrototype = oldAuthority ? Object.getPrototypeOf(oldAuthority) : null;
|
||||
const oldPrototypes = [Object.getPrototypeOf(store), Object.getPrototypeOf(provider), Object.getPrototypeOf(runtime)];
|
||||
const oldModelPrototypes = { hub: provider.hub ? Object.getPrototypeOf(provider.hub) : null,
|
||||
importer: provider.hub?.importer ? Object.getPrototypeOf(provider.hub.importer) : null };
|
||||
@@ -48,12 +52,16 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
|
||||
server.removeAllListeners('request'); server.on('request', handler);
|
||||
server.prependOnceListener('close', closeStorage);
|
||||
if (updateServiceInfo) {
|
||||
const file = path.join(store.directory, 'service-info.json');
|
||||
const info = readJson(file, {});
|
||||
atomicJson(file, { ...info, pid: process.pid, version: APP_VERSION, runtimeRoot: root, upgradedAt: new Date().toISOString() });
|
||||
const authority = hostAuthority({ appDirectory: root, server, store, provider, runtime });
|
||||
authority.initialize(); authority.refreshInstallation();
|
||||
}
|
||||
return { version: APP_VERSION, pid: process.pid, hasKey: provider.hasKey(), projects: store.projects.length, sessions: store.sessions.size, appDirectory: root };
|
||||
} catch (error) {
|
||||
if (oldAuthority) {
|
||||
for (const key of Object.keys(oldAuthority)) if (!Object.hasOwn(oldAuthorityProperties, key)) delete oldAuthority[key];
|
||||
Object.assign(oldAuthority, oldAuthorityProperties); Object.setPrototypeOf(oldAuthority, oldAuthorityPrototype);
|
||||
server.workbenchHostAuthority = oldAuthority;
|
||||
} else delete server.workbenchHostAuthority;
|
||||
server.removeListener('close', closeStorage);
|
||||
if (store.storage && store.storage !== oldStoreProperties.storage) {
|
||||
const filename = store.storage.filename;
|
||||
|
||||
@@ -10,6 +10,7 @@ import { Runtime } from './runtime.mjs';
|
||||
import { createRequestHandler, createSessionPublisher } from './app.mjs';
|
||||
import { APP_VERSION } from './diagnostics.mjs';
|
||||
import { ConfigImporter } from '../core/models/config-import.mjs';
|
||||
import { hostAuthority } from '../core/desktop/host-authority.mjs';
|
||||
|
||||
const appDirectory = process.env.AGENT_WORKBENCH_APP_DIR || path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const dataDirectory = process.env.AGENT_WORKBENCH_DATA_DIR || path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), '.local', 'share'), 'AgentWorkbench');
|
||||
@@ -40,13 +41,15 @@ try {
|
||||
store.on('update', createSessionPublisher(clients));
|
||||
|
||||
const server = http.createServer();
|
||||
server.workbenchReady = false;
|
||||
server.on('request', createRequestHandler({ appDirectory, server, store, provider, runtime, token, clients, started,
|
||||
getPort: () => actualPort, exampleProject, shutdown }));
|
||||
|
||||
async function shutdown() {
|
||||
if (closing) return; closing = true;
|
||||
clearInterval(modelImportSync);
|
||||
await runtime.stopAll();
|
||||
try { await Promise.all([provider.abortRequests(), runtime.stopAll()]); }
|
||||
catch (cause) { closing = false; provider.resumeRequests(); console.error('Workbench shutdown remains unverified: ' + provider.redact(cause.message)); return; }
|
||||
for (const response of clients) response.end();
|
||||
clients.clear();
|
||||
server.close(() => { store.close(); process.exit(0); });
|
||||
@@ -56,5 +59,7 @@ process.on('SIGINT', shutdown); process.on('SIGTERM', shutdown);
|
||||
server.on('error', error => { store.close(); console.error('Workbench could not start: ' + error.message); process.exitCode = 1; });
|
||||
server.listen(requestedPort, '127.0.0.1', () => {
|
||||
actualPort = server.address().port;
|
||||
try { hostAuthority({ appDirectory, server, store, provider, runtime }).initialize(); server.workbenchReady = true; }
|
||||
catch (cause) { console.error('Workbench registration failed: ' + provider.redact(cause.message)); server.close(() => { store.close(); process.exit(1); }); return; }
|
||||
console.log(JSON.stringify({ app: 'agent-workbench', ready: true, url: 'http://127.0.0.1:' + actualPort, version: APP_VERSION }));
|
||||
});
|
||||
|
||||
@@ -98,6 +98,22 @@ export class Provider {
|
||||
constructor(options = {}) { this.apiKey = process.env.AGENT_WORKBENCH_API_KEY || ''; this.fetcher = options.fetch; this.retryPolicy = options.retryPolicy; }
|
||||
hasKey() { return !!this.apiKey; }
|
||||
setKey(value) { this.apiKey = String(value ?? '').trim(); }
|
||||
requestOperation(signal) {
|
||||
if (this.requestsClosing) throw new Error('执行宿主正在停止模型请求。');
|
||||
const controller = new AbortController();
|
||||
let settled; const done = new Promise(resolve => { settled = resolve; });
|
||||
const operation = { controller, done, signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal,
|
||||
finish: () => { this.requestControllers.delete(operation); settled(); } };
|
||||
(this.requestControllers ??= new Set()).add(operation);
|
||||
return operation;
|
||||
}
|
||||
async abortRequests() {
|
||||
this.requestsClosing = true;
|
||||
const operations = [...(this.requestControllers ?? [])];
|
||||
for (const operation of operations) operation.controller.abort(new Error('用户停止执行宿主。'));
|
||||
await Promise.all(operations.map(operation => operation.done));
|
||||
}
|
||||
resumeRequests() { this.requestsClosing = false; }
|
||||
modelHub(store) { return this.hub ??= new ModelHub(store, this); }
|
||||
prepareConfig(config, store) { return this.modelHub(store).prepare(config); }
|
||||
redact(value, key = this.apiKey) {
|
||||
@@ -116,6 +132,7 @@ export class Provider {
|
||||
const headers = { 'Content-Type': 'application/json' };
|
||||
if (key) headers.Authorization = 'Bearer ' + key;
|
||||
const policy = { attempts: 3, delays: [500, 1500], timeoutMs: signal ? 60000 : 20000, totalTimeoutMs: signal ? 90000 : 20000, ...this.retryPolicy, ...options };
|
||||
const operation = this.requestOperation(signal); signal = operation.signal;
|
||||
const deadline = Date.now() + policy.totalTimeoutMs;
|
||||
const startedAt = Date.now();
|
||||
let attempts = 0;
|
||||
@@ -168,6 +185,7 @@ export class Provider {
|
||||
throw new Error('模型请求未能完成。');
|
||||
} finally {
|
||||
this.activeRequests--;
|
||||
operation.finish();
|
||||
if (signal?.aborted) this.lastRequest = { source: 'model_connection', stage: 'model_request',
|
||||
endpoint: base, route, model: config.model, status: 'interrupted', attempts,
|
||||
durationMs: Date.now() - startedAt, occurredAt: new Date().toISOString() };
|
||||
|
||||
@@ -661,5 +661,5 @@ export class Runtime {
|
||||
run.controller.abort(new Error('用户停止任务'));
|
||||
await run.promise;
|
||||
}
|
||||
async stopAll() { await this.workers?.stopAll(); await Promise.all([...this.active.keys()].map(id => this.stop(id))); await this.checks?.stopAll(); await this.deliveries?.stopAll(); await this.changeSets?.stopAll(); await this.workspaces?.stopAll(); await this.research?.stopAll(); await this.engines?.stopAll(); await this.browser?.stopAll(); await this.mcp?.stopAll(); await this.taskPlans?.settle(); }
|
||||
async stopAll() { await this.workers?.stopAll(); await Promise.all([...this.active.keys()].map(id => this.stop(id))); await this.controlledEngines?.stopAll(); await this.checks?.stopAll(); await this.deliveries?.stopAll(); await this.changeSets?.stopAll(); await this.workspaces?.stopAll(); await this.research?.stopAll(); await this.engines?.stopAll(); await this.browser?.stopAll(); await this.mcp?.stopAll(); await this.taskPlans?.settle(); }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { createHmac, timingSafeEqual } from 'node:crypto';
|
||||
|
||||
export const HOST_PROTOCOL = 'agent-workbench-host-v1';
|
||||
export const HOST_REGISTRATION_FILE = 'host-authority-v1.json';
|
||||
export const hostError = (message, code = 'HOST_IDENTITY_REJECTED', status = 409) => Object.assign(new Error(message), { code, status });
|
||||
export const canonicalHost = value => Array.isArray(value) ? value.map(canonicalHost) : value && typeof value === 'object'
|
||||
? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonicalHost(value[key])])) : value;
|
||||
export function hostProof(identity, challenge, secret) {
|
||||
if (!/^[a-f0-9]{64}$/.test(challenge) || !Buffer.isBuffer(secret) || secret.length !== 32) throw hostError('宿主核验挑战格式无效。', 'HOST_CHALLENGE_INVALID', 400);
|
||||
return createHmac('sha256', secret).update(JSON.stringify(canonicalHost({ identity, challenge }))).digest('hex');
|
||||
}
|
||||
export function verifyHostProof(reply, challenge, secret) {
|
||||
if (!reply?.identity || reply.challenge !== challenge || !/^[a-f0-9]{64}$/.test(reply.proof ?? '')) throw hostError('宿主没有提供匹配的实例核验。');
|
||||
const actual = Buffer.from(reply.proof, 'hex'), expected = Buffer.from(hostProof(reply.identity, challenge, secret), 'hex');
|
||||
if (!timingSafeEqual(actual, expected)) throw hostError('端口响应不属于登记的执行宿主。');
|
||||
return reply.identity;
|
||||
}
|
||||
export function assertHostStop(input, identity) {
|
||||
if (input?.confirmation !== 'stop-owned-host' || input.instanceId !== identity.instanceId || input.createdAt !== identity.createdAt
|
||||
|| input.runtimeIdentity !== identity.runtimeIdentity) throw hostError('停止确认已过期或不属于当前宿主。');
|
||||
}
|
||||
Reference in New Issue
Block a user