feat(desktop): attest and manage the owned Windows host lifecycle
This commit is contained in:
+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(); }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user