fix: preserve model state, isolate commands and harden local HTTP in 1.12.1

This commit is contained in:
Agent Workbench Dev
2026-10-30 23:01:19 +08:00
parent c1e9575259
commit f4bd0ad8dc
26 changed files with 373 additions and 68 deletions
+2 -7
View File
@@ -10,6 +10,7 @@ import { assertWorkspacesResolved } from '../shared/contracts/workspaces.mjs';
import { verifyWorkspaceProject } from './workspaces/git-workspaces.mjs';
import { assertMcpResolved } from './tools/mcp-contract.mjs';
import { bindPythonChecks, preparePythonInvocation, pythonEnvironment, readPythonEvidence, pythonResultBinding } from './python-runtime.mjs';
import { projectEnvironment } from './process-environment.mjs';
const at = () => new Date().toISOString();
const conflict = message => Object.assign(new Error(message), { status: 409 });
@@ -189,13 +190,7 @@ export class CheckRunner {
try { invocation = isPython ? await preparePythonInvocation(check, project, { signal }) : npmInvocation(check.name, this.runtimeDirectory); }
catch (error) { return { status: signal.aborted ? 'cancelled' : error.status === 409 ? 'stale' : 'failed', exitCode: null, durationMs: Date.now() - started, tests: null, stdout: '', stderr: error.message, reason: error.message }; }
return new Promise(resolve => {
const env = isPython ? pythonEnvironment() : { ...process.env, NO_COLOR: '1', CI: '1' };
delete env.FORCE_COLOR;
delete env.AGENT_WORKBENCH_API_KEY;
delete env.NODE_TEST_CONTEXT;
const priorPath = process.env.PATH || '';
for (const key of Object.keys(env)) if (key.toLowerCase() === 'path') delete env[key];
env.PATH = path.dirname(process.execPath) + path.delimiter + priorPath;
const env = isPython ? pythonEnvironment() : projectEnvironment({ NO_COLOR: '1', CI: '1' });
const child = spawn(invocation.executable, invocation.args, { cwd: safePath(project), env, windowsHide: true, detached: process.platform !== 'win32', stdio: [isPython ? 'pipe' : 'ignore', 'pipe', 'pipe'] });
const streams = { stdout: { head: '', tail: '', characters: 0, decoder: new StringDecoder('utf8') }, stderr: { head: '', tail: '', characters: 0, decoder: new StringDecoder('utf8') } };
let settled = false, timedOut = false, terminating = false, killTimer;
+22 -18
View File
@@ -72,23 +72,27 @@ export class ConfigImporter {
if (!preview || Date.now() - preview.created > 300000) throw new Error('导入预览已过期,请重新预览。');
const current = this.read(preview.source, preview.path);
if (current.fingerprint !== preview.fingerprint) { this.previews.delete(id); throw new Error('来源配置已变化,请重新预览再导入。'); }
const imported = [], conflicts = [];
const sourceId = digest({ source: preview.source, path: preview.path });
for (const item of current.entries) {
const previous = this.hub.state.connections.find(value => value.importOrigin === item.origin);
if (previous && previous.importRevision !== previous.revision) { conflicts.push(previous.name); continue; }
const value = this.hub.upsert({ ...(previous ?? {}), ...item, id: previous?.id, revision: previous?.revision, enabled: previous ? previous.enabled : true,
...(item.apiKey ? { apiKey: item.apiKey } : { apiKey: '' }) });
const stored = this.hub.connection(value.id); stored.source = preview.source; stored.importOrigin = item.origin; stored.importRevision = stored.revision;
imported.push(value.id);
}
const previousSource = this.hub.state.imports[sourceId];
const checkedAt = new Date().toISOString();
this.hub.state.imports[sourceId] = { source: preview.source, path: preview.path, enabled: autoSync === undefined ? previousSource?.enabled === true : autoSync === true,
lastFingerprint: current.fingerprint, lastCheckedAt: checkedAt, lastSyncedAt: imported.length ? checkedAt : previousSource?.lastSyncedAt ?? null,
lastResult: { imported: imported.length, conflicts } };
this.hub.save(); this.previews.delete(id);
return { imported, conflicts, sourceId };
const result = this.hub.editRegistry(() => {
const imported = [], conflicts = [];
const sourceId = digest({ source: preview.source, path: preview.path });
for (const item of current.entries) {
const previous = this.hub.state.connections.find(value => value.importOrigin === item.origin);
if (previous && previous.importRevision !== previous.revision) { conflicts.push(previous.name); continue; }
const value = this.hub.upsert({ ...(previous ?? {}), ...item, id: previous?.id, revision: previous?.revision, enabled: previous ? previous.enabled : true,
...(item.apiKey ? { apiKey: item.apiKey } : { apiKey: '' }) });
const stored = this.hub.connection(value.id); stored.source = preview.source; stored.importOrigin = item.origin; stored.importRevision = stored.revision;
imported.push(value.id);
}
const previousSource = this.hub.state.imports[sourceId];
const checkedAt = new Date().toISOString();
this.hub.state.imports[sourceId] = { source: preview.source, path: preview.path, enabled: autoSync === undefined ? previousSource?.enabled === true : autoSync === true,
lastFingerprint: current.fingerprint, lastCheckedAt: checkedAt, lastSyncedAt: imported.length ? checkedAt : previousSource?.lastSyncedAt ?? null,
lastResult: { imported: imported.length, conflicts } };
this.hub.save();
return { imported, conflicts, sourceId };
});
this.previews.delete(id);
return result;
}
toggle(id, enabled) {
const source = this.hub.state.imports[id]; if (!source) throw new Error('导入来源不存在。');
@@ -104,7 +108,7 @@ export class ConfigImporter {
if (read.fingerprint === source.lastFingerprint) { this.hub.save(); continue; }
const preview = this.preview(source.source, source.path);
reports.push(this.apply(preview.id, true));
} catch (cause) { source.lastError = '来源暂不可读取或格式变化,请重新预览核对。'; source.lastCheckedAt = new Date().toISOString(); this.hub.save(); reports.push({ id, error: source.lastError }); }
} catch (cause) { const current = this.hub.state.imports[id]; current.lastError = '来源暂不可读取或格式变化,请重新预览核对。'; current.lastCheckedAt = new Date().toISOString(); this.hub.save(); reports.push({ id, error: current.lastError }); }
}
return reports;
}
+39 -8
View File
@@ -26,7 +26,40 @@ export class ModelHub {
if (recovered) this.saveAttempts();
provider.credentials ??= new Map();
}
save() { this.state.revision++; this.store.storage.transaction(() => this.store.storage.setMeta('modelRegistry', this.state)); }
save(config = null) {
this.state.revision++;
if (this.editingRegistry) {
if (config) throw error('批量连接导入不能修改当前运行模式。');
return;
}
const persist = () => this.store.storage.setMeta('modelRegistry', this.state);
try {
if (config) this.store.saveConfig(config, { beforeSave: persist });
else this.store.storage.transaction(persist);
} catch (cause) {
// Keep runtime routing consistent with the authoritative committed state.
this.state = this.store.storage.meta('modelRegistry', { schema: 1, revision: 0,
selected: { type: 'legacy', id: legacyId }, connections: [], pools: [], imports: {} });
throw cause;
}
}
editRegistry(action) {
if (this.editingRegistry) return action();
const before = structuredClone(this.state), credentials = new Map(this.provider.credentials);
this.editingRegistry = true;
try {
return this.store.storage.transaction(() => {
const result = action();
this.store.storage.setMeta('modelRegistry', this.state);
return result;
});
} catch (cause) {
this.state = before;
this.provider.credentials.clear();
for (const [id, value] of credentials) this.provider.credentials.set(id, value);
throw cause;
} finally { this.editingRegistry = false; }
}
saveAttempts() { this.attempts = this.attempts.slice(-1000); this.store.storage.transaction(() => this.store.storage.setMeta('modelAttempts', this.attempts)); }
connections() {
return [{ id: legacyId, name: '原模型连接', brand: '兼容服务', protocol: 'chat-completions', baseUrl: this.store.config.baseUrl,
@@ -90,16 +123,14 @@ export class ModelHub {
maxAttempts: bounded(input.maxAttempts, 3, 1, 8), queueTimeoutMs: bounded(input.queueTimeoutMs, 15000, 100, 60000), revision: (previous?.revision ?? 0) + 1 };
this.state.pools = [...this.state.pools.filter(item => item.id !== value.id), value]; this.save(); return value;
}
select(input) {
select(input, config = null) {
if (input.type === 'connection') this.connection(input.id);
else if (input.type === 'pool') { if (!this.state.pools.some(item => item.id === input.id)) throw error('模型池不存在。'); }
else if (input.type !== 'legacy') throw error('模型选择无效。');
this.state.selected = { type: input.type, id: input.type === 'legacy' ? legacyId : input.id }; this.save();
if (input.type !== 'legacy') {
// Keep the original endpoint/key pair intact. Only a Run's immutable
// routing snapshot receives the selected member's endpoint and model.
this.store.saveConfig({ mode: 'compatible' });
}
this.state.selected = { type: input.type, id: input.type === 'legacy' ? legacyId : input.id };
// Selection and mode must commit together; the original endpoint/key pair
// stays intact and a Run alone receives its immutable routing snapshot.
this.save(config ?? (input.type !== 'legacy' ? { mode: 'compatible' } : null));
return this.view();
}
prepare(config) {
+11
View File
@@ -0,0 +1,11 @@
import path from 'node:path';
// Project commands receive system/runtime paths, never arbitrary host settings
// or provider credentials. Additional fields are explicit internal policy.
export function projectEnvironment(extra = {}) {
const allowed = /^(path|pathext|systemroot|systemdrive|windir|comspec|temp|tmp|userprofile|homedrive|homepath|home|appdata|localappdata|programfiles(?:\(x86\))?|commonprogramfiles(?:\(x86\))?|lang|lc_all)$/i;
const environment = Object.fromEntries(Object.entries(process.env).filter(([name]) => allowed.test(name)));
const inheritedPath = Object.entries(environment).find(([name]) => name.toLowerCase() === 'path')?.[1] || '';
for (const name of Object.keys(environment)) if (name.toLowerCase() === 'path') delete environment[name];
return { ...environment, PATH: [path.dirname(process.execPath), inheritedPath].filter(Boolean).join(path.delimiter), ...extra };
}
+2 -3
View File
@@ -4,6 +4,7 @@ import os from 'node:os';
import { createHash, randomUUID } from 'node:crypto';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { projectEnvironment } from './process-environment.mjs';
const executeFile = promisify(execFile);
const digest = bytes => createHash('sha256').update(bytes).digest('hex');
@@ -15,9 +16,7 @@ const fileIdentity = file => {
return { path: resolved, sha256: digest(fs.readFileSync(resolved)) };
};
export function pythonEnvironment() {
const environment = { ...process.env, NO_COLOR: '1', CI: '1', PYTEST_DISABLE_PLUGIN_AUTOLOAD: '1', PYTHONDONTWRITEBYTECODE: '1' };
for (const key of ['AGENT_WORKBENCH_API_KEY', 'NODE_TEST_CONTEXT', 'PYTEST_ADDOPTS', 'PYTEST_PLUGINS', 'PYTHONPATH', 'PYTHONHOME', 'PYTHONSTARTUP', 'FORCE_COLOR']) delete environment[key];
return environment;
return projectEnvironment({ NO_COLOR: '1', CI: '1', PYTEST_DISABLE_PLUGIN_AUTOLOAD: '1', PYTHONDONTWRITEBYTECODE: '1' });
}
function configurationFor(executable) {
for (const file of [path.join(path.dirname(executable), 'pyvenv.cfg'), path.join(path.dirname(executable), '..', 'pyvenv.cfg')]) {
+8 -2
View File
@@ -67,6 +67,11 @@ function allowRequest(request, url) {
}
return async (request, response) => {
try {
response.setHeader('Referrer-Policy', 'no-referrer');
response.setHeader('X-Frame-Options', 'DENY');
// Scripts and API requests belong to this workbench origin. Inline styles
// are limited to the existing React layout; model text never becomes HTML.
response.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'");
const actualPort = getPort();
if (server && (!server.listening || server.address().port !== actualPort)) throw new Error('本地执行宿主已经变化,请重新连接工作台。');
const url = new URL(request.url, 'http://127.0.0.1:' + actualPort);
@@ -562,9 +567,10 @@ return async (request, response) => {
maxTaskTokens: Math.trunc(Math.max(1000, Math.min(10000000, Number(input.maxTaskTokens) || store.config.maxTaskTokens))),
};
provider.validate(config);
if (Object.hasOwn(input, 'apiKey') && (typeof input.apiKey !== 'string' || input.apiKey.length > 16000)) throw new Error('模型凭据格式无效。');
if (provider.hub) provider.hub.select({ type: 'legacy' }, config);
else store.saveConfig(config);
if (Object.hasOwn(input, 'apiKey')) provider.setKey(input.apiKey);
if (provider.hub) provider.hub.select({ type: 'legacy' });
store.saveConfig(config);
return json(response, { ...store.config, hasKey: provider.hasKey() });
}
if (method === 'POST' && route === '/api/config/models') {
+1 -1
View File
@@ -1,6 +1,6 @@
import { randomUUID, createHash } from 'node:crypto';
export const APP_VERSION = '1.12.0';
export const APP_VERSION = '1.12.1';
export function executionEnvironment() {
const windows = process.platform === 'win32';
+11
View File
@@ -4,6 +4,8 @@ import { Provider } from './provider.mjs';
import { Runtime } from './runtime.mjs';
import { Store, atomicJson, readJson } from './store.mjs';
import { ArtifactStore } from '../core/storage/artifact-store.mjs';
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';
@@ -13,10 +15,13 @@ 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 (runtime.active.size || runtime.waiters.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, 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 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 };
const oldStoreProperties = { ...store };
const oldRuntimeProperties = { appDirectory: runtime.appDirectory, checks: runtime.checks, deliveries: runtime.deliveries, codeIndex: runtime.codeIndex, changeSets: runtime.changeSets, contextPlans: runtime.contextPlans, workspaces: runtime.workspaces, research: runtime.research, engines: runtime.engines, browser: runtime.browser, taskPlans: runtime.taskPlans, projectMemories: runtime.projectMemories, taskCheckpoints: runtime.taskCheckpoints, skills: runtime.skills, mcp: runtime.mcp };
const oldUpdates = store.listeners('update');
@@ -28,6 +33,10 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
Object.setPrototypeOf(store, Store.prototype);
Object.setPrototypeOf(provider, Provider.prototype);
Object.setPrototypeOf(runtime, Runtime.prototype);
if (provider.hub) {
Object.setPrototypeOf(provider.hub, ModelHub.prototype);
if (provider.hub.importer) Object.setPrototypeOf(provider.hub.importer, ConfigImporter.prototype);
}
runtime.appDirectory = root; runtime.checks = null; runtime.deliveries = null; runtime.codeIndex = null; runtime.changeSets = null; runtime.contextPlans = null; runtime.workspaces = null; runtime.research = null; runtime.engines = null; runtime.browser = null; runtime.taskPlans = null; runtime.projectMemories = null; runtime.taskCheckpoints = null; runtime.skills = null; runtime.mcp = null;
store.ensureStorage();
// A SQLite host can retain an artifact object from an earlier bundle.
@@ -56,6 +65,8 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
Object.assign(store, oldStoreProperties);
Object.assign(runtime, oldRuntimeProperties);
Object.setPrototypeOf(store, oldPrototypes[0]); Object.setPrototypeOf(provider, oldPrototypes[1]); Object.setPrototypeOf(runtime, oldPrototypes[2]);
if (oldModelPrototypes.hub) Object.setPrototypeOf(provider.hub, oldModelPrototypes.hub);
if (oldModelPrototypes.importer) Object.setPrototypeOf(provider.hub.importer, oldModelPrototypes.importer);
store.removeAllListeners('update'); for (const observer of oldUpdates) store.on('update', observer);
server.removeAllListeners('request'); for (const previous of oldHandlers) server.on('request', previous);
throw error;
+2
View File
@@ -119,6 +119,7 @@ export class Provider {
const deadline = Date.now() + policy.totalTimeoutMs;
const startedAt = Date.now();
let attempts = 0;
this.activeRequests = (this.activeRequests ?? 0) + 1;
try {
for (let attempt = 1; attempt <= policy.attempts; attempt++) {
signal?.throwIfAborted();
@@ -166,6 +167,7 @@ export class Provider {
}
throw new Error('模型请求未能完成。');
} finally {
this.activeRequests--;
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() };
+3 -6
View File
@@ -10,6 +10,7 @@ import { executionEnvironment, sessionContext, sessionSnapshot } from './diagnos
import { BudgetExceeded, checkBudget } from '../shared/contracts/execution.mjs';
import { CheckRunner } from '../core/check-runner.mjs';
import { inspectProject } from '../core/project-inspector.mjs';
import { projectEnvironment } from '../core/process-environment.mjs';
import { GitDelivery } from '../core/git-delivery.mjs';
import { ProjectIndex } from '../core/context/project-index.mjs';
import { RequestPlanner, verifyPlanEvidence } from '../core/context/request-plan.mjs';
@@ -101,7 +102,7 @@ export class Runtime {
this.active = new Map(); this.waiters = new Map();
}
isActive(id) { return this.active.has(id) || !!this.checks?.isActive(id) || !!this.deliveries?.isActive(id) || !!this.changeSets?.isActive(id) || !!this.workspaces?.isActive(id) || !!this.research?.isActive(id) || !!this.engines?.isActive(id) || !!this.browser?.isActive(id) || !!this.taskPlans?.isActive(id); }
hasActivity() { return this.active.size > 0 || (this.checks?.active.size ?? 0) > 0 || (this.deliveries?.active.size ?? 0) > 0 || (this.changeSets?.projects.size ?? 0) > 0 || (this.workspaces?.projects.size ?? 0) > 0 || (this.workspaces?.pending.size ?? 0) > 0 || (this.research?.active.size ?? 0) > 0 || (this.engines?.active.size ?? 0) > 0 || (this.browser?.active.size ?? 0) > 0 || (this.taskPlans?.active.size ?? 0) > 0; }
hasActivity() { return (this.provider.activeRequests ?? 0) > 0 || (this.provider.hub?.waiting ?? 0) > 0 || this.active.size > 0 || (this.checks?.active.size ?? 0) > 0 || (this.deliveries?.active.size ?? 0) > 0 || (this.changeSets?.projects.size ?? 0) > 0 || (this.workspaces?.projects.size ?? 0) > 0 || (this.workspaces?.pending.size ?? 0) > 0 || (this.research?.active.size ?? 0) > 0 || (this.engines?.active.size ?? 0) > 0 || (this.browser?.active.size ?? 0) > 0 || (this.taskPlans?.active.size ?? 0) > 0; }
projectIndexer() { return this.codeIndex ??= new ProjectIndex(); }
taskPlanner() { return this.taskPlans ??= new TaskPlanManager(this.store, { redact: value => this.provider.redact(value),
projectBusy: (projectId, exceptId) => this.projectHasActivity(projectId, exceptId) }); }
@@ -557,11 +558,7 @@ export class Runtime {
const executable = windows ? path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe') : '/bin/sh';
const bootstrap = "$workbenchUtf8 = [Text.UTF8Encoding]::new($false)\n[Console]::InputEncoding = $workbenchUtf8\n[Console]::OutputEncoding = $workbenchUtf8\n$OutputEncoding = $workbenchUtf8\n$workbenchCode = [Console]::In.ReadToEnd()\ntry {\n & ([scriptblock]::Create($workbenchCode))\n $workbenchSucceeded = $?\n if ($null -ne $LASTEXITCODE -and $LASTEXITCODE -ne 0) { exit $LASTEXITCODE }\n if (-not $workbenchSucceeded) { exit 1 }\n} catch { [Console]::Error.WriteLine($_.Exception.Message); [Console]::Error.WriteLine($_.FullyQualifiedErrorId); exit 1 }";
const argumentsList = windows ? ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(bootstrap, 'utf16le').toString('base64')] : ['-c', command];
const childEnv = { ...process.env };
const priorPath = process.env.PATH || '';
for (const key of Object.keys(childEnv)) if (key.toLowerCase() === 'path') delete childEnv[key];
childEnv.PATH = path.dirname(process.execPath) + path.delimiter + priorPath;
delete childEnv.AGENT_WORKBENCH_API_KEY;
const childEnv = projectEnvironment();
const child = spawn(executable, argumentsList, { cwd, windowsHide: true, stdio: [windows ? 'pipe' : 'ignore', 'pipe', 'pipe'], env: childEnv });
if (windows) { child.stdin.on('error', () => {}); child.stdin.end(command, 'utf8'); }
const decoders = { stdout: new StringDecoder('utf8'), stderr: new StringDecoder('utf8') };
+2 -2
View File
@@ -318,9 +318,9 @@ export class Store extends EventEmitter {
return session;
}
saveConfig(config) {
saveConfig(config, { beforeSave } = {}) {
const next = cleanConfig({ ...this.config, ...config, configRevision: (this.config.configRevision ?? 0) + 1 });
this.storage.transaction(() => this.storage.setMeta('config', next));
this.storage.transaction(() => { beforeSave?.(); this.storage.setMeta('config', next); });
this.config = next;
// A compatibility export for old launchers; SQLite is authoritative after migration.
try { atomicJson(path.join(this.directory, 'config.json'), this.config); } catch { this.publicationNotice = '配置已保存,兼容JSON导出未更新。'; }