@thincoder/core 0.11.3 → 0.11.5
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/CHANGELOG.md +23 -0
- package/advisor/compaction.mjs +40 -17
- package/advisor/loop.mjs +14 -6
- package/advisor/notice.mjs +1 -1
- package/advisor/timeline.mjs +4 -4
- package/agent/completion.mjs +19 -0
- package/agent/dispatch-gates.mjs +2 -0
- package/agent/dispatch.mjs +2 -2
- package/agent/family-tools.mjs +13 -9
- package/agent/helpers.mjs +10 -6
- package/agent/planning-step.mjs +453 -0
- package/agent/post-turn.mjs +70 -2
- package/agent/run-stages.mjs +22 -50
- package/agent/run-start.mjs +17 -0
- package/agent/setup-reminders.mjs +71 -8
- package/agent/setup.mjs +8 -39
- package/agent/spawn-child.mjs +6 -2
- package/agent/task-lifecycle.mjs +146 -0
- package/agent/turn-loop.mjs +73 -11
- package/agent-tools/batch-closeout.mjs +21 -34
- package/agent-tools/batch-gate.mjs +7 -5
- package/agent-tools/batch-ledger-bind.mjs +21 -1
- package/agent-tools/batch-lifecycle.mjs +7 -7
- package/agent-tools/batch-record-write.mjs +237 -280
- package/agent-tools/batch-supersede.mjs +3 -3
- package/agent-tools/batch.mjs +42 -9
- package/agent-tools/context.mjs +0 -13
- package/agent-tools/escalate-async.mjs +7 -1
- package/agent-tools/parent-channel.mjs +7 -6
- package/agent-tools/plan.mjs +103 -67
- package/agent-tools/review-facts.mjs +3 -3
- package/agent-tools/settings.mjs +2 -0
- package/agent-tools/spawn-gates.mjs +37 -11
- package/agent-tools/ssh-session.mjs +68 -25
- package/agent-tools/ssh-transfer.mjs +7 -2
- package/agent-tools/ssh-transport.mjs +2 -2
- package/agent-tools/ssh-vault.mjs +2 -2
- package/agent-tools/step.mjs +462 -0
- package/agent-tools/subagent-actions.mjs +6 -1
- package/agent-tools/subagent-run.mjs +7 -0
- package/agent-tools/subagent-spawn.mjs +1 -1
- package/agent-tools/subagent.mjs +17 -11
- package/agent-tools/task.mjs +178 -26
- package/agent-tools.mjs +1 -0
- package/agent.mjs +2 -0
- package/config-defaults.mjs +17 -1
- package/config-migrate.mjs +8 -5
- package/config.mjs +7 -0
- package/context.mjs +5 -4
- package/declaration.mjs +4 -4
- package/generate-title.mjs +0 -6
- package/i18n.mjs +4 -0
- package/ledger-cmd.mjs +11 -1
- package/ledger-tools.mjs +15 -4
- package/manifest-schema.mjs +1 -0
- package/model-context.mjs +34 -11
- package/model-specs.mjs +5 -2
- package/package.json +1 -1
- package/prompt-files.mjs +48 -11
- package/prompt-overlays.mjs +79 -8
- package/prompts/advisor-design.md +253 -206
- package/prompts/advisor-round1.md +151 -145
- package/prompts/advisor-round2.md +136 -130
- package/prompts/advisor-round3.md +140 -134
- package/prompts/common.md +244 -96
- package/prompts/consult-base.md +29 -30
- package/prompts/discipline-engineering.md +73 -519
- package/prompts/discipline-normal.md +28 -136
- package/prompts/knowledge/batch-before-write.md +8 -0
- package/prompts/knowledge/batch-cycle-register.md +15 -0
- package/prompts/knowledge/batch-progress-ledger.md +29 -0
- package/prompts/knowledge/business-gates.md +24 -24
- package/prompts/knowledge/decision-quality.md +8 -19
- package/prompts/knowledge/doc-discipline-d-rules.md +63 -0
- package/prompts/knowledge/doc-lookup.md +25 -24
- package/prompts/knowledge/document-writing.md +11 -32
- package/prompts/knowledge/documentation-evaluation.md +42 -42
- package/prompts/knowledge/eng-dispatch-ops.md +34 -0
- package/prompts/knowledge/eng-ledger-ops.md +26 -0
- package/prompts/knowledge/evidence-discipline.md +10 -32
- package/prompts/knowledge/normal-batch-discipline.md +13 -0
- package/prompts/knowledge/normal-coding-workflow.md +97 -99
- package/prompts/knowledge/normal-delivery-collaboration.md +107 -112
- package/prompts/knowledge/normal-work-management.md +44 -44
- package/prompts/knowledge/product-security.md +7 -26
- package/prompts/knowledge/project-records.md +69 -64
- package/prompts/knowledge/tool-advisor.md +17 -17
- package/prompts/knowledge/tool-apply-patch.md +14 -14
- package/prompts/knowledge/tool-bash.md +32 -31
- package/prompts/knowledge/tool-batch-eng-coder.md +19 -13
- package/prompts/knowledge/tool-batch-eng-designer.md +21 -14
- package/prompts/knowledge/tool-batch-review.md +18 -12
- package/prompts/knowledge/tool-batch.md +93 -85
- package/prompts/knowledge/tool-browser.md +59 -59
- package/prompts/knowledge/tool-code-search.md +2 -2
- package/prompts/knowledge/tool-consult-start.md +6 -6
- package/prompts/knowledge/tool-consult-stop.md +3 -3
- package/prompts/knowledge/tool-context.md +4 -4
- package/prompts/knowledge/tool-delete.md +16 -16
- package/prompts/knowledge/tool-doc-check.md +39 -39
- package/prompts/knowledge/tool-doc-graph-read.md +11 -11
- package/prompts/knowledge/tool-doc-graph.md +48 -48
- package/prompts/knowledge/tool-doc-search.md +3 -3
- package/prompts/knowledge/tool-edit.md +30 -30
- package/prompts/knowledge/tool-eng.md +1 -1
- package/prompts/knowledge/tool-execute.md +16 -16
- package/prompts/knowledge/tool-fetch.md +15 -15
- package/prompts/knowledge/tool-file-ops.md +15 -15
- package/prompts/knowledge/tool-get-current-time.md +3 -3
- package/prompts/knowledge/tool-git-read.md +15 -15
- package/prompts/knowledge/tool-git.md +26 -26
- package/prompts/knowledge/tool-glob.md +14 -14
- package/prompts/knowledge/tool-goal.md +5 -5
- package/prompts/knowledge/tool-grep.md +19 -18
- package/prompts/knowledge/tool-hashline-edit.md +13 -13
- package/prompts/knowledge/tool-insert-after.md +14 -14
- package/prompts/knowledge/tool-instance-list.md +3 -3
- package/prompts/knowledge/tool-instance-send.md +5 -5
- package/prompts/knowledge/tool-knowledge.md +12 -12
- package/prompts/knowledge/tool-ledger-read.md +20 -20
- package/prompts/knowledge/tool-ledger.md +44 -44
- package/prompts/knowledge/tool-lint.md +10 -10
- package/prompts/knowledge/tool-ls.md +11 -11
- package/prompts/knowledge/tool-lsp.md +8 -8
- package/prompts/knowledge/tool-main-history.md +1 -1
- package/prompts/knowledge/tool-manifest-read.md +7 -7
- package/prompts/knowledge/tool-manifest.md +43 -32
- package/prompts/knowledge/tool-memory-read.md +12 -12
- package/prompts/knowledge/tool-memory.md +14 -14
- package/prompts/knowledge/tool-notify-parent.md +10 -10
- package/prompts/knowledge/tool-operations.md +88 -88
- package/prompts/knowledge/tool-peek.md +10 -0
- package/prompts/knowledge/tool-peer-instances.md +1 -1
- package/prompts/knowledge/tool-plan.md +6 -3
- package/prompts/knowledge/tool-process-read.md +8 -8
- package/prompts/knowledge/tool-process.md +11 -11
- package/prompts/knowledge/tool-question.md +11 -13
- package/prompts/knowledge/tool-read-history-batch.md +13 -13
- package/prompts/knowledge/tool-read-history.md +19 -19
- package/prompts/knowledge/tool-read-image.md +8 -8
- package/prompts/knowledge/tool-read.md +17 -17
- package/prompts/knowledge/tool-recent-changes.md +4 -4
- package/prompts/knowledge/tool-repo-outline.md +2 -2
- package/prompts/knowledge/tool-settings-read.md +5 -7
- package/prompts/knowledge/tool-settings.md +10 -10
- package/prompts/knowledge/tool-skill.md +4 -4
- package/prompts/knowledge/tool-ssh.md +66 -66
- package/prompts/knowledge/tool-step.md +26 -0
- package/prompts/knowledge/tool-subagent.md +52 -50
- package/prompts/knowledge/tool-task.md +14 -11
- package/prompts/knowledge/tool-team-ledger-read.md +7 -7
- package/prompts/knowledge/tool-team-ledger.md +13 -13
- package/prompts/knowledge/tool-timer.md +14 -14
- package/prompts/knowledge/tool-tree.md +11 -11
- package/prompts/knowledge/tool-verify.md +11 -11
- package/prompts/knowledge/tool-wait-for.md +20 -20
- package/prompts/knowledge/tool-websearch.md +16 -14
- package/prompts/knowledge/tool-write.md +10 -10
- package/prompts/knowledge/upstream-protocol.md +37 -38
- package/prompts/persona-coder.md +22 -22
- package/prompts/persona-eng-coder.md +87 -81
- package/prompts/persona-eng-designer.md +173 -153
- package/prompts/persona-engineering.md +53 -554
- package/prompts/persona-explore.md +18 -15
- package/prompts/persona-normal.md +62 -63
- package/prompts/persona-plan.md +36 -32
- package/prompts/persona-tester.md +39 -39
- package/prompts/planning-next-moves.md +9 -0
- package/prompts/subagent-base.md +4 -16
- package/provider/errors.mjs +0 -24
- package/provider/list-models.mjs +20 -2
- package/session-lifecycle.mjs +4 -3
- package/tool-args.mjs +25 -0
- package/tool-docs/peek.md +3 -0
- package/tool-docs/plan.md +1 -1
- package/tool-docs/question.md +1 -1
- package/tool-docs/step.md +3 -0
- package/tools/edit-diff.mjs +4 -4
- package/tools/index.mjs +3 -2
- package/tools/peek.mjs +447 -0
- package/tools/question.mjs +87 -9
- package/tools/ssh.mjs +1 -1
- package/window-policy.mjs +107 -80
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agent-tools/step.mjs — 分叉上下文微步执行器(`STEP-FORK.md`)。
|
|
3
|
+
*
|
|
4
|
+
* 定位:介于普通机械工具与独立 `subagent` 之间的原生分叉微循环。
|
|
5
|
+
* - 从主 agent 当前实时上下文分叉(`buildForkedAgent`),复原逐字节相同的
|
|
6
|
+
* `systemPrompt` / `toolSchemas` / `_sessionHead` / `_retained` / `_inject` / `history` 前缀,
|
|
7
|
+
* 以最大化命中模型服务端的 KV Prefix Cache。
|
|
8
|
+
* - 分叉内的所有多轮思考、文件阅读、命令试错只留在分叉自身的 `history` 里,不进入主会话
|
|
9
|
+
* `history` 或 `_fullHistory`;仅把最终精炼结果作为单条工具返回值送回主会话。
|
|
10
|
+
* - 磁盘变更(`_touchedFiles` / `_mutatedThisRun` / `_mutationSeq` / 归属表)通过
|
|
11
|
+
* `mergeChildMutations` 回流主 agent,缓存命中与用量统计同样累加入主 agent。
|
|
12
|
+
*/
|
|
13
|
+
import { DESC } from "../tools/shared.mjs"
|
|
14
|
+
import { runTurnLoop } from "../agent/turn-loop.mjs"
|
|
15
|
+
import { callModelTurn } from "../agent/chat-call.mjs"
|
|
16
|
+
import { ContinueError } from "../agent/helpers.mjs"
|
|
17
|
+
import { isReadonlyAction } from "../agent/dispatch-gates.mjs"
|
|
18
|
+
import { allocRelay, emitRelayModel, wrapChildCallbacks, emitNestedChildEvent, stripEventTokensForCapture, CAPTURE_CAP_OPTS, TURN_CAP_MARK, STOPPED_MARK } from "../agent/spawn-child.mjs"
|
|
19
|
+
import { appendCappedText } from "../text-budget.mjs"
|
|
20
|
+
import { mergeChildMutations } from "./subagent-async.mjs"
|
|
21
|
+
import { armSyncChildAbort, classifySyncAbort } from "./subagent.mjs"
|
|
22
|
+
|
|
23
|
+
export const STEP_DEFAULT_MAX_TURNS = 25
|
|
24
|
+
export const STEP_HARD_MAX_TURNS = 40
|
|
25
|
+
|
|
26
|
+
/** 分叉内始终禁调的工具(不改 toolSchemas 字节,靠运行期包装器拦截以保住 KV Prefix Cache)。 */
|
|
27
|
+
const FORK_BLOCKED_TOOLS = new Set(["step", "question", "subagent", "advisor", "eng", "plan"])
|
|
28
|
+
/** 分叉内禁调的 `batch` 生命周期动作(批档建/关/替归主会话)。 */
|
|
29
|
+
const FORK_BLOCKED_BATCH_ACTIONS = new Set(["create", "close", "supersede"])
|
|
30
|
+
|
|
31
|
+
const STEP_TITLE_MAX = 60
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 归一 `step` 展示标题:优先取模型提供的 `title`,缺失/空白时从 `goal` 首行截取简短标题,
|
|
35
|
+
* 保证三端工具卡与活动块头栏始终可读(不再只显示裸 `step` / `step-ro#N`)。
|
|
36
|
+
*/
|
|
37
|
+
export function normalizeStepTitle(rawTitle, goal = "") {
|
|
38
|
+
const explicit = typeof rawTitle === "string" ? rawTitle.replace(/\s+/g, " ").trim() : ""
|
|
39
|
+
if (explicit) return explicit.length > STEP_TITLE_MAX ? explicit.slice(0, STEP_TITLE_MAX - 1) + "…" : explicit
|
|
40
|
+
const firstLine = String(goal ?? "").split(/\r?\n/, 1)[0].replace(/\s+/g, " ").trim()
|
|
41
|
+
if (!firstLine) return ""
|
|
42
|
+
return firstLine.length > 48 ? firstLine.slice(0, 47) + "…" : firstLine
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function clampMaxTurns(raw) {
|
|
46
|
+
const n = Number(raw)
|
|
47
|
+
if (!Number.isFinite(n) || n < 1) return STEP_DEFAULT_MAX_TURNS
|
|
48
|
+
return Math.min(Math.floor(n), STEP_HARD_MAX_TURNS)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 构造注入到末尾 `role: "tool"` 消息中的分叉指令。
|
|
53
|
+
* 关键不变量:必须以 `role: "tool"` 闭合主会话悬空的 `assistant(tool_calls)`,
|
|
54
|
+
* 绝不追加 `role: "user"` 消息——否则 `assembleRequestMessages` 中的 `turnAt`(最后一条
|
|
55
|
+
* user 消息索引)会后移,导致贴在主会话末尾 user 上的 A 段 9 格搬家并击穿 KV Cache 前缀。
|
|
56
|
+
*/
|
|
57
|
+
export function buildStepDirective({ goal, verify, readonly, maxTurns }) {
|
|
58
|
+
const lines = [
|
|
59
|
+
`[STEP FORK ACTIVE — you are now INSIDE the isolated step micro-loop; do NOT call step again. Only your final reply returns to the main conversation.]`,
|
|
60
|
+
`Goal: ${goal}`,
|
|
61
|
+
]
|
|
62
|
+
if (readonly) {
|
|
63
|
+
lines.push(`Mode: READONLY — inspect and gather evidence only; file edits and write commands are blocked.`)
|
|
64
|
+
}
|
|
65
|
+
if (verify) {
|
|
66
|
+
lines.push(`Verification required before finishing: ${verify}`)
|
|
67
|
+
}
|
|
68
|
+
lines.push(
|
|
69
|
+
`Budget: up to ${maxTurns} internal turns (stay scoped to the files/symbols in Goal and wrap up concisely once you have solid evidence — aim for 3–8 turns rather than crawling unrelated modules).`,
|
|
70
|
+
`Instructions:`,
|
|
71
|
+
`- Work directly from the inherited conversation context above; do not re-read files you already saw unless they changed.`,
|
|
72
|
+
`- When done, reply concisely (no further tool calls) with: (1) concrete findings or changes (file:line), (2) verification results, and (3) any remaining risks or next step.`,
|
|
73
|
+
)
|
|
74
|
+
return lines.join("\n")
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* 为分叉克隆主会话当前实时快照,保证:
|
|
79
|
+
* 1. `assembleRequestMessages(fork, { systemPrompt, toolsDeclared })` 从第 0 条消息直到
|
|
80
|
+
* 主会话末尾 `assistant(tool_calls)` 与主会话逐字节完全一致(KV Prefix Cache 零断裂)。
|
|
81
|
+
* 2. 闭合该末尾 `assistant(tool_calls)` 下的全部 tool_call_id(当前 step 得指令,同轮其他
|
|
82
|
+
* 并列 tool_call 得简短占位),不产生任何新增 `role: "user"` 消息。
|
|
83
|
+
* 3. 分叉拥有独立的 `history` 数组与轮元素副本、空 `_fullHistory`、`_recordStore = null`,
|
|
84
|
+
* 以及独立的 `_touchedFiles` / `_mutationSeq` / `_cacheHitTokens` / `_cacheMissTokens`。
|
|
85
|
+
*/
|
|
86
|
+
export function buildForkedAgent(parent, { toolCallId, goal, verify = "", readonly = false, maxTurns = STEP_DEFAULT_MAX_TURNS }) {
|
|
87
|
+
const clonedHistory = Array.isArray(parent.history)
|
|
88
|
+
? parent.history.map((turn) => ({
|
|
89
|
+
...turn,
|
|
90
|
+
messages: Array.isArray(turn?.messages) ? [...turn.messages] : [],
|
|
91
|
+
}))
|
|
92
|
+
: []
|
|
93
|
+
|
|
94
|
+
const lastTurn = clonedHistory.at(-1)
|
|
95
|
+
const lastMsg = lastTurn?.messages?.at(-1)
|
|
96
|
+
const directive = buildStepDirective({ goal, verify, readonly, maxTurns })
|
|
97
|
+
|
|
98
|
+
if (lastMsg?.role === "assistant" && Array.isArray(lastMsg.tool_calls) && lastMsg.tool_calls.length > 0) {
|
|
99
|
+
// 闭合悬空的 tool_calls:精确匹配当前 step 的 tool_call_id 塞入执行指令;
|
|
100
|
+
// 同轮其余并发 tool_call 塞简短占位,保证严校验 provider(OpenAI/DeepSeek/Anthropic)配对合法。
|
|
101
|
+
for (const tc of lastMsg.tool_calls) {
|
|
102
|
+
const id = tc?.id
|
|
103
|
+
if (!id) continue
|
|
104
|
+
lastTurn.messages.push({
|
|
105
|
+
role: "tool",
|
|
106
|
+
tool_call_id: id,
|
|
107
|
+
content: id === toolCallId
|
|
108
|
+
? directive
|
|
109
|
+
: "[deferred to parent turn — focus only on your active step]",
|
|
110
|
+
})
|
|
111
|
+
}
|
|
112
|
+
} else {
|
|
113
|
+
// 单元测试或合成调用(没有悬空 assistant(tool_calls))的兜底:仍不移动既有 history。
|
|
114
|
+
clonedHistory.push({
|
|
115
|
+
messages: [{ role: "user", content: directive }],
|
|
116
|
+
})
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
// 共享不可变运行配置与凭证
|
|
121
|
+
provider: parent.provider,
|
|
122
|
+
config: parent.config,
|
|
123
|
+
cwd: parent.cwd,
|
|
124
|
+
tools: parent.tools,
|
|
125
|
+
autoApprove: parent.autoApprove,
|
|
126
|
+
sessionId: parent.sessionId,
|
|
127
|
+
// 不借用 planMode(只读由 tools/dispatch 强制,避免与主会话 plan 槽位状态耦合);
|
|
128
|
+
// readonly 约束由 buildForkToolMap 在运行期机械强制。
|
|
129
|
+
planMode: false,
|
|
130
|
+
|
|
131
|
+
// KV Prefix Cache 冻结面(浅拷贝快照,且 _forkedStep=true 禁止 pushTimeReminder 改写 time 格)
|
|
132
|
+
_forkedStep: true,
|
|
133
|
+
_role: readonly ? "step-ro" : "step",
|
|
134
|
+
_sessionHead: parent._sessionHead,
|
|
135
|
+
_retained: Array.isArray(parent._retained) ? [...parent._retained] : [],
|
|
136
|
+
_inject: Array.isArray(parent._inject) ? [...parent._inject] : [],
|
|
137
|
+
_pendingInject: [],
|
|
138
|
+
_rules: parent._rules,
|
|
139
|
+
_sessionSkill: parent._sessionSkill,
|
|
140
|
+
_batchDoc: parent._batchDoc,
|
|
141
|
+
_upstream: { parent },
|
|
142
|
+
|
|
143
|
+
// 隔离的对话历史与记录(永不写回主会话磁盘记录)
|
|
144
|
+
history: clonedHistory,
|
|
145
|
+
_fullHistory: [],
|
|
146
|
+
_recordStore: null,
|
|
147
|
+
_recordCache: null,
|
|
148
|
+
|
|
149
|
+
// 独立的变更与统计面(结束后合并回 parent)
|
|
150
|
+
_touchedFiles: [],
|
|
151
|
+
_mutatedThisRun: false,
|
|
152
|
+
_mutationSeq: 0,
|
|
153
|
+
_fileAttribution: new Map(),
|
|
154
|
+
_cacheHitTokens: 0,
|
|
155
|
+
_cacheMissTokens: 0,
|
|
156
|
+
_usageTurns: 0,
|
|
157
|
+
_turnSeq: 0,
|
|
158
|
+
_currentTurn: 0,
|
|
159
|
+
_maxTurns: maxTurns,
|
|
160
|
+
_segmentTurns: 0,
|
|
161
|
+
_zeroWriteTurns: 0,
|
|
162
|
+
_zeroWriteStreak: 0,
|
|
163
|
+
_zeroWriteAlerted: false,
|
|
164
|
+
_emptyRetries: 0,
|
|
165
|
+
_overflowRetried: false,
|
|
166
|
+
// 三者同写同清(`turn-loop.mjs` 不变量):全存在才整体继承,否则全置 null
|
|
167
|
+
_lastPromptTokens: (parent._lastPromptTokens != null && parent._usageFixedBase != null && parent._usageAt) ? parent._lastPromptTokens : null,
|
|
168
|
+
_usageAt: (parent._lastPromptTokens != null && parent._usageFixedBase != null && parent._usageAt) ? { ...parent._usageAt } : null,
|
|
169
|
+
_usageFixedBase: (parent._lastPromptTokens != null && parent._usageFixedBase != null && parent._usageAt) ? parent._usageFixedBase : null,
|
|
170
|
+
_tokenSamples: Array.isArray(parent._tokenSamples) ? [...parent._tokenSamples] : [],
|
|
171
|
+
_stepContext: null,
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* 包装主会话的 `toolByName`(不修改 `toolSchemas` 字节!),在运行期拦截分叉禁调工具:
|
|
177
|
+
* - 禁递归 `step` 及父级交互/生命周期工具(`question` / `subagent` / `advisor` / `eng` / `plan`)
|
|
178
|
+
* - 禁 `batch` 的 `create` / `close` / `supersede`
|
|
179
|
+
* - `readonly === true` 时禁一切非只读工具调用
|
|
180
|
+
*/
|
|
181
|
+
export function buildForkToolMap(parentToolByName, { readonly = false } = {}) {
|
|
182
|
+
const map = new Map()
|
|
183
|
+
for (const [name, tool] of parentToolByName.entries()) {
|
|
184
|
+
if (FORK_BLOCKED_TOOLS.has(name)) {
|
|
185
|
+
map.set(name, {
|
|
186
|
+
...tool,
|
|
187
|
+
readonly: true,
|
|
188
|
+
execute: async () => `Error: tool '${name}' is disabled inside a step fork. Complete this step directly or return control to the main agent.`,
|
|
189
|
+
})
|
|
190
|
+
continue
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (name === "batch") {
|
|
194
|
+
map.set(name, {
|
|
195
|
+
...tool,
|
|
196
|
+
execute: async (args, ctx) => {
|
|
197
|
+
if (FORK_BLOCKED_BATCH_ACTIONS.has(args?.action)) {
|
|
198
|
+
return `Error: batch action '${args.action}' is reserved for the main agent; inside a step fork only read/append/edit/status are allowed.`
|
|
199
|
+
}
|
|
200
|
+
if (readonly && args?.action !== "status") {
|
|
201
|
+
return `Error: this step is readonly=true — batch '${args?.action}' is blocked.`
|
|
202
|
+
}
|
|
203
|
+
return tool.execute(args, ctx)
|
|
204
|
+
},
|
|
205
|
+
})
|
|
206
|
+
continue
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
if (readonly && !tool.readonly) {
|
|
210
|
+
map.set(name, {
|
|
211
|
+
...tool,
|
|
212
|
+
execute: async (args, ctx) => {
|
|
213
|
+
if (isReadonlyAction(name, args)) return tool.execute(args, ctx)
|
|
214
|
+
return `Error: this step is readonly=true — '${name}' is blocked because it may modify files or external state.`
|
|
215
|
+
},
|
|
216
|
+
})
|
|
217
|
+
continue
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
map.set(name, tool)
|
|
221
|
+
}
|
|
222
|
+
return map
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function formatCacheTelemetry(forkAgent) {
|
|
226
|
+
const hit = forkAgent._cacheHitTokens ?? 0
|
|
227
|
+
const miss = forkAgent._cacheMissTokens ?? 0
|
|
228
|
+
const total = hit + miss
|
|
229
|
+
const turns = forkAgent._usageTurns ?? 0
|
|
230
|
+
if (total <= 0) return `turns=${turns}`
|
|
231
|
+
const pct = Math.round((hit / total) * 100)
|
|
232
|
+
return `turns=${turns}, cache=${pct}% (${hit.toLocaleString()} hit / ${miss.toLocaleString()} miss)`
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function fallbackForkSummary(forkAgent, capturedText, note) {
|
|
236
|
+
const parts = []
|
|
237
|
+
if (note) parts.push(`[step ${note}]`)
|
|
238
|
+
const trimmed = stripEventTokensForCapture(capturedText ?? "").trim()
|
|
239
|
+
if (trimmed) {
|
|
240
|
+
parts.push(trimmed)
|
|
241
|
+
} else {
|
|
242
|
+
// 回退找分叉新增的最后一条非空 assistant 正文
|
|
243
|
+
const lastTurn = forkAgent.history.at(-1)
|
|
244
|
+
const msgs = Array.isArray(lastTurn?.messages) ? lastTurn.messages : []
|
|
245
|
+
for (let i = msgs.length - 1; i >= 0; i--) {
|
|
246
|
+
if (msgs[i]?.role === "assistant" && typeof msgs[i].content === "string" && msgs[i].content.trim()) {
|
|
247
|
+
parts.push(msgs[i].content.trim())
|
|
248
|
+
break
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
if (forkAgent._touchedFiles.length > 0) {
|
|
253
|
+
parts.push(`Modified files: ${forkAgent._touchedFiles.join(", ")}`)
|
|
254
|
+
}
|
|
255
|
+
return parts.join("\n\n") || "[step finished with no text output]"
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
async function executeStep(args, ctx, { forceReadonly = false } = {}) {
|
|
259
|
+
const goal = typeof args?.goal === "string" ? args.goal.trim() : ""
|
|
260
|
+
if (!goal) return "Error: step requires a non-empty 'goal'."
|
|
261
|
+
|
|
262
|
+
const parent = ctx?.agent
|
|
263
|
+
if (!parent) return "Error: step requires an active agent context."
|
|
264
|
+
if ((ctx?.depth ?? 0) > 0 || parent._forkedStep) {
|
|
265
|
+
return "Error: nested step calls are not allowed (depth > 0)."
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const engLocked = forceReadonly || parent.config?.agent?.engineering === true
|
|
269
|
+
if (engLocked) {
|
|
270
|
+
if (args?.readonly === false) {
|
|
271
|
+
return "Error: engineering mode step is read-only — writes are disabled inside step; use eng-coder for implementation."
|
|
272
|
+
}
|
|
273
|
+
if (typeof args?.verify === "string" && args.verify.trim()) {
|
|
274
|
+
return "Error: engineering mode step is read-only — command verification is disabled inside step; use verify or tester."
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const activeCtx = parent._stepContext
|
|
279
|
+
if (!activeCtx?.systemPrompt || !Array.isArray(activeCtx.toolSchemas) || !activeCtx.toolByName) {
|
|
280
|
+
return "Error: step context snapshot unavailable — active turn loop context missing."
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const readonly = engLocked ? true : args?.readonly === true
|
|
284
|
+
const verify = engLocked ? "" : (typeof args?.verify === "string" ? args.verify.trim() : "")
|
|
285
|
+
const maxTurns = clampMaxTurns(args?.maxTurns)
|
|
286
|
+
const title = normalizeStepTitle(args?.title, goal)
|
|
287
|
+
|
|
288
|
+
const forkAgent = buildForkedAgent(parent, {
|
|
289
|
+
toolCallId: ctx._toolCallId,
|
|
290
|
+
goal,
|
|
291
|
+
verify,
|
|
292
|
+
readonly,
|
|
293
|
+
maxTurns,
|
|
294
|
+
})
|
|
295
|
+
const forkToolByName = buildForkToolMap(activeCtx.toolByName, { readonly })
|
|
296
|
+
|
|
297
|
+
const relayPrefix = allocRelay(parent, readonly ? "step-ro" : "step")
|
|
298
|
+
const wrapped = wrapChildCallbacks(relayPrefix, ctx.callbacks)
|
|
299
|
+
let captured = ""
|
|
300
|
+
const forkCallbacks = {
|
|
301
|
+
...ctx.callbacks,
|
|
302
|
+
onToken: (t) => {
|
|
303
|
+
captured = appendCappedText(captured, String(t), CAPTURE_CAP_OPTS)
|
|
304
|
+
wrapped.onToken?.(t)
|
|
305
|
+
},
|
|
306
|
+
onReasoning: wrapped.onReasoning,
|
|
307
|
+
onToolCall: wrapped.onToolCall,
|
|
308
|
+
onToolOutput: wrapped.onToolOutput,
|
|
309
|
+
onUsage: (u) => {
|
|
310
|
+
ctx.callbacks?.onUsage?.(u)
|
|
311
|
+
},
|
|
312
|
+
onAgentTurn: null,
|
|
313
|
+
onTurnEnd: null,
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const syncKey = relayPrefix.replace(/\/$/, "")
|
|
317
|
+
// 透传给 dispatch-run.mjs → onToolResult 第 4 参 subKey,供 TUI/VSC 即时冻结对应 step 活动块
|
|
318
|
+
ctx._subagentKey = syncKey
|
|
319
|
+
const { ctrl, disarm } = armSyncChildAbort(
|
|
320
|
+
parent, syncKey, ctx.signal,
|
|
321
|
+
() => emitRelayModel(ctx.callbacks?.onToken, relayPrefix, forkAgent.provider?.model ?? "", title),
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
let content = ""
|
|
325
|
+
let statusNote = ""
|
|
326
|
+
try {
|
|
327
|
+
content = await runTurnLoop(forkAgent, {
|
|
328
|
+
maxTurns,
|
|
329
|
+
threshold: activeCtx.threshold,
|
|
330
|
+
toolSchemas: activeCtx.toolSchemas, // 逐字节复用主会话 toolSchemas
|
|
331
|
+
toolByName: forkToolByName,
|
|
332
|
+
systemPrompt: activeCtx.systemPrompt, // 逐字节复用主会话 systemPrompt
|
|
333
|
+
depth: (ctx.depth ?? 0) + 1,
|
|
334
|
+
signal: ctrl.signal,
|
|
335
|
+
autoTurn: false,
|
|
336
|
+
upstreamTurn: false,
|
|
337
|
+
suspDriven: false,
|
|
338
|
+
streamOutput: true,
|
|
339
|
+
consumeInjected: null,
|
|
340
|
+
consumeQueuedInput: null,
|
|
341
|
+
callbacks: forkCallbacks,
|
|
342
|
+
distillSignal: null,
|
|
343
|
+
})
|
|
344
|
+
emitNestedChildEvent(ctx, relayPrefix, "done")
|
|
345
|
+
} catch (err) {
|
|
346
|
+
if (err instanceof ContinueError) {
|
|
347
|
+
statusNote = `${TURN_CAP_MARK} (${maxTurns})`
|
|
348
|
+
// 撞帽优雅收口:保留已攒全部上下文再调 1 次纯总结(沿用同一 toolSchemas/systemPrompt 命中前缀缓存,
|
|
349
|
+
// 通过 _pendingInject 要求立刻输出最终结论、不再调工具),防止前 25 轮探索白费。
|
|
350
|
+
let wrapUpText = ""
|
|
351
|
+
try {
|
|
352
|
+
forkAgent._pendingInject = [{
|
|
353
|
+
role: "user",
|
|
354
|
+
content: `[step turn budget (${maxTurns}) reached — do NOT call any tools. Immediately write your final concise summary of all concrete findings/changes (with file:line), verification results, and what remains.]`,
|
|
355
|
+
}]
|
|
356
|
+
const wrapResp = await callModelTurn(forkAgent, {
|
|
357
|
+
systemPrompt: activeCtx.systemPrompt,
|
|
358
|
+
toolSchemas: activeCtx.toolSchemas,
|
|
359
|
+
streamOutput: false,
|
|
360
|
+
callbacks: forkCallbacks,
|
|
361
|
+
signal: ctrl.signal,
|
|
362
|
+
streamRuleFired: new Set(),
|
|
363
|
+
autoTurn: false,
|
|
364
|
+
depth: (ctx.depth ?? 0) + 1,
|
|
365
|
+
turn: maxTurns,
|
|
366
|
+
})
|
|
367
|
+
if (wrapResp?.usage) {
|
|
368
|
+
forkAgent._cacheHitTokens = (forkAgent._cacheHitTokens ?? 0) + (wrapResp.usage.prompt_cache_hit_tokens ?? 0)
|
|
369
|
+
forkAgent._cacheMissTokens = (forkAgent._cacheMissTokens ?? 0) + (wrapResp.usage.prompt_cache_miss_tokens ?? 0)
|
|
370
|
+
forkAgent._usageTurns = (forkAgent._usageTurns ?? 0) + 1
|
|
371
|
+
}
|
|
372
|
+
wrapUpText = String(wrapResp?.content ?? "").trim()
|
|
373
|
+
} catch { /* 收口调用失败时静默回退到捕获摘要 */ }
|
|
374
|
+
content = wrapUpText
|
|
375
|
+
? `[step ${statusNote}]\n\n${wrapUpText}${forkAgent._touchedFiles.length ? `\n\nModified files: ${forkAgent._touchedFiles.join(", ")}` : ""}`
|
|
376
|
+
: fallbackForkSummary(forkAgent, captured, statusNote)
|
|
377
|
+
emitNestedChildEvent(ctx, relayPrefix, "done")
|
|
378
|
+
} else {
|
|
379
|
+
const abortKind = classifySyncAbort(ctx.signal, ctx.signal, ctrl.signal, err)
|
|
380
|
+
if (abortKind === "targeted") {
|
|
381
|
+
statusNote = STOPPED_MARK
|
|
382
|
+
content = fallbackForkSummary(forkAgent, captured, statusNote)
|
|
383
|
+
emitNestedChildEvent(ctx, relayPrefix, "stopped")
|
|
384
|
+
} else {
|
|
385
|
+
throw err
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
} finally {
|
|
389
|
+
disarm()
|
|
390
|
+
// 合并磁盘写足迹与归属到主 agent(readonly 步通常为空,零副作用)
|
|
391
|
+
mergeChildMutations(parent, forkAgent)
|
|
392
|
+
// 把分叉的缓存统计累加到主 agent 的会话级统计
|
|
393
|
+
parent._cacheHitTokens = (parent._cacheHitTokens ?? 0) + (forkAgent._cacheHitTokens ?? 0)
|
|
394
|
+
parent._cacheMissTokens = (parent._cacheMissTokens ?? 0) + (forkAgent._cacheMissTokens ?? 0)
|
|
395
|
+
parent._usageTurns = (parent._usageTurns ?? 0) + (forkAgent._usageTurns ?? 0)
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
const cleanBody = stripEventTokensForCapture(content ?? "").trim() || fallbackForkSummary(forkAgent, captured, statusNote)
|
|
399
|
+
const meta = `[step ${readonly ? "readonly" : "exec"} | ${formatCacheTelemetry(forkAgent)}${forkAgent._touchedFiles.length ? ` | touched=${forkAgent._touchedFiles.length}` : ""}]`
|
|
400
|
+
return `${meta}\n${cleanBody}`
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
export const stepTool = {
|
|
404
|
+
name: "step",
|
|
405
|
+
description: DESC("step"),
|
|
406
|
+
readonly: false,
|
|
407
|
+
isParallelAction: (args) => args?.readonly === true,
|
|
408
|
+
parameters: {
|
|
409
|
+
type: "object",
|
|
410
|
+
properties: {
|
|
411
|
+
title: {
|
|
412
|
+
type: "string",
|
|
413
|
+
description: "Short human-readable title (3-8 words, e.g. 'Inspect config parsing', written in the user's language) displayed in the UI header bar so the user sees what this step is doing at a glance.",
|
|
414
|
+
},
|
|
415
|
+
goal: {
|
|
416
|
+
type: "string",
|
|
417
|
+
description: "Concrete objective for this single micro-step (what to inspect, change, or verify).",
|
|
418
|
+
},
|
|
419
|
+
readonly: {
|
|
420
|
+
type: "boolean",
|
|
421
|
+
description: "Set true for read-only exploration/checking (runs concurrently with other readonly steps and blocks writes); omit or false for steps that modify files (runs serially).",
|
|
422
|
+
},
|
|
423
|
+
verify: {
|
|
424
|
+
type: "string",
|
|
425
|
+
description: "Optional targeted command or check to execute inside this step before returning.",
|
|
426
|
+
},
|
|
427
|
+
maxTurns: {
|
|
428
|
+
type: "integer",
|
|
429
|
+
description: "Optional internal turn cap for this step (default 25, maximum 40).",
|
|
430
|
+
},
|
|
431
|
+
},
|
|
432
|
+
required: ["title", "goal"],
|
|
433
|
+
},
|
|
434
|
+
execute: (args, ctx) => executeStep(args, ctx, { forceReadonly: false }),
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** 工程模式主代理专用只读变体:schema 去除写参、机械强制 readonly=true,并发只读不绕写闸。 */
|
|
438
|
+
export const stepReadTool = {
|
|
439
|
+
name: "step",
|
|
440
|
+
description: "Fork the current conversation (reusing prefix cache) to run an isolated, read-only multi-turn investigation (contact-surface survey, drift check, or closeout verification) instead of chaining 3+ read/grep/git turns in the main chat; runs concurrently and blocks all writes.",
|
|
441
|
+
readonly: true,
|
|
442
|
+
parallel: true,
|
|
443
|
+
parameters: {
|
|
444
|
+
type: "object",
|
|
445
|
+
properties: {
|
|
446
|
+
title: {
|
|
447
|
+
type: "string",
|
|
448
|
+
description: "Short human-readable title (3-8 words, e.g. 'Survey render-core callers', written in the user's language) displayed in the UI header bar so the user sees what this step is doing at a glance.",
|
|
449
|
+
},
|
|
450
|
+
goal: {
|
|
451
|
+
type: "string",
|
|
452
|
+
description: "Concrete read-only investigation objective for this step (what contact surface, code/doc alignment, or delivery evidence to check).",
|
|
453
|
+
},
|
|
454
|
+
maxTurns: {
|
|
455
|
+
type: "integer",
|
|
456
|
+
description: "Optional internal turn cap for this read-only step (default 25, maximum 40).",
|
|
457
|
+
},
|
|
458
|
+
},
|
|
459
|
+
required: ["title", "goal"],
|
|
460
|
+
},
|
|
461
|
+
execute: (args, ctx) => executeStep(args, ctx, { forceReadonly: true }),
|
|
462
|
+
}
|
|
@@ -27,6 +27,8 @@ import { RECORD_WINDOW_MESSAGES } from "../session-store.mjs"
|
|
|
27
27
|
// ASYNC-RESULT-CONTAINER.md D1:池 accessor(absorb 双池——advisor 独立池无队列)
|
|
28
28
|
import { getAsyncPool } from "./async-settle.mjs"
|
|
29
29
|
import { settleConsultCheckpoint, settleTurnCheckpoint, resumedSendResult } from "./checkpoint.mjs"
|
|
30
|
+
// SSH-TO-CODER T3(batch 2026-11-26-ssh-to-coder):同步子代理结清时排空它自己的 ssh 池
|
|
31
|
+
import { discardSshSessions } from "./ssh-session.mjs"
|
|
30
32
|
|
|
31
33
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
32
34
|
// 查询面(status ∕ observe + 摘要助手族):2026-09-28 拆分(Module Split Policy——498/499
|
|
@@ -164,7 +166,7 @@ export async function executeEscalateAction(args, ctx) {
|
|
|
164
166
|
// G3(施工②):overlay 摘除——coder 人格槽由 assemblePrompt 场景表承载(G3 映射)。
|
|
165
167
|
child = createAgent({
|
|
166
168
|
provider,
|
|
167
|
-
tools: excludeSubagentTools(parent.tools), // TOOLS.md §6.
|
|
169
|
+
tools: excludeSubagentTools(parent.tools), // TOOLS.md §6.4:子代面按面排除(行内改——本档 Δ±0)
|
|
168
170
|
config: parent.config,
|
|
169
171
|
cwd: parent.cwd,
|
|
170
172
|
memory: parent.memory,
|
|
@@ -219,6 +221,8 @@ export async function executeEscalateAction(args, ctx) {
|
|
|
219
221
|
})
|
|
220
222
|
// Escalate mutations are the parent's mutations: verify/advisor guards must see them
|
|
221
223
|
mergeChildMutations(parent, child)
|
|
224
|
+
// SSH-TO-CODER T3:同步子代理退出即清它自己的 ssh 池(报告成功或失败都清)
|
|
225
|
+
discardSshSessions(child)
|
|
222
226
|
if (escErr) logEvent("child:error", { role: "escalate", id: escId, ms: Date.now() - escT0, err: errText(escErr.err, 200) })
|
|
223
227
|
else logEvent("child:done", { role: "escalate", id: escId, ms: Date.now() - escT0, kind: String(report).includes(TURN_CAP_MARK) ? "partial" : "ok" })
|
|
224
228
|
// docs/cli/design/TUI.md §6.8(round1 #2):escalate 与 spawn 同享 ctx._subagentKey——同步完成精确冻
|
|
@@ -231,6 +235,7 @@ export async function executeEscalateAction(args, ctx) {
|
|
|
231
235
|
// 仅 createAgent 失败/continue 询问抛出才到这(运行失败已在上面 catch 处理)
|
|
232
236
|
if (child) {
|
|
233
237
|
mergeChildMutations(parent, child)
|
|
238
|
+
discardSshSessions(child) // SSH-TO-CODER T3:异常退出也清
|
|
234
239
|
if (!escErr && !(ctx.signal?.aborted) && e?.name !== "AbortError") {
|
|
235
240
|
logEvent("child:error", { role: "escalate", id: escId, ms: Date.now() - escT0, err: errText(e, 200) })
|
|
236
241
|
}
|
|
@@ -18,6 +18,8 @@ import {
|
|
|
18
18
|
// ASYNC-RESULT-CONTAINER.md D3/D6:settle 公共收尾单点 + child signal 构建单点
|
|
19
19
|
import { bindChildController, buildChildSignal, settleAsyncEntry } from "./async-settle.mjs"
|
|
20
20
|
import { registerTurnCapCheckpoint } from "./checkpoint.mjs"
|
|
21
|
+
// SSH-TO-CODER T3(batch 2026-11-26-ssh-to-coder):子代理结清时排空它自己的 ssh 池
|
|
22
|
+
import { discardSshSessions } from "./ssh-session.mjs"
|
|
21
23
|
|
|
22
24
|
/** #309 任务书文本摘要(12 hex——**不留全文**,NF-L3 同族):条目自携与双点留痕的标识面。 */
|
|
23
25
|
function taskSeal(text) {
|
|
@@ -177,6 +179,11 @@ export function executeAsyncSpawn(parent, ctx, role, args, child, input, childOp
|
|
|
177
179
|
// §6.12 第 3 条合成器(第 24 批):原 message 前缀逐字保留 + 来源后缀
|
|
178
180
|
.catch((err) => { entry.error = deathLine(err, entry.controller?.signal) })
|
|
179
181
|
.finally(() => {
|
|
182
|
+
// SSH-TO-CODER T3:子代理的 ssh 池挂在它自己身上(`sshPool` 懒建)——退出即清,
|
|
183
|
+
// 不留一条父会话看不见、却还活着的远程连接(idle 600 s 只是保底)。
|
|
184
|
+
// 撞帽挂起(`_turnCapRec` 在场)是**暂停可续跑**,不是退出:那时不清池,
|
|
185
|
+
// 否则续跑段拿到的是「was closed when the run was stopped」墓碑——句子对续跑不实。
|
|
186
|
+
if (!entry._turnCapRec) discardSshSessions(child)
|
|
180
187
|
// SUBAGENT-OBSERVE-SEND D3(send→settle 竞态):settle 收尾时 _injected 仍残留
|
|
181
188
|
// = 消息入队后子代理在下一回合边界前 settle——未投递——附 settle 报告/错误提示
|
|
182
189
|
// (防父误以为引导已落地)。error 路径附 error;报告路径附 report 尾。
|
|
@@ -285,7 +285,7 @@ export function buildSpawnChild(parent, ctx, args, role, wantAsync, files, depen
|
|
|
285
285
|
} else {
|
|
286
286
|
tools = parent.tools
|
|
287
287
|
}
|
|
288
|
-
// Then the depth>0 exclusion (TOOLS.md §6.
|
|
288
|
+
// Then the depth>0 exclusion (TOOLS.md §6.4): role selection above, exclusion LAST — both
|
|
289
289
|
// branches converge here (`question` = interactive main-session tool; a child has no user to ask).
|
|
290
290
|
tools = excludeSubagentTools(tools)
|
|
291
291
|
|
package/agent-tools/subagent.mjs
CHANGED
|
@@ -36,7 +36,9 @@ import { executeStatusAction, executeEscalateAction, executePanelAction, execute
|
|
|
36
36
|
import { prepareScheduling, buildSpawnChild, executeConsumeDesignAction } from "./subagent-spawn.mjs"
|
|
37
37
|
import { executeDesignSlotsAction } from "./design-slots.mjs"
|
|
38
38
|
import { executeAsyncSpawn } from "./subagent-run.mjs"
|
|
39
|
-
|
|
39
|
+
// SSH-TO-CODER T3(batch 2026-11-26-ssh-to-coder):阻塞子代理结清时排空它自己的 ssh 池
|
|
40
|
+
import { discardSshSessions } from "./ssh-session.mjs"
|
|
41
|
+
import { ROUND_VALUES, EXPLORE_THOROUGHNESS_VALUES, composeTaskBookBrief, isEngineeringRole } from "./spawn-gates.mjs"
|
|
40
42
|
// #15 描述外置:描述文本单点 = tool-docs/subagent.md(DESC 单解析面,缺档抛错语义不变)
|
|
41
43
|
import { DESC } from "../tools/shared.mjs"
|
|
42
44
|
|
|
@@ -141,9 +143,9 @@ export const subagentTool = {
|
|
|
141
143
|
action: { type: "string", enum: ["spawn", "status", "escalate", "cancel", "panel", "consume-design", "observe", "send", "design-slots"], description: "Which action to run; `spawn` is the default. Semantics per action in the tool description." },
|
|
142
144
|
view: { type: "boolean", description: "action:'panel' only: true (default) = the live panel blocks as the user sees them; false without freeze = error. Mutually exclusive with freeze (freeze wins)." },
|
|
143
145
|
freeze: { type: "string", description: "action:'panel' only: block key of a digested-stuck block — reclaims it into the conversation; refused for running/done/unknown blocks or a still-pending report; works on the CLI TUI panel and on the desktop renderer panel (live readback of the blocks as the user sees them)." },
|
|
144
|
-
task: { type: "string", description: "For action:'spawn': non-engineering roles
|
|
145
|
-
context: { type: "string", description: "Optional background for non-engineering spawns (explore /
|
|
146
|
-
role: { type: "string", enum: ["explore", "
|
|
146
|
+
task: { type: "string", description: "For action:'spawn': non-engineering roles — OPTIONAL free-text supplement; read-only role (explore) requires goal + scope (knownFacts / acceptance / reportFormat optional), while coder / tester require all five. Engineering roles (eng-coder / eng-designer) take NO task-book text parameters — their task book is batch record §2 (batchDoc), read by the child itself. For action:'escalate': the brief (goal, constraints, entry files, acceptance criteria)." },
|
|
147
|
+
context: { type: "string", description: "Optional background for non-engineering spawns (explore / coder / tester) only; action:'spawn' only." },
|
|
148
|
+
role: { type: "string", enum: ["explore", "coder", "eng-coder", "eng-designer", "tester"], description: "The sub-agent role — see the role matrix in the tool description. Exact spelling required. action:'spawn' only (escalate spawns its own expert internally)." },
|
|
147
149
|
model: { type: "string", description: "action:'spawn': provider/model override ('provider:model', a provider, or a model name on the parent's provider) — defaults config.agent.subagentModels[role] → config.agent.subagentModel → the parent's provider; \"default\" inherits. action:'escalate': a consult candidate (default = the first)." },
|
|
148
150
|
designToken: { type: "string", description: "REQUIRED for role='eng-coder': the exact token issued by advisor(type='design') after the review passed — copy it verbatim from the design-slots row (the text after designToken=). missing or mismatched = the spawn is refused; an expired token is refused with expired named. Pass it on every eng-coder spawn, fix rounds included (they reuse the same token)." },
|
|
149
151
|
designId: { type: "string", description: "role='eng-coder': the designId echoed with the approved token — required to pick between concurrent designs (optional for one). action:'consume-design': the single-slot selector (required to pick between several; the gate refuses to guess); see designIds / expired / olderThanDays for batch consumption. action:'design-slots': filter the inventory to one slot (trimmed exact match; an empty string means no filter; an unknown id is refused with the held id list)." },
|
|
@@ -152,11 +154,12 @@ export const subagentTool = {
|
|
|
152
154
|
olderThanDays: { type: "number", description: "action:'consume-design' (batch): close out every slot older than N days (age > N; exactly ONE selector per call)." },
|
|
153
155
|
batchDoc: { type: "string", description: "REQUIRED for role='eng-coder'/'eng-designer': the batch record path (e.g. <repo>/docs/batches/<batch>-<topic>.md; relative paths resolve against the session cwd first, then candidate project roots — or absolute) — the task book this spawn implements/writes. This IS the task book for engineering roles — batch record §2, read by the child itself. Refused when absent, when the path does not resolve to a readable file, or when that record already has an in-flight spawn — one batch record serves one concurrent spawn: wait for the occupant to settle (or cancel it) before spawning again. The content is never validated. role='coder' (normal mode): optional — binds this spawn's §5 record-write channel (unbound ⇒ the main agent records §5 on its behalf); when provided the path must resolve to a readable file." },
|
|
154
156
|
round: { type: "string", enum: ROUND_VALUES, description: "REQUIRED for role='eng-coder'/'eng-designer': initial (first round for this design) or fix (a correction round reusing the same designId+designToken; docs FIRST). No default — missing = refused." },
|
|
155
|
-
goal: { type: "string", description: "REQUIRED for role='explore'/'
|
|
156
|
-
knownFacts: { type: "string", description: "REQUIRED for role='
|
|
157
|
-
scope: { type: "string", description: "REQUIRED for role='explore'/'
|
|
158
|
-
acceptance: { type: "string", description: "REQUIRED for role='
|
|
159
|
-
reportFormat: { type: "string", description: "REQUIRED for role='
|
|
157
|
+
goal: { type: "string", description: "REQUIRED for role='explore'/'coder'/'tester' (non-engineering task book): the task book's goal & why — what question to answer or what problem to solve (content only, no label — the runtime composes the labels)." },
|
|
158
|
+
knownFacts: { type: "string", description: "REQUIRED for role='coder'/'tester', OPTIONAL for role='explore': facts and file paths the parent already verified so the child does not re-explore them." },
|
|
159
|
+
scope: { type: "string", description: "REQUIRED for role='explore'/'coder'/'tester' (non-engineering task book): scope & forbidden scope — what to read / search and what not to touch." },
|
|
160
|
+
acceptance: { type: "string", description: "REQUIRED for role='coder'/'tester', OPTIONAL for role='explore': machine-verifiable acceptance criteria (commands / thresholds / assertion counts)." },
|
|
161
|
+
reportFormat: { type: "string", description: "REQUIRED for role='coder'/'tester', OPTIONAL for role='explore': the delivery-report format the child must produce." },
|
|
162
|
+
thoroughness: { type: "string", enum: EXPLORE_THOROUGHNESS_VALUES, description: "role='explore' only (optional): search depth preset (defaults to medium when omitted)." },
|
|
160
163
|
async: { type: "boolean", description: "Required: `true` = async spawn (report via the auto channel); `false` = blocking; omitting it is refused. At depth>0 every spawn is synchronous — an explicit `async: true` there is refused. action:'escalate' keeps its own form: omission there still means the async flight, and `false` asks for the blocking one." },
|
|
161
164
|
files: { type: "array", items: { type: "string" }, description: "action:'spawn' only: the file write-domain this task declares — file-level paths only (cwd-relative or absolute; directories rejected — they bypass the conflict detector). Overlapping-file tasks serialize automatically. Omit = no conflict detection." },
|
|
162
165
|
dependsOn: { type: "array", items: { type: "string" }, description: "action:'spawn' only: ids from prior async returns whose outcome this task needs — queues until every dependency settles, then starts. Consumed ids count as satisfied; a cancelled/failed dependency stays queued marked 'dependency cancelled' until you decide (AUTO sessions auto-start). Unknown ids error." },
|
|
@@ -249,8 +252,8 @@ export const subagentTool = {
|
|
|
249
252
|
if (parent.config?.agent?.engineering && role === "coder") {
|
|
250
253
|
throw new Error("Engineering mode: role='coder' is disabled — use role='eng-coder' for implementation tasks (or role='eng-designer' for design writing).")
|
|
251
254
|
}
|
|
252
|
-
if (
|
|
253
|
-
throw new Error("
|
|
255
|
+
if (role === "plan") {
|
|
256
|
+
throw new Error("role='plan' subagent is retired — plan micro-steps directly in the main session with `peek` + `task` (or enter read-only plan mode via the `plan` tool).")
|
|
254
257
|
}
|
|
255
258
|
if (!parent.config?.agent?.engineering && role === "eng-coder") {
|
|
256
259
|
throw new Error("Engineering mode is not active — use role='coder' for implementation tasks.")
|
|
@@ -370,6 +373,9 @@ export const subagentTool = {
|
|
|
370
373
|
// R7 防跨回合残留:成功/折叠②/整回合停①/错误③ 四出口统一注销(设计"三路径"
|
|
371
374
|
// 口径 = 成功/折叠/整回合停——错误③ 同样 rethrow 经 finally——同归本注销)
|
|
372
375
|
disarm()
|
|
376
|
+
// SSH-TO-CODER T3:阻塞子代理退出即清它自己的 ssh 池(四出口同归这里)。
|
|
377
|
+
// 阻塞路没有撞帽挂起(`registerTurnCapCheckpoint` 对 sync 族直接返 false)——不用判暂停。
|
|
378
|
+
discardSshSessions(child)
|
|
373
379
|
}
|
|
374
380
|
// §6.8.2 R23 D-R23c1(评审 #1 🅰——生成侧补发射):sync spawn 同步收尾——若本 spawn
|
|
375
381
|
// 处于嵌套上下文(ctx.callbacks 已是嵌套 wrapper——eng-coder 内 explore 审计)→
|