minimal-agent 0.18.20 → 0.18.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -3
- package/package.json +1 -1
- package/plugins/cron-runner/README.md +23 -0
- package/plugins/cron-runner/commands/cron.md +7 -1
- package/plugins/cron-runner/plugin.js +9 -2
- package/plugins/cron-runner/plugin.ts +10 -2
- package/plugins/cron-runner/src/commands.js +112 -25
- package/plugins/cron-runner/src/commands.ts +154 -33
- package/plugins/cron-runner/src/contract.js +70 -0
- package/plugins/cron-runner/src/contract.ts +70 -0
- package/plugins/cron-runner/src/requests.js +22 -13
- package/plugins/cron-runner/src/requests.ts +34 -14
- package/plugins/cron-runner/src/runs.js +63 -10
- package/plugins/cron-runner/src/runs.ts +107 -15
- package/plugins/cron-runner/src/scheduler.js +188 -76
- package/plugins/cron-runner/src/scheduler.ts +277 -94
- package/plugins/cron-runner/src/schema.js +52 -17
- package/plugins/cron-runner/src/schema.ts +73 -22
- package/plugins/cron-runner/src/service.js +29 -8
- package/plugins/cron-runner/src/service.ts +71 -18
- package/plugins/cron-runner/src/store.js +92 -30
- package/plugins/cron-runner/src/store.ts +156 -53
- package/plugins/cron-runner/src/transaction.js +24 -0
- package/plugins/cron-runner/src/transaction.ts +36 -0
- package/plugins/cron-runner/src/types.ts +30 -4
- package/plugins/cron-runner/test/lifecycle.test.ts +419 -0
- package/plugins/cron-runner/test/plugin-integration.test.ts +3 -2
- package/plugins/cron-runner/test/reliability.test.ts +2 -2
- package/plugins/cron-runner/test/store-and-scheduler.test.ts +9 -7
- package/plugins/workflow-runner/plugin.js +1 -0
- package/plugins/workflow-runner/plugin.ts +1 -0
- package/plugins/workflow-runner/src/index.js +1 -0
- package/plugins/workflow-runner/src/index.ts +2 -0
- package/plugins/workflow-runner/src/runner.js +6 -1
- package/plugins/workflow-runner/src/runner.ts +5 -1
- package/plugins/workflow-runner/src/types.ts +1 -0
- package/plugins/workflow-runner/test/api.test.ts +1 -0
- package/plugins/workflow-runner/test/apiCapabilities.test.ts +4 -0
- package/plugins/workflow-runner/test/apiConcurrencyGate.test.ts +1 -0
- package/plugins/workflow-runner/test/childWorkflow.test.ts +19 -0
- package/plugins/workflow-runner/test/embeddedExecution.test.ts +23 -3
- package/src/advisor/README.md +17 -6
- package/src/advisor/advisorNudge.js +23 -3
- package/src/advisor/advisorNudge.ts +20 -3
- package/src/advisor/deliveryReview.js +9 -2
- package/src/advisor/deliveryReview.ts +10 -2
- package/src/cli/args.js +1 -0
- package/src/cli/args.ts +1 -0
- package/src/cli/headlessTurn.js +143 -0
- package/src/cli/headlessTurn.ts +187 -0
- package/src/cli/lifecycle.js +52 -0
- package/src/cli/lifecycle.ts +59 -0
- package/src/cli/print.js +91 -240
- package/src/cli/print.ts +99 -301
- package/src/cli/quickModelSetup.js +3 -0
- package/src/cli/quickModelSetup.tsx +3 -0
- package/src/cli/streamJson.js +244 -334
- package/src/cli/streamJson.ts +248 -416
- package/src/cli/wizards/contextAdvisorWizard.js +0 -7
- package/src/cli/wizards/contextAdvisorWizard.tsx +0 -11
- package/src/cli/wizards/providerPresets.js +25 -14
- package/src/cli/wizards/providerPresets.ts +25 -14
- package/src/cli/wizards/providerWizard.js +29 -11
- package/src/cli/wizards/providerWizard.tsx +29 -11
- package/src/config/configDefaults.js +2 -2
- package/src/config/configDefaults.ts +2 -2
- package/src/config/configDiagnostics.js +7 -3
- package/src/config/configDiagnostics.ts +6 -3
- package/src/config/configFile.ts +1 -1
- package/src/context/compact.js +40 -10
- package/src/context/compact.ts +51 -12
- package/src/context/compactResources.js +39 -0
- package/src/context/compactResources.ts +35 -0
- package/src/context/manualCompact.js +20 -0
- package/src/context/manualCompact.ts +28 -0
- package/src/llm/client.js +4 -0
- package/src/llm/client.ts +4 -0
- package/src/llm/messageProvenance.js +1 -1
- package/src/llm/messageProvenance.ts +1 -1
- package/src/loop/README.md +4 -2
- package/src/loop/deliveryIntent.js +3 -2
- package/src/loop/deliveryIntent.ts +4 -2
- package/src/loop/messages.js +1 -0
- package/src/loop/messages.ts +1 -0
- package/src/loop/options.ts +2 -0
- package/src/loop.js +10 -2
- package/src/loop.ts +9 -2
- package/src/main.js +40 -45
- package/src/main.tsx +33 -52
- package/src/plugin-sdk.js +1 -1
- package/src/plugin-sdk.ts +1 -1
- package/src/plugins/artifactDelivery.js +76 -0
- package/src/plugins/artifactDelivery.ts +76 -0
- package/src/plugins/pluginApi.ts +4 -0
- package/src/plugins/pluginRunner.js +2 -0
- package/src/plugins/pluginRunner.ts +3 -0
- package/src/prompts/delegation.js +2 -2
- package/src/prompts/delegation.ts +2 -2
- package/src/prompts/policyRegistry.js +7 -5
- package/src/prompts/policyRegistry.ts +7 -5
- package/src/prompts/promptAssembly.js +2 -2
- package/src/prompts/promptAssembly.ts +2 -2
- package/src/runtime/requestIntent.js +86 -0
- package/src/runtime/requestIntent.ts +66 -0
- package/src/runtime/systemEvents.js +10 -1
- package/src/runtime/systemEvents.ts +9 -1
- package/src/session/commandTranscript.js +76 -0
- package/src/session/commandTranscript.ts +77 -0
- package/src/session/executionOutcome.js +25 -0
- package/src/session/executionOutcome.ts +34 -0
- package/src/session/runAgentTurn.js +8 -1
- package/src/session/runAgentTurn.ts +10 -1
- package/src/session/runTurn.js +40 -15
- package/src/session/runTurn.ts +38 -12
- package/src/session/sessionState.js +7 -2
- package/src/session/sessionState.ts +7 -2
- package/src/team/onlineToolContract.js +1 -0
- package/src/team/onlineToolContract.ts +1 -0
- package/src/tools/advisor/advisor.js +73 -30
- package/src/tools/advisor/advisor.ts +73 -33
- package/src/tools/advisor/advisorCoordination.js +44 -0
- package/src/tools/advisor/advisorCoordination.ts +45 -0
- package/src/tools/advisor/advisorDescription.js +1 -1
- package/src/tools/advisor/advisorDescription.ts +1 -1
- package/src/tools/agent/README.md +2 -0
- package/src/tools/agent/agent.js +7 -3
- package/src/tools/agent/agent.ts +7 -3
- package/src/tools/agent/agentHandoff.js +2 -1
- package/src/tools/agent/agentHandoff.ts +2 -1
- package/src/tools/agent/agentTaskService.js +26 -5
- package/src/tools/agent/agentTaskService.ts +25 -5
- package/src/tools/agent/agentTypes.js +2 -2
- package/src/tools/agent/agentTypes.ts +2 -2
- package/src/tools/agent/baselineAttach.js +14 -7
- package/src/tools/agent/baselineAttach.ts +14 -7
- package/src/tools/applypatch/applyPatch.js +39 -13
- package/src/tools/applypatch/applyPatch.ts +35 -15
- package/src/tools/bash/bash.js +3 -0
- package/src/tools/bash/bash.ts +3 -0
- package/src/tools/capabilities.js +1 -0
- package/src/tools/capabilities.ts +1 -0
- package/src/tools/download/download.js +147 -11
- package/src/tools/download/download.ts +193 -17
- package/src/tools/edit/edit.js +4 -4
- package/src/tools/edit/edit.ts +4 -4
- package/src/tools/edit/multi-edit.js +2 -2
- package/src/tools/edit/multi-edit.ts +2 -2
- package/src/tools/index.js +2 -0
- package/src/tools/index.ts +2 -0
- package/src/tools/powershell/powershell.js +2 -0
- package/src/tools/powershell/powershell.ts +2 -0
- package/src/tools/schedule/schedule.js +184 -0
- package/src/tools/schedule/schedule.ts +214 -0
- package/src/tools/shared/fileUtils.js +16 -6
- package/src/tools/shared/fileUtils.ts +15 -6
- package/src/tools/tasks/backgroundTaskService.js +108 -12
- package/src/tools/tasks/backgroundTaskService.ts +106 -14
- package/src/tools/tasks/taskOutput.js +15 -5
- package/src/tools/tasks/taskOutput.ts +13 -5
- package/src/tools/tasks/taskStop.js +2 -2
- package/src/tools/tasks/taskStop.ts +2 -2
- package/src/tools/toolPromptGuides.js +4 -3
- package/src/tools/toolPromptGuides.ts +4 -3
- package/src/tools/webfetch/webfetch.js +1 -1
- package/src/tools/webfetch/webfetch.ts +1 -1
- package/src/types.ts +6 -0
- package/src/ui/App.js +3 -1
- package/src/ui/App.tsx +2 -0
- package/src/ui/InputBox.js +2 -2
- package/src/ui/InputBox.tsx +2 -2
- package/src/ui/LiveArea.js +6 -1
- package/src/ui/LiveArea.tsx +6 -1
- package/src/ui/MessageList.js +2 -0
- package/src/ui/MessageList.tsx +2 -0
- package/src/ui/README.md +8 -2
- package/src/ui/activityPresentation.js +23 -3
- package/src/ui/activityPresentation.ts +22 -3
- package/src/ui/backgroundWake.js +20 -4
- package/src/ui/backgroundWake.ts +19 -4
- package/src/ui/commandTranscript.js +2 -69
- package/src/ui/commandTranscript.ts +2 -71
- package/src/ui/hooks/useBackgroundAgents.js +33 -0
- package/src/ui/hooks/useBackgroundAgents.ts +36 -0
- package/src/ui/hooks/useChat.js +46 -25
- package/src/ui/hooks/useChat.ts +36 -23
- package/src/web/protocol.ts +5 -2
- package/src/cli/wizards/advisorWizard.js +0 -152
- package/src/cli/wizards/advisorWizard.tsx +0 -203
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { belongsToDelivery } from '../../runtime/deliveryGate.js';
|
|
2
|
+
import { agentNeedsResolution, dependencyReceipt, readAgentLedgerStrict } from '../agent/agentTaskService.js';
|
|
3
|
+
/** Consultation is not delivery: independent criticism can run in parallel.
|
|
4
|
+
* Default to the current delivery's dependencies; early independent criticism
|
|
5
|
+
* is an explicit choice, never an accidental bypass of unfinished handoffs.
|
|
6
|
+
* Return control to the parent instead of blocking a tool while tasks need help. */
|
|
7
|
+
export async function advisorCoordination(input, ctx) {
|
|
8
|
+
const synthesis = input.purpose === 'synthesis' || (input.purpose === undefined && Boolean(ctx?.deliveryId));
|
|
9
|
+
const ids = [...new Set(input.depends_on ?? [])];
|
|
10
|
+
if (!synthesis && !ids.length) {
|
|
11
|
+
const running = [...(ctx?.sessionState?.agentTasks.tasks.values() ?? [])]
|
|
12
|
+
.filter(task => task.status === 'running').length;
|
|
13
|
+
return { ok: true, content: running
|
|
14
|
+
? '本次是独立并行复核,仍有后台子任务未返回;它们的结论未包含在本次材料中,不代表最终汇总验收。'
|
|
15
|
+
: '本次是独立第二意见,不代表主 Agent 已完成子任务验收。' };
|
|
16
|
+
}
|
|
17
|
+
if (!ctx)
|
|
18
|
+
return { ok: false, disposition: 'deferred', error: '依赖子任务的咨询需要会话上下文;请提供宿主上下文,或明确改为 independent 独立复核。' };
|
|
19
|
+
const ledger = await readAgentLedgerStrict(ctx);
|
|
20
|
+
if (ledger.kind === 'unknown')
|
|
21
|
+
return { ok: false, disposition: 'deferred', error: `顾问汇总暂缓:${ledger.reason}。先恢复账本,不假定依赖已完成。` };
|
|
22
|
+
if (synthesis && !ids.length && !ctx.deliveryId)
|
|
23
|
+
return { ok: false, disposition: 'deferred', error: '顾问汇总缺少当前交付标识;请用 depends_on 明确依赖任务,或 independent 做独立复核。' };
|
|
24
|
+
const selected = ids.length
|
|
25
|
+
? ids.map(id => ledger.records.find(task => task.id === id))
|
|
26
|
+
: ledger.records.filter(task => belongsToDelivery(task, ctx.deliveryId) && task.required !== false);
|
|
27
|
+
const pending = selected.flatMap((task, index) => {
|
|
28
|
+
if (!task)
|
|
29
|
+
return [`${ids[index]}:未找到`];
|
|
30
|
+
if (!ids.length && !agentNeedsResolution(task, ledger.records) && task.resolution?.action === 'waive')
|
|
31
|
+
return [];
|
|
32
|
+
if (task.status === 'running' || !dependencyReceipt(task, ctx, 1200))
|
|
33
|
+
return [`${task.id}:${task.status},需要读取报告、核实后 AgentResolve accept/complete`];
|
|
34
|
+
return [];
|
|
35
|
+
});
|
|
36
|
+
if (pending.length)
|
|
37
|
+
return { ok: false, disposition: 'deferred',
|
|
38
|
+
error: `顾问汇总暂缓,尚未发出模型请求:${pending.join(';')}。先 AgentWait/TaskOutput 获取结果;受阻时补充材料或接管。独立复核不依赖这些结论时可用 purpose=independent 且不填 depends_on。` };
|
|
39
|
+
const receipts = selected.flatMap(task => {
|
|
40
|
+
const receipt = task && dependencyReceipt(task, ctx, 1200);
|
|
41
|
+
return receipt ? [receipt] : [];
|
|
42
|
+
});
|
|
43
|
+
return { ok: true, content: `本次汇总的主 Agent 验收记录(不是子任务完整原文;关键证据仍须由主历史或 note 提供):\n${JSON.stringify(receipts)}` };
|
|
44
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { ToolCallContext, ToolResult } from '../../types.js';
|
|
2
|
+
import { belongsToDelivery } from '../../runtime/deliveryGate.js';
|
|
3
|
+
import { agentNeedsResolution, dependencyReceipt, readAgentLedgerStrict } from '../agent/agentTaskService.js';
|
|
4
|
+
|
|
5
|
+
/** Consultation is not delivery: independent criticism can run in parallel.
|
|
6
|
+
* Default to the current delivery's dependencies; early independent criticism
|
|
7
|
+
* is an explicit choice, never an accidental bypass of unfinished handoffs.
|
|
8
|
+
* Return control to the parent instead of blocking a tool while tasks need help. */
|
|
9
|
+
export async function advisorCoordination(
|
|
10
|
+
input: { purpose?: 'independent' | 'synthesis'; depends_on?: string[] },
|
|
11
|
+
ctx?: ToolCallContext,
|
|
12
|
+
): Promise<ToolResult> {
|
|
13
|
+
const synthesis = input.purpose === 'synthesis' || (input.purpose === undefined && Boolean(ctx?.deliveryId));
|
|
14
|
+
const ids = [...new Set(input.depends_on ?? [])];
|
|
15
|
+
if (!synthesis && !ids.length) {
|
|
16
|
+
const running = [...(ctx?.sessionState?.agentTasks.tasks.values() ?? [])]
|
|
17
|
+
.filter(task => task.status === 'running').length;
|
|
18
|
+
return { ok: true, content: running
|
|
19
|
+
? '本次是独立并行复核,仍有后台子任务未返回;它们的结论未包含在本次材料中,不代表最终汇总验收。'
|
|
20
|
+
: '本次是独立第二意见,不代表主 Agent 已完成子任务验收。' };
|
|
21
|
+
}
|
|
22
|
+
if (!ctx) return { ok: false, disposition: 'deferred', error: '依赖子任务的咨询需要会话上下文;请提供宿主上下文,或明确改为 independent 独立复核。' };
|
|
23
|
+
const ledger = await readAgentLedgerStrict(ctx);
|
|
24
|
+
if (ledger.kind === 'unknown')
|
|
25
|
+
return { ok: false, disposition: 'deferred', error: `顾问汇总暂缓:${ledger.reason}。先恢复账本,不假定依赖已完成。` };
|
|
26
|
+
if (synthesis && !ids.length && !ctx.deliveryId)
|
|
27
|
+
return { ok: false, disposition: 'deferred', error: '顾问汇总缺少当前交付标识;请用 depends_on 明确依赖任务,或 independent 做独立复核。' };
|
|
28
|
+
const selected = ids.length
|
|
29
|
+
? ids.map(id => ledger.records.find(task => task.id === id))
|
|
30
|
+
: ledger.records.filter(task => belongsToDelivery(task, ctx.deliveryId!) && task.required !== false);
|
|
31
|
+
const pending = selected.flatMap((task, index) => {
|
|
32
|
+
if (!task) return [`${ids[index]}:未找到`];
|
|
33
|
+
if (!ids.length && !agentNeedsResolution(task, ledger.records) && task.resolution?.action === 'waive') return [];
|
|
34
|
+
if (task.status === 'running' || !dependencyReceipt(task, ctx, 1200))
|
|
35
|
+
return [`${task.id}:${task.status},需要读取报告、核实后 AgentResolve accept/complete`];
|
|
36
|
+
return [];
|
|
37
|
+
});
|
|
38
|
+
if (pending.length) return { ok: false, disposition: 'deferred',
|
|
39
|
+
error: `顾问汇总暂缓,尚未发出模型请求:${pending.join(';')}。先 AgentWait/TaskOutput 获取结果;受阻时补充材料或接管。独立复核不依赖这些结论时可用 purpose=independent 且不填 depends_on。` };
|
|
40
|
+
const receipts = selected.flatMap(task => {
|
|
41
|
+
const receipt = task && dependencyReceipt(task, ctx, 1200);
|
|
42
|
+
return receipt ? [receipt] : [];
|
|
43
|
+
});
|
|
44
|
+
return { ok: true, content: `本次汇总的主 Agent 验收记录(不是子任务完整原文;关键证据仍须由主历史或 note 提供):\n${JSON.stringify(receipts)}` };
|
|
45
|
+
}
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
* 发给模型的 Advisor 工具描述(唯一一份)。
|
|
3
3
|
* 咨询时机、采纳规则住在 policyRegistry 的 capability.advisor;这里只讲工具本身的契约,避免两处各写一遍。
|
|
4
4
|
*/
|
|
5
|
-
export const ADVISOR_TOOL_DESCRIPTION = '
|
|
5
|
+
export const ADVISOR_TOOL_DESCRIPTION = '向顾问模型请求第二意见;容量由顾问模型上下文窗口和最大输出配置决定,没有独立输入配额。默认按当前交付做 synthesis,先获取并验收必要子任务报告,或用 depends_on 指定依赖。未就绪会暂缓,不发模型请求。purpose=independent 须显式选择,仅用于不依赖未返回报告的独立问题,说明已有证据和材料缺口,不用于绕过汇总依赖。必要搜索先做,Advisor 放批末,读意见后再规划后续操作。允许时只读核实工作区文件(不能运行命令或测试)。默认 reviewMode=brief 给重点短评;完整代码审查用 full,note 写范围、基线、证据和待挑战的问题;full 不扩大模型窗口,材料不足须说明未完成。';
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
* 发给模型的 Advisor 工具描述(唯一一份)。
|
|
3
3
|
* 咨询时机、采纳规则住在 policyRegistry 的 capability.advisor;这里只讲工具本身的契约,避免两处各写一遍。
|
|
4
4
|
*/
|
|
5
|
-
export const ADVISOR_TOOL_DESCRIPTION = '
|
|
5
|
+
export const ADVISOR_TOOL_DESCRIPTION = '向顾问模型请求第二意见;容量由顾问模型上下文窗口和最大输出配置决定,没有独立输入配额。默认按当前交付做 synthesis,先获取并验收必要子任务报告,或用 depends_on 指定依赖。未就绪会暂缓,不发模型请求。purpose=independent 须显式选择,仅用于不依赖未返回报告的独立问题,说明已有证据和材料缺口,不用于绕过汇总依赖。必要搜索先做,Advisor 放批末,读意见后再规划后续操作。允许时只读核实工作区文件(不能运行命令或测试)。默认 reviewMode=brief 给重点短评;完整代码审查用 full,note 写范围、基线、证据和待挑战的问题;full 不扩大模型窗口,材料不足须说明未完成。';
|
|
@@ -19,6 +19,8 @@
|
|
|
19
19
|
|
|
20
20
|
`write_scopes` 只限制修改,不限制读取外部模块,worktree 中的路径编辑也遵守显式范围。锁不等于授权,不能通过升级锁扩大任务范围。局部共享目录任务拒绝 Bash/PowerShell,构建验证交给主 Agent;局部范围拒绝无逐路径验证的 ApplyPatch 和 git-clean,使用有路径边界的编辑工具。需要持续并行构建的任务使用 worktree;隔离任务的命令仍不是 OS 沙箱,不能保证任意脚本不越界。
|
|
21
21
|
|
|
22
|
+
不能执行的 Bash/PowerShell/ApplyPatch 同时从该子任务的工具清单去除,运行时权限检查仍保留。`context.verification` 应明确验证责任:分工内未完成事项放 `remaining`,必须 blocked;预先约定的主 Agent 集成验证放 `parentNextSteps`,允许子任务 result,但主 Agent 仍必须验证后 accept,不能据此直接发布最终交付。
|
|
23
|
+
|
|
22
24
|
## 并行写任务
|
|
23
25
|
|
|
24
26
|
1. 主 Agent 确认验收与现有修改,复杂方案先请 Advisor 提第二意见,再记录采纳/拒绝理由。顾问不负责授权,也不要求所有小修改都经过顾问。
|
package/src/tools/agent/agent.js
CHANGED
|
@@ -45,7 +45,7 @@ import { acquireSubagentLease, normalizeWriteScopes } from './coordinator.js';
|
|
|
45
45
|
import { commitWorktreeChanges, createAgentWorktree, hasWorktreeChanges, removeAgentWorktree, worktreeChangedFiles, worktreeDiffStat, withAgentGitSignal, } from './worktree.js';
|
|
46
46
|
import { appendAgentEvent, attachAgentHistory, dependencyReceipt, loadAgentRecord, saveAgentRecord } from './agentTaskService.js';
|
|
47
47
|
import { agentReportTool } from './agentHandoff.js';
|
|
48
|
-
import { BASELINE_UNAVAILABLE, captureGitBaseline, needsChangeBaseline } from './baselineAttach.js';
|
|
48
|
+
import { BASELINE_UNAVAILABLE, baselineRevision, captureGitBaseline, needsChangeBaseline } from './baselineAttach.js';
|
|
49
49
|
import { disposeDetachedSessionState } from '../../session/sessionState.js';
|
|
50
50
|
let corePromise = null;
|
|
51
51
|
/** 首次调用时才真正加载 loop/tools——此刻模块图早已初始化完毕,环安全。 */
|
|
@@ -91,7 +91,7 @@ const inputSchema = z.object({
|
|
|
91
91
|
baseline: z.string().optional(),
|
|
92
92
|
interfaces: z.array(z.string()).max(20).optional(),
|
|
93
93
|
verification: z.array(z.string()).max(20).optional(),
|
|
94
|
-
}).optional().describe('
|
|
94
|
+
}).optional().describe('显式委派上下文包:目标、验收、接口、验证分工、引用和基线。不共享可变主历史。explore 没有 shell/Git;变更审查必须在 summary 提供差异或 references 给出可读 diff 文件,baseline 的 SHA 本身不够。主 Agent 运行测试并提供回执,不要求子任务执行未授权工具。关键事实注明来源和版本。'),
|
|
95
95
|
isolation: z
|
|
96
96
|
.enum(['none', 'worktree'])
|
|
97
97
|
.optional()
|
|
@@ -313,6 +313,9 @@ async function runAgentTaskImpl(input, signal, ctx, deps = {}) {
|
|
|
313
313
|
});
|
|
314
314
|
const subTools = filterToolsForRuntime(delegatedTools.filter((tool) => allowedTools.includes(tool.name)
|
|
315
315
|
&& (def.type !== 'explore' || tool.isReadOnly === true)
|
|
316
|
+
// Do not advertise commands which the write-scope guard cannot execute.
|
|
317
|
+
&& !(def.type === 'general' && !writeScopes.includes(rootScope[0])
|
|
318
|
+
&& (tool.name === 'ApplyPatch' || (!wt && ['Bash', 'PowerShell'].includes(tool.name))))
|
|
316
319
|
// The built-in write-scope adapters know the built-in argument/side-effect
|
|
317
320
|
// contracts. A replacement writer can only inherit a whole-workspace grant.
|
|
318
321
|
&& (writeScopes.includes(rootScope[0]) || tool.isReadOnly === true || ALL_TOOLS.includes(tool))), childRuntime);
|
|
@@ -822,7 +825,7 @@ async function runManagedAgentTaskImpl(input, signal, ctx, deps = {}) {
|
|
|
822
825
|
}
|
|
823
826
|
// 只读审查需要「改动前后」基线却没给:宿主自动附带 git diff HEAD;取不到就在派发前说清,不让子任务白跑。
|
|
824
827
|
if (!input.resume_agent_id && needsChangeBaseline(coreInput)) {
|
|
825
|
-
const baseline = await captureGitBaseline(ctx.sessionState.activeWorktree?.path ?? ctx.cwd ?? getWorkingDir(), signal);
|
|
828
|
+
const baseline = await captureGitBaseline(ctx.sessionState.activeWorktree?.path ?? ctx.cwd ?? getWorkingDir(), signal, baselineRevision(coreInput.context?.baseline) ?? 'HEAD');
|
|
826
829
|
// 取不到也照常派发(关键词只是启发式,可能只是「性能基线」之类的无关用法),
|
|
827
830
|
// 但把限制写进基线,子任务据此在报告里如实说明,而不是凭当前代码断言「新引入」。
|
|
828
831
|
coreInput = { ...coreInput, context: { ...coreInput.context, baseline: baseline ?? BASELINE_UNAVAILABLE } };
|
|
@@ -845,6 +848,7 @@ async function runManagedAgentTaskImpl(input, signal, ctx, deps = {}) {
|
|
|
845
848
|
let settle;
|
|
846
849
|
const completion = new Promise((resolvePromise) => { settle = resolvePromise; });
|
|
847
850
|
const task = {
|
|
851
|
+
background: Boolean(input.run_in_background && ctx.executionServices?.invocationPolicy?.backgroundTasks !== 'wait'),
|
|
848
852
|
provenance: ctx.messageProvenance,
|
|
849
853
|
parentMessageId,
|
|
850
854
|
deliveryId,
|
package/src/tools/agent/agent.ts
CHANGED
|
@@ -65,7 +65,7 @@ import {
|
|
|
65
65
|
} from './worktree.js';
|
|
66
66
|
import { appendAgentEvent, attachAgentHistory, dependencyReceipt, loadAgentRecord, saveAgentRecord, type AgentTaskRecord, type LiveAgentTask } from './agentTaskService.js';
|
|
67
67
|
import { agentReportTool } from './agentHandoff.js';
|
|
68
|
-
import { BASELINE_UNAVAILABLE, captureGitBaseline, needsChangeBaseline } from './baselineAttach.js';
|
|
68
|
+
import { BASELINE_UNAVAILABLE, baselineRevision, captureGitBaseline, needsChangeBaseline } from './baselineAttach.js';
|
|
69
69
|
import { disposeDetachedSessionState } from '../../session/sessionState.js';
|
|
70
70
|
|
|
71
71
|
// ---------------- 0. 环内模块懒加载(见文件头「循环依赖纪律」) ----------------
|
|
@@ -129,7 +129,7 @@ const inputSchema = z.object({
|
|
|
129
129
|
baseline: z.string().optional(),
|
|
130
130
|
interfaces: z.array(z.string()).max(20).optional(),
|
|
131
131
|
verification: z.array(z.string()).max(20).optional(),
|
|
132
|
-
}).optional().describe('
|
|
132
|
+
}).optional().describe('显式委派上下文包:目标、验收、接口、验证分工、引用和基线。不共享可变主历史。explore 没有 shell/Git;变更审查必须在 summary 提供差异或 references 给出可读 diff 文件,baseline 的 SHA 本身不够。主 Agent 运行测试并提供回执,不要求子任务执行未授权工具。关键事实注明来源和版本。'),
|
|
133
133
|
isolation: z
|
|
134
134
|
.enum(['none', 'worktree'])
|
|
135
135
|
.optional()
|
|
@@ -391,6 +391,9 @@ async function runAgentTaskImpl(
|
|
|
391
391
|
const subTools = filterToolsForRuntime(
|
|
392
392
|
delegatedTools.filter((tool) => allowedTools.includes(tool.name)
|
|
393
393
|
&& (def.type !== 'explore' || tool.isReadOnly === true)
|
|
394
|
+
// Do not advertise commands which the write-scope guard cannot execute.
|
|
395
|
+
&& !(def.type === 'general' && !writeScopes.includes(rootScope[0]!)
|
|
396
|
+
&& (tool.name === 'ApplyPatch' || (!wt && ['Bash', 'PowerShell'].includes(tool.name))))
|
|
394
397
|
// The built-in write-scope adapters know the built-in argument/side-effect
|
|
395
398
|
// contracts. A replacement writer can only inherit a whole-workspace grant.
|
|
396
399
|
&& (writeScopes.includes(rootScope[0]!) || tool.isReadOnly === true || ALL_TOOLS.includes(tool))),
|
|
@@ -892,7 +895,7 @@ async function runManagedAgentTaskImpl(
|
|
|
892
895
|
}
|
|
893
896
|
// 只读审查需要「改动前后」基线却没给:宿主自动附带 git diff HEAD;取不到就在派发前说清,不让子任务白跑。
|
|
894
897
|
if (!input.resume_agent_id && needsChangeBaseline(coreInput)) {
|
|
895
|
-
const baseline = await captureGitBaseline(ctx.sessionState.activeWorktree?.path ?? ctx.cwd ?? getWorkingDir(), signal);
|
|
898
|
+
const baseline = await captureGitBaseline(ctx.sessionState.activeWorktree?.path ?? ctx.cwd ?? getWorkingDir(), signal, baselineRevision(coreInput.context?.baseline) ?? 'HEAD');
|
|
896
899
|
// 取不到也照常派发(关键词只是启发式,可能只是「性能基线」之类的无关用法),
|
|
897
900
|
// 但把限制写进基线,子任务据此在报告里如实说明,而不是凭当前代码断言「新引入」。
|
|
898
901
|
coreInput = { ...coreInput, context: { ...coreInput.context, baseline: baseline ?? BASELINE_UNAVAILABLE } };
|
|
@@ -913,6 +916,7 @@ async function runManagedAgentTaskImpl(
|
|
|
913
916
|
let settle!: () => void;
|
|
914
917
|
const completion = new Promise<void>((resolvePromise) => { settle = resolvePromise; });
|
|
915
918
|
const task: LiveAgentTask = {
|
|
919
|
+
background: Boolean(input.run_in_background && ctx.executionServices?.invocationPolicy?.backgroundTasks !== 'wait'),
|
|
916
920
|
provenance: ctx.messageProvenance,
|
|
917
921
|
parentMessageId,
|
|
918
922
|
deliveryId,
|
|
@@ -11,6 +11,7 @@ const reportSchema = z.object({
|
|
|
11
11
|
completed: lines,
|
|
12
12
|
attempted: lines,
|
|
13
13
|
remaining: lines,
|
|
14
|
+
parentNextSteps: lines.optional().describe('任务书预先约定由主 Agent 执行的集成、组合验证;不计为子任务未完成。不得用它转移自己未完成的必要工作。'),
|
|
14
15
|
needed: z.string().min(1).max(2000).optional(),
|
|
15
16
|
evidenceRefs: z.array(z.string().min(1).max(200)).max(40),
|
|
16
17
|
findings: z.array(researchFindingSchema).max(24).optional(),
|
|
@@ -79,7 +80,7 @@ export function writeReviewEvidenceError(history, createdAt, refs, executed) {
|
|
|
79
80
|
export const agentReportTool = {
|
|
80
81
|
get promptGuide() { return BUILTIN_TOOL_PROMPT_GUIDES.AgentReport; }, // private channel; not in ALL_TOOLS
|
|
81
82
|
name: 'AgentReport', inputSchema: reportSchema, parameters: toToolParameters(reportSchema),
|
|
82
|
-
description: '向主 Agent 交接。help=求助但继续独立工作;blocked=交回现场并停止本次执行;result
|
|
83
|
+
description: '向主 Agent 交接。help=求助但继续独立工作;blocked=交回现场并停止本次执行;result=本次分工完成并停止,不等于主任务验收。本工具不询问用户、不授予权限。remaining 是自己未完成的必要工作,parentNextSteps 只放任务书预定的主 Agent 集成验证。填写完成项、尝试和真实子工具证据 ID。',
|
|
83
84
|
isReadOnly: true, isConcurrencySafe: false,
|
|
84
85
|
call: async () => ({ ok: false, error: 'AgentReport requires a parent channel' }),
|
|
85
86
|
callWithContext: async (input, _signal, ctx) => {
|
|
@@ -13,6 +13,7 @@ const reportSchema = z.object({
|
|
|
13
13
|
completed: lines,
|
|
14
14
|
attempted: lines,
|
|
15
15
|
remaining: lines,
|
|
16
|
+
parentNextSteps: lines.optional().describe('任务书预先约定由主 Agent 执行的集成、组合验证;不计为子任务未完成。不得用它转移自己未完成的必要工作。'),
|
|
16
17
|
needed: z.string().min(1).max(2000).optional(),
|
|
17
18
|
evidenceRefs: z.array(z.string().min(1).max(200)).max(40),
|
|
18
19
|
findings: z.array(researchFindingSchema).max(24).optional(),
|
|
@@ -79,7 +80,7 @@ export function writeReviewEvidenceError(
|
|
|
79
80
|
export const agentReportTool: Tool<z.infer<typeof reportSchema>> = {
|
|
80
81
|
get promptGuide() { return BUILTIN_TOOL_PROMPT_GUIDES.AgentReport; }, // private channel; not in ALL_TOOLS
|
|
81
82
|
name: 'AgentReport', inputSchema: reportSchema, parameters: toToolParameters(reportSchema),
|
|
82
|
-
description: '向主 Agent 交接。help=求助但继续独立工作;blocked=交回现场并停止本次执行;result
|
|
83
|
+
description: '向主 Agent 交接。help=求助但继续独立工作;blocked=交回现场并停止本次执行;result=本次分工完成并停止,不等于主任务验收。本工具不询问用户、不授予权限。remaining 是自己未完成的必要工作,parentNextSteps 只放任务书预定的主 Agent 集成验证。填写完成项、尝试和真实子工具证据 ID。',
|
|
83
84
|
isReadOnly: true, isConcurrencySafe: false,
|
|
84
85
|
call: async () => ({ ok: false, error: 'AgentReport requires a parent channel' }),
|
|
85
86
|
callWithContext: async (input, _signal, ctx) => {
|
|
@@ -233,10 +233,18 @@ export function attachAgentHistory(task, history) {
|
|
|
233
233
|
export async function stopAllAgentTasks(state) {
|
|
234
234
|
const running = [...state.tasks.values()].filter((t) => t.status === 'running');
|
|
235
235
|
running.forEach((t) => t.abort.abort());
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
236
|
+
if (running.length) {
|
|
237
|
+
let timer;
|
|
238
|
+
try {
|
|
239
|
+
await Promise.race([
|
|
240
|
+
Promise.allSettled(running.map((t) => t.completion)),
|
|
241
|
+
new Promise((resolve) => { timer = setTimeout(resolve, 5000); }),
|
|
242
|
+
]);
|
|
243
|
+
}
|
|
244
|
+
finally {
|
|
245
|
+
clearTimeout(timer);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
240
248
|
for (const [id, task] of state.tasks)
|
|
241
249
|
if (task.status !== 'running')
|
|
242
250
|
state.tasks.delete(id);
|
|
@@ -264,8 +272,20 @@ export async function takeAgentNotifications(ctx) {
|
|
|
264
272
|
const key = `${task.id}:${task.attemptId ?? task.createdAt}`;
|
|
265
273
|
if (!delivered.has(`agent-notice:${key}`)) {
|
|
266
274
|
const result = task.result;
|
|
275
|
+
const target = task.deliveryId ?? task.parentMessageId;
|
|
276
|
+
const origin = target && ctx.deliveryId ? target === ctx.deliveryId ? '当前目标' : '先前目标' : '来源待确认';
|
|
277
|
+
const date = new Date(task.createdAt);
|
|
278
|
+
const time = Number.isFinite(date.getTime()) ? date.toISOString() : '时间未知';
|
|
279
|
+
// Prefer a bounded, valid handoff object to slicing JSON in half. The
|
|
280
|
+
// complete report/evidence remains in TaskOutput and the durable ledger.
|
|
281
|
+
const handoff = task.handoff;
|
|
282
|
+
const report = handoff ? JSON.stringify({
|
|
283
|
+
kind: handoff.kind, summary: handoff.summary.slice(0, 1200),
|
|
284
|
+
needed: handoff.needed?.slice(0, 500),
|
|
285
|
+
parentNextSteps: handoff.parentNextSteps?.slice(0, 3).map(step => step.slice(0, 200)),
|
|
286
|
+
}) : (result?.ok ? result.content : result?.error ?? '').slice(0, 3000);
|
|
267
287
|
messages.push({ role: 'user', timestamp: Date.now(), id: `agent-notice:${key}`,
|
|
268
|
-
content: `[子 Agent 完成通知]\n子任务 ${task.id} (${task.description}) 已${task.status}。\n
|
|
288
|
+
content: `[子 Agent 完成通知]\n子任务 ${task.id} (${task.description}) 已${task.status}。\n来源:${origin} · 派发于 ${time}\n${report}\n完整现场用 TaskOutput 获取;这是状态通知,不是新派发或验收。先前目标不要默默混入当前交付;失败或未完成时请决定续接、重分配或亲自接管,不把缺口当作已完成。` });
|
|
269
289
|
}
|
|
270
290
|
// Only consume in memory. A crash before the parent transcript is saved
|
|
271
291
|
// leaves the durable outbox pending, so the next process can deliver it.
|
|
@@ -346,6 +366,7 @@ export async function agentCoordinationContext(ctx) {
|
|
|
346
366
|
handoff: r.handoff ? {
|
|
347
367
|
kind: r.handoff.kind, summary: r.handoff.summary.slice(0, 600),
|
|
348
368
|
needed: r.handoff.needed?.slice(0, 400), remaining: r.handoff.remaining.slice(0, 4).map((s) => s.slice(0, 200)),
|
|
369
|
+
parentNextSteps: r.handoff.parentNextSteps?.slice(0, 4).map(s => s.slice(0, 200)),
|
|
349
370
|
} : undefined,
|
|
350
371
|
result: !r.handoff && r.result ? (r.result.ok ? r.result.content : r.result.error).slice(0, 500) : undefined,
|
|
351
372
|
}));
|
|
@@ -43,6 +43,8 @@ export interface AgentTaskRecord {
|
|
|
43
43
|
notificationPending?: boolean;
|
|
44
44
|
}
|
|
45
45
|
export interface LiveAgentTask extends AgentTaskRecord {
|
|
46
|
+
/** Host execution mode, separate from the normalized child input. */
|
|
47
|
+
background?: boolean;
|
|
46
48
|
abort: AbortController;
|
|
47
49
|
completion: Promise<void>;
|
|
48
50
|
events: EventEmitter;
|
|
@@ -314,10 +316,15 @@ export async function stopAllAgentTasks(state: AgentTaskState): Promise<void> {
|
|
|
314
316
|
(t) => t.status === 'running',
|
|
315
317
|
);
|
|
316
318
|
running.forEach((t) => t.abort.abort());
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
319
|
+
if (running.length) {
|
|
320
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
321
|
+
try {
|
|
322
|
+
await Promise.race([
|
|
323
|
+
Promise.allSettled(running.map((t) => t.completion)),
|
|
324
|
+
new Promise<void>((resolve) => { timer = setTimeout(resolve, 5000); }),
|
|
325
|
+
]);
|
|
326
|
+
} finally { clearTimeout(timer); }
|
|
327
|
+
}
|
|
321
328
|
for (const [id, task] of state.tasks) if (task.status !== 'running') state.tasks.delete(id);
|
|
322
329
|
}
|
|
323
330
|
|
|
@@ -341,8 +348,20 @@ export async function takeAgentNotifications(ctx: ToolCallContext): Promise<Mess
|
|
|
341
348
|
const key = `${task.id}:${task.attemptId ?? task.createdAt}`;
|
|
342
349
|
if (!delivered.has(`agent-notice:${key}`)) {
|
|
343
350
|
const result = task.result;
|
|
351
|
+
const target = task.deliveryId ?? task.parentMessageId;
|
|
352
|
+
const origin = target && ctx.deliveryId ? target === ctx.deliveryId ? '当前目标' : '先前目标' : '来源待确认';
|
|
353
|
+
const date = new Date(task.createdAt);
|
|
354
|
+
const time = Number.isFinite(date.getTime()) ? date.toISOString() : '时间未知';
|
|
355
|
+
// Prefer a bounded, valid handoff object to slicing JSON in half. The
|
|
356
|
+
// complete report/evidence remains in TaskOutput and the durable ledger.
|
|
357
|
+
const handoff = task.handoff;
|
|
358
|
+
const report = handoff ? JSON.stringify({
|
|
359
|
+
kind: handoff.kind, summary: handoff.summary.slice(0, 1200),
|
|
360
|
+
needed: handoff.needed?.slice(0, 500),
|
|
361
|
+
parentNextSteps: handoff.parentNextSteps?.slice(0, 3).map(step => step.slice(0, 200)),
|
|
362
|
+
}) : (result?.ok ? result.content : result?.error ?? '').slice(0, 3000);
|
|
344
363
|
messages.push({ role: 'user', timestamp: Date.now(), id: `agent-notice:${key}`,
|
|
345
|
-
content: `[子 Agent 完成通知]\n子任务 ${task.id} (${task.description}) 已${task.status}。\n
|
|
364
|
+
content: `[子 Agent 完成通知]\n子任务 ${task.id} (${task.description}) 已${task.status}。\n来源:${origin} · 派发于 ${time}\n${report}\n完整现场用 TaskOutput 获取;这是状态通知,不是新派发或验收。先前目标不要默默混入当前交付;失败或未完成时请决定续接、重分配或亲自接管,不把缺口当作已完成。` });
|
|
346
365
|
}
|
|
347
366
|
// Only consume in memory. A crash before the parent transcript is saved
|
|
348
367
|
// leaves the durable outbox pending, so the next process can deliver it.
|
|
@@ -428,6 +447,7 @@ export async function agentCoordinationContext(ctx: ToolCallContext): Promise<{
|
|
|
428
447
|
handoff: r.handoff ? {
|
|
429
448
|
kind: r.handoff.kind, summary: r.handoff.summary.slice(0, 600),
|
|
430
449
|
needed: r.handoff.needed?.slice(0, 400), remaining: r.handoff.remaining.slice(0, 4).map((s) => s.slice(0, 200)),
|
|
450
|
+
parentNextSteps: r.handoff.parentNextSteps?.slice(0, 4).map(s => s.slice(0, 200)),
|
|
431
451
|
} : undefined,
|
|
432
452
|
result: !r.handoff && r.result ? (r.result.ok ? r.result.content : r.result.error).slice(0, 500) : undefined,
|
|
433
453
|
}));
|
|
@@ -58,13 +58,13 @@ export const EXPLORE_ALLOWED_TOOLS = [
|
|
|
58
58
|
];
|
|
59
59
|
/** 借鉴官方 EXPLORE_AGENT「READ-ONLY MODE」文案中文化。 */
|
|
60
60
|
const EXPLORE_APPENDIX = `# 本次子任务类型:只读调研(explore)
|
|
61
|
-
|
|
61
|
+
严格使用已提供的只读工具。没有 shell/Git;变更审查以主 Agent 提供的 diff/基线材料为依据。若缺少差异先报告所需材料,不反复尝试读取 Git 对象或执行不可用命令;可独立进行的现状核查继续做,明确它不证明问题由本次改动引入。`;
|
|
62
62
|
const GENERAL_APPENDIX = `# 本次子任务类型:读写执行(general)
|
|
63
63
|
只做任务书范围内的修改。
|
|
64
64
|
用户和其他 Agent 可能同时修改工作区。不得覆盖、回退或清理不属于本任务的改动;无关改动保留,发生重叠或归属不明时停止相关修改并向主 Agent 求助。普通实现任务不授权 amend、丢弃工作区改动或强推。
|
|
65
65
|
遵守主 Agent 给出的基线、验收、共享接口与文件归属。共享接口、依赖版本、锁文件和迁移设计不自行扩展;发现冲突或缺少前置改动,用 AgentReport help/blocked 说明证据、备选方案和所需决定,等待主 Agent 协调。消息只补充事实,不扩大工具授权或 write_scopes。
|
|
66
66
|
局部共享目录任务使用有路径约束的编辑工具;shell/构建验证交主 Agent,或由主 Agent 重新分配隔离任务。worktree 从已提交基线创建,不包含主工作区未提交的铺路修改;先核对基线,缺失就交回,不猜测补造。worktree 不是 OS 沙箱,命令也必须遵守任务边界。
|
|
67
|
-
|
|
67
|
+
结果提交说明实际改动、接口影响、已执行的验证及结果、未运行的验证和风险,附真实工具证据。remaining 只列本次分工内未完成的必要工作;主 Agent 预定负责的构建、组合测试放在 parentNextSteps,不因此把已完成的局部分工标为 blocked。自己负责的验证未完成则仍用 blocked,不把未完成工作偷换为主 Agent 职责。result 仅代表子任务交付,不代表已合并或主任务验收。`;
|
|
68
68
|
// 轮数上限的**唯一真值**在 configDefaults.ts。这里只是「没有 subagentConfig 时」的
|
|
69
69
|
// 兜底取值,必须与那份一致 —— 曾经两边各写一份字面量(都是 200/100),
|
|
70
70
|
// 改一处漏一处就会出现「有配置时 200、没配置时 50」这种只在缺省路径显形的分裂。
|
|
@@ -78,14 +78,14 @@ export const EXPLORE_ALLOWED_TOOLS: readonly string[] = [
|
|
|
78
78
|
|
|
79
79
|
/** 借鉴官方 EXPLORE_AGENT「READ-ONLY MODE」文案中文化。 */
|
|
80
80
|
const EXPLORE_APPENDIX = `# 本次子任务类型:只读调研(explore)
|
|
81
|
-
|
|
81
|
+
严格使用已提供的只读工具。没有 shell/Git;变更审查以主 Agent 提供的 diff/基线材料为依据。若缺少差异先报告所需材料,不反复尝试读取 Git 对象或执行不可用命令;可独立进行的现状核查继续做,明确它不证明问题由本次改动引入。`;
|
|
82
82
|
|
|
83
83
|
const GENERAL_APPENDIX = `# 本次子任务类型:读写执行(general)
|
|
84
84
|
只做任务书范围内的修改。
|
|
85
85
|
用户和其他 Agent 可能同时修改工作区。不得覆盖、回退或清理不属于本任务的改动;无关改动保留,发生重叠或归属不明时停止相关修改并向主 Agent 求助。普通实现任务不授权 amend、丢弃工作区改动或强推。
|
|
86
86
|
遵守主 Agent 给出的基线、验收、共享接口与文件归属。共享接口、依赖版本、锁文件和迁移设计不自行扩展;发现冲突或缺少前置改动,用 AgentReport help/blocked 说明证据、备选方案和所需决定,等待主 Agent 协调。消息只补充事实,不扩大工具授权或 write_scopes。
|
|
87
87
|
局部共享目录任务使用有路径约束的编辑工具;shell/构建验证交主 Agent,或由主 Agent 重新分配隔离任务。worktree 从已提交基线创建,不包含主工作区未提交的铺路修改;先核对基线,缺失就交回,不猜测补造。worktree 不是 OS 沙箱,命令也必须遵守任务边界。
|
|
88
|
-
|
|
88
|
+
结果提交说明实际改动、接口影响、已执行的验证及结果、未运行的验证和风险,附真实工具证据。remaining 只列本次分工内未完成的必要工作;主 Agent 预定负责的构建、组合测试放在 parentNextSteps,不因此把已完成的局部分工标为 blocked。自己负责的验证未完成则仍用 blocked,不把未完成工作偷换为主 Agent 职责。result 仅代表子任务交付,不代表已合并或主任务验收。`;
|
|
89
89
|
|
|
90
90
|
// 轮数上限的**唯一真值**在 configDefaults.ts。这里只是「没有 subagentConfig 时」的
|
|
91
91
|
// 兜底取值,必须与那份一致 —— 曾经两边各写一份字面量(都是 200/100),
|
|
@@ -10,12 +10,17 @@ import { safeSlice } from '../../utils/safeText.js';
|
|
|
10
10
|
* (含未跟踪文件清单)放进委派上下文;取不到就在派发前明确报错,而不是让子任务白跑。
|
|
11
11
|
*/
|
|
12
12
|
const NEEDS_BASELINE = /新引入|是否(?:由|为).{0,12}(?:变更|改动|提交|修改)(?:引入|造成|导致)|引入了?(?:回归|缺陷|问题)|回归(?:缺陷|问题)|基线|baseline|git\s+diff|(?:对比|比较|比对).{0,16}(?:HEAD|工作区|基线|改动前)|(?:HEAD|基线).{0,16}(?:对比|比较|比对)|\bregression\b|newly introduced|introduced by/i;
|
|
13
|
+
/** A revision is a pointer, not readable evidence. Never accept Git options here. */
|
|
14
|
+
export function baselineRevision(value) {
|
|
15
|
+
const match = /^(?:HEAD\s*[:=]\s*)?([0-9a-f]{7,40}|HEAD(?:[~^]\d*)?)$/i.exec(value?.trim() ?? '');
|
|
16
|
+
return match?.[1];
|
|
17
|
+
}
|
|
13
18
|
/** 只读子任务的任务书是否需要「改动前后」基线,且调用方没有提供。 */
|
|
14
19
|
export function needsChangeBaseline(input) {
|
|
15
20
|
if (input.agent_type === 'general')
|
|
16
21
|
return false;
|
|
17
22
|
if (input.context?.baseline?.trim())
|
|
18
|
-
return
|
|
23
|
+
return baselineRevision(input.context.baseline) !== undefined;
|
|
19
24
|
const text = [
|
|
20
25
|
input.prompt,
|
|
21
26
|
input.description ?? '',
|
|
@@ -49,21 +54,23 @@ async function git(args, cwd, signal) {
|
|
|
49
54
|
* 取 `HEAD → 工作区` 的差异作为基线文本;不是 git 仓库、没有提交或 git 不可用时返回 undefined。
|
|
50
55
|
* 无改动也是有效基线(明确告诉子任务「工作区与 HEAD 一致」)。
|
|
51
56
|
*/
|
|
52
|
-
export async function captureGitBaseline(cwd, signal) {
|
|
53
|
-
|
|
57
|
+
export async function captureGitBaseline(cwd, signal, revision = 'HEAD') {
|
|
58
|
+
if (!baselineRevision(revision))
|
|
59
|
+
return undefined;
|
|
60
|
+
const head = (await git(['rev-parse', '--verify', `${revision}^{commit}`], cwd, signal))?.trim();
|
|
54
61
|
if (!head)
|
|
55
62
|
return undefined;
|
|
56
63
|
const status = await git(['-c', 'status.relativePaths=true', '-c', 'color.status=false', 'status', '--short', '--untracked-files=all', '--', '.'], cwd, signal);
|
|
57
|
-
const diffArgs = ['diff', '--relative', '--no-renames', '--no-ext-diff', '--no-textconv',
|
|
64
|
+
const diffArgs = ['diff', '--relative', '--no-renames', '--no-ext-diff', '--no-textconv', head];
|
|
58
65
|
const stat = await git([...diffArgs, '--stat', '--', '.'], cwd, signal);
|
|
59
66
|
const diff = await git([...diffArgs, '--no-color', '--', '.'], cwd, signal);
|
|
60
67
|
if (status === undefined || stat === undefined || diff === undefined)
|
|
61
68
|
return undefined;
|
|
62
69
|
const untracked = status.split('\n').filter((line) => line.startsWith('??')).map((line) => line.slice(3).trim());
|
|
63
|
-
const header = `[宿主自动附带的基线:git diff
|
|
64
|
-
+ '修改前的内容在 `-`
|
|
70
|
+
const header = `[宿主自动附带的基线:git diff ${revision}(基线提交=${head});子任务不能运行 git,请以此为「改动前」依据。`
|
|
71
|
+
+ '修改前的内容在 `-` 行与基线提交,修改后在 `+` 行与工作区。]';
|
|
65
72
|
const parts = [header];
|
|
66
|
-
parts.push(status.trim() ? `文件状态:\n${status.trim()}` : '
|
|
73
|
+
parts.push(status.trim() ? `文件状态:\n${status.trim()}` : diff.trim() ? '工作区没有未提交改动;下方为相对指定基线的已提交差异。' : `工作区与 ${revision} 一致,没有未提交改动。`);
|
|
67
74
|
if (untracked.length)
|
|
68
75
|
parts.push(`未跟踪的新文件(不在 diff 里,请直接 Read):${untracked.join('、')}`);
|
|
69
76
|
if (stat.trim())
|
|
@@ -20,10 +20,16 @@ export interface BaselineCheckInput {
|
|
|
20
20
|
context?: { baseline?: string; researchQuestions?: unknown; goal?: string; acceptance?: string };
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
+
/** A revision is a pointer, not readable evidence. Never accept Git options here. */
|
|
24
|
+
export function baselineRevision(value?: string): string | undefined {
|
|
25
|
+
const match = /^(?:HEAD\s*[:=]\s*)?([0-9a-f]{7,40}|HEAD(?:[~^]\d*)?)$/i.exec(value?.trim() ?? '');
|
|
26
|
+
return match?.[1];
|
|
27
|
+
}
|
|
28
|
+
|
|
23
29
|
/** 只读子任务的任务书是否需要「改动前后」基线,且调用方没有提供。 */
|
|
24
30
|
export function needsChangeBaseline(input: BaselineCheckInput): boolean {
|
|
25
31
|
if (input.agent_type === 'general') return false;
|
|
26
|
-
if (input.context?.baseline?.trim()) return
|
|
32
|
+
if (input.context?.baseline?.trim()) return baselineRevision(input.context.baseline) !== undefined;
|
|
27
33
|
const text = [
|
|
28
34
|
input.prompt,
|
|
29
35
|
input.description ?? '',
|
|
@@ -61,19 +67,20 @@ async function git(args: string[], cwd: string, signal?: AbortSignal): Promise<s
|
|
|
61
67
|
* 取 `HEAD → 工作区` 的差异作为基线文本;不是 git 仓库、没有提交或 git 不可用时返回 undefined。
|
|
62
68
|
* 无改动也是有效基线(明确告诉子任务「工作区与 HEAD 一致」)。
|
|
63
69
|
*/
|
|
64
|
-
export async function captureGitBaseline(cwd: string, signal?: AbortSignal): Promise<string | undefined> {
|
|
65
|
-
|
|
70
|
+
export async function captureGitBaseline(cwd: string, signal?: AbortSignal, revision = 'HEAD'): Promise<string | undefined> {
|
|
71
|
+
if (!baselineRevision(revision)) return undefined;
|
|
72
|
+
const head = (await git(['rev-parse', '--verify', `${revision}^{commit}`], cwd, signal))?.trim();
|
|
66
73
|
if (!head) return undefined;
|
|
67
74
|
const status = await git(['-c', 'status.relativePaths=true', '-c', 'color.status=false', 'status', '--short', '--untracked-files=all', '--', '.'], cwd, signal);
|
|
68
|
-
const diffArgs = ['diff', '--relative', '--no-renames', '--no-ext-diff', '--no-textconv',
|
|
75
|
+
const diffArgs = ['diff', '--relative', '--no-renames', '--no-ext-diff', '--no-textconv', head];
|
|
69
76
|
const stat = await git([...diffArgs, '--stat', '--', '.'], cwd, signal);
|
|
70
77
|
const diff = await git([...diffArgs, '--no-color', '--', '.'], cwd, signal);
|
|
71
78
|
if (status === undefined || stat === undefined || diff === undefined) return undefined;
|
|
72
79
|
const untracked = status.split('\n').filter((line) => line.startsWith('??')).map((line) => line.slice(3).trim());
|
|
73
|
-
const header = `[宿主自动附带的基线:git diff
|
|
74
|
-
+ '修改前的内容在 `-`
|
|
80
|
+
const header = `[宿主自动附带的基线:git diff ${revision}(基线提交=${head});子任务不能运行 git,请以此为「改动前」依据。`
|
|
81
|
+
+ '修改前的内容在 `-` 行与基线提交,修改后在 `+` 行与工作区。]';
|
|
75
82
|
const parts = [header];
|
|
76
|
-
parts.push(status.trim() ? `文件状态:\n${status.trim()}` : '
|
|
83
|
+
parts.push(status.trim() ? `文件状态:\n${status.trim()}` : diff.trim() ? '工作区没有未提交改动;下方为相对指定基线的已提交差异。' : `工作区与 ${revision} 一致,没有未提交改动。`);
|
|
77
84
|
if (untracked.length) parts.push(`未跟踪的新文件(不在 diff 里,请直接 Read):${untracked.join('、')}`);
|
|
78
85
|
if (stat.trim()) parts.push(`统计:\n${stat.trim()}`);
|
|
79
86
|
// status、未跟踪清单、stat 都可能独自达到进程上限;预算约束整个注入文本。
|
|
@@ -8,7 +8,7 @@ import { buildPatchSummary } from '../shared/diffSummary.js';
|
|
|
8
8
|
import { fileActivityMetadata } from '../shared/fileActivity.js';
|
|
9
9
|
import { emitFileMutation } from '../shared/fileMutationBus.js';
|
|
10
10
|
import { hashFileBytes, recordRead } from '../shared/fileState.js';
|
|
11
|
-
import {
|
|
11
|
+
import { atomicWriteFile, encodeTextFile, hasBinaryExtension, readTextFile, } from '../shared/fileUtils.js';
|
|
12
12
|
import { DEFAULT_MAX_RESULT_SIZE_CHARS } from '../types.js';
|
|
13
13
|
const schema = z.object({
|
|
14
14
|
patch: z.string().min(1).max(10_000_000).describe('Complete Codex-style patch envelope'),
|
|
@@ -150,16 +150,17 @@ async function workspacePath(raw, cwd) {
|
|
|
150
150
|
return absolute;
|
|
151
151
|
}
|
|
152
152
|
export function applyHunks(original, hunks) {
|
|
153
|
-
|
|
154
|
-
const
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
153
|
+
// Keep terminators on their source lines: context is evidence, not replacement text.
|
|
154
|
+
const lines = Array.from(original.matchAll(/([^\r\n]*)(\r\n|\r|\n|$)/g))
|
|
155
|
+
.filter((match) => match[0].length > 0)
|
|
156
|
+
.map((match) => ({ text: match[1], ending: match[2] }));
|
|
157
|
+
const preferredEnding = lines.find((line) => line.ending)?.ending ?? '\n';
|
|
158
|
+
const trailingNewline = lines.length === 0 || lines.at(-1).ending !== '';
|
|
158
159
|
let cursor = 0;
|
|
159
160
|
let lineDelta = 0;
|
|
160
161
|
for (const hunk of hunks) {
|
|
161
162
|
if (hunk.header) {
|
|
162
|
-
const anchor = lines.findIndex((line, index) => index >= cursor && line.includes(hunk.header));
|
|
163
|
+
const anchor = lines.findIndex((line, index) => index >= cursor && line.text.includes(hunk.header));
|
|
163
164
|
if (anchor < 0)
|
|
164
165
|
fail(`找不到 hunk 锚点:${hunk.header}`);
|
|
165
166
|
cursor = anchor;
|
|
@@ -170,7 +171,7 @@ export function applyHunks(original, hunks) {
|
|
|
170
171
|
const after = hunk.lines
|
|
171
172
|
.filter((line) => line.kind !== 'delete')
|
|
172
173
|
.map((line) => line.text);
|
|
173
|
-
const matchesAt = (start) => before.every((line, offset) => lines[start + offset] === line);
|
|
174
|
+
const matchesAt = (start) => before.every((line, offset) => lines[start + offset]?.text === line);
|
|
174
175
|
let at = -1;
|
|
175
176
|
if (hunk.endOfFile) {
|
|
176
177
|
const last = lines.length - before.length;
|
|
@@ -183,7 +184,7 @@ export function applyHunks(original, hunks) {
|
|
|
183
184
|
else if (!before.length) {
|
|
184
185
|
at =
|
|
185
186
|
hunk.oldStart === undefined
|
|
186
|
-
?
|
|
187
|
+
? lines.length
|
|
187
188
|
: Math.max(cursor, Math.min(lines.length, hunk.oldStart - (hunk.oldCount === 0 ? 0 : 1) + lineDelta));
|
|
188
189
|
}
|
|
189
190
|
else {
|
|
@@ -204,11 +205,36 @@ export function applyHunks(original, hunks) {
|
|
|
204
205
|
}
|
|
205
206
|
if (at < 0)
|
|
206
207
|
fail(`hunk 上下文与当前文件不匹配:${before.join('\n').slice(0, 240)}`);
|
|
207
|
-
|
|
208
|
+
const touchesEnd = at + before.length === lines.length;
|
|
209
|
+
let sourceIndex = at;
|
|
210
|
+
let lastIsAdded = false;
|
|
211
|
+
const replacement = [];
|
|
212
|
+
for (const line of hunk.lines) {
|
|
213
|
+
if (line.kind === 'context') {
|
|
214
|
+
replacement.push(lines[sourceIndex++]);
|
|
215
|
+
lastIsAdded = false;
|
|
216
|
+
}
|
|
217
|
+
else if (line.kind === 'delete')
|
|
218
|
+
sourceIndex++;
|
|
219
|
+
else {
|
|
220
|
+
replacement.push({ text: line.text, ending: preferredEnding });
|
|
221
|
+
lastIsAdded = true;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
// Retain our existing no-final-newline contract when rewriting or extending EOF.
|
|
225
|
+
if (touchesEnd && !trailingNewline && lastIsAdded) {
|
|
226
|
+
replacement[replacement.length - 1] = { ...replacement.at(-1), ending: '' };
|
|
227
|
+
}
|
|
228
|
+
lines.splice(at, before.length, ...replacement);
|
|
229
|
+
// Appending after an unterminated source line necessarily adds a separator.
|
|
230
|
+
for (let index = Math.max(0, at - 1); index < Math.min(lines.length - 1, at + replacement.length); index++) {
|
|
231
|
+
if (!lines[index].ending)
|
|
232
|
+
lines[index] = { ...lines[index], ending: preferredEnding };
|
|
233
|
+
}
|
|
208
234
|
cursor = at + after.length;
|
|
209
235
|
lineDelta += after.length - before.length;
|
|
210
236
|
}
|
|
211
|
-
return
|
|
237
|
+
return lines.map((line) => line.text + line.ending).join('');
|
|
212
238
|
}
|
|
213
239
|
async function stagePatch(operations, cwd) {
|
|
214
240
|
const staged = [];
|
|
@@ -248,7 +274,7 @@ async function stagePatch(operations, cwd) {
|
|
|
248
274
|
});
|
|
249
275
|
continue;
|
|
250
276
|
}
|
|
251
|
-
const updated =
|
|
277
|
+
const updated = applyHunks(snapshot.content, operation.hunks);
|
|
252
278
|
if (operation.moveTo) {
|
|
253
279
|
const target = await workspacePath(operation.moveTo, cwd);
|
|
254
280
|
claim(target);
|
|
@@ -354,7 +380,7 @@ async function call(input, context) {
|
|
|
354
380
|
}
|
|
355
381
|
export const applyPatchTool = {
|
|
356
382
|
name: 'ApplyPatch',
|
|
357
|
-
description: '提交 Codex 格式补丁,必须用 *** Begin Patch / *** End Patch 包络,不接受裸 git diff。支持 Add/Update/Delete File、Move to
|
|
383
|
+
description: '提交 Codex 格式补丁,必须用 *** Begin Patch / *** End Patch 包络,不接受裸 git diff。支持 Add/Update/Delete File、Move to;路径相对工作区。无旧行、无行号的纯新增 hunk 追加到末尾。保留未修改行的换行符,仅支持无损 UTF-8(可带 BOM)或带 BOM 的 UTF-16LE,其他编码拒绝修改。先校验,写入失败尝试回滚,不保证跨文件断电原子性。',
|
|
358
384
|
inputSchema: schema,
|
|
359
385
|
parameters: toToolParameters(schema),
|
|
360
386
|
isReadOnly: false,
|