import { approvalPresentation } from '../shared/approval-presentation.mjs'; import { PreviewManager } from '../core/preview/preview-manager.mjs'; import { LocalFilePreviews } from '../core/preview/local-file-preview.mjs'; import { BrowsingManager } from '../core/browser/browsing-manager.mjs'; import { browsingToolDefinitions, browsingAction } from '../shared/contracts/browsing.mjs'; import { publicEnvironmentDiagnostic } from '../core/environment/environment-manager.mjs'; import { EnvironmentManager } from '../core/environment/environment-manager.mjs'; import { spawn, execFile } from 'node:child_process'; import path from 'node:path'; import { randomUUID } from 'node:crypto'; import { sanitizeModelText } from '../core/models/upstream-error.mjs'; 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 { inspectDiagnosticContext } from '../core/tasks/diagnostic-context.mjs'; import { BudgetExceeded, checkBudget } from '../shared/contracts/execution.mjs'; import { tokenBudgetState,checkModelDispatchBudget } from '../shared/contracts/model-reservation.mjs'; import { taskToolAllowed, taskContract } from '../shared/contracts/task-control.mjs'; import { CheckRunner } from '../core/check-runner.mjs'; import { inspectProject } from '../core/project-inspector.mjs'; import { projectEnvironment } from '../core/process-environment.mjs'; import { GitDelivery } from '../core/git-delivery.mjs'; import { ProjectIndex } from '../core/context/project-index.mjs'; import { RequestPlanner, verifyPlanEvidence } from '../core/context/request-plan.mjs'; import { ENGINE_SEED_RESERVATION } from '../shared/contracts/engine-context.mjs'; import { InputAttachments } from '../core/context/input-attachments.mjs'; import { BudgetResume } from '../core/context/budget-resume.mjs'; import { artifactPage, filePage, readMessageBudget, readBatchBudget, spendReadBudget, recordArtifactRead, recordBrowserRead, recordFileRead, recordUnchangedCheck, clearReadStreak, recordSessionInspection, recordUnchangedAction, readCoverageContext, readMetadataReserve, BROWSER_READ_HINT, beginReadTurn, finishReadTurn, orderReadCalls } from '../core/context/read-budget.mjs'; import { taskDeliveryProgress } from '../core/context/delivery-progress.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 { EngineRunner } from '../core/engines/engine-runner.mjs'; import { BrowserManager, publicBrowserPlan } from '../core/browser/browser-manager.mjs'; import { browserPlanInput } from '../shared/contracts/browser.mjs'; import { TaskPlanManager } from '../core/tasks/task-plan-manager.mjs'; import { RequirementReview } from '../core/tasks/requirement-review.mjs'; import { recordTurnProgress } from '../core/context/turn-progress-recorder.mjs'; import { FileResults } from '../core/tasks/file-results.mjs'; import { fileResultInput, fileResultToolDefinitions } from '../shared/contracts/file-results.mjs'; import { verifiedCheck } from '../core/delivery-report.mjs'; import { currentBrowserVerification } from '../core/browser/browser-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'; import { WorkerManager } from '../core/tasks/worker-manager.mjs'; import { EvaluationManager } from '../core/evaluation/evaluation-manager.mjs'; import { WORKER_TOOLS, COLLABORATION_CLOSED, workerForSession, assertWorkerTool, assertWorkersResolved, workerUsage, workerConflict } from '../shared/contracts/workers.mjs'; const workerAuthority = Symbol('internal-worker-start'); // How many times one run may recover from an output-token-ceiling truncation by // asking the model to split its proposals. A model that keeps overflowing past this // still fails with the original diagnostic rather than looping on the budget. const OUTPUT_TRUNCATION_RECOVERY_LIMIT = 2; const labels = { diagnose_environment:'诊断工程环境',plan_environment:'准备依赖计划',prepare_environment:'执行依赖准备',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.inspect_browser_tabs = '核对本任务浏览标签页'; labels.observe_browser_tab = '观察所属浏览页面'; labels.act_browser_tab = '执行原页面固定动作'; labels.plan_task = '保存任务依赖计划'; labels.verify_task_step = '核验任务步骤原证据'; labels.inspect_task_plan = '核对任务计划与未完成项'; labels.verify_existing_files = '核对当前已有成果'; 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_existing_files') { fileResultInput(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 === 'inspect_browser_tabs') { if (Object.keys(args).length) throw new Error('标签页查询不接受附加参数。'); return; } if (['observe_browser_tab','act_browser_tab'].includes(tool)) { const {tab_id,...input}=args; if(typeof tab_id!=='string')throw new Error('需要当前Task的标签页ID。'); if(tool==='act_browser_tab')browsingAction(input); else if(Object.keys(input).length)throw new Error('观察不接受脚本或附加参数。'); 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 = ['diagnose_environment','plan_environment','inspect_session', 'inspect_project', 'index_project', 'plan_checks', 'plan_delivery', 'delivery_report'].includes(tool) ? [] : tool === 'read_artifact' ? ['artifact_id'] : tool === 'prepare_environment' ? ['plan_id','fingerprint'] : 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 (tool === 'read_file' && args.expected_sha256 !== undefined && (typeof args.expected_sha256 !== 'string' || !/^[a-f0-9]{64}$/i.test(args.expected_sha256))) throw new Error('文件续读expected_sha256需要64位SHA256。'); 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.browsing?.isActive(id) || !!this.previews?.isActive(id) || !!this.environments?.isActive(id) || !!this.evaluations?.isActive(id) || this.active.has(id) || !!this.workers?.isActive(id) || !!this.controlledEngines?.isActive(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.provider.hub?.catalog?.active.size ?? 0) > 0 || (this.provider.hub?.networkChecks?.active.size ?? 0) > 0 || (this.browsing?.active.size ?? 0) > 0 || (this.previews?.active.size ?? 0) > 0 || (this.environments?.active.size ?? 0) > 0 || (this.evaluations?.active.size ?? 0) > 0 || (this.provider.activeRequests ?? 0) > 0 || (this.provider.hub?.waiting ?? 0) > 0 || this.active.size > 0 || (this.workers?.active.size ?? 0) > 0 || (this.controlledEngines?.drivers.size ?? 0) > 0 || (this.mcp?.active.size ?? 0) > 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; } evaluationManager() { return this.evaluations ??= new EvaluationManager(this.store, this); } workerManager() { return this.workers ??= new WorkerManager(this.store, this); } projectIndexer() { return this.codeIndex ??= new ProjectIndex({ cacheDirectory: path.join(this.store.directory, 'cache', 'project-index') }); } fileResults() { return this.results ??= new FileResults(this.store); } async fileDelivery(session) { const task = this.store.owned('task', session.taskId, session.id), delivery = this.fileResults().completion(session); if (!delivery.satisfied) return { ...delivery, stopReason: 'delivery_incomplete', message: delivery.requiresChange ? '当前要求包含修改,尚无对应追加要求之后的实际文件改动。已有成果核对不能代替修改。' : '要求的文件尚无当前有效成果或已应用改动。' + (delivery.missingPaths.length ? '缺少:' + delivery.missingPaths.join('、') + '。' : '') + '请完整读取并核对已有成果,或生成可审查改动。' }; const policy = taskContract(task).checks; if (policy !== 'skip' && (policy === 'required' || task.verification?.status !== 'not_configured')) { const inspection = await inspectProject(this.store.project(session.projectId)); if (!verifiedCheck(this.store, session, inspection)) return { ...delivery, satisfied: false, stopReason: 'verification_incomplete', message: '当前工程检查尚无对应当前输入的通过证据,已有成果不能代替检查。' }; } const browser = await currentBrowserVerification(this.store, session); if (browser.required && browser.status !== 'passed') return { ...delivery, satisfied: false, stopReason: 'verification_incomplete', message: '当前页面验收尚未通过,已有成果不能代替页面检查。' }; return delivery; } async completeFileResults(session) { if (this.projectHasActivity(session.projectId)) throw Object.assign(new Error('工程仍有活动,请停止或等待原操作结束后核对成果。'), { status: 409 }); const taskId = session.taskId, runId = session.runId; if (workerForSession(this.store, session)) throw Object.assign(new Error('受限子任务不能独立结束父项目成果。'), { status: 409 }); if (session.changes.some(change => ['pending', 'conflict'].includes(change.status)) || [...this.store.core.tool.values()].some(tool => tool.taskId === taskId && tool.requiresVerification)) throw Object.assign(new Error('仍有待审改动或未知结果,请先核对原操作。'), { status: 409 }); assertWorkspacesResolved(this.store, session.projectId, { includePrepared: true }); assertWorkersResolved(this.store, session.projectId); assertMcpResolved(this.store, session.projectId); assertChangeSetsResolved(this.store, session.projectId); const delivery = await this.fileDelivery(session); if (!delivery.satisfied) throw Object.assign(new Error(delivery.message), { status: 409 }); const plan = await this.taskPlanner().inspect(session, { candidates: false }); if (plan.configured && !plan.all_verified) throw Object.assign(new Error('原执行计划仍有未核验步骤,请先核对。'), { status: 409 }); await this.requirementReview().assertReady(session); if (session.taskId !== taskId || session.runId !== runId || this.projectHasActivity(session.projectId) || !this.fileResults().completion(session).satisfied) throw Object.assign(new Error('核对期间任务、文件或活动已变化,请重新核对。'), { status: 409 }); const task = this.store.owned('task', taskId, session.id); task.delivery = { ...delivery, at: now(), checks: taskContract(task).checks === 'skip' ? 'not_requested' : task.verification.status }; session.status = 'completed'; this.store.message(session, 'system', '已按当前成果结束任务;' + (delivery.newChanges ? '实际修改另列。' : '无新增修改。') + '原运行、检查与Git记录保留,未请求模型。'); this.store.save(session, { type: 'file_result.task_completed' }); } requirementReview() { return new RequirementReview(this.store, { planner: this.taskPlanner(), redact: value => this.provider.redact(value) }); } 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) }); } previewManager() { return this.previews ??= new PreviewManager(this.store, { runtimeDirectory: this.appDirectory ? path.join(this.appDirectory, 'runtime') : null, redact: value => this.provider.redact(value), projectBusy: projectId => this.projectHasActivity(projectId) }); } localFilePreviews() { return this.filePreviews ??= new LocalFilePreviews(this.store); } browsingManager() { return this.browsing ??= new BrowsingManager(this.store, { redact: value => this.provider.redact(value), workbenchOrigin: this.workbenchOrigin }); } 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); } inputAttachments() { return this.inputs ??= new InputAttachments(this.store,{busy:projectId=>this.projectHasActivity(projectId)}); } budgetResumes(){return this.resumes??=new BudgetResume(this.store,this.provider,this);} resumeBudget(id,input){const session=this.store.session(id),plan=this.budgetResumes().verify(session,input);return this.start(id,'',true,{resumePlan:plan});} engineRunner() { return this.controlledEngines ??= new EngineRunner(this.store, this.provider, { appDirectory: this.appDirectory }); } memoryManager() { return this.projectMemories ??= new ProjectMemoryManager(this.store); } checkpointManager() { return this.taskCheckpoints ??= new TaskCheckpointManager(this.store, { taskPlans: this.taskPlanner(), redact: value => this.provider.redact(value) }); } 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, { excludeGroupId = null, excludeEvaluationId = null } = {}) { return !!this.previews?.projectActive(projectId) || !!this.environments?.projectActive(projectId) || !!this.evaluations?.projectActive(projectId, excludeEvaluationId) || !!this.workers?.projectActive(projectId, excludeGroupId) || !!this.controlledEngines?.projectActive(projectId, exceptSessionId) || [...this.active.entries()].some(([id, run]) => id !== exceptSessionId && run.project.id === projectId) || !!this.environments?.projectActive(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.previews?.projectLive(projectId) || !!this.evaluations?.projectActive(projectId) || !!this.workers?.projectActive(projectId) || !!this.controlledEngines?.projectActive(projectId) || [...this.active.values()].some(run => run.project.id === projectId) || !!this.environments?.projectActive(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, { beforeApply: (session, set) => this.workerManager().verifyMerge(session, set), projectBusy: (projectId, exceptId) => !!this.evaluations?.projectActive(projectId) || !!this.workers?.projectActive(projectId) || !!this.controlledEngines?.projectActive(projectId, exceptId) || [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.environments?.projectActive(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) }); } environmentManager() { return this.environments ??= new EnvironmentManager(this.store, { runtimeDirectory: this.appDirectory ? path.join(this.appDirectory,'runtime') : null, redact: value => this.provider.redact(value), projectBusy: (projectId,exceptId) => this.projectHasActivity(projectId,exceptId) }); } 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.environments?.projectActive(projectId) || !!this.evaluations?.projectActive(projectId) || !!this.workers?.projectActive(projectId) || !!this.controlledEngines?.projectActive(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.evaluations?.projectActive(projectId) || !!this.workers?.projectActive(projectId) || !!this.controlledEngines?.projectActive(projectId, exceptId) || [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.environments?.projectActive(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) }); } startWorker(session, worker, config) { if (workerForSession(this.store, session) !== worker || !this.workers?.active.has(worker.collaborationId) || this.store.core.collaboration.get(worker.collaborationId)?.status !== 'running') throw workerConflict('子任务只能由所属父协作启动。'); return this.start(session.id, worker.goal, true, { workerAuthorization: workerAuthority, worker, workerConfig: config }); } start(id, content, resume = false, { instructionSource = null, workerAuthorization = null, worker = null, workerConfig = null, attachmentIds=[],resumePlan=null } = {}) { if (this.provider.hub?.networkChecks?.active.size) throw Object.assign(new Error('连接诊断正在执行,请等待结束或在模型中心停止诊断,再开始任务。'), { status: 409 }); const session = this.store.session(id); assertWorkersResolved(this.store, session.projectId); const boundWorker = workerForSession(this.store, session); if (workerAuthorization !== null && workerAuthorization !== workerAuthority || workerConfig && workerAuthorization !== workerAuthority || boundWorker && (workerAuthorization !== workerAuthority || boundWorker !== worker)) throw workerConflict('受限子任务请在父协作中开始或继续,不能替换目标或配置。'); if (!boundWorker && [...this.store.core.evaluation.values()].some(batch => batch.projectId === session.projectId && !['completed', 'retained'].includes(batch.status))) throw workerConflict('工程已有未收尾评测,请在评测中处理原样本或保留现场结束。'); if (!boundWorker && [...this.store.core.collaboration.values()].some(group => group.projectId === session.projectId && !COLLABORATION_CLOSED.has(group.status))) throw workerConflict('项目已有未收尾父协作,请先处理子任务和合并审查,再发送新目标。'); 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); const attachments=this.inputAttachments().validateSelection(session,attachmentIds); if(attachments.length&&this.store.core.task.get(session.taskId)?.attachmentIds?.length&&!['completed','idle'].includes(this.store.core.task.get(session.taskId).status))throw Object.assign(new Error('当前任务已有截图,请新建任务再添加。'),{status:409}); safePath(project); const controller = new AbortController(); const initialConfig = structuredClone(resumePlan?.config ?? workerConfig ?? this.store.config); const config = resumePlan || workerConfig ? initialConfig : this.provider.prepareConfig ? this.provider.prepareConfig(initialConfig, this.store) : initialConfig; if (config.mode !== 'demo') this.provider.validate(config); if (attachments.length && config.mode==='demo') throw Object.assign(new Error('演示执行器不会读取图片,请先选择支持视觉的模型连接。'),{status:409}); if (attachments.length && !config.modelRouting) throw Object.assign(new Error('请在模型中心添加并声明支持视觉的连接,再发送图片。'),{status:409}); const record = this.store.beginRun(session, content, resume, config, { instructionSource, inputAttachments:attachments,resumePlan }); const run = { controller, id: record.id, taskId: record.taskId, project, record, config, ...(worker ? { worker } : {}) }; 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) { const userMessage=this.store.message(session, 'user', String(content)); if(attachments.length)userMessage.attachmentIds=attachments.map(row=>row.boundAttachmentId); 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); try { const status = session.status; if (record.purpose === 'diagnostic') session.status = record.taskStatusBefore; this.store.finishRun(session, record, run.stopReason ?? null, { status }); } finally { this.active.delete(id); } }); run.promise.catch(() => {}); return session; } async capturePauseInputs(run) { if (!run.worker && run.record.purpose !== 'diagnostic' && ['no_progress', 'step_limit'].includes(run.stopReason)) { try { run.record.finalSourceFingerprint = (await inspectProject(run.project)).sourceFingerprint; } catch { /* No fingerprint means no claim of unchanged inputs. */ } } } 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 }); if (taskContract(task).checks === 'skip' && task.delivery?.status === 'files_applied') throw Object.assign(new Error('文件已按原要求应用完成,无需自动检查;如需追加工作,请明确发送新的要求。'), { status: 409 }); const result = this.start(id, '', true, { instructionSource: 'review-action' }); this.store.message(session, 'system', '审查操作:改动已应用,继续核对原目标。原有范围与限制保留,此操作没有追加测试要求。'); return result; } async run(session, config, run) { const signal = run.controller.signal; let projectionLogged = false; let currentStep = null; 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); const originalTask = this.store.core.task.get(run.taskId); if (!run.worker && run.record.purpose !== 'diagnostic' && originalTask.stagnation?.count >= 2) { const current = await inspectProject(run.project); if (current.sourceFingerprint === originalTask.stagnation.sourceFingerprint) throw new BudgetExceeded('no_progress', '连续两次运行未增加源码改动、检查结果或新的读取依据。本次未请求模型;请根据原日志修改源码或发送具体调整,避免重复空续接。'); originalTask.stagnation = null; } recordTurnProgress(this.store, session, run.record, null, 'baseline'); 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); currentStep = stepRecord; const task = this.store.core.task.get(run.taskId); config.inputImages=this.inputAttachments().images(session,task); if(config.inputImages.length&&config.mode==='demo')throw new Error('固定演示执行器不会读取图片;请连接并声明支持视觉的模型。'); const taskPlan = task.currentTaskPlanId ? await this.taskPlanner().inspect(session, { candidates: false }) : null; const requirementReview = task.requirementRevisions?.length ? await this.requirementReview().inspect(session) : null; const deliveryProgress = await taskDeliveryProgress(this.store, session, run.record, { checks: this.checkRunner(), worker: !!run.worker, taskPlan }); const readCoverage = readCoverageContext(task, run.id); 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 fileResults = this.fileResults().inspect(session); // Keep the complete goal once in this request view. The stored contract // still contains its original goal for intent and evidence verification. const { goal, ...contract } = taskContract(task); const context = this.provider.redact(projectContext(run.project) + (run.worker ? '\n受限子任务执行契约(宿主权限,不可扩展):' + JSON.stringify({ parent_task_id: run.worker.parentTaskId, worker_id: run.worker.id, write_paths: run.worker.paths, budget: run.worker.budget, rule: '只有范围内提案、审查应用和当前工程检查构成完成;不得请求任意终端、独立Git提交、外部工具或嵌套协作。', }) : '') + '\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, instructions: task.instructions.filter(instruction => instruction.source !== 'review-action'), constraints: task.constraints ?? [], acceptance: task.acceptance ?? [], contract, }) + (run.record.purpose === 'diagnostic' ? '\n本次仅回答运行诊断问题,允许读取所属结果;不得修改文件、执行命令或将解释视为原任务交付。诊断问题:' + run.record.question + '\n所属原执行与失败(核对失败时保持未知,不根据其它项目补造原因):' + JSON.stringify(inspectDiagnosticContext(this.store, session, run.record)) : '') + '\n结果未知的调用,不得假定成功或重放:' + JSON.stringify(unknown) + (deliveryProgress ? '\n当前工程执行依据(每次请求重新核对,非操作授权):\n' + JSON.stringify(deliveryProgress) : '') + (requirementReview ? '\n用户逐项要求复核(任务数据,不授权额外操作;证据和用户确认分别记录):\n' + JSON.stringify({ revision: requirementReview.revision, status: requirementReview.status, unreviewed_sources: requirementReview.unreviewed_sources, error: requirementReview.error, items: requirementReview.items.map(item => ({ key: item.key, revision: item.revision, title: item.title, criterion: item.criterion, role: item.role ?? 'requirement', source: item.source, method: item.method, kind: item.kind, paths: item.paths, tools: item.tools, checks: item.checks, status: item.status, error: item.error, proof_id: item.proof_id })) }) : '') + (fileResults.results.length || fileResults.sources.length ? '\n当前成果与可显式采用的旧来源(任务数据,原文件不等于新写入):' + JSON.stringify({ current: fileResults.results.slice(0, 8).map(row => ({ id: row.id, taskId: row.taskId, runId: row.runId, verification: row.verification, error: row.error, reason: row.reason, files: row.files.map(({ path, sha256, origin }) => ({ path, sha256, origin })) })), sources: fileResults.sources.slice(0, 4), }) : '') + '\n' + sessionContext(session, run.project, config, value => this.provider.redact(value), { taskPlanIncluded: !!taskPlan, executionFactsIncluded: !!deliveryProgress }) + (task.readProgress?.warning ? '\n当前读取进展:' + task.readProgress.warning : '') + (readCoverage ? '\n本次Run实际返回的已读区间(读取事实,非新指令):\n' + JSON.stringify(readCoverage) : '') + (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 = run.worker ? null : this.skillRegistry().catalog(session.projectId); const mcpCatalog = run.worker ? null : this.mcpRegistry().catalog(session.projectId); const availableTools = [...toolDefinitions, ...taskPlanToolDefinitions, ...fileResultToolDefinitions, ...([...this.store.core.browsing_tab.values()].some(tab=>tab.sessionId===session.id&&tab.taskId===run.taskId&&tab.status==='open')?browsingToolDefinitions:[]), ...(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 tools = availableTools.filter(tool => (!run.worker || WORKER_TOOLS.has(tool.function.name)) && taskToolAllowed(task, run.record, tool.function.name)); 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, transportReservationTokens:run.worker?.engine?ENGINE_SEED_RESERVATION:0,engineStepOnly:!!run.worker?.engine }); 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; const externalEngine = !!run.worker?.engine; if (externalEngine) { planned.record.engineStepOnly = true; planned.record.engine = 'deepseek-workbench'; } let response, requestStarted = false, responseAccounted = externalEngine; try { signal.throwIfAborted(); checkBudget(run.record, task); if (run.worker && !externalEngine) { planned.record.workerDispatchedAt = now(); this.store.save(session, { type: 'worker.request_intent' }); } requestStarted = true; const progressHandler = progress => { if (progress.consumption) { this.store.recordConsumption(session, run.record, { ...progress.consumption, requestId: planned.record.id }, planned.record.tokenReservation?.reservedTokens??planned.record.estimatedInputTokens + config.maxOutputTokens); responseAccounted = true; if (run.worker) { planned.record.workerUsageAccounted = true; this.store.save(session); } return; } if (progress.responseCapture !== undefined || progress.streamCapture !== undefined) { const raw = progress.responseCapture ?? progress.streamCapture; const decoded = raw.toString('utf8'), redacted = sanitizeModelText(decoded, value => this.provider.redact(value)); const captured = redacted === decoded ? raw : Buffer.from(redacted, 'utf8'); const artifact = this.store.artifactStore.write(session, run.record, captured, { kind: progress.streamCapture !== undefined ? 'model-stream-response' : 'model-http-response', mediaType: 'text/plain' }); this.store.core.artifact.set(artifact.id, artifact); if (progress.modelIdentity) progress.modelIdentity.responseSource = { artifactId: artifact.id, sha256: artifact.sha256, sessionId: session.id, scope: progress.streamCapture !== undefined ? 'sse-stream' : 'http-body' }; if (progress.upstream) Object.assign(progress.upstream, { artifactId: artifact.id, artifactSha256: artifact.sha256, artifactScope: progress.streamCapture !== undefined ? 'sse-stream' : 'http-body', sessionId: session.id }); if (progress.upstream?.capture) Object.assign(progress.upstream.capture, { retention: 'artifact', storedBytes: artifact.bytes }); this.store.save(session); return; } if (!requestEvent) requestEvent = this.store.event(session, { kind: externalEngine ? 'engine' : 'model', runId: run.id, source: externalEngine ? 'controlled_engine' : 'model_connection', label: externalEngine ? '受控引擎执行' : '请求模型服务', phase: 'running', startedAt: now(), contextPlanId: planned.record.id }); if (progress.engineRunId) requestEvent.engineRunId = progress.engineRunId; planned.record.status = progress.phase === 'running' || progress.phase === 'retrying' ? 'requesting' : planned.record.status; planned.record.requestAttempts = Math.max(planned.record.requestAttempts, progress.attempt ?? 0); stepRecord.modelAttempts = Math.max(stepRecord.modelAttempts, progress.attempt ?? 0); requestEvent.phase = progress.phase; requestEvent.attempts = progress.attempt; if (progress.streaming) requestEvent.stream = { status: 'receiving', protocol: progress.protocol, sequence: progress.streamSequence, bytes: progress.streamBytes, textCharacters: progress.textCharacters, textPreview: this.provider.redact(progress.textPreview ?? '').slice(0, 8000), toolFragments: progress.toolFragments }; if (progress.stream) requestEvent.stream = { ...requestEvent.stream, ...progress.stream, status: progress.stream.terminal ? 'completed' : 'receiving' }; if (progress.phase === 'failed' && requestEvent.stream) requestEvent.stream.status = 'incomplete'; if (progress.connectionId) { requestEvent.connectionId = progress.connectionId; requestEvent.modelAttemptId = progress.modelAttemptId; requestEvent.actualModel = progress.model; } if (progress.modelIdentity) requestEvent.modelIdentity = progress.modelIdentity; requestEvent.label = progress.switching ? '正在切换模型池连接' : progress.phase === 'retrying' ? '正在重试模型连接' : progress.phase === 'completed' ? '模型响应已收到' : progress.phase === 'failed' ? '模型连接失败' : '请求模型服务'; if (externalEngine) requestEvent.label = progress.phase === 'completed' ? '引擎原结果已收到' : '受控引擎执行'; requestEvent.output = progress.phase === 'retrying' ? '第 ' + progress.attempt + ' 次请求失败,将自动重试(最多 ' + progress.maxAttempts + ' 次)。' : progress.phase === 'completed' ? '模型响应已收到;工具请求将在校验后执行。' : progress.streaming ? '正在接收模型输出,工具参数完整核对前不会执行。' : progress.diagnostic?.message ?? '正在等待模型响应。'; if (externalEngine) requestEvent.output = progress.phase === 'completed' ? '原引擎工具请求或最终输出已返回,后续按所属任务核验。' : '等待所属引擎;实际模型尝试另有记录。'; if (progress.diagnostic) requestEvent.diagnostic = progress.diagnostic; if (progress.durationMs !== undefined) requestEvent.durationMs = progress.durationMs; if (['completed', 'failed'].includes(progress.phase)) requestEvent.finishedAt = now(); this.store.save(session); }; const requestConfig=config.modelRouting&&!externalEngine?{...config,modelRouting:{...config.modelRouting,maxAttempts:Math.min(config.modelRouting.maxAttempts,planned.record.maxBudgetAttempts)}}:config; response = externalEngine ? await this.engineRunner().complete(session, run, planned.messages, progressHandler, planned.record, tools) : await this.provider.complete(requestConfig, planned.messages, run.project, signal, progressHandler, planned.record, tools, {maxBudgetAttempts:planned.record.maxBudgetAttempts,beforeDispatch:({previousFailure}={})=>checkModelDispatchBudget(this.store,session,run.record,requestConfig,planned.body,0,previousFailure)}); if (response.compatibility?.length && requestEvent) { requestEvent.compatibility = response.compatibility; this.store.save(session); } this.requestPlanner().finish(session, planned.record, { response, attempts: planned.record.requestAttempts }); if (run.worker && !externalEngine && !responseAccounted) { this.store.recordResponse(session, run.record, response.usage, planned.record.estimatedInputTokens + Math.ceil(Buffer.byteLength(JSON.stringify(response.message), 'utf8') / 3) + 8); planned.record.workerUsageAccounted = true; this.store.save(session); responseAccounted = true; } } catch (error) { if (requestEvent?.stream && requestEvent.stream.status !== 'completed') { requestEvent.stream.status = signal.aborted ? 'interrupted' : 'incomplete'; requestEvent.phase = signal.aborted ? 'interrupted' : 'failed'; requestEvent.finishedAt = now(); } 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.tokenReservation?.reservedTokens??planned.record.estimatedInputTokens + config.maxOutputTokens); planned.record.workerUsageAccounted = true; this.store.save(session, { type: 'worker.request_usage_unknown' }); } try { checkBudget(run.record,task); } catch(budget){ if(error.diagnostic?.kind==='model_identity') { error.diagnostic.budgetStopReason=budget.reason; throw error; } if(budget instanceof BudgetExceeded&&error.diagnostic)budget.contextBudget={modelFailure:structuredClone(error.diagnostic)}; throw budget; } // Bounded recovery for a response stopped at the output-token ceiling. The // truncated turn is never executed or appended to history; instead the model // is told it was cut off and asked to split its proposals, then the run // continues. The failed attempt and its usage are already accounted above. // Recoveries are capped per run so a model that keeps overflowing still stops. if (error.diagnostic?.reason === 'output_truncated' && !signal.aborted) { run.record.outputTruncationRecoveries = (run.record.outputTruncationRecoveries ?? 0) + 1; if (run.record.outputTruncationRecoveries <= OUTPUT_TRUNCATION_RECOVERY_LIMIT) { this.store.finishStep(session, stepRecord); const note = '上一次响应在达到单次输出上限前被截断(finish_reason=length),其中的工具调用整体未执行(即使某个工具参数已完整也未应用,避免落地被截断的半成品)。请把这次改动拆小:每次响应只提交一个文件的 propose_file/propose_patch,或分多轮 prepare_change_set,不要在一个响应里堆叠多个大参数工具。原目标和已读依据都保留。'; // The truncated assistant turn was never appended, so the conversation // stays valid. Feed the instruction to the model as a standalone turn // in the provider history, and mirror it to the visible chat log. session.providerMessages.push({ role: 'user', content: note }); this.store.event(session, { kind: 'context', runId: run.id, label: '模型输出被上限截断,已请求拆分后继续', phase: 'completed', contextPlanId: planned.record.id, output: '第 ' + run.record.outputTruncationRecoveries + '/' + OUTPUT_TRUNCATION_RECOVERY_LIMIT + ' 次恢复:上一响应 finish_reason=length,未执行任何工具,原响应与用量已保存。' }); this.store.message(session, 'system', note); continue; } error.diagnostic.outputTruncationRecoveries = run.record.outputTruncationRecoveries - 1; } 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项上限;这批工具未执行,原响应和用量已保存。'); run.readMessageBytes = readMessageBudget(planned.record, message); run.readBatchBudget = readBatchBudget(planned.record, message); beginReadTurn(task, run.id, stepRecord.id); run.readPageCharacters = planned.record.budget.inputBudget - planned.record.nextReadFixedInputTokens - (planned.record.workingRetentionTokens ?? 0) < 4096 ? 2000 : Infinity; const executionCalls = orderReadCalls(run.readBatchBudget, calls, call => { const args = JSON.parse(call.function.arguments); validateToolArgs(call.function.name, args); const size = call.function.name === 'read_file' ? fs.statSync(safePath(run.project, args.path)).size : this.store.owned('artifact', args.artifact_id, session.id).bytes; return Math.max(0, Math.min(size - (args.offset ?? 0), args.limit ?? (call.function.name === 'read_artifact' ? 2000 : Infinity))); }); 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); if (!responseAccounted) 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 (run.record.purpose === 'diagnostic') { session.status = 'completed'; run.stopReason = 'diagnostic_answered'; } else if (session.status === 'completed' && taskContract(task).kind === 'file') { const delivery = await this.fileDelivery(session); if (!delivery.satisfied) { session.status = 'paused'; run.stopReason = delivery.stopReason; this.store.message(session, 'system', '答复已收到,但' + delivery.message); } else task.delivery = { ...delivery, at: now(), checks: taskContract(task).checks === 'skip' ? 'not_requested' : task.verification?.status ?? 'not_configured' }; } else if (session.status === 'completed' && taskContract(task).checks !== 'skip' && (['failed', 'stale', 'unknown', 'unverified', 'running'].includes(task.verification?.status) || taskContract(task).checks === 'required' && task.verification?.status !== 'passed')) { session.status = 'paused'; run.stopReason = 'verification_incomplete'; this.store.message(session, 'system', '答复已收到,但当前任务的工程检查尚未通过,不能视为交付完成。原目标与检查结果已保留。'); } if (externalEngine) await this.engineRunner().finish(session, run); if (session.status === 'completed' && run.worker) { try { await this.workerManager().output(session, run.worker); signal.throwIfAborted(); } catch (error) { if (signal.aborted) throw error; session.status = 'paused'; run.stopReason = 'worker_incomplete'; this.store.message(session, 'system', '子任务还不能交付:' + this.provider.redact(error.message ?? String(error)) + '。原目标和结果已保存。'); } } if (session.status === 'completed' && task.currentTaskPlanId && run.record.purpose !== 'diagnostic') { 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', '任务计划仍有未核验、失效或待更新的步骤,原任务已保存。请核对执行计划后继续;模型文字不代替实际完成。'); } } if (session.status === 'completed' && task.requirementRevisions?.length && run.record.purpose !== 'diagnostic') { const review = await this.requirementReview().inspect(session); if (!review.all_resolved) { session.status = 'paused'; run.stopReason = 'requirements_incomplete'; this.store.message(session, 'system', '答复已保留;用户要求仍有待复核、失效或未审阅来源,请在任务的要求与证据中核对。'); } } this.store.save(session); return; } let deliveryReview = null, mcpReview = null; const preparedSets = new Set(); for (const call of executionCalls) { 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); const invocation = [...this.store.core.tool.values()].findLast(row => row.runId === run.id && row.callId === call.id); if (invocation?.resultArtifactId) (stepRecord.progressToolIds ??= []).push(invocation.id); spendReadBudget(run.readBatchBudget, call, result); session.providerMessages.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(result) }); if (call.function.name === 'prepare_change_set' && result.status === 'awaiting_review') preparedSets.add(result.change_set_id); 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(); } finishReadTurn(task, run.id, stepRecord.id); 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; } // Settle the whole model turn first: later proposals can make a sealed // set partial, and later tools may fail or need verification/stop. for (const id of preparedSets) { let ready = false; try { ready = await this.changeSetManager().reviewReady(session, id, run.record); } catch (error) { this.store.event(session, { kind: 'system', source: 'workbench', label: '变更批次交接预检未通过', phase: 'failed', output: this.provider.redact(error.message ?? String(error)) }); } signal.throwIfAborted(); if (!ready) continue; run.record.review = { kind: 'change_set', changeSetId: id, fingerprint: this.store.core.change_set.get(id).fingerprint, status: 'pending' }; session.status = 'needs_review'; run.stopReason = 'change_set_review'; this.store.message(session, 'system', '当前任务的完整变更批次已封存,同轮工具结果已保存。请审查并应用或撤销批次;等待审查期间不继续请求模型。应用后可显式续接原任务进行检查。'); this.store.save(session, { type: 'change_set.awaiting_review', detail: { changeSetId: id } }); return; } stepRecord.progressSettled = true; recordTurnProgress(this.store, session, run.record, stepRecord); if (this.store.core.task.get(run.taskId).readProgress?.pause) throw new BudgetExceeded('no_progress', '模型连续重复读取工件或核对相同的工程状态,未推进当前任务。实际结果和原任务已保存,请核对后继续。'); } run.stopReason = 'step_limit'; await this.capturePauseInputs(run); session.status = 'paused'; 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'; if(budget)run.record.budgetPause={schema:1,reason:budget.reason,createdAt:now(),taskId:run.taskId,runId:run.id, ...(budget.contextBudget??{}),runUsage:structuredClone(run.record.usage),taskUsage:structuredClone(this.store.core.task.get(run.taskId).usage), tokenAccounting:tokenBudgetState(run.record,this.store.core.task.get(run.taskId)), runBudget:structuredClone(run.record.budget),taskBudget:structuredClone(this.store.core.task.get(run.taskId).budget), note:'本地预留与上游报告用量分开记录。单个在途响应可能超过预估;超额后停止后续请求,未知用量保持未知。'}; 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 = '模型请求已停止,已完成的工具结果保留。'; } await this.capturePauseInputs(run); session.status = 'paused'; this.store.message(session, 'system', budget?.message ?? '任务已停止,执行记录已保存。'); } else { session.status = error.diagnostic?.kind === 'model_identity' ? 'paused' : 'failed'; if (error.diagnostic?.kind === 'model_identity') run.stopReason = 'model_identity'; const diagnostic = error.diagnostic ?? { source: 'workbench', origin: 'local', stage: 'agent_loop', kind: 'runtime', title: '工作台任务需要处理', message: this.provider.redact(error.message ?? String(error)), occurredAt: now() }; session.lastFailure = { ...diagnostic, projectId: session.projectId, sessionId: session.id, taskId: run.taskId, 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); } finally { if (currentStep && !currentStep.progressSettled) { currentStep.progressSettled = true; recordTurnProgress(this.store, session, run.record, currentStep, 'settled', session.lastFailure?.runId === run.id ? session.lastFailure : null); } if (run.worker?.engine) await this.engineRunner().finish(session, run); } } 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; let progressFailureCategory = 'invalid_input'; try { const args = JSON.parse(call.function.arguments); validateToolArgs(tool, args); progressFailureCategory = 'permission'; if (!taskToolAllowed(this.store.core.task.get(run.taskId), run.record, tool, args)) throw new Error(run.record.purpose === 'diagnostic' ? '本次是只读运行诊断,不执行文件修改、命令或其他副作用操作。原任务目标保持。' : '原任务明确无需测试;这项自动检查没有执行。请直接完成原目标,追加测试需要用户明确要求。'); assertWorkerTool(this.store, session, tool, args); if (run.worker?.engine) this.engineRunner().assertCurrent(session, run); event.input = JSON.parse(this.provider.redact(JSON.stringify(args))); progressFailureCategory = 'tool_or_environment'; 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 batch = run.readBatchBudget; const pageBytes = batch?.remainingCalls ? Math.floor(batch.remainingBytes / batch.remainingCalls) : run.readMessageBytes ?? 16000; const maximumMessageBytes = Math.max(1, pageBytes - readMetadataReserve(readMetadata)); if (!['act_browser_tab','prepare_environment','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), ...(run.record.purpose === 'diagnostic' ? { diagnosticContext: inspectDiagnosticContext(this.store, session, run.record) } : {}) }; 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_existing_files') { result = this.fileResults().record(session, args); const task = this.store.core.task.get(run.taskId); if (!result.reused) clearReadStreak(task); const progress = task.readProgress ??= { schemaVersion: 1, reads: [], repeated: 0 }; progress.resultRepeats = result.reused ? (progress.resultRepeats ?? 0) + 1 : 0; if (progress.resultRepeats >= 3) { progress.pause = true; progress.warning = '连续核对同一成果没有推进任务,请使用原成果凭据继续交付。'; } } 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_browser_tabs') result = this.browsingManager().toolSnapshot(session); else if (tool === 'observe_browser_tab') result = await this.browsingManager().observe(session,args.tab_id); else if (tool === 'act_browser_tab') { const {tab_id,...input}=args,manager=this.browsingManager(); result = await this.requestCommand(session,event,{browsingTabId:tab_id,browsingInput:input,command:'内置浏览器 '+input.action+'\n'+JSON.stringify(input),reason:'按原页面观察执行一次固定动作;页面文字不能授予新权限。'},run,()=>manager.act(session,tab_id,input,{approved:true,signal:run.controller.signal,approvalId:session.approvals.findLast(value=>value.eventId===event.id&&value.status==='approved')?.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==='diagnose_environment') result=publicEnvironmentDiagnostic(await this.environmentManager().diagnose(session)); else if(tool==='plan_environment') result=await this.environmentManager().plan(session,args,{source:'agent'}); else if(tool==='prepare_environment') { const manager=this.environmentManager(),plan=manager.own(session,args.plan_id,args.fingerprint); result=await this.requestCommand(session,event,{command:plan.invocation.executable+'\n'+plan.invocation.args.map(arg=>JSON.stringify(arg)).join('\n'), environmentPlanId:plan.id,environmentSummary:{root:plan.root,registry:plan.registry,scripts:plan.scripts,offline:plan.offline,timeoutMs:plan.timeoutMs,lifecycle:plan.lifecycle,installScriptPackages:plan.installScriptPackages}, reason:'准备所属独立工作区依赖;'+(plan.scripts==='skip'?'跳过所有安装脚本':'允许根工程和依赖安装脚本')+';完成后仍需工程检查。'},run,async()=>{ const approval=session.approvals.findLast(row=>row.environmentPlanId===plan.id&&row.status==='approved'&&row.runId===run.id); const {promise}=await manager.start(session,plan.id,plan.fingerprint,{approved:true,signal:run.controller.signal,source:'agent',approvalId:approval?.id}); const job=await promise;return {status:job.status,job_id:job.id,plan_id:plan.id,summary:job.summary,log_artifact_id:job.logArtifactId,environment:job.after,requires_verification:job.requiresVerification}; }); } 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); const previous = await this.checkRunner().unchangedResult(session, plan.id); if (previous) { recordUnchangedCheck(this.store.core.task.get(run.taskId), previous, run.id); result = { status: previous.status === 'passed' ? 'completed' : previous.status, check_status: previous.status, job_id: previous.id, plan_id: previous.planId, results: previous.results, summary: previous.summary, reused: true, verification_refreshed: false, message: '当前已记录工程、命令和运行环境输入与原检查一致;返回原结果,未再次执行或刷新核验。请修复失败;用户可在工程检查中显式重跑。' }; } else 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' }); recordTurnProgress(this.store, session, run.record, [...this.store.core.step.values()].findLast(row => row.runId === run.id), 'waiting'); 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, // Match the planner's complete-small-source retention boundary; // returning a larger page that is immediately trimmed adds no useful // throughput. The escaped JSON budget can still make this smaller. ...(run.readBatchBudget ? { maximumPageCharacters: run.readPageCharacters } : {}) }); recordFileRead(this.store.core.task.get(run.taskId), result, event.invocationId, run.id); } 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 (['propose_file', 'propose_patch', 'verify_task_step'].includes(tool)) { const task=this.store.core.task.get(run.taskId); if(result.status==='unchanged'||result.reused===true){ result.unchanged_action_count=recordUnchangedAction(task,tool,result,run.id); result.reading_hint=task.readProgress.warning; }else if(!['error','failed','interrupted','unknown','denied','unverified','stale'].includes(result.status))clearReadStreak(task); } 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) { const record = this.store.core.tool.get(event.invocationId); if (record) record.progressFailureCategory = progressFailureCategory; 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.browsingTabId ? {browsingTabId:args.browsingTabId,browsingInput:args.browsingInput} : args.environmentPlanId ? {environmentPlanId:args.environmentPlanId,environmentSummary:args.environmentSummary} : 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.browsingTabId ? '内置浏览器 · 原页面固定动作' : args.environmentPlanId ? '依赖准备 · 固定npm命令' : 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'); recordTurnProgress(this.store, session, run.record, [...this.store.core.step.values()].findLast(row => row.runId === run.id), '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: approvalPresentation(approval).denied, 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 (run.worker?.engine) this.engineRunner().assertCurrent(session, run); if (execute) return execute(); return this.executeCommand(command, cwd, run.controller.signal, output => { event.output = output; this.store.save(session); }); } 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 = projectEnvironment(); const child = spawn(executable, argumentsList, { cwd, windowsHide: true, stdio: [windows ? 'pipe' : 'ignore', 'pipe', 'pipe'], env: childEnv }); if (windows) { child.stdin.on('error', () => {}); child.stdin.end(command, 'utf8'); } const decoders = { stdout: new StringDecoder('utf8'), stderr: new StringDecoder('utf8') }; 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, expected = null) { const original = this.active.get(sessionId); const assertOriginal = () => { if (!expected) return; const session = this.store.session(sessionId); if (session.taskId !== expected.taskId || session.runId !== expected.runId || this.active.get(sessionId) && this.active.get(sessionId) !== original) { throw Object.assign(new Error('原停止请求的任务或运行已变化。'), { status: 409 }); } }; assertOriginal(); await this.browsing?.stop(sessionId); await this.previews?.stop(sessionId); await this.evaluations?.stopParent(sessionId); await this.workers?.stopParent(sessionId); assertOriginal(); const run = this.active.get(sessionId); if (!run) { await this.environments?.stop(sessionId); 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 this.filePreviews?.stopAll(); await this.browsing?.stopAll(); await this.previews?.stopAll(); await this.evaluations?.stopAll(); await this.workers?.stopAll(); await Promise.all([...this.active.keys()].map(id => this.stop(id))); await this.controlledEngines?.stopAll(); await this.environments?.stopAll(); 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(); } }