Files
Agent-Workbench/src/server/runtime.mjs
T
2026-10-30 20:34:54 +08:00

610 lines
54 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { spawn, execFile } from 'node:child_process';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { StringDecoder } from 'node:string_decoder';
import { setImmediate as yieldExecution } from 'node:timers/promises';
import { safePath, listFiles, readLines, searchFiles, proposeFile, proposePatch } from './files.mjs';
import { projectContext, toolDefinitions, researchToolDefinitions, engineToolDefinitions, browserToolDefinitions } from './provider.mjs';
import { now, repairToolPairs } from './store.mjs';
import { executionEnvironment, sessionContext, sessionSnapshot } from './diagnostics.mjs';
import { BudgetExceeded, checkBudget } from '../shared/contracts/execution.mjs';
import { CheckRunner } from '../core/check-runner.mjs';
import { inspectProject } from '../core/project-inspector.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';
import { artifactPage, filePage, readMessageBudget, recordArtifactRead, recordBrowserRead, clearReadStreak, recordSessionInspection, readMetadataReserve, BROWSER_READ_HINT } from '../core/context/read-budget.mjs';
import { ChangeSetManager } from '../core/workspaces/change-sets.mjs';
import { assertChangeSetsResolved } from '../shared/contracts/change-sets.mjs';
import { pendingDeliveryReview } from '../shared/contracts/delivery-review.mjs';
import { WorkspaceManager, verifyWorkspaceProject } from '../core/workspaces/git-workspaces.mjs';
import { assertWorkspacesResolved, projectWorkspaceIdentity } from '../shared/contracts/workspaces.mjs';
import { ResearchManager } from '../core/research-manager.mjs';
import { EngineManager } from '../core/engine-manager.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';
import { taskPlanInput, taskProofInput, PLAN_READ_TOOLS } from '../shared/contracts/task-plans.mjs';
import { taskPlanToolDefinitions } from '../shared/contracts/task-plan-tools.mjs';
import { ProjectMemoryManager } from '../core/memory/project-memory.mjs';
import { TaskCheckpointManager } from '../core/tasks/task-checkpoint-manager.mjs';
import { SkillRegistry, skillToolDefinitions, skillReadInput } from '../core/skills/skill-registry.mjs';
import { McpRegistry } from '../core/tools/mcp-registry.mjs';
import { mcpToolDefinitions, mcpCallInput, assertMcpResolved } from '../core/tools/mcp-contract.mjs';
const labels = { inspect_session: '核对工作台运行记录', inspect_project: '识别工程与Git基线', index_project: '建立工程符号索引', query_code: '定位工程符号与导入', propose_patch: '准备精确补丁', plan_checks: '准备工程检查计划', run_checks: '执行工程检查', plan_delivery: '准备Git交付预览', delivery_report: '生成工程证据报告', read_artifact: '读取执行日志工件', list_files: '查看项目文件', read_file: '读取文件', search_files: '搜索项目', propose_file: '准备文件改动', run_command: '运行终端命令' };
labels.prepare_change_set = '准备多文件变更集';
labels.list_research_targets = '查看本任务登记工件';
labels.analyze_research_target = 'REA静态分析登记工件';
labels.read_research_evidence = '读取原REA Evidence字段';
labels.inspect_engine_checks = '查看本任务外部引擎核验';
labels.plan_browser = '准备页面检查计划';
labels.run_browser = '运行实际浏览器检查';
labels.read_browser_result = '读取原页面执行结果';
labels.plan_task = '保存任务依赖计划';
labels.verify_task_step = '核验任务步骤原证据';
labels.inspect_task_plan = '核对任务计划与未完成项';
labels.read_registered_skill = '读取已登记技能修订';
labels.call_registered_mcp = '请求调用已登记MCP工具';
export function validateToolArgs(tool, args) {
if (!Object.hasOwn(labels, tool)) throw new Error('当前能力表没有工具:' + tool);
if (!args || typeof args !== 'object' || Array.isArray(args)) throw new Error('工具参数必须是 JSON 对象。');
if (tool === 'read_registered_skill') { skillReadInput(args); return; }
if (tool === 'call_registered_mcp') { mcpCallInput(args); return; }
if (tool === 'plan_task') { taskPlanInput(args); return; }
if (tool === 'verify_task_step') { taskProofInput(args); return; }
if (tool === 'inspect_task_plan') { if (Object.keys(args).length) throw new Error('任务计划查询只读取当前Task,不接受执行命令。'); return; }
if (tool === 'plan_browser') { browserPlanInput(args); return; }
if (['run_browser', 'read_browser_result'].includes(tool)) {
const key = tool === 'run_browser' ? 'plan_id' : 'browser_job_id';
if (typeof args[key] !== 'string' || Object.keys(args).some(field => ![key, ...(tool === 'read_browser_result' ? ['section', 'offset', 'limit'] : [])].includes(field))) throw new Error('浏览器工具需要所属计划或结果ID,不能添加执行脚本。');
if (args.section !== undefined && !['page', 'steps', 'console', 'requests', 'overview'].includes(args.section)) throw new Error('浏览器原结果字段无效。');
for (const field of ['offset', 'limit']) if (args[field] !== undefined && (!Number.isSafeInteger(args[field]) || args[field] < (field === 'limit' ? 1 : 0) || field === 'limit' && args[field] > 16000)) throw new Error('浏览器结果分页范围无效。');
return;
}
if (tool === 'inspect_engine_checks') {
if (Object.keys(args).length) throw new Error('引擎核验查询只读取当前任务的已保存结果。');
return;
}
if (['list_research_targets', 'analyze_research_target', 'read_research_evidence'].includes(tool)) {
if (tool === 'analyze_research_target' && (typeof args.target_id !== 'string' || !['javascript', 'pe-imports', 'pe-resources'].includes(args.operation))) throw new Error('REA分析需要登记target_id和实际支持的静态分析方式。');
if (tool === 'read_research_evidence' && (typeof args.research_job_id !== 'string' || args.pointer !== undefined && typeof args.pointer !== 'string')) throw new Error('Evidence读取需要research_job_id及有效字段。');
if (args.refresh !== undefined || args.path !== undefined) throw new Error('模型只能使用已登记工件,重新分析由用户发起。');
for (const field of ['offset', 'limit']) if (args[field] !== undefined && (!Number.isInteger(args[field]) || args[field] < (field === 'limit' ? 1 : 0) || field === 'limit' && args[field] > 16000)) throw new Error('Evidence分页范围无效。');
if (args.pointer !== undefined && args.pointer.length > 400) throw new Error('Evidence字段超过400字符。');
return;
}
if (tool === 'prepare_change_set') {
if (!Array.isArray(args.change_ids) || !args.change_ids.length || args.change_ids.length > 32
|| args.change_ids.some(id => typeof id !== 'string' || !/^[a-f0-9-]{36}$/i.test(id))
|| new Set(args.change_ids).size !== args.change_ids.length) throw new Error('变更集需要1到32个不同的提案ID。');
return;
}
const required = ['inspect_session', 'inspect_project', 'index_project', 'plan_checks', 'plan_delivery', 'delivery_report'].includes(tool) ? [] : tool === 'read_artifact' ? ['artifact_id'] : tool === 'run_checks' ? ['plan_id'] : tool === 'list_files' || tool === 'read_file' ? ['path'] : ['search_files', 'query_code'].includes(tool) ? ['query']
: tool === 'propose_patch' ? ['path', 'base_sha256', 'reason'] : tool === 'propose_file' ? ['path', 'content', 'reason'] : ['command', 'reason'];
for (const field of required) if (typeof args[field] !== 'string') throw new Error('工具参数 ' + field + ' 必须是文本。');
for (const field of ['depth', 'start_line', 'end_line', 'offset', 'limit']) if (args[field] !== undefined && (!Number.isInteger(args[field]) || args[field] < 0)) throw new Error('工具参数 ' + field + ' 必须是非负整数。');
if (tool === 'read_file' && args.limit !== undefined && (args.limit < 1 || args.limit > 16000)) throw new Error('文件分页limit需要1到16000个字符。');
if (args.case_sensitive !== undefined && typeof args.case_sensitive !== 'boolean') throw new Error('case_sensitive 必须是布尔值。');
if (tool === 'plan_checks' && args.names !== undefined && (!Array.isArray(args.names) || args.names.some(name => typeof name !== 'string'))) throw new Error('检查脚本名称需要文本数组。');
if (tool === 'plan_delivery' && args.message !== undefined && typeof args.message !== 'string') throw new Error('提交说明需要文本。');
if (tool === 'query_code' && (args.kind !== undefined && !['all', 'symbols', 'imports', 'files'].includes(args.kind) || args.query.length > 200)) throw new Error('索引查询类型无效或查询超过200字。');
if (tool === 'propose_patch' && (!/^[a-f0-9]{64}$/i.test(args.base_sha256) || !Array.isArray(args.edits) || !args.edits.length || args.edits.length > 32)) throw new Error('精确补丁需要有效SHA256和1到32个替换。');
}
export class Runtime {
constructor(store, provider, { appDirectory } = {}) {
this.store = store; this.provider = provider;
this.appDirectory = appDirectory;
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; }
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) }); }
browserManager() { return this.browser ??= new BrowserManager(this.store, { appDirectory: this.appDirectory,
redact: value => this.provider.redact(value), projectBusy: (projectId, exceptId) => this.projectHasActivity(projectId, exceptId) }); }
engineManager() {
return this.engines ??= new EngineManager(this.store, { appDirectory: this.appDirectory,
redact: value => this.provider.redact(value), projectBusy: projectId => this.projectHasActivity(projectId) });
}
requestPlanner() { return this.contextPlans ??= new RequestPlanner(this.store); }
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) }); }
skillRegistry() { return this.skills ??= new SkillRegistry(this.store, {
redact: value => this.provider.redact(value), projectBusy: projectId => this.projectHasActivity(projectId) }); }
mcpRegistry() { return this.mcp ??= new McpRegistry(this.store, { taskPlans: this.taskPlanner(),
redact: value => this.provider.redact(value), projectBusy: (projectId, exceptId) => this.projectHasActivity(projectId, exceptId) }); }
researchManager() {
return this.research ??= new ResearchManager(this.store, { appDirectory: this.appDirectory,
redact: value => this.provider.redact(value), projectBusy: (projectId, exceptId) => this.projectHasActivity(projectId, exceptId) });
}
projectHasActivity(projectId, exceptSessionId = null) {
return [...this.active.entries()].some(([id, run]) => id !== exceptSessionId && run.project.id === projectId) || !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.projectActive(projectId) || !!this.browser?.projectActive(projectId) || !!this.taskPlans?.projectActive(projectId);
}
workspaceManager() {
return this.workspaces ??= new WorkspaceManager(this.store, { initialize: this.store.core.workspace.size === 0,
redact: value => this.provider.redact(value), projectBusy: projectId =>
[...this.active.values()].some(run => run.project.id === projectId) || !!this.checks?.projectActive(projectId)
|| !!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) =>
[...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) });
}
checkRunner() {
return this.checks ??= new CheckRunner(this.store, { redact: value => this.provider.redact(value), runtimeDirectory: this.appDirectory ? path.join(this.appDirectory, 'runtime') : null,
pythonRunnerPath: path.join(this.appDirectory ?? process.cwd(), 'scripts', 'python-check-runner.py'),
projectBusy: (projectId, exceptId) => [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.projectActive(projectId) || !!this.browser?.projectActive(projectId) || !!this.taskPlans?.projectActive(projectId) });
}
gitDelivery() {
return this.deliveries ??= new GitDelivery(this.store, { redact: value => this.provider.redact(value),
projectBusy: (projectId, exceptId) => [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.checks?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.projectActive(projectId) || !!this.browser?.projectActive(projectId) || !!this.taskPlans?.projectActive(projectId) });
}
start(id, content, resume = false, { instructionSource = null } = {}) {
const session = this.store.session(id);
assertMcpResolved(this.store, session.projectId);
if (pendingDeliveryReview(this.store, session)) throw Object.assign(new Error('当前任务已有待确认的Git交付预览。请在任务记录中审查并确认提交,或撤回预览后继续。'), { status: 409 });
assertChangeSetsResolved(this.store, session.projectId, { includePrepared: true });
assertWorkspacesResolved(this.store, session.projectId, { includePrepared: true });
if (this.isActive(id) || this.projectHasActivity(session.projectId)) throw Object.assign(new Error('这个项目已有任务、检查或Git交付在执行。'), { status: 409 });
if ([...this.store.core.delivery_job.values()].some(job => job.projectId === session.projectId && job.requiresVerification)) throw Object.assign(new Error('项目有结果未知的Git交付,请先在所属任务中核对提交结果。'), { status: 409 });
if (!resume && (typeof content !== 'string' || !content.trim() || content.length > 20000)) throw new Error('任务内容不能为空,也不能超过 20,000 字符。');
const project = this.store.project(session.projectId);
safePath(project);
const controller = new AbortController();
const initialConfig = structuredClone(this.store.config);
const config = this.provider.prepareConfig ? this.provider.prepareConfig(initialConfig, this.store) : initialConfig;
if (config.mode !== 'demo') this.provider.validate(config);
const record = this.store.beginRun(session, content, resume, config, { instructionSource });
const run = { controller, id: record.id, taskId: record.taskId, project, record, config };
this.active.set(id, run);
session.status = 'running'; session.recoveryNotice = null; session.executionMode = config.mode;
session.runId = run.id;
if (session.title === '新任务') session.title = String(content).replace(/\s+/g, ' ').slice(0, 28);
if (!resume || content) {
this.store.message(session, 'user', String(content));
session.providerMessages.push({ role: 'user', content: String(content) });
}
if (resume) this.store.message(session, 'system', '从已保存的执行记录继续,已完成的工具结果保留。');
session.failure = null;
this.store.save(session);
const deadline = record.budget.maxDurationMs > 0 ? setTimeout(() => controller.abort(new BudgetExceeded('time_limit', '已到达本次运行的时间预算,执行记录已保存。')), record.budget.maxDurationMs) : null;
run.promise = this.run(session, config, run).finally(() => {
clearTimeout(deadline); this.active.delete(id);
this.store.finishRun(session, record, run.stopReason ?? null);
});
return session;
}
resume(id, content) {
const session = this.store.session(id);
if (content) return this.start(id, content);
if (session.status === 'needs_review') throw Object.assign(new Error(pendingDeliveryReview(this.store, session)
? '请在任务记录中确认或撤回已有Git预览,再继续任务。' : '请先审查待处理改动;继续请求模型不能代替文件审核。'), { status: 409 });
if (!['failed', 'paused'].includes(session.status)) throw Object.assign(new Error('当前任务已经结束。可以发送新的任务,或查看待审查改动。'), { status: 409 });
return this.start(id, '', true);
}
continueReviewed(id) {
const session = this.store.session(id), run = this.store.core.run.get(session.runId), task = this.store.core.task.get(session.taskId);
if (this.isActive(id) || this.checks?.projectActive(session.projectId)) throw Object.assign(new Error('请等待正在执行的任务或检查结束。'), { status: 409 });
const stoppedForReview = run?.status === 'needs_review' || run?.status === 'paused' && run.stopReason === 'step_limit';
if (!task || run?.taskId !== task.id || !stoppedForReview || pendingDeliveryReview(this.store, session) || session.changes.some(change => ['pending', 'conflict'].includes(change.status))
|| [...this.store.core.tool.values()].some(tool => tool.taskId === task.id && tool.requiresVerification)
|| !session.changes.some(change => change.status === 'applied' && (!change.taskId || change.taskId === task.id))) throw Object.assign(new Error('当前没有已审查并应用、需要继续交付的任务改动。'), { status: 409 });
const content = '本任务的改动已经审查并应用。请继续原始目标,识别并实际执行工程检查,依据失败日志修复,完成审查和交付说明。';
return this.start(id, content, true, { instructionSource: 'review-action' });
}
async run(session, config, run) {
const signal = run.controller.signal;
let projectionLogged = false;
try {
// Immediate providers and local tools still need to deliver UI events and
// process stop/deadline input between completed, persisted operations.
await yieldExecution(undefined, { signal });
await verifyWorkspaceProject(this.store, run.project);
for (let step = 0; step < config.maxSteps; step++) {
signal.throwIfAborted();
checkBudget(run.record, this.store.core.task.get(run.taskId));
const stepRecord = this.store.beginStep(session, run.record);
const task = this.store.core.task.get(run.taskId);
const taskPlan = task.currentTaskPlanId ? await this.taskPlanner().inspect(session, { candidates: false }) : null;
const state = session.changes.filter(change => change.taskId === task.id || ['pending', 'conflict'].includes(change.status))
.map(change => ({ path: change.path, status: change.status, id: change.id, changeSetId: change.changeSetId ?? null }));
const unknown = [...this.store.core.tool.values()].filter(tool => tool.taskId === task.id && tool.requiresVerification)
.map(tool => ({ invocation_id: tool.id, call_id: tool.callId, tool: tool.tool, status: tool.state, requires_verification: true }));
const context = this.provider.redact(projectContext(run.project) + '\n当前项目/会话/任务身份:' + JSON.stringify({
project_id: run.project.id, session_id: session.id, task_id: task.id, workspace: projectWorkspaceIdentity(run.project) }) + '\n当前Task文件提案状态:' + JSON.stringify(state)
+ '\n当前任务目标与全部追加要求(用户任务数据,完整保留):\n' + JSON.stringify({
goal: task.goal, instructions: task.instructions, constraints: task.constraints ?? [], acceptance: task.acceptance ?? [],
}) + '\n结果未知的调用,不得假定成功或重放:' + JSON.stringify(unknown)
+ '\n' + sessionContext(session, run.project, config, value => this.provider.redact(value))
+ (task.readProgress?.warning ? '\n当前读取进展:' + task.readProgress.warning : '')
+ (taskPlan ? '\n当前Task依赖计划与尚未核验的原步骤(任务数据,不授权额外操作):\n' + JSON.stringify({
plan_id: taskPlan.plan_id, revision: taskPlan.revision, status: taskPlan.status, contract_artifact_id: taskPlan.contract_artifact_id,
remaining_steps: taskPlan.remaining_steps, error: taskPlan.error,
steps: taskPlan.steps.map(({ candidates, evidence, ...step }) => ({ ...step, evidence_id: evidence?.id ?? null })),
}) : ''));
const skillCatalog = this.skillRegistry().catalog(session.projectId);
const mcpCatalog = this.mcpRegistry().catalog(session.projectId);
const tools = [...toolDefinitions, ...taskPlanToolDefinitions, ...(skillCatalog.entries.some(value => value.status === 'current') ? skillToolDefinitions : []),
...(mcpCatalog.entries.length ? mcpToolDefinitions : []),
...([...this.store.core.research_target.values()].some(target => target.sessionId === session.id && target.taskId === run.taskId) ? researchToolDefinitions : []),
...([...this.store.core.engine_job.values()].some(job => job.sessionId === session.id && job.taskId === run.taskId) ? engineToolDefinitions : []),
...(this.browserManager().builds(run.project).length || [...this.store.core.browser_plan.values()].some(plan => plan.sessionId === session.id && plan.taskId === run.taskId) ? browserToolDefinitions : [])];
const projectMemory = await this.memoryManager().context(session, { redact: value => this.provider.redact(value) });
signal.throwIfAborted();
const planned = this.requestPlanner().prepare(session, run.record, config, { system: context, tools, stepId: stepRecord.id, projectMemory, skillCatalog, mcpCatalog });
if (planned.record.archivedGroups && !projectionLogged) {
projectionLogged = true; session.compactions++;
this.store.event(session, { kind: 'context', label: '整理请求上下文', phase: 'completed', contextPlanId: planned.record.id,
output: '完整请求输入估算 ' + planned.record.beforeInputTokens + ' → ' + planned.record.estimatedInputTokens +
' tokens;省略 ' + planned.record.archivedGroups + ' 个完整消息组,原历史和参数已保存为SHA256工件。估算与服务实际用量分别记录。' });
}
let requestEvent;
let response;
try {
signal.throwIfAborted(); checkBudget(run.record, task);
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 });
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' ? '模型连接失败' : '请求模型服务';
requestEvent.output = progress.phase === 'retrying' ? '第 ' + progress.attempt + ' 次请求失败,将自动重试(最多 ' + progress.maxAttempts + ' 次)。'
: progress.phase === 'completed' ? '模型响应已收到;工具请求将在校验后执行。'
: progress.diagnostic?.message ?? '正在等待模型响应。';
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);
this.requestPlanner().finish(session, planned.record, { response, attempts: planned.record.requestAttempts });
} 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 });
throw error;
}
signal.throwIfAborted();
const message = response.message;
const calls = message.tool_calls ?? [];
run.readMessageBytes = readMessageBudget(planned.record, message);
const previousIds = new Set(session.providerMessages.flatMap(item => (item.tool_calls ?? []).map(call => call.id)));
if (new Set(calls.map(call => call.id)).size !== calls.length || calls.some(call => previousIds.has(call.id))) throw new Error('模型返回了重复的工具调用 ID,请重新发送任务。');
session.providerMessages.push(message);
this.store.recordResponse(session, run.record, response.usage, planned.record.estimatedInputTokens + Math.ceil(Buffer.byteLength(JSON.stringify(message), 'utf8') / 3) + 8);
for (const call of calls) {
const event = { id: randomUUID(), createdAt: now(), startedAt: now(), kind: 'tool', phase: 'queued',
toolCallId: call.id, tool: call.function.name, label: labels[call.function.name] ?? call.function.name, taskId: run.taskId, runId: run.id };
session.events.push(event); this.store.registerInvocation(session, call, run.record, event);
}
if (message.content) this.store.message(session, 'assistant', message.content);
else this.store.save(session);
checkBudget(run.record, this.store.core.task.get(run.taskId));
if (!calls.length) {
this.store.finishStep(session, stepRecord);
session.status = session.changes.some(change => ['pending', 'conflict'].includes(change.status)) ? 'needs_review' : 'completed';
if (session.status === 'completed' && task.currentTaskPlanId) {
const finalPlan = await this.taskPlanner().inspect(session, { candidates: false });
if (!finalPlan.all_verified) {
session.status = 'paused'; run.stopReason = 'task_plan_incomplete';
this.store.message(session, 'system', '任务计划仍有未核验、失效或待更新的步骤,原任务已保存。请核对执行计划后继续;模型文字不代替实际完成。');
}
}
this.store.save(session); return;
}
let deliveryReview = null, mcpReview = null;
for (const call of calls) {
let result;
if (deliveryReview || mcpReview) {
const event = session.events.find(value => value.toolCallId === call.id && value.runId === run.id);
this.store.beginInvocation(session, call, run.record, event);
result = mcpReview ? { status: 'interrupted', reason: 'mcp_review', mcp_job_id: mcpReview,
message: '外部MCP结果待核对,这项后续调用未执行,不会自动重放。' }
: { status: 'interrupted', reason: 'git_review', plan_id: deliveryReview.id,
message: 'Git预览已经准备,等待用户确认。这项后续调用未执行,不会自动重放。' };
event.phase = 'interrupted'; event.finishedAt = now(); event.output = result.message;
this.store.finishInvocation(session, event, result);
}
else if (signal.aborted) result = { status: 'interrupted', message: '用户停止了任务,这次调用没有执行。' };
else result = await this.executeTool(session, call, run);
session.providerMessages.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(result) });
if (call.function.name === 'call_registered_mcp' && result.requires_verification) mcpReview = result.mcp_job_id;
if (call.function.name === 'plan_delivery' && result.status === 'awaiting_review') {
deliveryReview = this.store.owned('delivery_plan', result.plan_id, session.id);
run.record.review = { kind: 'git_delivery', planId: deliveryReview.id, status: 'pending', preparedAt: now() };
}
this.store.save(session);
await yieldExecution(undefined, { signal });
signal.throwIfAborted();
}
this.store.finishStep(session, stepRecord);
if (mcpReview) {
session.status = 'paused'; run.stopReason = 'mcp_review';
this.store.message(session, 'system', '外部MCP操作结果待核对,原任务和后续未执行调用已保存。请在MCP运行记录查看原始输入与结果后人工核对,再显式继续。');
this.store.save(session); return;
}
if (deliveryReview) {
session.status = 'needs_review'; run.stopReason = 'git_review';
this.store.message(session, 'system', 'Git交付预览已保存。请在任务记录中审查并确认本地提交,或撤回预览。等待确认期间不继续请求模型。');
this.store.save(session, { type: 'delivery.awaiting_review', detail: { planId: deliveryReview.id } });
return;
}
if (this.store.core.task.get(run.taskId).readProgress?.pause) throw new BudgetExceeded('no_progress',
'模型连续重复读取工件或核对相同的工程状态,未推进当前任务。实际结果和原任务已保存,请核对后继续。');
}
session.status = 'paused';
run.stopReason = 'step_limit';
this.store.message(session, 'assistant', '已到达本次工具步数上限。执行记录已保存,可以查看结果后继续。');
this.store.save(session);
} catch (error) {
this.store.interruptPending(session, run.record);
const repaired = repairToolPairs(session.providerMessages, callId => this.store.savedToolResult(session.id, callId));
if (repaired.changed) session.providerMessages = repaired.messages;
const budget = error instanceof BudgetExceeded ? error : signal.reason instanceof BudgetExceeded ? signal.reason : null;
if (signal.aborted || budget) {
run.stopReason = budget?.reason ?? 'cancelled';
for (const event of session.events.filter(item => item.kind === 'model' && item.runId === run.id && ['running', 'retrying'].includes(item.phase))) {
event.phase = 'interrupted'; event.finishedAt = now(); event.output = '模型请求已停止,已完成的工具结果保留。';
}
session.status = 'paused';
this.store.message(session, 'system', budget?.message ?? '任务已停止,执行记录已保存。');
} else {
session.status = 'failed';
const diagnostic = error.diagnostic ?? { source: 'workbench', stage: 'agent_loop', kind: 'runtime',
title: '工作台任务需要处理', message: this.provider.redact(error.message ?? String(error)), occurredAt: now() };
session.lastFailure = { ...diagnostic, runId: run.id };
const message = this.store.message(session, 'system', diagnostic.message);
session.failure = { ...session.lastFailure, messageId: message.id };
this.store.event(session, { kind: 'error', source: diagnostic.source, label: diagnostic.title, phase: 'failed',
output: diagnostic.message, diagnostic: session.lastFailure });
}
this.store.save(session);
}
}
async executeTool(session, call, run) {
const tool = call.function.name;
const event = session.events.find(value => value.toolCallId === call.id && value.runId === run.id)
?? this.store.event(session, { kind: 'tool', toolCallId: call.id, tool, label: labels[tool] ?? tool, phase: 'queued', startedAt: now() });
this.store.beginInvocation(session, call, run.record, event);
let result;
try {
const args = JSON.parse(call.function.arguments);
validateToolArgs(tool, args);
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 } : {}),
...(tool === 'read_browser_result' ? { repeated_read_count: Number.MAX_SAFE_INTEGER, reading_hint: BROWSER_READ_HINT } : {}) };
const maximumMessageBytes = Math.max(1, (run.readMessageBytes ?? 16000) - readMetadataReserve(readMetadata));
if (!['run_command', 'run_checks', 'run_browser'].includes(tool)) this.store.invocationState(session, event, 'running');
else this.store.save(session);
if (tool === 'inspect_session') result = { ...sessionSnapshot(session, run.project, run.config, value => this.provider.redact(value)), execution: this.store.executionSnapshot(session) };
else if (tool === 'read_registered_skill') {
verifyPlanEvidence(this.store, session, this.store.owned('context_plan', run.record.currentContextPlanId, session.id));
result = this.skillRegistry().read(session, run.record, args, { maximumMessageBytes, callId: call.id });
recordArtifactRead(this.store.core.task.get(run.taskId), this.store.owned('artifact', result.artifact_id, session.id), result, event.invocationId, run.id);
}
else if (tool === 'call_registered_mcp') {
verifyPlanEvidence(this.store, session, this.store.owned('context_plan', run.record.currentContextPlanId, session.id));
const manager = this.mcpRegistry(), registration = manager.prepareCall(session, run.record, args);
result = await this.requestCommand(session, event, { mcpRegistrationId: registration.id,
command: 'MCP程序 ' + registration.launch.executable.path + '\n入口 ' + (registration.launch.entry?.path ?? '(直接程序)')
+ '\n工具 ' + args.tool + '\n参数 ' + JSON.stringify(args.arguments) + '\n契约 ' + args.contract_sha256,
reason: '启动已登记的外部程序并调用所选工具;进程拥有当前用户权限,独立进程不等于系统沙箱。' }, run, async () => {
manager.prepareCall(session, run.record, args);
const started = manager.start(session, { id: registration.id, configurationRevision: registration.configurationRevision, confirm: true },
{ source: 'agent', signal: run.controller.signal, call: args, invocationId: event.invocationId });
const job = await started.promise;
return { status: job.status, mcp_job_id: job.id, report_artifact_id: job.reportArtifactId ?? null,
report_sha256: job.reportSha256 ?? null, requires_verification: job.requiresVerification,
message: job.error?.message ?? '外部工具原结果已保存,使用read_artifact读取报告。外部结果不代替工程验收。' };
});
}
else if (tool === 'plan_task') { const plan = await this.taskPlanner().plan(session, args, { source: 'agent' });
result = { status: 'planned', plan_id: plan.id, revision: plan.revision, steps: plan.steps, contract_artifact_id: plan.contractArtifactId,
note: '计划已保存,步骤尚未核验;保留原目标和通过条件,按原工具结果核验,不直接标记完成。' }; }
else if (tool === 'inspect_task_plan') result = await this.taskPlanner().inspect(session, { candidates: false });
else if (tool === 'verify_task_step') result = await this.taskPlanner().verify(session, args, { source: 'agent' });
else if (tool === 'inspect_engine_checks') result = { status: 'completed', engine_checks: this.engineManager().jobs(session)
.filter(job => job.taskId === run.taskId).map(job => this.engineManager().summary(session, job)), note: '已保存的引擎连接核验;完整原记录使用report_artifact_id读取,查询不会启动引擎。' };
else if (tool === 'list_research_targets') result = { targets: this.researchManager().targets(session), jobs: this.researchManager().jobs(session).filter(job => job.taskId === run.taskId).map(job => this.researchManager().result(job)) };
else if (tool === 'analyze_research_target') {
const manager = this.researchManager(), started = manager.start(session, args.target_id, args.operation, { source: 'agent', signal: run.controller.signal });
result = manager.result(await started.promise);
}
else if (tool === 'read_research_evidence') result = this.researchManager().readEvidence(session, args.research_job_id,
{ ...args, maximumMessageBytes, callId: call.id });
else if (tool === 'inspect_project') result = await inspectProject(run.project);
else if (tool === 'plan_browser') result = { ...publicBrowserPlan(await this.browserManager().plan(session, args, { source: 'agent' })),
note: '计划已封存,页面尚未运行。run_browser请求确认后执行;steps为空只观察页面,不能代替验收。' };
else if (tool === 'read_browser_result') {
result = this.browserManager().readResult(session, args.browser_job_id, { ...args, maximumMessageBytes, callId: call.id });
recordBrowserRead(this.store.core.task.get(run.taskId), result, event.invocationId, run.id);
}
else if (tool === 'run_browser') {
const manager = this.browserManager(), plan = manager.planFor(session, args.plan_id);
result = await this.requestCommand(session, event, { browserPlanId: plan.id,
browserSummary: { buildDirectory: plan.build.directory, buildSha256: plan.build.sha256, viewport: plan.viewport, steps: plan.steps },
command: '浏览器检查 ' + plan.build.directory + plan.path + '\n视口 ' + plan.viewport.width + '×' + plan.viewport.height + '\n' + plan.steps.length + ' 个步骤 · 计划 ' + plan.id.slice(0, 8),
reason: '按封存范围操作实际页面,保存DOM、断言、请求和截图。' }, run, async () => {
const started = manager.start(session, plan.id, { source: 'agent', signal: run.controller.signal }); return manager.result(session, await started.promise);
});
}
else if (tool === 'index_project') {
const index = await this.projectIndexer().refresh(run.project);
if (session.taskId !== run.record.taskId || session.runId !== run.record.id) throw new Error('建立索引期间Task/Run已切换,请重新读取当前任务。');
const artifact = this.store.artifactStore.write(session, run.record, JSON.parse(this.provider.redact(JSON.stringify(index))), { kind: 'project-index' });
this.store.core.artifact.set(artifact.id, artifact);
result = { status: index.coverage.truncated ? 'partial' : 'indexed', ...this.projectIndexer().summary(index), artifact_id: artifact.id,
symbols: index.symbols.slice(0, 12), imports: index.imports.slice(0, 8), note: '完整索引在本Task的工件中。定位后读取实际行;文件SHA256用于精确补丁,索引不等同于运行验证。' };
}
else if (tool === 'query_code') {
const index = await this.projectIndexer().refresh(run.project);
if (session.taskId !== run.record.taskId || session.runId !== run.record.id) throw new Error('索引查询期间Task/Run已切换,请重新读取当前任务。');
result = this.projectIndexer().query(index, args);
}
else if (tool === 'read_artifact') {
const artifact = this.store.owned('artifact', args.artifact_id, session.id), text = this.store.artifactStore.read(artifact);
result = artifactPage(artifact, text, args, { callId: call.id, maximumMessageBytes });
recordArtifactRead(this.store.core.task.get(run.taskId), artifact, result, event.invocationId, run.id);
}
else if (tool === 'prepare_change_set') {
const set = await this.changeSetManager().prepare(session, args.change_ids, { source: 'agent' });
result = { status: 'awaiting_review', change_set_id: set.id, task_id: set.taskId, fingerprint: set.fingerprint,
files: set.files.map(file => ({ path: file.path, change_id: file.changeId, base_sha256: file.baseSha256, sha256: file.sha256 })),
note: '只封存了整批审查范围,未写入项目。请用户在改动面板审核整个批次并确认应用。' };
}
else if (tool === 'plan_checks') result = await this.checkRunner().plan(session, args.names);
else if (tool === 'plan_delivery') {
const plan = await this.gitDelivery().plan(session, args.message === undefined ? {} : { message: args.message }, { source: 'agent' });
result = { status: 'awaiting_review', plan_id: plan.id, task_id: plan.taskId, paths: plan.paths, message: plan.message,
author: plan.author, parent: plan.snapshot.head, branch: plan.snapshot.branch, source_fingerprint: plan.sourceFingerprint,
diff_artifact_id: plan.diffArtifactId, check_job_id: plan.checkJobId, policy: plan.policy,
note: '只准备了预览,尚未提交。用户在任务记录中审核并确认本地Git提交。' };
}
else if (tool === 'delivery_report') {
const saved = await this.gitDelivery().report(session, { source: 'agent' });
result = { status: 'completed', report_status: saved.report.status, artifact_id: saved.artifactId, markdown_artifact_id: saved.markdownArtifactId,
verified_check_job_id: saved.report.verifiedCheckJobId, source_fingerprint: saved.report.source.fingerprint,
note: saved.report.task.note };
}
else if (tool === 'run_checks') {
const plan = this.checkRunner().planFor(session, args.plan_id);
result = await this.requestCommand(session, event, { command: plan.checks.map(check => check.command).join('\n'), checkPlanId: plan.id,
checkScripts: plan.checks.map(check => ({ name: check.name, script: check.script, lifecycle: check.lifecycle,
...(check.python ? { python: { runtime: check.python.runtime, mode: check.python.mode } } : {}) })),
reason: '执行工程检查计划 ' + plan.id.slice(0, 8) + ';保存测试数量、退出码和日志。' }, run, async () => {
const { promise } = await this.checkRunner().start(session, plan.id, { signal: run.controller.signal, source: 'agent' });
const job = await promise;
return { status: job.status === 'cancelled' ? 'interrupted' : job.status === 'passed' ? 'completed' : job.status,
check_status: job.status, job_id: job.id, plan_id: job.planId, results: job.results, summary: job.summary,
requires_verification: job.requiresVerification === true, fingerprint: job.fingerprint };
});
}
else if (tool === 'list_files') result = listFiles(run.project, args.path, args.depth ?? 3, 500);
else if (tool === 'read_file') result = filePage(readLines(run.project, args), args, { callId: call.id, maximumMessageBytes });
else if (tool === 'search_files') result = searchFiles(run.project, args);
else if (tool === 'propose_file') result = proposeFile(this.store, session, args);
else if (tool === 'propose_patch') result = proposePatch(this.store, session, args);
else if (tool === 'run_command') result = await this.requestCommand(session, event, args, run);
else throw new Error('当前能力表没有工具:' + tool);
if (proofHint) result.tool_invocation_id = event.invocationId;
event.phase = ['denied', 'interrupted', 'unknown', 'unverified', 'stale'].includes(result.status) ? result.status : ['failed', 'error'].includes(result.status) ? 'failed' : 'completed';
if (tool === 'inspect_session') recordSessionInspection(this.store.core.task.get(run.taskId), result);
else if (!['read_artifact', 'read_browser_result', 'read_registered_skill'].includes(tool) && !['error', 'interrupted', 'unknown', 'denied'].includes(result.status)) clearReadStreak(this.store.core.task.get(run.taskId));
if (typeof result.stdout === 'string') { result.stdout = this.provider.redact(result.stdout); result.stderr = this.provider.redact(result.stderr ?? ''); }
event.output = this.provider.redact(typeof result.stdout === 'string' ? result.stdout + (result.stderr ? '\n' + result.stderr : '') : JSON.stringify(result).slice(0, 16000));
if (result.exit_code !== undefined) event.exitCode = result.exit_code;
} catch (error) {
result = { status: run.controller.signal.aborted ? 'interrupted' : 'error', message: this.provider.redact(error.message ?? String(error)) };
event.phase = result.status === 'interrupted' ? 'interrupted' : 'failed';
event.output = result.message;
}
event.finishedAt = now();
event.durationMs = Date.parse(event.finishedAt) - Date.parse(event.startedAt);
result = JSON.parse(this.provider.redact(JSON.stringify(result)));
this.store.finishInvocation(session, event, result);
return result;
}
async requestCommand(session, event, args, run, execute) {
const command = String(args.command ?? '').trim();
const maximum = args.mcpRegistrationId && execute ? 24000 : 6000;
if (!command || command.length > maximum) throw new Error(maximum === 6000
? '终端命令不能为空,也不能超过 6,000 字符。' : 'MCP审批内容不能为空,也不能超过24,000字符;参数仍按工具契约核对。');
const approval = { id: randomUUID(), toolCallId: event.toolCallId, eventId: event.id, invocationId: event.invocationId,
taskId: run.taskId, runId: run.id, projectId: session.projectId, command,
...(execute ? args.mcpRegistrationId ? { mcpRegistrationId: args.mcpRegistrationId } : args.browserPlanId ? { browserPlanId: args.browserPlanId, browserSummary: args.browserSummary } : { checkPlanId: args.checkPlanId, checkScripts: args.checkScripts } : {}),
reason: String(args.reason ?? '').slice(0, 800), cwd: args.mcpRegistrationId ? '所属MCP临时目录(将在启动后记录)' : run.project.root,
shell: args.mcpRegistrationId ? 'MCP · 外部独立进程' : args.browserPlanId ? '浏览器 · 独立Edge环境' : execute ? '工程检查器 · 直接进程' : executionEnvironment().shell, status: 'pending', createdAt: now() };
session.approvals.push(approval);
event.phase = 'waiting'; session.status = 'awaiting_approval';
this.store.invocationState(session, event, 'waiting');
const decision = await new Promise(resolve => {
const signal = run.controller.signal;
const settle = value => { this.waiters.delete(approval.id); signal.removeEventListener('abort', cancel); resolve(value); };
const cancel = () => { if (approval.status === 'pending') approval.status = 'interrupted'; this.store.save(session); settle(false); };
this.waiters.set(approval.id, { sessionId: session.id, settle, runId: run.id });
signal.addEventListener('abort', cancel, { once: true });
if (signal.aborted) cancel();
});
if (!decision) { if (!run.controller.signal.aborted) session.status = 'running'; return { status: run.controller.signal.aborted ? 'interrupted' : 'denied', message: '命令未执行。', requires_verification: false }; }
run.controller.signal.throwIfAborted();
const cwd = safePath(run.project);
event.phase = 'running'; event.executedAt = now(); session.status = 'running';
this.store.invocationState(session, event, 'running');
if (execute) return execute();
return this.executeCommand(command, cwd, run.controller.signal, output => {
event.output = output; this.store.save(session);
});
}
decide(sessionId, approvalId, allow) {
const session = this.store.session(sessionId);
const approval = session.approvals.find(item => item.id === approvalId);
const waiter = this.waiters.get(approvalId);
if (!approval || approval.status !== 'pending' || !waiter || waiter.sessionId !== sessionId || waiter.runId !== session.runId
|| approval.runId !== session.runId || approval.taskId !== session.taskId || approval.projectId !== session.projectId) throw Object.assign(new Error('确认请求已过期;需要重新请求命令。'), { status: 409 });
approval.status = allow ? 'approved' : 'denied'; approval.decidedAt = now();
this.store.save(session); waiter.settle(!!allow);
}
executeCommand(command, cwd, signal, onOutput) {
return new Promise(resolve => {
const windows = process.platform === 'win32';
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 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') };
let stdout = '', stderr = '', truncated = false, timedOut = false, killed = false, lastUpdate = 0, settled = false;
const append = (kind, data) => {
const previous = kind === 'stdout' ? stdout : stderr;
const joined = previous + data;
if (joined.length > 32000) truncated = true;
if (kind === 'stdout') stdout = joined.slice(0, 32000); else stderr = joined.slice(0, 32000);
if (Date.now() - lastUpdate > 250) { lastUpdate = Date.now(); onOutput(stdout + (stderr ? '\n' + stderr : '')); }
};
const terminate = () => {
if (killed || !child.pid || settled) return;
killed = true;
if (windows) execFile('taskkill.exe', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true }, () => {});
else child.kill('SIGTERM');
};
const finish = (code, error) => {
if (settled) return; settled = true;
clearTimeout(timeout); signal.removeEventListener('abort', terminate);
resolve({ status: signal.aborted ? 'interrupted' : timedOut || error || code !== 0 ? 'failed' : 'completed',
exit_code: code, stdout, stderr: error ? stderr + '\n' + error.message : stderr,
truncated, timed_out: timedOut, command });
};
const timeout = setTimeout(() => { timedOut = true; terminate(); }, 60000);
signal.addEventListener('abort', terminate, { once: true });
child.stdout.on('data', data => append('stdout', decoders.stdout.write(data)));
child.stderr.on('data', data => append('stderr', decoders.stderr.write(data)));
child.stdout.on('end', () => append('stdout', decoders.stdout.end()));
child.stderr.on('end', () => append('stderr', decoders.stderr.end()));
child.on('error', error => finish(null, error));
child.on('close', code => finish(code));
if (signal.aborted) terminate();
});
}
async stop(sessionId) {
const run = this.active.get(sessionId);
if (!run) { await this.checks?.stop(sessionId); await this.deliveries?.stop(sessionId); await this.changeSets?.stop(sessionId); await this.workspaces?.stop(sessionId); await this.research?.stop(sessionId); await this.engines?.stop(sessionId); await this.browser?.stop(sessionId); await this.mcp?.stop(sessionId); await this.taskPlans?.settle(sessionId); return; }
const session = this.store.session(sessionId);
session.status = 'stopping'; this.store.save(session);
run.controller.abort(new Error('用户停止任务'));
await run.promise;
}
async stopAll() { await Promise.all([...this.active.keys()].map(id => this.stop(id))); await this.checks?.stopAll(); await this.deliveries?.stopAll(); await this.changeSets?.stopAll(); await this.workspaces?.stopAll(); await this.research?.stopAll(); await this.engines?.stopAll(); await this.browser?.stopAll(); await this.mcp?.stopAll(); await this.taskPlans?.settle(); }
}