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;
|
||||
|
||||
Reference in New Issue
Block a user