feat: seal isolated worker recovery, parent integration and review console

This commit is contained in:
Agent Workbench Dev
2026-10-31 02:02:06 +08:00
parent 3abc0e8595
commit 2ada7b899f
34 changed files with 2877 additions and 64 deletions
+38 -2
View File
@@ -10,6 +10,7 @@ import { publicEngineJob } from '../shared/contracts/engines.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';
import { workerForProject, workerConflict, assertWorkersResolved } from '../shared/contracts/workers.mjs';
export function createSessionPublisher(clients) {
return session => {
@@ -85,6 +86,7 @@ return async (request, response) => {
if (method === 'GET' && !action) return json(response, registry.view(projectId));
if (method === 'GET' && action === 'content') return json(response, registry.content(projectId, url.searchParams.get('id'), Number(url.searchParams.get('revision'))));
if (method === 'POST') {
if (workerForProject(store, projectId)) throw workerConflict('受限子项目不能修改Skills登记,请返回父项目。');
const input = await body(request);
if (!action) return json(response, registry.register(projectId, input), 201);
if (action === 'toggle') return json(response, registry.toggle(projectId, input));
@@ -95,7 +97,7 @@ return async (request, response) => {
if (mcpMatch) {
const registry = runtime.mcpRegistry(), projectId = mcpMatch[1];
if (method === 'GET' && !mcpMatch[2]) return json(response, registry.view(projectId));
if (method === 'POST') { const input = await body(request);
if (method === 'POST') { if (workerForProject(store, projectId)) throw workerConflict('受限子项目不能修改MCP登记,请返回父项目。'); const input = await body(request);
return json(response, mcpMatch[2] ? registry.configure(projectId, input) : registry.register(projectId, input), mcpMatch[2] ? 200 : 201); }
}
const projectMemoryMatch = route.match(/^\/api\/projects\/([a-f0-9-]+)\/memories$/i);
@@ -112,11 +114,13 @@ return async (request, response) => {
const sessionMemoryArchiveMatch = route.match(/^\/api\/sessions\/([a-f0-9-]+)\/memories\/([a-f0-9-]+)\/archive$/i);
if (sessionMemoryArchiveMatch && method === 'POST') {
const session = store.session(sessionMemoryArchiveMatch[1]);
if (workerForProject(store, session.projectId)) throw workerConflict('受限子任务不能修改项目记忆,请返回父项目。');
await body(request);
return json(response, memories.archive(session, sessionMemoryArchiveMatch[2]));
}
if (sessionMemoryMatch && method === 'POST') {
const session = store.session(sessionMemoryMatch[1]);
if (workerForProject(store, session.projectId)) throw workerConflict('受限子任务不能修改项目记忆,请返回父项目。');
const input = await body(request);
return json(response, await memories.create(session, input), 201);
}
@@ -232,6 +236,7 @@ return async (request, response) => {
if (method === 'GET' && route === '/api/sessions') return json(response, store.listSessions());
if (method === 'POST' && route === '/api/sessions') {
const input = await body(request);
if (workerForProject(store, input.projectId)) throw workerConflict('隔离项目使用原受限子会话,请从父协作打开。');
await verifyWorkspaceProject(store, store.project(input.projectId));
return json(response, store.publicSession(store.createSession(input.projectId)), 201);
}
@@ -239,6 +244,37 @@ return async (request, response) => {
if (sessionMatch) {
const id = sessionMatch[1], action = sessionMatch[2] ?? '';
const session = store.session(id);
if (method === 'POST' && workerForProject(store, session.projectId)
&& /^(?:mcp|engines|research|workspaces|delivery|browser|task-plans|task-proofs|task-checkpoints|collaborations)(?:\/|-|$)/.test(action)) throw workerConflict('受限子任务只开放原目标的读取、范围内改动和已审批检查;此操作请返回父项目。');
if (method === 'GET' && action === 'collaborations') return json(response, runtime.workerManager().view(session));
if (method === 'POST' && action === 'collaborations') {
const group = await runtime.workerManager().plan(session, await body(request));
return json(response, { group, session: store.publicSession(session) }, 201);
}
const collaboration = action.match(/^collaborations\/([a-f0-9-]+)\/(prepare|start|stop|collect|merge|finalize|discard|reconcile|acknowledge|collection|evidence)$/);
if (collaboration) {
const manager = runtime.workerManager();
if (method === 'GET' && ['collection', 'evidence'].includes(collaboration[2])) {
const group = manager.own(session, collaboration[1], null, { current: false });
return json(response, collaboration[2] === 'collection' ? await manager.readCollection(session, group) : manager.readEvidence(session, group));
}
if (method === 'POST' && !['collection', 'evidence'].includes(collaboration[2])) {
const input = await body(request);
if (Object.keys(input).some(key => !['fingerprint', 'workerId', 'evidenceSha256', 'retain'].includes(key))) throw workerConflict('协作操作字段无效,不能添加命令或模型配置。');
const group = manager.own(session, collaboration[1], input.fingerprint);
let result;
if (collaboration[2] === 'prepare') result = manager.prepare(session, group.id, input.fingerprint);
else if (collaboration[2] === 'start') result = manager.start(session, group.id, input.fingerprint, input.workerId ?? null);
else if (collaboration[2] === 'stop') { await runtime.stop(session.id); result = group; }
else if (collaboration[2] === 'collect') result = manager.collect(session, group.id, input.fingerprint);
else if (collaboration[2] === 'merge') result = manager.prepareMerge(session, group.id, input.fingerprint);
else if (collaboration[2] === 'finalize') result = await manager.finalize(session, group.id, input.fingerprint);
else if (collaboration[2] === 'discard') result = manager.discard(session, group.id, input.fingerprint);
else if (collaboration[2] === 'reconcile') result = manager.reconcile(session, group.id, input.fingerprint);
else result = await manager.acknowledge(session, group.id, input.fingerprint, input.evidenceSha256, input.retain === true);
return json(response, { group: result.group ?? result, session: store.publicSession(session) }, result.promise ? 202 : 200);
}
}
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 === 'mcp/jobs') return json(response, runtime.mcpRegistry().jobs(session));
@@ -545,7 +581,7 @@ return async (request, response) => {
}
if (method === 'POST' && ['proposals', 'patch-proposals'].includes(action)) {
const input = await body(request);
if (runtime.checks?.projectActive(session.projectId) || runtime.deliveries?.projectActive(session.projectId) || runtime.changeSets?.projectActive(session.projectId) || runtime.workspaces?.projectActive(session.projectId)) throw Object.assign(new Error('工程检查、Git交付、文件批次或工作区正在执行,请等待结束后再编辑文件。'), { status: 409 });
if (runtime.workers?.projectActive(session.projectId) || runtime.checks?.projectActive(session.projectId) || runtime.deliveries?.projectActive(session.projectId) || runtime.changeSets?.projectActive(session.projectId) || runtime.workspaces?.projectActive(session.projectId)) throw Object.assign(new Error('协作、工程检查、Git交付、文件批次或工作区正在执行,请等待结束后再编辑文件。'), { status: 409 });
assertWorkspacesResolved(store, session.projectId, { includePrepared: true });
await verifyWorkspaceProject(store, store.project(session.projectId));
if (action === 'patch-proposals') proposePatch(store, session, input);
+2 -1
View File
@@ -127,7 +127,7 @@ export function searchFiles(project, args) {
scope: '有数量/体积上限的文本搜索;无结果不表示所有文件都已搜索。' };
}
export function proposeFile(store, session, args, { patch = null } = {}) {
export function proposeFile(store, session, args, { patch = null, sourceBinding = null } = {}) {
assertWorkersResolved(store, session.projectId);
assertWorkerWriteScope(store, session, args.path);
assertMcpResolved(store, session.projectId);
@@ -150,6 +150,7 @@ export function proposeFile(store, session, args, { patch = null } = {}) {
id: randomUUID(), path: args.path, reason: String(args.reason ?? '建议修改').slice(0, 600), status: 'pending',
baseExists: !!original, baseSha256: original?.sha256 ?? null, baseContent,
...(patch ? { editKind: 'exact-patch', patch } : {}),
...(sourceBinding ? { sourceBinding: structuredClone(sourceBinding) } : {}),
content, sha256: hash(Buffer.from(content, 'utf8')), diff: parts, createdAt: now(),
additions: parts.filter(part => part.added).reduce((sum, part) => sum + (part.count ?? 0), 0),
deletions: parts.filter(part => part.removed).reduce((sum, part) => sum + (part.count ?? 0), 0),
+5 -2
View File
@@ -139,7 +139,7 @@ export class Runtime {
|| !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.projectActive(projectId) || !!this.browser?.projectActive(projectId) || !!this.taskPlans?.projectActive(projectId) });
}
changeSetManager() {
return this.changeSets ??= new ChangeSetManager(this.store, { projectBusy: (projectId, exceptId) =>
return this.changeSets ??= new ChangeSetManager(this.store, { beforeApply: (session, set) => this.workerManager().verifyMerge(session, set), projectBusy: (projectId, exceptId) =>
!!this.workers?.projectActive(projectId) || [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId)
|| !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.projectActive(projectId) || !!this.browser?.projectActive(projectId) || !!this.taskPlans?.projectActive(projectId) });
}
@@ -270,6 +270,7 @@ export class Runtime {
let response, requestStarted = false, responseAccounted = false;
try {
signal.throwIfAborted(); checkBudget(run.record, task);
if (run.worker) { 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 });
@@ -290,17 +291,19 @@ export class Runtime {
this.requestPlanner().finish(session, planned.record, { response, attempts: planned.record.requestAttempts });
if (run.worker) {
this.store.recordResponse(session, run.record, response.usage, planned.record.estimatedInputTokens + Math.ceil(Buffer.byteLength(JSON.stringify(response.message), 'utf8') / 3) + 8);
responseAccounted = true; this.store.save(session);
planned.record.workerUsageAccounted = true; this.store.save(session); responseAccounted = true;
}
} catch (error) {
this.requestPlanner().finish(session, planned.record, { error: Object.assign(new Error(this.provider.redact(error.message ?? String(error))), { name: signal.aborted ? 'AbortError' : error.name }), attempts: planned.record.requestAttempts });
if (run.worker && requestStarted && !responseAccounted) {
this.store.recordResponse(session, run.record, null, planned.record.estimatedInputTokens + config.maxOutputTokens);
planned.record.workerUsageAccounted = true;
this.store.save(session, { type: 'worker.request_usage_unknown' });
}
throw error;
}
signal.throwIfAborted();
if (run.worker) checkBudget(run.record, task);
const message = response.message;
const calls = message.tool_calls ?? [];
if (run.worker && (calls.length > 16 || workerUsage(this.store, run.worker).toolCalls + calls.length > run.worker.budget.maxToolCalls)) throw new BudgetExceeded('worker_tool_limit', '子任务工具次数超出固定累计预算或单次16项上限;这批工具未执行,原响应和用量已保存。');
+28 -3
View File
@@ -13,7 +13,7 @@ import { ENGINE_ACTIVE, publicEngineJob } from '../shared/contracts/engines.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';
import { COLLABORATION_ACTIVE } from '../shared/contracts/workers.mjs';
import { COLLABORATION_ACTIVE, COLLABORATION_CLOSED } from '../shared/contracts/workers.mjs';
export const now = () => new Date().toISOString();
@@ -191,8 +191,17 @@ export class Store extends EventEmitter {
for (const step of this.core.step.values()) if (step.sessionId === session.id && ['running', 'waiting'].includes(step.status)) {
step.status = 'interrupted'; step.finishedAt = now(); changed = true;
}
for (const plan of this.core.context_plan.values()) if (plan.sessionId === session.id && ['prepared', 'requesting'].includes(plan.status)) {
plan.status = 'interrupted'; plan.finishedAt = now(); plan.error = '进程中断,未保存完整模型响应;不自动发送请求或重放工具。'; changed = true;
for (const plan of this.core.context_plan.values()) if (plan.sessionId === session.id) {
if (plan.workerDispatchedAt && !plan.workerUsageAccounted) {
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));
plan.workerUsageAccounted = true; plan.workerUsageRecovered = true; changed = true;
}
}
if (['prepared', 'requesting'].includes(plan.status)) {
plan.status = 'interrupted'; plan.finishedAt = now(); plan.error = '进程中断,未保存完整模型响应;不自动发送请求或重放工具。'; changed = true;
}
}
for (const job of this.core.check_job.values()) if (job.sessionId === session.id && ['queued', 'running', 'waiting'].includes(job.status)) {
job.requiresVerification = job.status !== 'queued'; job.status = job.requiresVerification ? 'unknown' : 'interrupted'; job.finishedAt = now();
@@ -295,6 +304,18 @@ export class Store extends EventEmitter {
}
if (changed) this.save(session, { type: 'session.recovered' });
}
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)))
|| [...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();
group.summary = '所属子执行或父批次仍有未知结果,原协作需要核对;不自动重放。';
const session = this.session(group.sessionId); session.status = 'paused'; session.recoveryNotice = group.summary;
this.save(session, { type: 'collaboration.recovered_children' });
}
}
}
save(session, { type = 'session.updated', detail = {} } = {}) {
@@ -507,6 +528,10 @@ export class Store extends EventEmitter {
savedToolResult(sessionId, callId) {
const record = [...this.core.tool.values()].find(value => value.sessionId === sessionId && value.callId === callId);
if (record?.state === 'resolved_external' && record.review?.result === 'unknown-preserved') return {
status: 'unknown', requires_verification: false, invocation_id: record.id, evidence_sha256: record.review.evidenceSha256,
message: '原结果保持未知,用户已核对原输入与现场;此调用不会重放,重新检查须使用新计划与审批。',
};
if (!record || !['completed', 'failed', 'denied', 'interrupted', 'unknown'].includes(record.state)) return null;
if (record.resultArtifactId) {
try { return JSON.parse(this.artifactStore.read(this.core.artifact.get(record.resultArtifactId))); }