feat: connect controlled engines to owned Tasks, approvals and budget ledger

This commit is contained in:
Agent Workbench Dev
2026-10-31 05:04:55 +08:00
parent a01c41811b
commit f0eecbda47
27 changed files with 1653 additions and 33 deletions
+3 -3
View File
@@ -1,14 +1,14 @@
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { engineDigest, engineError } from '../../shared/contracts/engines.mjs';
import { engineDigest, engineError, engineCanonicalDigest } from '../../shared/contracts/engines.mjs';
import { resolveDeepSeekInstallation, assertDeepSeekInstallation, engineFileIdentity } from './deepseek-installation.mjs';
import { CONTROLLED_BRIDGE_PLUGIN, CONTROLLED_DISABLED_PLUGINS, canonicalEngineValue } from './controlled-plugin.mjs';
import { CONTROLLED_BRIDGE_PLUGIN, CONTROLLED_DISABLED_PLUGINS } from './controlled-plugin.mjs';
export const CONTROLLED_ENGINE_SCOPE = 'deepseek-workbench-engine-v1';
export const CONTROLLED_CRITICAL_FILES = Object.freeze(['packages/core/tools/lib/index.js', 'packages/core/agent/lib/index.js',
'packages/core/agent-loop/lib/index.js', 'packages/core/system-prompt/lib/index.js', 'packages/llm/llm/lib/index.js',
'packages/llm/llm-retry/lib/index.js', 'vendor/include/lib/index.js']);
export const controlledDigest = value => engineDigest(canonicalEngineValue(value));
export const controlledDigest = engineCanonicalDigest;
export function resolveControlledInstallation(appDirectory = process.cwd(), root) {
const base = resolveDeepSeekInstallation(appDirectory, root);
+1
View File
@@ -59,6 +59,7 @@ export async function apply(ctx, config) {
tools: options.tools ?? [], toolHistory: options.toolHistory ?? null,
model: options.model, maxTokens: options.maxTokens ?? config.maxOutputTokens }, options.signal);
const message = result.message;
if (result.finishReason === 'length') throw new Error('Owned model output reached its bound; incomplete tools are not executed.');
if (!message || message.role !== 'assistant' || typeof message.content !== 'string'
|| message.tool_calls !== undefined && !Array.isArray(message.tool_calls)) throw new Error('Invalid owned model result.');
let index = 0;
+37 -2
View File
@@ -6,6 +6,7 @@ import { DeepSeekAdapter } from './deepseek-adapter.mjs';
import { engineFileIdentity } from './deepseek-installation.mjs';
import { engineError } from '../../shared/contracts/engines.mjs';
import { isId } from '../../shared/contracts/execution.mjs';
import { readOwnedProcessTree } from '../owned-process-tree.mjs';
import { CONTROLLED_BRIDGE_PLUGIN } from './controlled-plugin.mjs';
import { assertControlledInstallation, controlledDigest, controlledPatch, controlledToolCatalogue, CONTROLLED_ENGINE_SCOPE } from './controlled-installation.mjs';
@@ -18,6 +19,7 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
constructor(installation, options = {}) {
super(installation, options); this.maximumFrameBytes = options.maximumFrameBytes ?? 4 * 1024 * 1024;
this.pending = new Set(); this.closed = false;
this.processTreeReader = options.processTreeReader ?? readOwnedProcessTree;
}
async open({ directory, cwd, owner, sdkSessionId, tools, config, signal, onModel, onTool, onState = () => {}, onNotification = () => {} }) {
for (const field of ['sessionId', 'projectId', 'taskId', 'runId', 'jobId']) if (!isId(owner?.[field])) throw engineError('受控引擎所属身份无效。', 400);
@@ -59,6 +61,15 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
{ timeoutMs: this.timeoutMs, maximumFrameBytes: this.maximumFrameBytes, cancellationMethod: null });
this.report.process = { pid: this.client.pid, connectionId: this.client.id, startedAt: this.client.startedAt, ownership: 'one-process-per-engine-run' };
onState('starting', this.report.process);
this.publishOwnership = () => onState('ownership', this.report.process);
try { await this.captureTree(); } catch (error) { this.report.process.treeObservationError = error.message; throw error; }
this.treeTimer = setInterval(() => {
if (this.closed || this.treePending) return;
this.treePending = this.captureTree().catch(error => {
this.report.process.treeObservationError = error.message; this.client.fail(error);
this.publishOwnership();
}).finally(() => { this.treePending = null; });
}, 1200); this.treeTimer.unref();
this.client.on('server-request', request => {
this.report.rejectedServerRequests.push({ id: request.id, method: request.method, parametersSha256: controlledDigest(request.params ?? {}) });
this.client.fail(engineError('原SDK反向请求未在受控契约中开放。'));
@@ -94,8 +105,19 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
if (engineFileIdentity(input.path).sha256 !== input.sha256) throw engineError('所属叠加插件或启动输入发生变化。');
}
}
async captureTree(publish = true) {
const info = this.report.process, tree = await this.processTreeReader(info);
if (tree.supported) {
if (tree.root) info.rootCreatedAt ??= tree.root.createdAt;
const known = new Map((info.descendants ?? []).map(value => [value.pid + ':' + value.createdAt, value]));
for (const value of tree.processes) if (value.pid !== info.pid) known.set(value.pid + ':' + value.createdAt, value);
info.descendants = [...known.values()].sort((left, right) => left.pid - right.pid);
info.treeRemainingPids = tree.processes.map(value => value.pid); info.treeObservedAt = at();
}
if (publish) this.publishOwnership?.(); return tree;
}
async handleBridge(request, response, { authentication, onModel, onTool, signal }) {
if (this.closed || signal?.aborted || request.method !== 'POST' || !['/model', '/tool'].includes(request.url)
if (this.closed || this.client?.exited === true || signal?.aborted || request.method !== 'POST' || !['/model', '/tool'].includes(request.url)
|| request.headers.origin !== undefined || request.headers['content-type'] !== 'application/json'
|| !equalSecret(request.headers.authorization, authentication)) throw engineError('桥请求不属于当前受控Run。', 403);
const chunks = []; let size = 0;
@@ -153,6 +175,7 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
if (!assistant || !Array.isArray(assistant.data?.message?.content)) throw engineError('所属活动没有完整assistant原消息。');
const ends = activity.filter(event => event?.type === 'turn/end');
this.report.activity = { receiptIndex: receipt, endEvents: ends };
if (ends.length !== 1 || ends[0].data?.reason?.kind !== 'completed') throw engineError('所属活动没有唯一的正常结束事件,原输出不能视为完成。');
this.report.finalText = assistant.data.message.content.filter(block => block.type === 'text').map(block => block.text).join('');
return this.report.finalText;
}
@@ -160,21 +183,33 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
if (this.closePromise) return this.closePromise;
const interrupted = force || this.parentSignal?.aborted === true;
this.closed = true;
clearInterval(this.treeTimer);
this.bridgeController?.abort(new Error('所属引擎正在关闭。'));
return this.closePromise = (async () => {
let failure = null;
if (this.client) {
await this.treePending;
if (!interrupted && !this.client.exited) {
try { await this.client.request('shutdown', {}, { timeoutMs: 1000 }); } catch (error) { failure = error; }
}
try { this.report.cleanup = await this.client.close({ force: interrupted || !!failure }); } catch (error) { failure ??= error; }
try {
const tree = await this.captureTree(false);
this.report.cleanup ??= { rootExited: false };
this.report.cleanup.treeConfirmed = tree.supported ? tree.processes.length === 0 && !!this.report.process.rootCreatedAt
&& !this.report.process.treeObservationError : this.report.cleanup.rootExited;
this.report.cleanup.remainingProcesses = tree.processes;
} catch (error) {
failure ??= error; this.report.cleanup ??= { rootExited: false }; this.report.cleanup.treeConfirmed = false;
}
this.report.trace = this.client.trace; this.report.stderr = this.client.stderr;
}
if (this.guard) { this.guard.closeAllConnections(); await new Promise(resolve => this.guard.close(resolve)); }
await Promise.allSettled([...this.pending]);
if (!interrupted && this.report.launchInputs) { try { this.verifyLaunch(); } catch (error) { failure ??= error; } }
if (!interrupted && this.report.cleanup?.exit?.code !== 0) failure ??= engineError('所属引擎未正常退出。');
this.report.finishedAt = at(); this.report.status = failure || !this.report.cleanup?.rootExited ? 'unknown' : interrupted ? 'cancelled' : 'closed';
this.report.finishedAt = at(); this.report.status = this.client && (!this.report.cleanup?.rootExited || !this.report.cleanup?.treeConfirmed)
? 'unknown' : failure ? 'failed' : interrupted ? 'cancelled' : 'closed';
if (failure) this.report.error = failure.message;
return this.report;
})();
+268
View File
@@ -0,0 +1,268 @@
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { randomUUID } from 'node:crypto';
import { ControlledDeepSeekSession } from './controlled-session.mjs';
import { resolveControlledInstallation, assertControlledInstallation, controlledDigest } from './controlled-installation.mjs';
import { engineRunInput, engineRunReport, verifyEngineInput, nativeMessagesToChat } from '../../shared/contracts/engine-execution.mjs';
import { engineError } from '../../shared/contracts/engines.mjs';
import { modelSnapshot, accountedTokens, checkBudget, BudgetExceeded } from '../../shared/contracts/execution.mjs';
import { completionBody, requestMetrics } from '../../shared/contracts/model-request.mjs';
import { workerForSession } from '../../shared/contracts/workers.mjs';
const at = () => new Date().toISOString();
const deferred = () => {
let resolve, reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
promise.catch(() => {}); return { promise, resolve, reject };
};
export class EngineRunner {
constructor(store, provider, { appDirectory = process.cwd(), sessionFactory = installation => new ControlledDeepSeekSession(installation), directoryRoot = null } = {}) {
this.store = store; this.provider = provider; this.appDirectory = appDirectory; this.sessionFactory = sessionFactory;
this.directoryRoot = directoryRoot; this.drivers = new Map();
}
availability(root) { return resolveControlledInstallation(this.appDirectory, root); }
selected(input) {
const installation = this.availability(input.root);
if (installation.controlledStatus !== 'available' || installation.controlledSha256 !== input.controlledSha256) {
throw engineError('受控引擎与刚才检测的程序/插件身份不一致,请重新检测后制定新计划。');
}
return installation;
}
assertCurrent(session, run) {
const driver = this.drivers.get(run.id);
if (!driver || driver.session !== session || driver.run !== run) throw engineError('原引擎执行不属于当前Run。');
driver.assertInput(); driver.native?.verifyLaunch?.();
}
complete(session, run, messages, progress, planned, tools) {
let driver = this.drivers.get(run.id);
if (!driver) {
if (workerForSession(this.store, session) !== run.worker || !run.worker?.engine) throw engineError('外部引擎只能在所属受限子工程中执行。');
assertControlledInstallation(run.worker.engine);
driver = new EngineRunDriver(this, session, run, planned, tools); this.drivers.set(run.id, driver);
}
return driver.complete(messages, progress).catch(error => { driver.fail(error); throw error; });
}
async finish(session, run) {
const driver = this.drivers.get(run.id); if (!driver) return;
try { await driver.close(); } finally { this.drivers.delete(run.id); }
if (driver.job.requiresVerification) {
session.status = 'paused'; run.stopReason = 'engine_verification';
this.store.message(session, 'system', '所属外部引擎的原进程或结果待核对。请在父工程核对原输入与现场后继续。');
} else if (driver.job.status !== 'completed' && session.status === 'completed') {
session.status = 'paused'; run.stopReason = 'engine_incomplete';
this.store.message(session, 'system', '原引擎没有完成全部协议和结果核验,不能交付。');
}
return driver.job;
}
}
class EngineRunDriver {
constructor(manager, session, run, seedPlan, tools) {
this.manager = manager; this.store = manager.store; this.provider = manager.provider; this.session = session; this.run = run;
this.queue = []; this.waiter = null; this.pendingCalls = new Map(); this.finished = false;
const base = path.resolve(manager.directoryRoot ?? path.join(os.tmpdir(), 'AgentWorkbench-Engine-Runs'));
fs.mkdirSync(base, { recursive: true }); if (fs.lstatSync(base).isSymbolicLink()) throw engineError('引擎运行目录不能是链接。');
const id = randomUUID();
this.job = { schemaVersion: 1, id, sessionId: session.id, projectId: session.projectId, taskId: run.taskId, runId: run.id,
workerId: run.worker.id, collaborationId: run.worker.collaborationId, installation: structuredClone(run.worker.engine),
sdkSessionId: randomUUID(), directory: path.join(base, id), model: modelSnapshot(run.config), budget: { ...run.record.budget, maxToolCalls: run.worker.budget.maxToolCalls },
tools: structuredClone(tools), sourceContextPlanId: seedPlan.id, sourceRequestSha256: seedPlan.requestSha256,
status: 'queued', startedAt: at(), finishedAt: null, requiresVerification: false, verified: false, native: null, requests: [], calls: [] };
const artifact = this.store.artifactStore.write(session, run.record, engineRunInput(this.job), { kind: 'engine-run-input' });
this.store.core.artifact.set(artifact.id, artifact); this.job.inputArtifactId = artifact.id; this.job.inputSha256 = artifact.sha256;
run.record.engine = 'deepseek-workbench'; run.record.engineRunId = id;
this.save('queued');
}
save(phase) { this.store.putRecord('engine_run', this.session, this.job, 'engine_run.' + phase); }
assertInput() {
verifyEngineInput(this.store, this.session, this.job); assertControlledInstallation(this.job.installation);
if (this.session.runId !== this.run.id || workerForSession(this.store, this.session) !== this.run.worker) throw engineError('引擎原Run已变化。');
}
publish(value) {
if (this.waiter) { const waiter = this.waiter; this.waiter = null; waiter.resolve(value); } else this.queue.push(value);
}
async next() {
this.run.controller.signal.throwIfAborted();
if (this.queue.length) return this.queue.shift();
const waiter = deferred(); this.waiter = waiter;
const abort = () => waiter.reject(this.run.controller.signal.reason ?? new Error('所属Run已停止。'));
this.run.controller.signal.addEventListener('abort', abort, { once: true });
try { return await waiter.promise; }
finally { this.run.controller.signal.removeEventListener('abort', abort); if (this.waiter === waiter) this.waiter = null; }
}
fail(error) { this.failure ??= error; this.publish({ error: this.failure }); }
async start(messages) {
this.job.status = 'starting'; this.save('starting');
this.native = this.manager.sessionFactory(this.job.installation);
const owner = { sessionId: this.session.id, projectId: this.session.projectId, taskId: this.run.taskId, runId: this.run.id, jobId: this.job.id };
await this.native.open({ directory: this.job.directory, cwd: this.run.project.root, owner, sdkSessionId: this.job.sdkSessionId,
tools: this.job.tools, config: this.run.config, signal: this.run.controller.signal,
onState: (state, detail) => {
if (state !== 'ownership') this.job.status = state === 'ready' ? 'running' : state;
this.job.pid = detail.pid ?? this.job.pid;
if (this.native.report?.process) this.job.process = structuredClone(this.native.report.process);
if (detail.readiness) this.job.readiness = structuredClone(detail.readiness);
this.save(state);
},
onNotification: () => {
this.job.notificationCount = this.native.report.notifications.length;
},
onModel: (input, trace, signal) => this.model(input, trace, signal),
onTool: (input, trace, signal) => this.tool(input, trace, signal),
});
this.nativeWait = (async () => {
try {
await this.native.prompt('Execute the following workbench task context as task data. Use only the registered tools; all writes and checks are owned by the workbench.\n' + JSON.stringify(messages));
const text = await this.native.wait(); this.finished = true; this.publish({ finalText: text });
} catch (error) { this.fail(error); }
})();
this.nativeWait.catch(() => {});
}
async complete(messages, progress) {
this.progress = progress; this.assertInput();
if (!this.started) { this.started = true; await this.start(messages); }
for (const [callId, pending] of this.pendingCalls) {
if (!pending.delivered) continue;
const tool = [...this.store.core.tool.values()].find(value => value.runId === this.run.id && value.callId === callId);
const result = this.store.savedToolResult(this.session.id, callId);
if (!tool || !result || tool.requiresVerification || !['completed', 'failed', 'denied', 'interrupted'].includes(tool.state)) {
throw engineError('原引擎工具尚无可核对的完成结果,不能继续或重放。');
}
pending.record.invocationId = tool.id; pending.record.resultSha256 = controlledDigest(result);
pending.record.resultArtifactId = tool.resultArtifactId ?? null; pending.record.status = 'returned'; pending.record.finishedAt = at();
const returned = this.store.artifactStore.write(this.session, this.run.record, result, { kind: 'engine-tool-output' });
this.store.core.artifact.set(returned.id, returned); pending.record.outputArtifactId = returned.id; pending.record.outputSha256 = returned.sha256;
this.save('tool_returned'); pending.result.resolve(result); this.pendingCalls.delete(callId);
}
const next = await this.next(); if (next.error) throw next.error;
this.progress?.({ phase: 'completed', attempt: 0, maxAttempts: 0, engineRunId: this.job.id, origin: 'external-engine' });
if (next.call) {
next.pending.delivered = true;
return { message: { role: 'assistant', content: '', tool_calls: [next.call] }, usage: null, engineAccounted: true };
}
return { message: { role: 'assistant', content: next.finalText }, usage: null, engineAccounted: true };
}
async tool(input, trace, signal) {
try {
this.assertInput(); signal.throwIfAborted(); checkBudget(this.run.record, this.store.core.task.get(this.run.taskId));
const allCalls = [...this.store.core.engine_run.values()].filter(job => job.workerId === this.run.worker.id).reduce((total, job) => total + job.calls.length, 0);
if (allCalls >= this.run.worker.budget.maxToolCalls) throw new BudgetExceeded('worker_tool_limit', '原引擎工具次数已到所属子任务累计上限。');
const callId = this.job.id + ':' + input.callId;
if (this.pendingCalls.has(callId) || this.job.calls.some(call => call.callId === callId)) throw engineError('原引擎调用已经登记,不会再次执行。');
const record = { sourceCallId: input.callId, callId, name: input.name, argumentsSha256: controlledDigest(input.arguments),
bridgeTraceId: trace.id, status: 'received', receivedAt: at() };
const artifact = this.store.artifactStore.write(this.session, this.run.record, { owner: trace.id, ...input }, { kind: 'engine-tool-input' });
this.store.core.artifact.set(artifact.id, artifact); record.inputArtifactId = artifact.id; record.inputSha256 = artifact.sha256;
const pending = { record, result: deferred(), delivered: false }; this.job.calls.push(record); this.pendingCalls.set(callId, pending);
this.job.status = 'waiting_tool'; this.save('tool_received');
const abort = () => pending.result.reject(signal.reason ?? new Error('所属引擎工具已停止。'));
signal.addEventListener('abort', abort, { once: true });
this.publish({ call: { id: callId, type: 'function', function: { name: input.name, arguments: JSON.stringify(input.arguments) } }, pending });
try { return await pending.result.promise; } finally { signal.removeEventListener('abort', abort); }
} catch (error) { this.fail(error); throw error; }
}
async model(input, trace, signal) {
let request, dispatched = false;
if (this.modelActive) { const error = engineError('所属引擎已有模型请求,不能并发扩展封存预算。'); this.fail(error); throw error; }
this.modelActive = true;
try {
this.assertInput(); signal.throwIfAborted();
const task = this.store.core.task.get(this.run.taskId); checkBudget(this.run.record, task);
const messages = nativeMessagesToChat(input), tools = input.tools.map(tool => ({ type: 'function', function: tool }));
const config = { ...this.run.config, maxOutputTokens: input.maxTokens }, body = completionBody(config, messages, tools), metrics = requestMetrics(body);
const maximumAttempts = config.mode === 'demo' ? 1 : config.modelRouting?.maxAttempts ?? 1;
const credit = Math.min(this.run.record.budget.maxTokens - accountedTokens(this.run.record.usage), task.budget.maxTokens - accountedTokens(task.usage));
const estimate = metrics.estimatedInputTokens + 128 + config.maxOutputTokens;
const attempts = Math.min(maximumAttempts, Math.floor(credit / estimate), this.run.worker.budget.maxSteps - task.usage.requests);
if (metrics.estimatedInputTokens + 128 + config.maxOutputTokens > config.contextLimit || attempts < 1) {
throw new BudgetExceeded('engine_input_budget', '原引擎完整模型输入或累计尝试超出封存预算,未发送模型请求。');
}
const selected = config.modelRouting ? { ...config, modelRouting: { ...config.modelRouting, maxAttempts: attempts } } : config;
request = { id: randomUUID(), bridgeTraceId: trace.id, sourceSha256: controlledDigest(input), requestSha256: metrics.sha256,
requestBytes: metrics.bytes, estimatedInputTokens: metrics.estimatedInputTokens, reservedPerAttempt: estimate,
maxAttempts: attempts, accountedAttempts: 0, observedAttempts: 0, status: 'prepared', startedAt: at() };
const owner = { sessionId: this.session.id, projectId: this.session.projectId, taskId: this.run.taskId, runId: this.run.id };
const plan = { ...request, ...owner };
const artifact = this.store.artifactStore.write(this.session, this.run.record,
JSON.parse(this.provider.redact(JSON.stringify({ schemaVersion: 1, owner, native: input, body, plan }))), { kind: 'engine-model-input' });
this.store.core.artifact.set(artifact.id, artifact); request.inputArtifactId = artifact.id; request.inputSha256 = artifact.sha256;
this.job.requests.push(request);
const modelEvent = this.store.event(this.session, { kind: 'model', source: 'engine_model_bridge', engineRunId: this.job.id, engineModelRequestId: request.id,
taskId: this.job.taskId, runId: this.job.runId, label: '引擎请求模型服务', phase: 'running', startedAt: at(),
output: '原引擎完整输入已封存,模型服务由工作台代理。' });
request.eventId = modelEvent.id; request.status = 'dispatched'; request.dispatchedAt = at(); this.job.status = 'running'; this.save('model_intent');
dispatched = true;
const response = await this.provider.complete(selected, messages, this.run.project, signal, progress => {
if (progress.phase === 'running') {
const attempt = progress.attempt ?? 1;
if (!Number.isSafeInteger(attempt) || attempt < 1 || attempt > request.maxAttempts) throw engineError('模型尝试超出原引擎封存预算。');
request.observedAttempts = Math.max(request.observedAttempts, attempt);
}
if (progress.connectionId) { request.connectionId = progress.connectionId; request.actualModel = progress.model; }
modelEvent.phase = progress.phase; modelEvent.attempts = progress.attempt; modelEvent.connectionId = progress.connectionId ?? null;
modelEvent.actualModel = progress.model ?? config.model;
modelEvent.label = progress.switching ? '引擎切换模型池连接' : progress.phase === 'failed' ? '引擎模型请求失败' : progress.phase === 'completed' ? '引擎模型响应已收到' : '引擎请求模型服务';
if (['completed', 'failed'].includes(progress.phase)) modelEvent.finishedAt = at();
this.save('model_progress');
}, plan, tools, { attempts: 1 });
const count = Math.max(1, request.observedAttempts);
request.actualAttemptsFinal = count; request.responseReceivedAt = at(); request.status = 'responded';
while (request.accountedAttempts < count - 1) {
request.accountedAttempts++; this.store.recordResponse(this.session, this.run.record, null, estimate);
}
request.accountedAttempts++; request.usage = response.usage ?? null;
this.store.recordResponse(this.session, this.run.record, response.usage, estimate);
this.save('model_usage');
const output = JSON.parse(this.provider.redact(JSON.stringify(response))), saved = this.store.artifactStore.write(this.session, this.run.record, output, { kind: 'engine-model-output' });
this.store.core.artifact.set(saved.id, saved); request.responseArtifactId = saved.id; request.responseSha256 = saved.sha256;
request.status = 'completed'; request.finishedAt = at(); this.save('model_completed');
modelEvent.phase = 'completed'; modelEvent.finishedAt = at(); modelEvent.output = '原模型响应与尝试用量已保存。'; this.save('model_event_completed');
checkBudget(this.run.record, task); signal.throwIfAborted(); return output;
} catch (error) {
this.fail(error);
if (request) {
request.actualAttemptsFinal ??= request.observedAttempts || request.maxAttempts;
if (dispatched) while (request.accountedAttempts < request.actualAttemptsFinal) {
request.accountedAttempts++; this.store.recordResponse(this.session, this.run.record, null, request.reservedPerAttempt);
}
request.status = signal.aborted ? 'interrupted' : 'failed'; request.error = this.provider.redact(error.message); request.finishedAt = at(); this.save('model_failed');
const event = this.session.events.find(value => value.id === request.eventId);
if (event) { event.phase = request.status; event.finishedAt = at(); event.output = request.error; this.save('model_event_failed'); }
}
throw error;
} finally {
this.modelActive = false;
}
}
async close() {
if (this.closePromise) return this.closePromise;
return this.closePromise = this.finishClose();
}
async finishClose() {
this.job.status = 'closing'; this.save('closing');
for (const pending of this.pendingCalls.values()) pending.result.reject(new Error('所属引擎已结束,未返回结果保留原状态。'));
let native;
try { native = this.native ? await this.native.close({ force: !this.finished || !!this.failure || this.run.controller.signal.aborted }) : null; }
catch (error) { this.failure ??= error; }
if (this.nativeWait) await this.nativeWait;
this.job.native = native ? JSON.parse(this.provider.redact(JSON.stringify(native))) : null;
const launched = !!this.native?.client || !!native?.process?.pid || !!this.job.pid;
const unknown = launched && (!native?.cleanup?.rootExited || native?.cleanup?.treeConfirmed === false || native?.status === 'unknown');
this.job.requiresVerification = unknown;
this.job.status = unknown ? 'unknown' : this.finished && !this.failure && native?.status === 'closed' ? 'completed'
: this.run.controller.signal.aborted ? 'cancelled' : 'failed';
this.job.verified = this.job.status === 'completed'; this.job.finishedAt = at();
this.job.error = this.failure ? this.provider.redact(this.failure.message) : native?.error ?? null;
this.job.originalOutcome = { status: this.job.status, requiresVerification: this.job.requiresVerification, verified: this.job.verified, error: this.job.error };
try {
verifyEngineInput(this.store, this.session, this.job);
const artifact = this.store.artifactStore.write(this.session, this.run.record, engineRunReport(this.job), { kind: 'engine-run-report' });
this.store.core.artifact.set(artifact.id, artifact); this.job.reportArtifactId = artifact.id; this.job.reportSha256 = artifact.sha256;
this.save('finished');
} catch (error) {
this.job.status = 'unknown'; this.job.requiresVerification = true; this.job.verified = false;
this.job.error = '原引擎结果尚未完整封存:' + this.provider.redact(error.message); this.save('seal_failed');
}
}
}
+38 -6
View File
@@ -15,6 +15,8 @@ import { parseTestEvidence } from '../check-runner.mjs';
import { verifyPlanEvidence } from '../context/request-plan.mjs';
import { repairToolPairs } from '../../server/store.mjs';
import { readOwnedProcessTree } from '../owned-process-tree.mjs';
import { assertControlledInstallation } from '../engines/controlled-installation.mjs';
import { verifyEngineInput, originalEngineRun, assertEngineWorkerResult } from '../../shared/contracts/engine-execution.mjs';
const at = () => new Date().toISOString();
const sourceIdentity = source => Object.fromEntries(['root', 'head', 'reference', 'branch', 'gitDir', 'commonDir', 'indexSha256',
@@ -81,6 +83,7 @@ export class WorkerManager {
|| [...this.store.core.collaboration.values()].some(group => group.projectId === session.projectId && !COLLABORATION_CLOSED.has(group.status))) throw workerConflict('项目已有未收尾的父协作,请先完成或明确保留原成果。');
const initial = structuredClone(this.store.config), config = this.runtime.provider.prepareConfig ? this.runtime.provider.prepareConfig(initial, this.store) : initial;
const definition = collaborationInput(input, config), project = this.store.project(session.projectId);
const engine = definition.engine ? this.runtime.engineRunner().selected(definition.engine) : null;
const temporaryId = randomUUID(), controller = new AbortController(), active = { sessionId: session.id, projectId: project.id, group: { children: [], status: 'planning' }, controller };
active.promise = new Promise(resolve => { active.settle = resolve; });
this.active.set(temporaryId, active);
@@ -95,7 +98,7 @@ export class WorkerManager {
const group = { schemaVersion: 1, id: randomUUID(), projectId: project.id, sessionId: session.id, taskId: session.taskId, runId: run.id,
goal: definition.goal, budget: definition.budget, model: modelSnapshot(config), config: configView(config),
source: { identity: sourceIdentity(source), changedPaths: source.changedPaths, dirty: source.dirty, scope: source.scope },
children: definition.children.map(child => ({ ...child, id: randomUUID(), workspaceId: randomUUID(), projectId: randomUUID(), sessionId: randomUUID(), taskId: randomUUID() })),
children: definition.children.map(child => ({ ...child, ...(engine ? { engine: structuredClone(engine) } : {}), id: randomUUID(), workspaceId: randomUUID(), projectId: randomUUID(), sessionId: randomUUID(), taskId: randomUUID() })),
status: 'planned', requiresVerification: false, createdAt: at(), updatedAt: at(), startedAt: null, deadline: null, finishedAt: null,
summary: '父子目标、范围、模型和预算已封存,尚未创建工作区或请求模型。', collection: null, merge: null };
group.fingerprint = workerHash(collaborationSeal(group));
@@ -141,7 +144,7 @@ export class WorkerManager {
await this.initializeChild(group, child); this.save(session, group, 'workspace_registered');
await this.faultInjector?.('workspace_registered', group, child); signal.throwIfAborted();
}
await this.sourceFor(group); group.status = 'ready'; group.summary = '两个独立工作区已核对,来源HEAD、索引和已有修改保持。可以开始受限子任务。';
await this.sourceFor(group); group.status = 'ready'; group.summary = group.children.length + ' 个独立工作区已核对,来源HEAD、索引和已有修改保持。可以开始受限子任务。';
} catch (error) {
const uncertain = group.children.some(child => { const workspace = this.store.core.workspace.get(child.workspaceId); return workspace && (workspace.status !== 'ready'
|| !this.store.core.worker.has(child.id) && this.store.sessions.get(child.sessionId)?.taskId); });
@@ -195,11 +198,16 @@ export class WorkerManager {
this.store.putRecord('worker', session, worker, 'worker.ready'); return worker;
}
configFor(group, worker) {
if (worker.engine) {
assertControlledInstallation(worker.engine);
for (const job of this.store.core.engine_run.values()) if (job.workerId === worker.id) verifyEngineInput(this.store, this.store.session(worker.sessionId), job);
}
const initial = structuredClone(this.store.config), current = this.runtime.provider.prepareConfig ? this.runtime.provider.prepareConfig(initial, this.store) : initial;
if (JSON.stringify(modelSnapshot(current)) !== JSON.stringify(group.model)) throw workerConflict('模型连接或池快照已变化;不能在原协作中悄悄替换模型。');
const usage = workerUsage(this.store, worker), remaining = group.deadline - Date.now();
if (remaining <= 0) throw new BudgetExceeded('time_limit', '父协作总时限已用完,原任务与成果保留。');
if (usage.accountedTokens >= worker.budget.maxTokens || usage.steps >= worker.budget.maxSteps || usage.toolCalls >= worker.budget.maxToolCalls) throw new BudgetExceeded('worker_budget', '子任务累计预算已用完,续接不能重置预算。');
if (usage.accountedTokens >= worker.budget.maxTokens || usage.steps >= worker.budget.maxSteps || usage.toolCalls >= worker.budget.maxToolCalls
|| worker.engine && usage.requests >= worker.budget.maxSteps) throw new BudgetExceeded('worker_budget', '子任务累计预算已用完,续接不能重置预算。');
return { ...group.config, maxSteps: worker.budget.maxSteps - usage.steps, maxTaskTokens: worker.budget.maxTokens,
maxRunTokens: worker.budget.maxTokens - usage.accountedTokens, maxRunDurationMs: remaining };
}
@@ -227,7 +235,7 @@ export class WorkerManager {
group.requiresVerification = outcomes.some(outcome => outcome.status === 'rejected') || workers.some(worker => worker.requiresVerification || ['running', 'stopping'].includes(worker.status));
group.status = group.requiresVerification ? 'unknown' : workers.every(worker => worker.status === 'completed') ? 'ready_to_collect'
: workers.some(worker => this.store.session(worker.sessionId).status === 'needs_review') ? 'awaiting_review' : 'paused';
group.summary = group.status === 'ready_to_collect' ? '两个子任务均有实际改动和当前通过的检查,等待父任务核对原成果。'
group.summary = group.status === 'ready_to_collect' ? group.children.length + ' 个子任务均有实际改动和当前通过的检查,等待父任务核对原成果。'
: group.status === 'awaiting_review' ? '子任务提案已保存,请分别审查应用后继续;完成状态以实际检查为准。' : '子任务已停止或需要处理,已完成结果保留。';
} catch (error) { group.status = 'paused'; group.summary = this.runtime.provider.redact(error.message ?? String(error)); }
session.status = group.status === 'awaiting_review' ? 'needs_review' : 'paused'; this.save(session, group, group.status); return group;
@@ -263,7 +271,7 @@ export class WorkerManager {
return worker;
}
uncertain(worker) {
return ['tool', 'check_job', 'change_set', 'delivery_job'].flatMap(kind => [...this.store.core[kind].values()]
return ['tool', 'check_job', 'change_set', 'delivery_job', 'engine_run'].flatMap(kind => [...this.store.core[kind].values()]
.filter(value => value.taskId === worker.taskId && (value.requiresVerification || value.status === 'unknown' || value.state === 'unknown'))
.map(value => ({ kind, id: value.id })));
}
@@ -283,6 +291,7 @@ export class WorkerManager {
const baseline = this.baseline(session, worker), project = this.store.project(worker.projectId);
await verifyWorkspaceProject(this.store, project);
if (this.uncertain(worker).length) throw workerConflict('子任务仍有结果未知的工具、检查或文件批次');
assertEngineWorkerResult(this.store, session, worker);
if (session.changes.some(change => ['pending', 'conflict'].includes(change.status))) throw workerConflict('子任务仍有未审查改动');
const before = new Map(baseline.files.map(file => [workerPathKey(file.path), file]));
const { inspection, files: current } = await this.inventory(project), after = new Map(current.map(file => [workerPathKey(file.path), file]));
@@ -546,6 +555,24 @@ export class WorkerManager {
logSha256: this.store.core.artifact.get(result.logArtifactId)?.sha256 ?? null })) });
}
const session = this.store.sessions.get(child.sessionId);
const engines = [];
for (const job of this.store.core.engine_run.values()) if (job.taskId === child.taskId) {
verifyEngineInput(this.store, session, job);
if (job.reportArtifactId) originalEngineRun(this.store, session, job);
const processInfo = job.process ?? job.native?.process;
let tree = null;
if (job.requiresVerification || job.status === 'unknown') {
if (processInfo) {
tree = await readOwnedProcessTree(processInfo);
if (!tree.supported || tree.processes.length) throw workerConflict('原引擎进程树仍存活或无法核对,请先人工核对原创建身份;不会按历史PID停止。');
}
}
engines.push({ id: job.id, status: job.status, requiresVerification: !!job.requiresVerification,
inputArtifactId: job.inputArtifactId, inputSha256: job.inputSha256, reportArtifactId: job.reportArtifactId ?? null,
reportSha256: job.reportSha256 ?? null, process: processInfo ?? null, remainingProcesses: tree?.processes ?? null,
missingProcessIdentity: !processInfo && job.status === 'unknown', requests: job.requests, calls: job.calls,
originalOutcome: job.originalOutcome ?? null, error: job.error ?? null });
}
const tools = [...this.store.core.tool.values()].filter(value => value.taskId === child.taskId && value.requiresVerification).map(tool => {
const call = session?.providerMessages.flatMap(message => message.tool_calls ?? []).find(call => call.id === tool.callId);
const input = call?.function.arguments;
@@ -562,7 +589,7 @@ export class WorkerManager {
children.push({ id: child.id, workspaceId: child.workspaceId, workspaceStatus: workspace?.status ?? 'absent',
workerStatus: worker?.status ?? 'absent', taskId: child.taskId, sessionId: child.sessionId, projectId: child.projectId,
inventoryFingerprint: inventory ? workerHash(inventory.files) : null, sourceFingerprint: inventory?.inspection.sourceFingerprint ?? null, inventoryError,
tools, checks, changes, changeSets: [...this.store.core.change_set.values()].filter(set => set.taskId === child.taskId).map(set => ({ id: set.id, status: set.status, requiresVerification: !!set.requiresVerification, observationFingerprint: set.observationFingerprint ?? null })) });
tools, checks, changes, ...(engines.length ? { engines } : {}), changeSets: [...this.store.core.change_set.values()].filter(set => set.taskId === child.taskId).map(set => ({ id: set.id, status: set.status, requiresVerification: !!set.requiresVerification, observationFingerprint: set.observationFingerprint ?? null })) });
}
const parent = this.store.session(group.sessionId);
return { schemaVersion: 1, kind: 'worker-recovery-observation', collaborationId: group.id, groupFingerprint: group.fingerprint,
@@ -612,10 +639,15 @@ export class WorkerManager {
if (!retain && !merged && JSON.stringify(current.source) !== JSON.stringify(group.source.identity)) throw workerConflict('父来源已经变化,只能明确保留现场后重新规划。');
if (current.children.some(child => !['ready', 'absent', 'prepared', 'discarded', 'resolved_external'].includes(child.workspaceStatus))) throw workerConflict('原工作区仍需专门核对,不能开始子执行或结束恢复。');
if (!retain && current.children.some(child => ['discarded', 'resolved_external'].includes(child.workspaceStatus))) throw workerConflict('原工作区没有核对为可执行,只能明确保留现场结束。');
if (!retain && current.children.some(child => child.engines?.some(job => job.missingProcessIdentity))) throw workerConflict('引擎原进程创建身份没有封存,只能人工处理后明确保留现场结束。');
if (!retain) await this.recoverMerge(session, group);
for (const child of group.children) {
const worker = this.store.core.worker.get(child.id); if (!worker) continue;
const childSession = this.store.session(child.sessionId);
for (const job of this.store.core.engine_run.values()) if (job.taskId === child.taskId && job.requiresVerification) {
job.review = { source: 'user', evidenceSha256, reviewedAt: at(), result: 'unknown-preserved' };
job.status = 'resolved_external'; job.requiresVerification = false;
}
for (const tool of this.store.core.tool.values()) if (tool.taskId === child.taskId && tool.requiresVerification) {
tool.originalState = tool.state; tool.state = 'resolved_external'; tool.requiresVerification = false;
tool.review = { source: 'user', evidenceSha256, reviewedAt: at(), result: 'unknown-preserved' };
+17
View File
@@ -7,6 +7,7 @@ import { assertProposalUnsealed } from '../shared/contracts/change-sets.mjs';
import { assertWorkspacesResolved } from '../shared/contracts/workspaces.mjs';
import { verifyWorkspaceProject } from '../core/workspaces/git-workspaces.mjs';
import { publicEngineJob } from '../shared/contracts/engines.mjs';
import { publicEngineRun, verifyEngineInput, originalEngineRun } from '../shared/contracts/engine-execution.mjs';
import { verifyBrowserJob } from '../core/browser/browser-manager.mjs';
import { ConfigImporter } from '../core/models/config-import.mjs';
import { ProjectMemoryManager } from '../core/memory/project-memory.mjs';
@@ -185,6 +186,7 @@ return async (request, response) => {
}
if (method === 'GET' && route === '/api/research/availability') return json(response, runtime.researchManager().availability());
if (method === 'GET' && route === '/api/engines/deepseek/availability') return json(response, runtime.engineManager().availability(url.searchParams.has('root') ? url.searchParams.get('root') : undefined));
if (method === 'GET' && route === '/api/engines/deepseek/controlled-availability') return json(response, runtime.engineRunner().availability(url.searchParams.has('root') ? url.searchParams.get('root') : undefined));
if (method === 'GET' && route === '/api/events') {
const cursor = Math.max(cursorNumber(url.searchParams.get('after')), cursorNumber(request.headers['last-event-id']));
if (cursor > store.eventCursor) throw Object.assign(new Error('事件游标超出当前历史,请重新加载工作台。'), { status: 409 });
@@ -277,6 +279,21 @@ return async (request, response) => {
}
if (method === 'GET' && !action) return json(response, store.publicSession(session));
if (method === 'GET' && action === 'execution') return json(response, store.executionSnapshot(session));
if (method === 'GET' && action === 'engine-runs') return json(response, [...store.core.engine_run.values()].filter(job => job.sessionId === id).slice(-30).map(publicEngineRun));
const engineRun = action.match(/^engine-runs\/([a-f0-9-]+)\/(input|report|download)$/);
if (method === 'GET' && engineRun) {
const job = store.owned('engine_run', engineRun[1], id);
const text = engineRun[2] === 'input' ? store.artifactStore.read(verifyEngineInput(store, session, job)) : originalEngineRun(store, session, job);
if (engineRun[2] !== 'download') {
const artifact = store.owned('artifact', engineRun[2] === 'input' ? job.inputArtifactId : job.reportArtifactId, id);
const offset = cursorNumber(url.searchParams.get('offset')), limit = Math.min(16000, url.searchParams.has('limit') ? cursorNumber(url.searchParams.get('limit')) : 4000);
if (!limit || offset > text.length) throw Object.assign(new Error('原引擎记录的读取位置或页长超出范围。'), { status: 400 });
return json(response, { ...artifact, content: text.slice(offset, offset + limit), offset, totalCharacters: text.length, truncated: offset + limit < text.length });
}
response.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff', ...(engineRun[2] === 'download' ? { 'Content-Disposition': 'attachment; filename="agent-workbench-engine-run-' + job.id + '.json"' } : {}) });
response.end(text); return;
}
if (method === 'GET' && action === 'mcp/jobs') return json(response, runtime.mcpRegistry().jobs(session));
if (method === 'POST' && action === 'mcp/probe') {
const started = runtime.mcpRegistry().start(session, await body(request));
+2 -2
View File
@@ -177,13 +177,13 @@ export class Provider {
const response = await this.request(config, '/models', undefined, undefined, key);
return (response.data ?? response.models ?? []).map(item => String(item.id ?? item.name)).filter(Boolean).slice(0, 100);
}
async complete(config, messages, project, signal, onProgress, requestPlan = null, tools = toolDefinitions) {
async complete(config, messages, project, signal, onProgress, requestPlan = null, tools = toolDefinitions, requestPolicy = {}) {
const body = completionBody(config, messages, tools);
assertPlannedRequest(body, requestPlan);
if (config.mode === 'demo') return this.demo(messages, project);
this.validate(config);
const execute = async (selected, key, input, progress) => {
const value = await this.request(selected, '/chat/completions', input, signal, key, progress, config.modelRouting ? { attempts: 1 } : {});
const value = await this.request(selected, '/chat/completions', input, signal, key, progress, { ...(config.modelRouting ? { attempts: 1 } : {}), ...requestPolicy });
if (!value.choices?.[0]?.message || value.choices[0].finish_reason === 'length') throw new ModelRequestError({ kind: 'protocol', source: 'model_connection',
stage: 'model_request', title: '模型响应不完整', message: '模型响应缺少完整message或达到输出上限,未执行工具。', retryable: false, occurredAt: new Date().toISOString() });
return value;
+22 -6
View File
@@ -22,6 +22,7 @@ import { WorkspaceManager, verifyWorkspaceProject } from '../core/workspaces/git
import { assertWorkspacesResolved, projectWorkspaceIdentity } from '../shared/contracts/workspaces.mjs';
import { ResearchManager } from '../core/research-manager.mjs';
import { EngineManager } from '../core/engine-manager.mjs';
import { EngineRunner } from '../core/engines/engine-runner.mjs';
import { BrowserManager, publicBrowserPlan } from '../core/browser/browser-manager.mjs';
import { browserPlanInput } from '../shared/contracts/browser.mjs';
import { TaskPlanManager } from '../core/tasks/task-plan-manager.mjs';
@@ -118,6 +119,7 @@ export class Runtime {
redact: value => this.provider.redact(value), projectBusy: projectId => this.projectHasActivity(projectId) });
}
requestPlanner() { return this.contextPlans ??= new RequestPlanner(this.store); }
engineRunner() { return this.controlledEngines ??= new EngineRunner(this.store, this.provider, { appDirectory: this.appDirectory }); }
memoryManager() { return this.projectMemories ??= new ProjectMemoryManager(this.store); }
checkpointManager() { return this.taskCheckpoints ??= new TaskCheckpointManager(this.store, {
taskPlans: this.taskPlanner(), redact: value => this.provider.redact(value) }); }
@@ -267,29 +269,38 @@ export class Runtime {
' tokens;省略 ' + planned.record.archivedGroups + ' 个完整消息组,原历史和参数已保存为SHA256工件。估算与服务实际用量分别记录。' });
}
let requestEvent;
let response, requestStarted = false, responseAccounted = false;
const externalEngine = !!run.worker?.engine;
if (externalEngine) { planned.record.engineStepOnly = true; planned.record.engine = 'deepseek-workbench'; }
let response, requestStarted = false, responseAccounted = externalEngine;
try {
signal.throwIfAborted(); checkBudget(run.record, task);
if (run.worker) { planned.record.workerDispatchedAt = now(); this.store.save(session, { type: 'worker.request_intent' }); }
if (run.worker && !externalEngine) { planned.record.workerDispatchedAt = now(); this.store.save(session, { type: 'worker.request_intent' }); }
requestStarted = true;
response = await this.provider.complete(config, planned.messages, run.project, signal, progress => {
if (!requestEvent) requestEvent = this.store.event(session, { kind: 'model', runId: run.id, source: 'model_connection', label: '请求模型服务', phase: 'running', startedAt: now(), contextPlanId: planned.record.id });
const progressHandler = progress => {
if (!requestEvent) requestEvent = this.store.event(session, { kind: externalEngine ? 'engine' : 'model', runId: run.id,
source: externalEngine ? 'controlled_engine' : 'model_connection', label: externalEngine ? '受控引擎执行' : '请求模型服务', phase: 'running', startedAt: now(), contextPlanId: planned.record.id });
if (progress.engineRunId) requestEvent.engineRunId = progress.engineRunId;
planned.record.status = progress.phase === 'running' || progress.phase === 'retrying' ? 'requesting' : planned.record.status;
planned.record.requestAttempts = Math.max(planned.record.requestAttempts, progress.attempt ?? 0);
stepRecord.modelAttempts = Math.max(stepRecord.modelAttempts, progress.attempt ?? 0);
requestEvent.phase = progress.phase; requestEvent.attempts = progress.attempt;
if (progress.connectionId) { requestEvent.connectionId = progress.connectionId; requestEvent.modelAttemptId = progress.modelAttemptId; requestEvent.actualModel = progress.model; }
requestEvent.label = progress.switching ? '正在切换模型池连接' : progress.phase === 'retrying' ? '正在重试模型连接' : progress.phase === 'completed' ? '模型响应已收到' : progress.phase === 'failed' ? '模型连接失败' : '请求模型服务';
if (externalEngine) requestEvent.label = progress.phase === 'completed' ? '引擎原结果已收到' : '受控引擎执行';
requestEvent.output = progress.phase === 'retrying' ? '第 ' + progress.attempt + ' 次请求失败,将自动重试(最多 ' + progress.maxAttempts + ' 次)。'
: progress.phase === 'completed' ? '模型响应已收到;工具请求将在校验后执行。'
: progress.diagnostic?.message ?? '正在等待模型响应。';
if (externalEngine) requestEvent.output = progress.phase === 'completed' ? '原引擎工具请求或最终输出已返回,后续按所属任务核验。' : '等待所属引擎;实际模型尝试另有记录。';
if (progress.diagnostic) requestEvent.diagnostic = progress.diagnostic;
if (progress.durationMs !== undefined) requestEvent.durationMs = progress.durationMs;
if (['completed', 'failed'].includes(progress.phase)) requestEvent.finishedAt = now();
this.store.save(session);
}, planned.record, tools);
};
response = externalEngine
? await this.engineRunner().complete(session, run, planned.messages, progressHandler, planned.record, tools)
: await this.provider.complete(config, planned.messages, run.project, signal, progressHandler, planned.record, tools);
this.requestPlanner().finish(session, planned.record, { response, attempts: planned.record.requestAttempts });
if (run.worker) {
if (run.worker && !externalEngine) {
this.store.recordResponse(session, run.record, response.usage, planned.record.estimatedInputTokens + Math.ceil(Buffer.byteLength(JSON.stringify(response.message), 'utf8') / 3) + 8);
planned.record.workerUsageAccounted = true; this.store.save(session); responseAccounted = true;
}
@@ -323,6 +334,7 @@ export class Runtime {
if (!calls.length) {
this.store.finishStep(session, stepRecord);
session.status = session.changes.some(change => ['pending', 'conflict'].includes(change.status)) ? 'needs_review' : 'completed';
if (externalEngine) await this.engineRunner().finish(session, run);
if (session.status === 'completed' && run.worker) {
try { await this.workerManager().output(session, run.worker); signal.throwIfAborted(); }
catch (error) {
@@ -407,6 +419,8 @@ export class Runtime {
output: diagnostic.message, diagnostic: session.lastFailure });
}
this.store.save(session);
} finally {
if (run.worker?.engine) await this.engineRunner().finish(session, run);
}
}
async executeTool(session, call, run) {
@@ -419,6 +433,7 @@ export class Runtime {
const args = JSON.parse(call.function.arguments);
validateToolArgs(tool, args);
assertWorkerTool(this.store, session, tool, args);
if (run.worker?.engine) this.engineRunner().assertCurrent(session, run);
event.input = JSON.parse(this.provider.redact(JSON.stringify(args)));
const proofHint = !!this.store.core.task.get(run.taskId)?.currentTaskPlanId && PLAN_READ_TOOLS.includes(tool);
const readMetadata = { ...(proofHint ? { tool_invocation_id: event.invocationId } : {}),
@@ -580,6 +595,7 @@ export class Runtime {
const cwd = safePath(run.project);
event.phase = 'running'; event.executedAt = now(); session.status = 'running';
this.store.invocationState(session, event, 'running');
if (run.worker?.engine) this.engineRunner().assertCurrent(session, run);
if (execute) return execute();
return this.executeCommand(command, cwd, run.controller.signal, output => {
event.output = output; this.store.save(session);
+26 -2
View File
@@ -10,6 +10,7 @@ import { ACTIVE_STATES, CORE_KINDS, createTask, createRun, ownedRecord, emptyUsa
import { WORKSPACE_ACTIVE, projectWorkspaceIdentity, assertWorkspacePath } from '../shared/contracts/workspaces.mjs';
import { RESEARCH_ACTIVE } from '../shared/contracts/research.mjs';
import { ENGINE_ACTIVE, publicEngineJob } from '../shared/contracts/engines.mjs';
import { ENGINE_RUN_ACTIVE, publicEngineRun, verifyEngineModelInput } from '../shared/contracts/engine-execution.mjs';
import { BROWSER_ACTIVE } from '../shared/contracts/browser.mjs';
import { publicBrowserPlan } from '../core/browser/browser-manager.mjs';
import { MCP_ACTIVE } from '../core/tools/mcp-contract.mjs';
@@ -192,7 +193,7 @@ export class Store extends EventEmitter {
step.status = 'interrupted'; step.finishedAt = now(); changed = true;
}
for (const plan of this.core.context_plan.values()) if (plan.sessionId === session.id) {
if (plan.workerDispatchedAt && !plan.workerUsageAccounted) {
if (plan.workerDispatchedAt && !plan.workerUsageAccounted && !plan.engineStepOnly) {
const run = this.core.run.get(plan.runId);
if (run && this.core.task.get(run.taskId)?.workerId) {
this.recordResponse(session, run, null, plan.estimatedInputTokens + (run.model.maxOutputTokens ?? 2048));
@@ -252,6 +253,28 @@ export class Store extends EventEmitter {
worker.summary = '子执行在宿主中断时没有完整收尾;原进程结束及实际修改待核对,不按历史PID停止进程或重放工具。';
session.status = 'paused'; session.recoveryNotice = worker.summary; changed = true;
}
for (const job of this.core.engine_run.values()) if (job.sessionId === session.id && ENGINE_RUN_ACTIVE.has(job.status)) {
for (const request of job.requests) if (request.dispatchedAt && !request.finishedAt) {
const run = this.core.run.get(job.runId);
try {
verifyEngineModelInput(this, session, job, request);
const count = request.actualAttemptsFinal ?? request.maxAttempts;
if (run) while (request.accountedAttempts < count) {
request.accountedAttempts++; this.recordResponse(session, run, null, request.reservedPerAttempt);
request.recoveredUnknownAttempts = (request.recoveredUnknownAttempts ?? 0) + 1;
}
} catch (error) {
request.verificationError = error.message;
if (run) this.recordResponse(session, run, null, Math.max(0, this.core.task.get(job.taskId).budget.maxTokens - accountedTokens(this.core.task.get(job.taskId).usage)));
request.recoveryConservativeCharge = true;
}
request.status = 'interrupted'; request.finishedAt = now();
request.error = '宿主中断,原模型结果未完整封存;按原尝试预算核对,不自动请求。';
}
job.status = 'unknown'; job.requiresVerification = true; job.verified = false; job.finishedAt = now();
job.error = '受控引擎宿主中断,原工具/模型结果及进程树待核对。原输入保留,不按历史PID终止或重放。';
session.status = 'paused'; session.recoveryNotice = job.error; changed = true;
}
for (const job of this.core.engine_job.values()) if (job.sessionId === session.id && ENGINE_ACTIVE.has(job.status)) {
job.status = 'unknown'; job.requiresVerification = true; job.verification = null; job.finishedAt = now();
job.summary = '外部引擎连接检查中断,原进程关闭状态未知。不会根据历史PID停止进程或重放请求,请查看所属原记录。';
@@ -307,7 +330,7 @@ export class Store extends EventEmitter {
for (const group of this.core.collaboration.values()) {
const unresolved = group.children.some(child => this.core.worker.get(child.id)?.requiresVerification
|| this.core.workspace.get(child.workspaceId)?.requiresVerification
|| ['tool', 'check_job', 'change_set'].some(kind => [...this.core[kind].values()].some(record => record.taskId === child.taskId && record.requiresVerification)))
|| ['tool', 'check_job', 'change_set', 'engine_run'].some(kind => [...this.core[kind].values()].some(record => record.taskId === child.taskId && record.requiresVerification)))
|| [...this.core.change_set.values()].some(set => set.taskId === group.taskId && set.requiresVerification);
if (!COLLABORATION_CLOSED.has(group.status) && unresolved && (!group.requiresVerification || group.status !== 'unknown')) {
group.status = 'unknown'; group.requiresVerification = true; group.finishedAt = now();
@@ -584,6 +607,7 @@ export class Store extends EventEmitter {
researchTargets: [...this.core.research_target.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-32),
researchJobs: [...this.core.research_job.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-20),
engineJobs: [...this.core.engine_job.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-20).map(publicEngineJob),
engineRuns: [...this.core.engine_run.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-20).map(publicEngineRun),
browserPlans: [...this.core.browser_plan.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-5).map(publicBrowserPlan),
browserJobs: [...this.core.browser_job.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-12),
contextPlans: [...this.core.context_plan.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-30),
+113
View File
@@ -0,0 +1,113 @@
import { engineError, engineCanonicalDigest as controlledDigest } from './engines.mjs';
import { requestMetrics } from './model-request.mjs';
export const ENGINE_RUN_ACTIVE = new Set(['queued', 'starting', 'initializing', 'running', 'waiting_tool', 'closing', 'stopping']);
export function selectedEngineInput(input) {
if (!input || typeof input !== 'object' || Array.isArray(input)
|| Object.keys(input).some(key => !['id', 'root', 'controlledSha256'].includes(key))
|| input.id !== 'deepseek-harness' || typeof input.root !== 'string'
|| !/^[a-f0-9]{64}$/.test(input.controlledSha256 ?? '')) throw engineError('请选择已经检测并封存身份的受控DeepSeek引擎。', 400);
return structuredClone(input);
}
export function engineRunInput(job) {
return { schemaVersion: 1, id: job.id, sessionId: job.sessionId, projectId: job.projectId, taskId: job.taskId, runId: job.runId,
workerId: job.workerId, collaborationId: job.collaborationId, installation: job.installation, sdkSessionId: job.sdkSessionId,
directory: job.directory, model: job.model, budget: job.budget, tools: job.tools,
sourceContextPlanId: job.sourceContextPlanId, sourceRequestSha256: job.sourceRequestSha256 };
}
export function engineRunReport(job) {
return { schemaVersion: 1, owner: { sessionId: job.sessionId, projectId: job.projectId, taskId: job.taskId, runId: job.runId, jobId: job.id },
inputSha256: job.inputSha256, installationSha256: job.installation.controlledSha256, sdkSessionId: job.sdkSessionId,
outcome: job.originalOutcome, native: job.native, requests: job.requests, calls: job.calls };
}
export function publicEngineRun(job) {
const { native, requests, calls, ...view } = job;
return { ...view, nativeSummary: { status: native?.status ?? null, pid: native?.process?.pid ?? job.pid ?? null,
rootExited: native?.cleanup?.rootExited ?? null, treeConfirmed: native?.cleanup?.treeConfirmed ?? null,
receipt: native?.receipt ?? null, notifications: native?.notifications?.length ?? job.notificationCount ?? 0 },
modelRequests: requests?.length ?? 0, toolRequests: calls?.length ?? 0 };
}
export function verifyEngineInput(store, session, job) {
store.owned('engine_run', job.id, session.id);
const input = store.owned('artifact', job.inputArtifactId, session.id);
if (input.kind !== 'engine-run-input' || input.taskId !== job.taskId || input.runId !== job.runId || input.sha256 !== job.inputSha256
|| store.artifactStore.read(input) !== JSON.stringify(engineRunInput(job))) throw engineError('受控引擎与原任务/范围/程序输入不一致。');
return input;
}
export function originalEngineRun(store, session, job) {
verifyEngineInput(store, session, job);
const artifact = store.owned('artifact', job.reportArtifactId, session.id);
if (artifact.kind !== 'engine-run-report' || artifact.taskId !== job.taskId || artifact.runId !== job.runId || artifact.sha256 !== job.reportSha256) {
throw engineError('受控引擎原报告身份无效。');
}
const bytes = store.artifactStore.read(artifact);
if (bytes !== JSON.stringify(engineRunReport(job))) throw engineError('受控引擎原报告与当前账本不一致。');
return bytes;
}
export function verifyEngineModelInput(store, session, job, request) {
const artifact = store.owned('artifact', request.inputArtifactId, session.id);
if (artifact.kind !== 'engine-model-input' || artifact.taskId !== job.taskId || artifact.runId !== job.runId || artifact.sha256 !== request.inputSha256) throw engineError('原引擎模型输入工件归属无效。');
const input = JSON.parse(store.artifactStore.read(artifact)), metrics = requestMetrics(input.body);
for (const key of ['id', 'bridgeTraceId', 'sourceSha256', 'requestSha256', 'requestBytes', 'estimatedInputTokens', 'reservedPerAttempt', 'maxAttempts']) {
if (input.plan[key] !== request[key]) throw engineError('原引擎模型请求或尝试预算与封存输入不一致。');
}
if (input.owner.sessionId !== job.sessionId || input.owner.taskId !== job.taskId || input.owner.runId !== job.runId || input.owner.projectId !== job.projectId
|| controlledDigest(input.native) !== request.sourceSha256 || metrics.sha256 !== request.requestSha256 || metrics.bytes !== request.requestBytes
|| !Number.isSafeInteger(request.maxAttempts) || request.maxAttempts < 1 || request.maxAttempts > 8
|| request.reservedPerAttempt !== metrics.estimatedInputTokens + 128 + input.body.max_tokens) throw engineError('原引擎模型输入、归属或预算核对失败。');
return input;
}
export function assertEngineWorkerResult(store, session, worker) {
if (!worker.engine) return;
const job = [...store.core.engine_run.values()].findLast(value => value.sessionId === session.id && value.runId === worker.currentRunId);
if (!job || job.status !== 'completed' || job.requiresVerification || !job.verified
|| job.installation.controlledSha256 !== worker.engine.controlledSha256) throw engineError('原引擎运行缺少完整协议、停止和账本依据。');
originalEngineRun(store, session, job);
if (job.calls.some(call => call.status !== 'returned' || !call.invocationId)
|| job.requests.some(request => request.status !== 'completed')) throw engineError('引擎原调用或模型请求尚未完整核对。');
for (const call of job.calls) {
const tool = store.owned('tool', call.invocationId, session.id), result = store.savedToolResult(session.id, call.callId);
if (tool.runId !== job.runId || tool.callId !== call.callId || tool.requiresVerification || controlledDigest(result) !== call.resultSha256) {
throw engineError('引擎原工具结果与自有执行账本不一致。');
}
const artifact = store.owned('artifact', call.outputArtifactId, session.id);
if (artifact.kind !== 'engine-tool-output' || artifact.taskId !== job.taskId || artifact.runId !== job.runId || artifact.sha256 !== call.outputSha256
|| store.artifactStore.read(artifact) !== JSON.stringify(result)) throw engineError('反馈给原引擎的工具结果工件不一致。');
}
for (const request of job.requests) {
verifyEngineModelInput(store, session, job, request);
const artifact = store.owned('artifact', request.responseArtifactId, session.id);
if (artifact.kind !== 'engine-model-output' || artifact.taskId !== job.taskId || artifact.runId !== job.runId || artifact.sha256 !== request.responseSha256
|| !JSON.parse(store.artifactStore.read(artifact)).message || request.accountedAttempts !== request.actualAttemptsFinal) throw engineError('原引擎模型输出或尝试账本未完整核对。');
}
}
export function nativeMessagesToChat(input) {
if (!input || !Array.isArray(input.messages)) throw engineError('原引擎模型输入没有消息数组。');
const messages = input.messages.map(message => {
if (!message || !['system', 'developer', 'user', 'assistant', 'tool'].includes(message.role) || !Array.isArray(message.content)) {
throw engineError('原引擎消息不符合已验证的文本协议。');
}
const text = [], calls = [];
for (const block of message.content) {
if (block?.type === 'text' && typeof block.text === 'string') text.push(block.text);
else if (block?.type === 'reasoning' && typeof block.text === 'string') {
// Reasoning is not promoted into user-visible text or a tool request.
} else if (block?.type === 'tool-call' && message.role === 'assistant' && typeof block.id === 'string'
&& typeof block.name === 'string' && typeof block.arguments === 'string') {
JSON.parse(block.arguments); calls.push({ id: block.id, type: 'function', function: { name: block.name, arguments: block.arguments } });
} else throw engineError('当前受控桥只接入文本和完整工具调用,原内容类型尚未验证。');
}
if (message.role === 'tool') {
if (typeof message.toolCallId !== 'string' || !message.toolCallId) throw engineError('原工具消息缺少toolCallId。');
return { role: 'tool', tool_call_id: message.toolCallId, content: text.join('') };
}
return { role: message.role, content: text.join(''), ...(calls.length ? { tool_calls: calls } : {}) };
});
if (input.system !== null && input.system !== undefined) {
if (typeof input.system !== 'string') throw engineError('原单次系统提示格式无效。');
messages.unshift({ role: 'system', content: input.system });
}
return messages;
}
+3
View File
@@ -10,6 +10,9 @@ export const ENGINE_LIMITS = Object.freeze([
]);
export const engineError = (message, status = 409, code = 'ENGINE_CONTRACT') => Object.assign(new Error(message), { status, code });
export const engineDigest = value => createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(value), 'utf8').digest('hex');
const canonical = value => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object'
? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value;
export const engineCanonicalDigest = value => engineDigest(canonical(value));
export function engineInput(job) {
return { schemaVersion: 1, jobId: job.id, sessionId: job.sessionId, projectId: job.projectId,
+1 -1
View File
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
export const EXECUTION_SCHEMA = 1;
export const ACTIVE_STATES = new Set(['running', 'awaiting_approval', 'stopping']);
export const CORE_KINDS = ['task', 'run', 'step', 'tool', 'artifact', 'check_plan', 'check_job', 'delivery_plan', 'delivery_job', 'change_set', 'context_plan', 'workspace', 'research_target', 'research_job', 'engine_job', 'browser_plan', 'browser_job', 'task_plan', 'task_proof', 'memory', 'task_checkpoint', 'mcp_job', 'collaboration', 'worker'];
export const CORE_KINDS = ['task', 'run', 'step', 'tool', 'artifact', 'check_plan', 'check_job', 'delivery_plan', 'delivery_job', 'change_set', 'context_plan', 'workspace', 'research_target', 'research_job', 'engine_job', 'engine_run', 'browser_plan', 'browser_job', 'task_plan', 'task_proof', 'memory', 'task_checkpoint', 'mcp_job', 'collaboration', 'worker'];
export const timestamp = () => new Date().toISOString();
export const isId = value => typeof value === 'string' && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value);
+10 -6
View File
@@ -1,5 +1,6 @@
import { createHash } from 'node:crypto';
import { isId, accountedTokens, emptyUsage } from './execution.mjs';
import { selectedEngineInput } from './engine-execution.mjs';
export const WORKER_TOOLS = new Set(['inspect_session', 'inspect_project', 'index_project', 'query_code', 'read_artifact',
'list_files', 'read_file', 'search_files', 'propose_file', 'propose_patch', 'prepare_change_set', 'plan_checks', 'run_checks']);
@@ -29,8 +30,9 @@ const text = (value, maximum, label) => {
};
export function collaborationInput(input, config) {
if (!input || Array.isArray(input) || Object.keys(input).some(key => !['goal', 'budget', 'children'].includes(key))) throw workerConflict('协作只接受父目标、预算和两个子任务。');
if (!Array.isArray(input.children) || input.children.length !== 2) throw workerConflict('本阶段需要两个受限子任务。');
if (!input || Array.isArray(input) || Object.keys(input).some(key => !['goal', 'budget', 'children', 'engine'].includes(key))) throw workerConflict('协作只接受父目标、预算、子任务和已检测的引擎。');
const engine = input.engine === undefined ? null : selectedEngineInput(input.engine);
if (!Array.isArray(input.children) || input.children.length !== (engine ? 1 : 2)) throw workerConflict(engine ? '受控引擎计划需要一个所属子工程。' : '本阶段需要两个受限子任务。');
const raw = input.budget ?? {};
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || Object.keys(raw).some(key => !['maxTokens', 'maxSteps', 'maxToolCalls', 'maxDurationMs'].includes(key))) throw workerConflict('协作预算字段无效。');
const tokenMaximum = Math.min(config.maxTaskTokens ?? 1000000, config.maxRunTokens ?? 200000);
@@ -47,12 +49,12 @@ export function collaborationInput(input, config) {
if (new Set(paths.map(workerPathKey)).size !== paths.length) throw workerConflict('子任务范围不能重复。');
const part = item.budget ?? {};
if (!part || Array.isArray(part) || Object.keys(part).some(key => !['maxTokens', 'maxSteps', 'maxToolCalls'].includes(key))) throw workerConflict('子预算字段无效。');
const allocate = key => index === 0 ? Math.floor(budget[key] / 2) : budget[key] - Math.floor(budget[key] / 2);
const allocate = key => engine ? budget[key] : index === 0 ? Math.floor(budget[key] / 2) : budget[key] - Math.floor(budget[key] / 2);
return { label: text(item.label, 64, '子任务名称'), goal: text(item.goal, 8000, '子目标'), paths,
budget: Object.fromEntries(['maxTokens', 'maxSteps', 'maxToolCalls'].map(key => [key, bounded(part[key], allocate(key), key === 'maxTokens' ? 500 : 1, budget[key], key)])) };
});
for (const key of ['maxTokens', 'maxSteps', 'maxToolCalls']) if (children.reduce((sum, child) => sum + child.budget[key], 0) > budget[key]) throw workerConflict('子任务预算之和不能超过父预算:' + key);
return { goal: text(input.goal, 20000, '父目标'), budget, children };
return { goal: text(input.goal, 20000, '父目标'), budget, children, ...(engine ? { engine } : {}) };
}
export function collaborationSeal(group) {
@@ -64,7 +66,8 @@ export function workerSeal(worker) {
parentSessionId: worker.parentSessionId, parentTaskId: worker.parentTaskId, parentRunId: worker.parentRunId,
projectId: worker.projectId, sessionId: worker.sessionId, taskId: worker.taskId, workspaceId: worker.workspaceId,
label: worker.label, goal: worker.goal, paths: worker.paths, budget: worker.budget, model: worker.model, baseCommit: worker.baseCommit,
baselineArtifactId: worker.baselineArtifactId, baselineSha256: worker.baselineSha256, baselineRunId: worker.baselineRunId };
baselineArtifactId: worker.baselineArtifactId, baselineSha256: worker.baselineSha256, baselineRunId: worker.baselineRunId,
...(worker.engine ? { engine: worker.engine } : {}) };
}
export function workerForProject(store, projectId) {
return [...(store.core.worker?.values() ?? [])].find(value => value.projectId === projectId) ?? null;
@@ -79,7 +82,8 @@ export function workerForSession(store, session) {
|| definition.taskId !== worker.taskId || definition.projectId !== worker.projectId || definition.sessionId !== worker.sessionId
|| definition.workspaceId !== worker.workspaceId || JSON.stringify(definition.paths) !== JSON.stringify(worker.paths)
|| JSON.stringify(definition.budget) !== JSON.stringify(worker.budget) || definition.goal !== worker.goal
|| JSON.stringify(group.model) !== JSON.stringify(worker.model)) throw workerConflict('子任务与父任务的封存分工不一致。');
|| JSON.stringify(group.model) !== JSON.stringify(worker.model)
|| JSON.stringify(definition.engine) !== JSON.stringify(worker.engine)) throw workerConflict('子任务与父任务的封存分工不一致。');
const task = store.core.task.get(worker.taskId);
if (!task || task.goal !== worker.goal || task.workerId !== worker.id || task.budget.maxTokens !== worker.budget.maxTokens) throw workerConflict('子任务目标、身份或累计预算已变化。');
const original = store.owned('artifact', worker.contractArtifactId, session.id);