feat(runtime): default to passthrough and persist execution permissions
This commit is contained in:
+105
-44
@@ -1,3 +1,4 @@
|
||||
import { unrestricted, ceiling, openToolDefinitions, automaticApproval } from '../shared/contracts/execution-policy.mjs';
|
||||
import { approvalPresentation } from '../shared/approval-presentation.mjs';
|
||||
import { PreviewManager } from '../core/preview/preview-manager.mjs';
|
||||
import { LocalFilePreviews } from '../core/preview/local-file-preview.mjs';
|
||||
@@ -12,9 +13,10 @@ import { sanitizeModelText } from '../core/models/upstream-error.mjs';
|
||||
import { OUTPUT_TRUNCATED_HINT } from '../core/models/protocols.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 { safePath, listFiles, readLines, searchFiles, proposeFile, proposePatch, applyChange, rollbackChange } from './files.mjs';
|
||||
import { ensureGitBaseline } from '../core/workspaces/git-baseline.mjs';
|
||||
import { proposeFileChunk, discardFileDraft, pendingFileDrafts } from '../core/workspaces/file-proposal-drafts.mjs';
|
||||
import { projectContext, toolDefinitions, researchToolDefinitions, engineToolDefinitions, browserToolDefinitions } from './provider.mjs';
|
||||
import { projectContext, toolDefinitions, automaticToolDefinitions, 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';
|
||||
@@ -88,24 +90,28 @@ labels.propose_file_chunk = '组装长文件提案';
|
||||
labels.discard_file_draft = '放弃未完成文件草稿';
|
||||
labels.read_registered_skill = '读取已登记技能修订';
|
||||
labels.call_registered_mcp = '请求调用已登记MCP工具';
|
||||
labels.rollback_change = '回滚已应用改动';
|
||||
labels.open_browser_tab = '打开浏览器页面';
|
||||
|
||||
export function validateToolArgs(tool, args) {
|
||||
export function validateToolArgs(tool, args, config = {}) {
|
||||
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 === 'read_registered_skill') { skillReadInput(args, config); 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 === 'plan_task') { taskPlanInput(args, config); return; }
|
||||
if (tool === 'rollback_change') { if (typeof args.change_id !== 'string' || Object.keys(args).some(key => key !== 'change_id')) throw new Error('回滚需要当前会话中的改动ID。'); return; }
|
||||
if (tool === 'open_browser_tab') { if (typeof args.url !== 'string' || Object.keys(args).some(key => !['url', 'reason'].includes(key))) throw new Error('打开浏览页面需要网址。'); return; }
|
||||
if (tool === 'verify_existing_files') { fileResultInput(args, { config }); 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 (['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, config); else if(Object.keys(input).length)throw new Error('观察不接受脚本或附加参数。'); return; }
|
||||
if (tool === 'plan_browser') { browserPlanInput(args, config); 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('浏览器结果分页范围无效。');
|
||||
for (const field of ['offset', 'limit']) if (args[field] !== undefined && (!Number.isSafeInteger(args[field]) || args[field] < (field === 'limit' ? 1 : 0) || field === 'limit' && args[field] > Number.MAX_SAFE_INTEGER)) throw new Error('浏览器结果分页范围无效。');
|
||||
return;
|
||||
}
|
||||
if (tool === 'inspect_engine_checks') {
|
||||
@@ -116,12 +122,12 @@ export function validateToolArgs(tool, args) {
|
||||
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字符。');
|
||||
for (const field of ['offset', 'limit']) if (args[field] !== undefined && (!Number.isInteger(args[field]) || args[field] < (field === 'limit' ? 1 : 0) || field === 'limit' && args[field] > Number.MAX_SAFE_INTEGER)) throw new Error('Evidence分页范围无效。');
|
||||
if (args.pointer !== undefined && args.pointer.length > ceiling(config, 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
|
||||
if (!Array.isArray(args.change_ids) || !args.change_ids.length || !unrestricted(config) && 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;
|
||||
@@ -131,13 +137,13 @@ export function validateToolArgs(tool, args) {
|
||||
: 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.limit !== undefined && (args.limit < 1 || args.limit > Number.MAX_SAFE_INTEGER)) 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个替换。');
|
||||
if (tool === 'query_code' && (args.kind !== undefined && !['all', 'symbols', 'imports', 'files'].includes(args.kind) || args.query.length > ceiling(config, 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 || !unrestricted(config) && args.edits.length > 32)) throw new Error('精确补丁需要有效SHA256和1到32个替换。');
|
||||
}
|
||||
|
||||
export class Runtime {
|
||||
@@ -150,7 +156,10 @@ export class Runtime {
|
||||
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') }); }
|
||||
projectIndexer() {
|
||||
if (!this.codeIndex || this.codeIndex.open !== unrestricted(this.store)) this.codeIndex = new ProjectIndex({ executionMode: this.store.config.executionMode, cacheDirectory: path.join(this.store.directory, 'cache', 'project-index') });
|
||||
return this.codeIndex;
|
||||
}
|
||||
fileResults() { return this.results ??= new FileResults(this.store); }
|
||||
async fileDelivery(session) {
|
||||
if (pendingFileDrafts(session).length) return { satisfied: false, stopReason: 'file_draft_incomplete', message: '仍有未完成的分段文件草稿;请继续组装完整提案或显式放弃,片段不能视为交付。' };
|
||||
@@ -257,22 +266,29 @@ export class Runtime {
|
||||
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 });
|
||||
const pendingDelivery = pendingDeliveryReview(this.store, session);
|
||||
if (pendingDelivery && unrestricted(this.store) && pendingDelivery.status === 'planned' && !pendingDelivery.jobId) this.gitDelivery().discardPlan(session, pendingDelivery.id);
|
||||
if (pendingDeliveryReview(this.store, session)) throw Object.assign(new Error('Git操作已有执行记录需要核对,请在任务记录中核对实际结果。'), { status: 409 });
|
||||
if (unrestricted(this.store)) {
|
||||
for (const set of this.store.core.change_set.values()) if (set.sessionId === session.id && set.taskId === session.taskId && set.status === 'prepared' && !set.attemptedAt && !set.requiresVerification) {
|
||||
this.changeSetManager().discard(session, set.id, set.fingerprint);
|
||||
}
|
||||
}
|
||||
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 字符。');
|
||||
if (!resume && (typeof content !== 'string' || !content.trim() || !unrestricted(this.store) && 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});
|
||||
if(!unrestricted(this.store)&&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});
|
||||
if (!unrestricted(config) && 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);
|
||||
@@ -334,13 +350,13 @@ export class Runtime {
|
||||
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) {
|
||||
if (!unrestricted(config) && !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++) {
|
||||
for (let step = 0; config.maxSteps === 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);
|
||||
@@ -361,13 +377,13 @@ export class Runtime {
|
||||
// still contains its original goal for intent and evidence verification.
|
||||
const { goal, ...contract } = taskContract(task);
|
||||
const stablePrefix = config.historyPolicy === 'preserve';
|
||||
const fixedRules = projectContext(run.project, { inventory: false });
|
||||
const fixedRules = projectContext(run.project, { inventory: false, config: run.config });
|
||||
const workerContract = 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提交、外部工具或嵌套协作。',
|
||||
}) : '';
|
||||
const fixedContext = fixedRules + workerContract;
|
||||
const context = this.provider.redact((stablePrefix ? projectContext(run.project).slice(fixedRules.length) : projectContext(run.project) + workerContract) + '\n当前项目/会话/任务身份:' + JSON.stringify({
|
||||
const context = this.provider.redact((stablePrefix ? projectContext(run.project, {config: run.config}).slice(fixedRules.length) : projectContext(run.project, {config: run.config}) + workerContract) + '\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,
|
||||
@@ -395,12 +411,12 @@ export class Runtime {
|
||||
}) : ''));
|
||||
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 : []),
|
||||
const availableTools = [...toolDefinitions, ...(unrestricted(config) ? automaticToolDefinitions : []), ...taskPlanToolDefinitions, ...fileResultToolDefinitions, ...(unrestricted(config) || [...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 tools = openToolDefinitions(availableTools.filter(tool => unrestricted(config) || (!run.worker || WORKER_TOOLS.has(tool.function.name)) && taskToolAllowed(task, run.record, tool.function.name)), config);
|
||||
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: stablePrefix ? this.provider.redact(fixedContext) : context, contextTail: stablePrefix ? context : null, tools, stepId: stepRecord.id, projectMemory, skillCatalog, mcpCatalog,
|
||||
@@ -493,7 +509,7 @@ export class Runtime {
|
||||
// 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) {
|
||||
if (config.capacityMode !== 'passthrough' && 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);
|
||||
@@ -515,15 +531,15 @@ export class Runtime {
|
||||
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项上限;这批工具未执行,原响应和用量已保存。');
|
||||
if (!unrestricted(config) && 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.readStateGrowthTokens ? Infinity : planned.record.budget.inputBudget - planned.record.nextReadFixedInputTokens
|
||||
run.readPageCharacters = unrestricted(config) || planned.record.readStateGrowthTokens ? Infinity : 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);
|
||||
validateToolArgs(call.function.name, args, config);
|
||||
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)));
|
||||
@@ -548,14 +564,14 @@ export class Runtime {
|
||||
session.status = 'paused'; run.stopReason = 'file_draft_incomplete';
|
||||
this.store.message(session, 'system', '仍有未完成的分段文件草稿,片段不能作为完整交付;原片段和续接位置已保存。');
|
||||
}
|
||||
else if (session.status === 'completed' && taskContract(task).kind === 'file') {
|
||||
else if (!unrestricted(config) && 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)
|
||||
else if (!unrestricted(config) && 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', '答复已收到,但当前任务的工程检查尚未通过,不能视为交付完成。原目标与检查结果已保留。');
|
||||
@@ -569,14 +585,14 @@ export class Runtime {
|
||||
this.store.message(session, 'system', '子任务还不能交付:' + this.provider.redact(error.message ?? String(error)) + '。原目标和结果已保存。');
|
||||
}
|
||||
}
|
||||
if (session.status === 'completed' && task.currentTaskPlanId && run.record.purpose !== 'diagnostic') {
|
||||
if (!unrestricted(config) && 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') {
|
||||
if (!unrestricted(config) && 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';
|
||||
@@ -647,7 +663,7 @@ export class Runtime {
|
||||
}
|
||||
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',
|
||||
if (!unrestricted(config) && this.store.core.task.get(run.taskId).readProgress?.pause) throw new BudgetExceeded('no_progress',
|
||||
'模型连续重复读取工件或核对相同的工程状态,未推进当前任务。实际结果和原任务已保存,请核对后继续。');
|
||||
}
|
||||
run.stopReason = 'step_limit';
|
||||
@@ -702,7 +718,7 @@ export class Runtime {
|
||||
let progressFailureCategory = 'invalid_input';
|
||||
try {
|
||||
const args = JSON.parse(call.function.arguments);
|
||||
validateToolArgs(tool, args);
|
||||
validateToolArgs(tool, args, run.config);
|
||||
progressFailureCategory = 'permission';
|
||||
if (!taskToolAllowed(this.store.core.task.get(run.taskId), run.record, tool, args)) throw new Error(run.record.purpose === 'diagnostic'
|
||||
? '本次是只读运行诊断,不执行文件修改、命令或其他副作用操作。原任务目标保持。' : '原任务明确无需测试;这项自动检查没有执行。请直接完成原目标,追加测试需要用户明确要求。');
|
||||
@@ -710,6 +726,7 @@ export class Runtime {
|
||||
if (run.worker?.engine) this.engineRunner().assertCurrent(session, run);
|
||||
event.input = JSON.parse(this.provider.redact(JSON.stringify(args)));
|
||||
progressFailureCategory = 'tool_or_environment';
|
||||
if (unrestricted(run.config) && ['propose_file', 'propose_patch', 'propose_file_chunk', 'prepare_change_set', 'plan_delivery'].includes(tool)) await ensureGitBaseline(this.store, session, { signal: run.controller.signal });
|
||||
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 } : {}) };
|
||||
@@ -798,16 +815,29 @@ export class Runtime {
|
||||
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 === 'open_browser_tab') {
|
||||
result = await this.requestCommand(session, event, { command: '打开浏览器 ' + args.url, reason: args.reason ?? '打开任务需要的页面。' }, run,
|
||||
() => this.browsingManager().open(session, { url: args.url, interact: true, approved: true }));
|
||||
}
|
||||
else if (tool === 'rollback_change') {
|
||||
const change = rollbackChange(this.store, session, args.change_id);
|
||||
result = { status: change.status, change_id: change.id, path: change.path, note: '已恢复原字节;原改动及Git历史保留。' };
|
||||
}
|
||||
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') {
|
||||
if (unrestricted(run.config) && args.change_ids.every(id => session.changes.some(row => row.id === id && row.status === 'applied'))) {
|
||||
result = { status: 'completed', changes: args.change_ids.map(id => { const row = session.changes.find(value => value.id === id); return { change_id: row.id, path: row.path, sha256: row.sha256, status: row.status }; }), note: '这些提案已在开放模式自动应用,未重复写入。' };
|
||||
} else {
|
||||
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: '只封存了整批审查范围,未写入项目。请用户在改动面板审核整个批次并确认应用。' };
|
||||
if (unrestricted(run.config)) { const operation = await this.changeSetManager().start(session, set.id, set.fingerprint, { source: 'agent' }); await operation.promise; session.status = 'running'; result.status = set.status; result.note = set.summary; }
|
||||
}
|
||||
}
|
||||
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'});
|
||||
@@ -828,6 +858,16 @@ export class Runtime {
|
||||
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提交。' };
|
||||
if (unrestricted(run.config)) {
|
||||
const operation = await this.gitDelivery().start(session, plan.id, { source: 'agent' });
|
||||
const abort = () => { this.gitDelivery().stop(session.id, operation.job.id).catch(() => {}); };
|
||||
run.controller.signal.addEventListener('abort', abort, { once: true });
|
||||
if (run.controller.signal.aborted) abort();
|
||||
try {
|
||||
const job = await operation.promise;
|
||||
result = { ...result, status: job.status, job_id: job.id, commit: job.commit, requires_verification: job.requiresVerification, note: job.summary };
|
||||
} finally { run.controller.signal.removeEventListener('abort', abort); }
|
||||
}
|
||||
}
|
||||
else if (tool === 'delivery_report') {
|
||||
const saved = await this.gitDelivery().report(session, { source: 'agent' });
|
||||
@@ -891,6 +931,14 @@ export class Runtime {
|
||||
event.phase = result.status === 'interrupted' ? 'interrupted' : 'failed';
|
||||
event.output = result.message;
|
||||
}
|
||||
if (unrestricted(run.config) && ['propose_file', 'propose_patch', 'propose_file_chunk'].includes(tool)) {
|
||||
const pending = session.changes.filter(change => change.taskId === run.taskId && change.status === 'pending' && !change.changeSetId);
|
||||
for (const change of pending) {
|
||||
try { applyChange(this.store, session, change.id); result = { ...result, status: 'applied', applied: true, message: '改动已自动写入项目,差异、原字节备份和Git基线可核对。' }; session.status = 'running'; }
|
||||
catch (cause) { result = { ...result, status: 'error', message: this.provider.redact(cause.message) }; event.phase = 'failed'; }
|
||||
}
|
||||
}
|
||||
if (unrestricted(run.config)) event.output = this.provider.redact(typeof result.stdout === 'string' ? result.stdout + (result.stderr ? '\n' + result.stderr : '') : JSON.stringify(result));
|
||||
event.finishedAt = now();
|
||||
event.durationMs = Date.parse(event.finishedAt) - Date.parse(event.startedAt);
|
||||
result = JSON.parse(this.provider.redact(JSON.stringify(result)));
|
||||
@@ -899,7 +947,7 @@ export class Runtime {
|
||||
}
|
||||
async requestCommand(session, event, args, run, execute) {
|
||||
const command = String(args.command ?? '').trim();
|
||||
const maximum = args.mcpRegistrationId && execute ? 24000 : 6000;
|
||||
const maximum = unrestricted(run.config) ? Infinity : 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,
|
||||
@@ -911,11 +959,13 @@ export class Runtime {
|
||||
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 policy = automaticApproval(this.store.config, args);
|
||||
approval.approvalMode = policy.mode; approval.policyRevision = this.store.config.configRevision;
|
||||
const decision = policy.approve ? (approval.status = 'approved', approval.decisionSource = policy.source, approval.decidedAt = now(), this.store.save(session), true) : 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 });
|
||||
this.waiters.set(approval.id, { sessionId: session.id, settle, runId: run.id, action: args });
|
||||
signal.addEventListener('abort', cancel, { once: true });
|
||||
if (signal.aborted) cancel();
|
||||
});
|
||||
@@ -926,9 +976,10 @@ export class Runtime {
|
||||
this.store.invocationState(session, event, 'running');
|
||||
if (run.worker?.engine) this.engineRunner().assertCurrent(session, run);
|
||||
if (execute) return execute();
|
||||
if (unrestricted(run.config)) await ensureGitBaseline(this.store, session, { signal: run.controller.signal });
|
||||
return this.executeCommand(command, cwd, run.controller.signal, output => {
|
||||
event.output = output; this.store.save(session);
|
||||
});
|
||||
}, run.config);
|
||||
}
|
||||
decide(sessionId, approvalId, allow) {
|
||||
const session = this.store.session(sessionId);
|
||||
@@ -939,7 +990,17 @@ export class Runtime {
|
||||
approval.status = allow ? 'approved' : 'denied'; approval.decidedAt = now();
|
||||
this.store.save(session); waiter.settle(!!allow);
|
||||
}
|
||||
executeCommand(command, cwd, signal, onOutput) {
|
||||
permissionsChanged() {
|
||||
for (const [approvalId, waiter] of this.waiters) {
|
||||
const policy = automaticApproval(this.store.config, waiter.action);
|
||||
if (!policy.approve) continue;
|
||||
const session = this.store.session(waiter.sessionId), approval = session.approvals.find(row => row.id === approvalId);
|
||||
if (!approval || approval.status !== 'pending') continue;
|
||||
approval.approvalMode = policy.mode; approval.decisionSource = policy.source; approval.policyRevision = this.store.config.configRevision;
|
||||
this.decide(session.id, approvalId, true);
|
||||
}
|
||||
}
|
||||
executeCommand(command, cwd, signal, onOutput, config = this.store.config) {
|
||||
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';
|
||||
@@ -953,8 +1014,8 @@ export class Runtime {
|
||||
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 (!unrestricted(config) && joined.length > 32000) truncated = true;
|
||||
if (kind === 'stdout') stdout = unrestricted(config) ? joined : joined.slice(0, 32000); else stderr = unrestricted(config) ? joined : joined.slice(0, 32000);
|
||||
if (Date.now() - lastUpdate > 250) { lastUpdate = Date.now(); onOutput(stdout + (stderr ? '\n' + stderr : '')); }
|
||||
};
|
||||
const terminate = () => {
|
||||
@@ -970,7 +1031,7 @@ export class Runtime {
|
||||
exit_code: code, stdout, stderr: error ? stderr + '\n' + error.message : stderr,
|
||||
truncated, timed_out: timedOut, command });
|
||||
};
|
||||
const timeout = setTimeout(() => { timedOut = true; terminate(); }, 60000);
|
||||
const timeout = unrestricted(config) ? null : 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)));
|
||||
|
||||
Reference in New Issue
Block a user