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')]) {