fix: preserve model state, isolate commands and harden local HTTP in 1.12.1
This commit is contained in:
+8
-2
@@ -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,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';
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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() };
|
||||
|
||||
@@ -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') };
|
||||
|
||||
@@ -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导出未更新。'; }
|
||||
|
||||
Reference in New Issue
Block a user