Files
Agent-Workbench/src/server/runtime.mjs
T

442 lines
36 KiB
JavaScript

import { spawn, execFile } from 'node:child_process';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { StringDecoder } from 'node:string_decoder';
import { safePath, listFiles, readLines, searchFiles, proposeFile, proposePatch } from './files.mjs';
import { projectContext, toolDefinitions } 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 } from '../core/context/request-plan.mjs';
import { artifactPage, readMessageBudget, recordArtifactRead, clearReadStreak } 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';
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 = '准备多文件变更集';
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 === '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 (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); }
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; }
projectIndexer() { return this.codeIndex ??= new ProjectIndex(); }
requestPlanner() { return this.contextPlans ??= new RequestPlanner(this.store); }
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);
}
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) });
}
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) });
}
checkRunner() {
return this.checks ??= new CheckRunner(this.store, { redact: value => this.provider.redact(value), runtimeDirectory: this.appDirectory ? path.join(this.appDirectory, 'runtime') : null,
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) });
}
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) });
}
start(id, content, resume = false, { instructionSource = null } = {}) {
const session = this.store.session(id);
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 config = structuredClone(this.store.config);
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 {
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 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 : ''));
const planned = this.requestPlanner().prepare(session, run.record, config, { system: context, tools: toolDefinitions, stepId: stepRecord.id });
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;
requestEvent.label = 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);
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';
this.store.save(session); return;
}
let deliveryReview = null;
for (const call of calls) {
let result;
if (deliveryReview) {
const event = session.events.find(value => value.toolCallId === call.id && value.runId === run.id);
this.store.beginInvocation(session, call, run.record, event);
result = { 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 === '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);
signal.throwIfAborted();
}
this.store.finishStep(session, stepRecord);
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)));
if (!['run_command', 'run_checks'].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 === 'inspect_project') result = await inspectProject(run.project);
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: run.readMessageBytes ?? 16000 });
recordArtifactRead(this.store.core.task.get(run.taskId), artifact, result, event.invocationId);
}
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 })),
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 = readLines(run.project, args);
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);
event.phase = ['denied', 'interrupted', 'unknown', 'unverified', 'stale'].includes(result.status) ? result.status : result.status === 'failed' ? 'failed' : 'completed';
if (tool !== 'read_artifact' && !['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();
if (!command || command.length > 6000) throw new Error('终端命令不能为空,也不能超过 6,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 ? { checkPlanId: args.checkPlanId, checkScripts: args.checkScripts } : {}),
reason: String(args.reason ?? '').slice(0, 800), cwd: run.project.root, shell: 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); 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(); }
}