thincoder 0.12.59 → 0.12.60
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 +38 -3
- package/README.md +2 -2
- package/bin/thincoder.mjs +80 -19
- package/package.json +4 -3
- package/src/acp/bridge.mjs +7 -4
- package/src/advisor/messages.mjs +24 -4
- package/src/advisor/run.mjs +35 -33
- package/src/advisor.mjs +25 -6
- package/src/agent/completion.mjs +17 -11
- package/src/agent/dispatch.mjs +102 -19
- package/src/agent/helpers.mjs +36 -0
- package/src/agent/record-results.mjs +46 -10
- package/src/agent/run-stages.mjs +227 -0
- package/src/agent/setup-reminders.mjs +62 -0
- package/src/agent/setup.mjs +18 -2
- package/src/agent/spawn-child.mjs +29 -4
- package/src/agent-tools/advisor-async.mjs +456 -0
- package/src/agent-tools/advisor.mjs +110 -108
- package/src/agent-tools/async-settle.mjs +191 -0
- package/src/agent-tools/consult.mjs +121 -102
- package/src/agent-tools/design-token.mjs +104 -0
- package/src/agent-tools/eng.mjs +24 -29
- package/src/agent-tools/escalate-async.mjs +286 -0
- package/src/agent-tools/read-history.mjs +155 -31
- package/src/agent-tools/recent-changes.mjs +2 -1
- package/src/agent-tools/settings.mjs +7 -17
- package/src/agent-tools/subagent-actions.mjs +168 -130
- package/src/agent-tools/subagent-async.mjs +129 -174
- package/src/agent-tools/subagent-panel.mjs +153 -0
- package/src/agent-tools/subagent-run.mjs +202 -0
- package/src/agent-tools/subagent-scheduler.mjs +45 -21
- package/src/agent-tools/subagent-spawn.mjs +406 -0
- package/src/agent-tools/subagent.mjs +107 -555
- package/src/agent-tools/verify.mjs +118 -270
- package/src/agent.mjs +57 -190
- package/src/cli/distill-command.mjs +10 -4
- package/src/cli/make-agent.mjs +3 -1
- package/src/cli/memory-command.mjs +2 -1
- package/src/cli/permission.mjs +2 -2
- package/src/cli/setup-wizard.mjs +17 -12
- package/src/config.mjs +56 -8
- package/src/context.mjs +5 -147
- package/src/crash-reports.mjs +123 -0
- package/src/distill.mjs +11 -11
- package/src/explore-distill.mjs +155 -0
- package/src/memory/code-sync.mjs +2 -1
- package/src/memory/core.mjs +6 -193
- package/src/memory/delete.mjs +234 -0
- package/src/memory/docs.mjs +58 -48
- package/src/memory.mjs +3 -1
- package/src/peer-domains.mjs +265 -0
- package/src/peer-instances.mjs +231 -0
- package/src/prompt-overlays.mjs +25 -0
- package/src/prompts/advisor-design.md +9 -76
- package/src/prompts/advisor-round1.md +9 -68
- package/src/prompts/advisor-round2.md +7 -54
- package/src/prompts/advisor-round3.md +7 -54
- package/src/prompts/coder.md +7 -50
- package/src/prompts/consult-base.md +4 -24
- package/src/prompts/discipline.md +26 -44
- package/src/prompts/eng-coder.md +7 -32
- package/src/prompts/engineering-sub.md +3 -23
- package/src/prompts/engineering.md +53 -306
- package/src/prompts/explore.md +3 -12
- package/src/prompts/main.md +10 -32
- package/src/prompts/methodology-template.md +28 -48
- package/src/prompts/plan.md +2 -9
- package/src/prompts/system.md +16 -35
- package/src/provider/core.mjs +6 -67
- package/src/provider/errors.mjs +76 -0
- package/src/provider/retry.mjs +8 -45
- package/src/session-gc.mjs +214 -0
- package/src/session-guard.mjs +47 -0
- package/src/session-rename.mjs +38 -0
- package/src/session-slots.mjs +181 -58
- package/src/session.mjs +48 -89
- package/src/token-ttl.mjs +273 -0
- package/src/tools/checklist-sync.mjs +181 -0
- package/src/tools/checklist.mjs +52 -39
- package/src/tools/edit-batch.mjs +109 -10
- package/src/tools/edit-diff.mjs +110 -27
- package/src/tools/edit.md +17 -12
- package/src/tools/execute.mjs +31 -4
- package/src/tools/file.mjs +11 -6
- package/src/tools/git.mjs +14 -6
- package/src/tools/glob-dialect.mjs +130 -0
- package/src/tools/glob.md +3 -3
- package/src/tools/grep.md +1 -1
- package/src/tools/index.mjs +5 -6
- package/src/tools/ops.mjs +175 -3
- package/src/tools/patch.mjs +3 -3
- package/src/tools/question.md +3 -0
- package/src/tools/read.md +0 -1
- package/src/tools/shared.mjs +14 -13
- package/src/tools/system.mjs +44 -9
- package/src/tools/wait_for.md +22 -0
- package/src/tui/agent-turn.mjs +17 -228
- package/src/tui/cmd-config.mjs +48 -7
- package/src/tui/cmd-eng.mjs +20 -16
- package/src/tui/cmd-mcp.mjs +8 -2
- package/src/tui/cmd-new.mjs +3 -2
- package/src/tui/cmd-session.mjs +19 -4
- package/src/tui/cmd-think.mjs +10 -10
- package/src/tui/cmd-upgrade.mjs +19 -4
- package/src/tui/config-helpers.mjs +28 -16
- package/src/tui/distill-cmd.mjs +1 -1
- package/src/tui/index.mjs +3 -2
- package/src/tui/interaction.mjs +3 -3
- package/src/tui/mouse.mjs +7 -1
- package/src/tui/pickers.mjs +40 -22
- package/src/tui/render-segments.mjs +27 -10
- package/src/tui/startup.mjs +4 -0
- package/src/tui/subagent-blocks.mjs +95 -263
- package/src/tui/subagent-children.mjs +176 -0
- package/src/tui/subagent-freeze.mjs +172 -0
- package/src/tui/subagent-panel.mjs +61 -23
- package/src/tui/suspension-drive.mjs +351 -0
- package/src/tui/tool-args.mjs +3 -3
- package/src/tui/tool-display.mjs +142 -0
- package/src/tui/tool-events.mjs +37 -173
- package/src/tui/tui-lifecycle.mjs +29 -0
- package/src/tui/update-notice.mjs +4 -0
- package/src/tui/wizard.mjs +12 -6
- package/src/tools/pdf-parse-text.mjs +0 -497
- package/src/tools/pdf-parse-xref.mjs +0 -499
- package/src/tools/pdf.mjs +0 -155
- package/src/tools/read_pdf.md +0 -21
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* run-stages.mjs — runAgent 主循环的阶段函数族(CLI,2026-09-05 实践轮:agent.mjs
|
|
3
|
+
* runAgent 383 ≥300 按骨干—细节两层提取——VS Code 端同构文件(双端 parity——拆分
|
|
4
|
+
* 两端同步))。本文件承载:回合压缩检查(runCompactionCheck)、回合注入组
|
|
5
|
+
* (injectTurnReminders——plan cadence + eng 状态)、回合收尾(finalizeAgentTurn——
|
|
6
|
+
* consult 清理/async 池分流/guard 继承)与其收集器(collectSettledAsync——自
|
|
7
|
+
* agent.mjs 迁入,agent.mjs 内无其他引用)。verbatim 迁移 + 签名化,语义零变。
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { compressIfNeeded, compressFallback, COMPRESS_FAILURE_LIMIT } from "../context.mjs"
|
|
11
|
+
import { ensureAutoReminder, injectEngineeringReminder, ContinueError } from "./helpers.mjs"
|
|
12
|
+
import { cleanupConsultSessions } from "../agent-tools/consult.mjs"
|
|
13
|
+
import { logEvent } from "../log.mjs"
|
|
14
|
+
// ASYNC-RESULT-CONTAINER.md D1:池 accessor(absorb 双池——advisor 独立池无队列)
|
|
15
|
+
import { getAsyncPool } from "../agent-tools/async-settle.mjs"
|
|
16
|
+
// R10 L3 (MULTI-INSTANCE-COLLAB §2a.5 D-L3a):回合末域登记 flush(写工具钩子累积 →
|
|
17
|
+
// 整写一次本实例 peers 文件——无写入跳过;失败容忍不抛)
|
|
18
|
+
import { flushPeerDomains } from "../peer-domains.mjs"
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 响应后置提醒注入(2026-09-05 实践轮——自 runAgent 响应处理链提取,verbatim):
|
|
22
|
+
* 流规则 warning(warn 动作——流已完成——去重注入,模型下轮可见)+ 异常 finish
|
|
23
|
+
* reason 警告(响应可能不完整/截断——reasonMap 人类化描述注入)。
|
|
24
|
+
*/
|
|
25
|
+
export function injectResponseReminders(agent, response) {
|
|
26
|
+
// Stream rule warnings (action: "warn"): stream completed; inject de-duplicated
|
|
27
|
+
// warnings so the model sees them before its next response.
|
|
28
|
+
if (response._warnings?.length) {
|
|
29
|
+
const deDuplicated = [...new Map(response._warnings.map(w => [w.name || w.pattern, w])).values()]
|
|
30
|
+
agent.history.push({
|
|
31
|
+
role: "user",
|
|
32
|
+
content: `[System reminder — stream rule warnings from your last response:\n${deDuplicated.map(w => `- ${w.name || w.pattern}: ${w.message}`).join("\n")}]`,
|
|
33
|
+
})
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Warn on abnormal finish reasons — the response may be incomplete/truncated.
|
|
37
|
+
if (response.finishReason && response.finishReason !== "stop" && response.finishReason !== "tool_calls") {
|
|
38
|
+
const reasonMap = {
|
|
39
|
+
length: "output token limit reached after exhausting continuations",
|
|
40
|
+
insufficient_system_resource: "provider inference resources exhausted — consider retrying or switching models",
|
|
41
|
+
content_filter: "response blocked by provider content filtering",
|
|
42
|
+
}
|
|
43
|
+
const detail = reasonMap[response.finishReason] || `unknown reason "${response.finishReason}"`
|
|
44
|
+
agent.history.push({
|
|
45
|
+
role: "user",
|
|
46
|
+
content: `[System reminder: the previous turn ended abnormally — ${detail}. The assistant response that follows may be incomplete.]`,
|
|
47
|
+
})
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 回合压缩检查(2026-09-05 实践轮——自 runAgent 主循环提取):仅安全点(history 以
|
|
53
|
+
* 完整交换结尾——user/tool 位)。成功:失败计数清零/计划提醒 cadence 复位/停滞检测
|
|
54
|
+
* 计数复位(recentCallSigs——runAgent 回合级局部——经 ctx 传对象引用)/压缩完成事件
|
|
55
|
+
* /AUTO 提醒重注入。失败:AbortError 透传;计数 + Q3 onCompressFail;
|
|
56
|
+
* COMPRESS_FAILURE_LIMIT 连续失败降级 compressFallback(确定性截断——不发 LLM)。
|
|
57
|
+
*/
|
|
58
|
+
export async function runCompactionCheck(agent, ctx) {
|
|
59
|
+
const { threshold, callbacks, compactionOverhead, signal, recentCallSigs } = ctx
|
|
60
|
+
try {
|
|
61
|
+
if (await compressIfNeeded(agent, threshold, callbacks, compactionOverhead, signal)) {
|
|
62
|
+
agent._compressFailures = 0
|
|
63
|
+
agent._planReminderAtLen = 0 // After compression history shrinks, reset cadence so reminders resume
|
|
64
|
+
recentCallSigs.length = 0 // After compression history is rebuilt, reset stall detection counter
|
|
65
|
+
// Completion info (CONTEXT-COMPACTION §7 D-C2): { mode, tokensFreed, elapsedMs } —
|
|
66
|
+
// the TUI panel renders it; callers that ignore the arg keep prior onCompress semantics.
|
|
67
|
+
callbacks.onCompress?.(agent._lastCompressInfo ?? {})
|
|
68
|
+
ensureAutoReminder(agent)
|
|
69
|
+
}
|
|
70
|
+
} catch (compressError) {
|
|
71
|
+
// AbortError must not be swallowed: user cancellation must propagate
|
|
72
|
+
if (compressError?.name === "AbortError" || signal?.aborted) throw compressError
|
|
73
|
+
agent._compressFailures = (agent._compressFailures ?? 0) + 1
|
|
74
|
+
// Q3 (CONTEXT-COMPACTION §7 D-C1): a failed compression is surfaced to the panel;
|
|
75
|
+
// COMPRESS_FAILURE_LIMIT consecutive failures still degrade to compressFallback.
|
|
76
|
+
callbacks?.onCompressFail?.(compressError)
|
|
77
|
+
if (agent._compressFailures >= COMPRESS_FAILURE_LIMIT) {
|
|
78
|
+
agent._compressFailures = 0
|
|
79
|
+
if (compressFallback(agent)) callbacks.onCompress?.(agent._lastCompressInfo ?? {})
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 回合注入组(2026-09-05 实践轮——自 runAgent 主循环提取):plan-mode 提醒 cadence
|
|
86
|
+
* (稀疏 2 轮/满 5 轮/新用户消息重置——限制不淡化)+ 工程模式状态注入(depth-0 每新
|
|
87
|
+
* 用户消息一次——见 injectEngineeringReminder)。verbatim——语义零变。
|
|
88
|
+
*/
|
|
89
|
+
export async function injectTurnReminders(agent, ctx) {
|
|
90
|
+
const { depth } = ctx
|
|
91
|
+
// Plan-mode reminder cadence: re-inject constraint reminders while plan mode is active
|
|
92
|
+
// (sparse every 2 turns, full every 5 / on new user message) so the restriction never fades.
|
|
93
|
+
if (agent.planMode) {
|
|
94
|
+
const lastMsg = agent.history.at(-1)
|
|
95
|
+
const realUserMsg = lastMsg?.role === "user"
|
|
96
|
+
&& typeof lastMsg.content === "string"
|
|
97
|
+
&& !lastMsg.content.startsWith("[System reminder:")
|
|
98
|
+
&& !lastMsg.content.startsWith("[User interrupt:")
|
|
99
|
+
const newUserSince = realUserMsg && agent.history.length > (agent._planReminderAtLen ?? 0)
|
|
100
|
+
const { planReminderForTurn } = await import("../agent-tools/plan.mjs")
|
|
101
|
+
const reminder = planReminderForTurn(agent, newUserSince)
|
|
102
|
+
if (reminder) {
|
|
103
|
+
agent._planReminderAtLen = agent.history.length + 1
|
|
104
|
+
agent.history.push({ role: "user", content: reminder, transient: true })
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Engineering-mode status injection on every new user message (design-before-code
|
|
109
|
+
// vs standard discipline) — see injectEngineeringReminder.
|
|
110
|
+
if (depth === 0) {
|
|
111
|
+
injectEngineeringReminder(agent)
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* 回合收尾(2026-09-05 实践轮——自 runAgent finally 提取,verbatim + 签名化):
|
|
117
|
+
* consult 清理(无孤儿烧 token 的 consult children)→ async 池回合尾分流(Ctrl+C
|
|
118
|
+
* 清池不注入 / ContinueError 留池续跑 / 其余 collectSettledAsync)→ auto-turn guard
|
|
119
|
+
* 标记继承(对象字段清单——正常结束才继承;中止丢弃;ContinueError 由续跑快照)。
|
|
120
|
+
*/
|
|
121
|
+
export async function finalizeAgentTurn(agent, ctx) {
|
|
122
|
+
const { signal, autoTurn, suspDriven, thrownError } = ctx
|
|
123
|
+
// R10 L3(MULTI-INSTANCE-COLLAB §2a.5 D-L3a):回合末登记 flush——本回合写足迹整写
|
|
124
|
+
// 一次(首行执行:收尾链后续任何异常都不吞登记);无写入 → 跳过(hot 窗口自然衰减)。
|
|
125
|
+
flushPeerDomains(agent)
|
|
126
|
+
// R17(AGENT-LOOP.md §25 D-R17a): consultation sessions are cross-turn
|
|
127
|
+
// background work now — NO unconditional turn-end cleanup (the old rule aborted
|
|
128
|
+
// leftover consult children at every turn end because check-loop consumption was
|
|
129
|
+
// turn-scoped). Sessions stay alive across normal turn ends (and ContinueError
|
|
130
|
+
// resumes); the Ctrl+C abort branch below is the only path that aborts them
|
|
131
|
+
// (cleanupConsultSessions — marked stopped → no digest), and the suspension
|
|
132
|
+
// driver aborts them on its own abort unwind.
|
|
133
|
+
// Async subagent turn-end handling (AGENT-LOOP.md §15 D-A3 + §17 D-S1). Lifecycle:
|
|
134
|
+
// - Ctrl+C (plain abort): children were aborted with the parent signal — clear
|
|
135
|
+
// WITHOUT injecting stale errors (user explicitly stopped); consultation
|
|
136
|
+
// sessions are cross-turn background work since R17 — the abort branch is the
|
|
137
|
+
// ONLY normal-path place that aborts them (cleanupConsultSessions marks
|
|
138
|
+
// stopped → their settles never reach the digest stream).
|
|
139
|
+
// - Ctrl+I (interrupt): keeps the pool AND the consult sessions: the turn
|
|
140
|
+
// resumes with the interrupt message, children stay tracked (in a suspension
|
|
141
|
+
// session children hold agent._sessionSignal and a digest's own Ctrl+I must
|
|
142
|
+
// not orphan them).
|
|
143
|
+
// - ContinueError (turn cap): no wait, no injection — children keep running and
|
|
144
|
+
// the RESUME run's turn-end collection takes over.
|
|
145
|
+
// - anything else: inject the SETTLED entries only; running/queued stay in the
|
|
146
|
+
// pool for the suspension session (D-S1 — no allSettled turn-end wait).
|
|
147
|
+
if (signal?.aborted && !signal?.reason?.interrupt) {
|
|
148
|
+
const subPool = getAsyncPool(agent, "subagent")
|
|
149
|
+
const advPool = getAsyncPool(agent, "advisor")
|
|
150
|
+
if ((subPool?.size ?? 0) > 0 || (advPool?.size ?? 0) > 0) {
|
|
151
|
+
logEvent("ev:stopped", { poolN: (subPool?.size ?? 0) + (advPool?.size ?? 0), where: "turn-end-abort" })
|
|
152
|
+
}
|
|
153
|
+
subPool?.clear()
|
|
154
|
+
advPool?.clear()
|
|
155
|
+
agent._asyncQueue = []
|
|
156
|
+
// R17: the consult family dies with the user stop (marked stopped — no digest).
|
|
157
|
+
cleanupConsultSessions(agent)
|
|
158
|
+
// ASYNC-RESULT-CONTAINER.md D2:pending 单容器——中止丢弃 consult/escalate 族停靠
|
|
159
|
+
// (原 _pendingConsultResults/_pendingEscalateResults 同口径——VSC 同语义 filter);
|
|
160
|
+
// subagent/advisor 停靠保留(挂起期 settle 的已完成结果不随中止丢)。
|
|
161
|
+
agent._pendingAsyncResults = (agent._pendingAsyncResults ?? []).filter((e) => e.role !== "consult" && e.role !== "escalate")
|
|
162
|
+
} else if (thrownError instanceof ContinueError) {
|
|
163
|
+
// keep _asyncSubagents/_asyncAdvisors/_consultSessions — the resumed run continues them
|
|
164
|
+
} else {
|
|
165
|
+
const injectedAdvisor = await collectSettledAsync(agent, { suspDriven })
|
|
166
|
+
// §24 D-24b: a normally-ended USER run with no review/child activity closes
|
|
167
|
+
// the OPEN code instances — the converged/abandoned thread must not burn the
|
|
168
|
+
// 5-round cap of a later task (the next code review starts a fresh round 1).
|
|
169
|
+
// Digest auto-turns are exempt (their disposition precedes the fix round).
|
|
170
|
+
// A run whose turn-end collection just INJECTED a settled review report
|
|
171
|
+
// (headless, suspDriven=false) must NOT close: the model has not digested
|
|
172
|
+
// the findings yet — the fix round that follows still continues the thread.
|
|
173
|
+
if (!autoTurn && !injectedAdvisor) {
|
|
174
|
+
const { closeOpenCodeAdvisorRuns } = await import("../agent-tools/advisor-async.mjs")
|
|
175
|
+
closeOpenCodeAdvisorRuns(agent)
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
agent._inAutoTurn = false
|
|
179
|
+
// §17 D-S6: auto-turn guard marks survive into the next USER run (restored at its
|
|
180
|
+
// !resume reset above). Normal ends only — abort discards; ContinueError lets the
|
|
181
|
+
// auto-resumed run snapshot at its own end.
|
|
182
|
+
if (autoTurn && !(signal?.aborted && !signal?.reason?.interrupt) && !(thrownError instanceof ContinueError)) {
|
|
183
|
+
agent._inheritedGuard = {
|
|
184
|
+
_mutatedThisRun: agent._mutatedThisRun, _verifiedThisRun: agent._verifiedThisRun,
|
|
185
|
+
_verifyPassed: agent._verifyPassed, _calledAdvisorThisRun: agent._calledAdvisorThisRun,
|
|
186
|
+
_touchedFiles: agent._touchedFiles, _verifyRetries: agent._verifyRetries,
|
|
187
|
+
_advisorRound: agent._advisorRound,
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Turn-end async subagent collection (AGENT-LOOP.md §17 D-S1 + §17.5 supersede):
|
|
194
|
+
* two modes, selected by the caller's driver context (17.5.2/17.5.4 #2):
|
|
195
|
+
* - suspDriven=false (fallback — headless/direct runAgent callers without a
|
|
196
|
+
* suspension driver): inject every entry that SETTLED during this run
|
|
197
|
+
* (XML-escaped report/error — child reports may carry file/webpage content;
|
|
198
|
+
* >64K offloaded with preview + path) and remove it from the pool. Running/
|
|
199
|
+
* queued STAY — no allSettled wait. Results never lost without a session.
|
|
200
|
+
* - suspDriven=true (the interaction layer runs suspensionSession after this
|
|
201
|
+
* run): NO direct inject — settled entries STAY pooled (settled not consumed)
|
|
202
|
+
* for the session's first sweepSettledToPending → digest turn (§17.5 — done
|
|
203
|
+
* 条目留池等消化轮注入;status 在 sweep 前仍从池读——17.5.2 不变面(§19.8:check 已删——自动通道为唯一消费方))。
|
|
204
|
+
* maybeRefillAsync runs in both modes (starts queued heads whose slot freed).
|
|
205
|
+
* Single ownership: entries settled inside a suspension session were moved to
|
|
206
|
+
* _pendingAsyncResults by the settle callback, so this only sees user-turn
|
|
207
|
+
* settles (no double inject — D-S3 points ①/②). The ⟦ev⟧done freeze is NOT
|
|
208
|
+
* emitted here — each settle callback emits it (§15 D-A3).
|
|
209
|
+
* 2026-09-05 实践轮:自 agent.mjs 迁入(agent.mjs 内仅 finalize 引用——随收尾同迁)。
|
|
210
|
+
*/
|
|
211
|
+
async function collectSettledAsync(agent, { suspDriven = false } = {}) {
|
|
212
|
+
const maps = [getAsyncPool(agent, "subagent"), getAsyncPool(agent, "advisor")].filter((m) => m instanceof Map && m.size > 0)
|
|
213
|
+
if (maps.length === 0) return false
|
|
214
|
+
const { maybeRefillAsync, injectAsyncResult } = await import("../agent-tools/subagent.mjs")
|
|
215
|
+
maybeRefillAsync(agent) // start queued heads now that slots may have freed — no waiting
|
|
216
|
+
if (suspDriven) return false // §17.5: settled stays pooled — the suspension session digests it
|
|
217
|
+
let injectedAdvisor = false
|
|
218
|
+
for (const map of maps) {
|
|
219
|
+
for (const e of [...map.values()]) {
|
|
220
|
+
if (!e.done) continue // still running — stays in the pool (D-S1)
|
|
221
|
+
await injectAsyncResult(agent, e)
|
|
222
|
+
if (e.role === "advisor") injectedAdvisor = true
|
|
223
|
+
map.delete(String(e.id))
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return injectedAdvisor
|
|
227
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agent/setup-reminders.mjs — per-turn transient reminders
|
|
3
|
+
* (SESSION.md §11.1 — 2026-09-06 需求池 R5/R8/R9/R11 合并设计; R10 L1 peer 注入同文件).
|
|
4
|
+
*
|
|
5
|
+
* One unified transient user reminder per turn covers the whole self-awareness
|
|
6
|
+
* family: env identity (R8 — §10 D-1 END 常量先例:静态常量,不做 cmdline 判别),
|
|
7
|
+
* engineering mode (R9), active model (R11), restart awareness (R5 resumed).
|
|
8
|
+
* Change awareness needs no dedicated injection — every turn carries the
|
|
9
|
+
* CURRENT state, so a mode/model flip shows up in the next turn's line.
|
|
10
|
+
* git is NOT a field here (§11.1: CLI 不重复注入 clean|dirty 摘要) — the rich
|
|
11
|
+
* git-context injection (branch/commits/uncommitted — helpers.mjs
|
|
12
|
+
* collectGitContext, wired in setup.mjs) carries it.
|
|
13
|
+
* Peer awareness (R10 L1) rides the same per-turn transient channel:
|
|
14
|
+
* pushPeerReminder injects the live co-cwd instance list when present.
|
|
15
|
+
*/
|
|
16
|
+
import { END } from "../session-slots.mjs"
|
|
17
|
+
import { peerInstances } from "../peer-instances.mjs"
|
|
18
|
+
|
|
19
|
+
/** env-state line builder — pure, unit-testable. */
|
|
20
|
+
export function envStateLine({ mode, model, resumed }) {
|
|
21
|
+
return `[System reminder: env: ${END}, mode: ${mode}, model: ${model}, resumed: ${resumed ? "yes" : "no"}.]`
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Push the per-turn env-state reminder (setup.mjs calls it for depth-0 runs —
|
|
26
|
+
* the line describes the MAIN agent's host/mode/model identity). resumed=yes
|
|
27
|
+
* exactly once: the first turn after a restored session (setup.mjs sets
|
|
28
|
+
* agent._envResumed alongside the `process restarted` reminder); consumed here
|
|
29
|
+
* so every later turn reads resumed=no (T-E5).
|
|
30
|
+
* Degrades safely: activeModel null → provider.model → "unknown" (T-E12);
|
|
31
|
+
* a missing config/history never throws (T-E13).
|
|
32
|
+
*/
|
|
33
|
+
export function pushEnvStateReminder(agent) {
|
|
34
|
+
const mode = agent.config?.agent?.engineering ? "eng" : "normal"
|
|
35
|
+
const model = agent.activeModel ?? agent.provider?.model ?? "unknown"
|
|
36
|
+
const resumed = agent._envResumed === true
|
|
37
|
+
agent._envResumed = false
|
|
38
|
+
agent.history.push({ role: "user", content: envStateLine({ mode, model, resumed }), transient: true })
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* R10 L1 peer reminder(MULTI-INSTANCE-COLLAB §2a.4 D-L1a——仿 pushEnvStateReminder
|
|
43
|
+
* 形态:depth-0、transient:true——注入纪律同 env-state)。有同伴(非 self > 0)才注入
|
|
44
|
+
* ——无同伴零开销(peerInstances 惰性 mtime 缓存保证:manifest 未变零 exec)。任何
|
|
45
|
+
* 感知失败静默跳过(注入绝不打断回合)。文案(设计逐字):"本目录另有 N 个活跃
|
|
46
|
+
* thincoder({end} pid={pid}…)——文件操作注意避让"。
|
|
47
|
+
*/
|
|
48
|
+
export function pushPeerReminder(agent) {
|
|
49
|
+
let peers
|
|
50
|
+
try {
|
|
51
|
+
peers = peerInstances(agent.cwd).filter((p) => !p.self)
|
|
52
|
+
} catch {
|
|
53
|
+
return // 感知失败降级——不注入
|
|
54
|
+
}
|
|
55
|
+
if (peers.length === 0) return
|
|
56
|
+
const who = peers.map((p) => (p.end ? `${p.end} pid=${p.pid}` : `pid=${p.pid}`)).join("、")
|
|
57
|
+
agent.history.push({
|
|
58
|
+
role: "user",
|
|
59
|
+
content: `[System reminder: 本目录另有 ${peers.length} 个活跃 thincoder(${who})——文件操作注意避让]`,
|
|
60
|
+
transient: true,
|
|
61
|
+
})
|
|
62
|
+
}
|
package/src/agent/setup.mjs
CHANGED
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
collectGitContext, loadProjectInstructions, OUTLINE_INJECT_PREFIX,
|
|
16
16
|
DEFAULT_MAX_TURNS, ensureAutoReminder,
|
|
17
17
|
} from "./helpers.mjs"
|
|
18
|
+
import { pushEnvStateReminder, pushPeerReminder } from "./setup-reminders.mjs"
|
|
18
19
|
import { readFileSync, existsSync } from "node:fs"
|
|
19
20
|
import { resolve, dirname } from "node:path"
|
|
20
21
|
import { fileURLToPath } from "node:url"
|
|
@@ -113,6 +114,9 @@ export async function prepareRun(agent, input, callbacks, {
|
|
|
113
114
|
}
|
|
114
115
|
if (wasRestored && !agent._restartReminderInjected) {
|
|
115
116
|
agent._restartReminderInjected = true
|
|
117
|
+
// SESSION.md §11.1 R5: the per-turn env-state reminder carries resumed:yes
|
|
118
|
+
// on THIS first turn after the restore (consumed by pushEnvStateReminder).
|
|
119
|
+
agent._envResumed = true
|
|
116
120
|
agent.history.push({ role: "user", content: `[System reminder: process restarted at ${new Date().toISOString()}.]`, transient: true })
|
|
117
121
|
}
|
|
118
122
|
if (agent.memory && !agent.history.some((m) => typeof m.content === "string" && m.content.startsWith(OUTLINE_INJECT_PREFIX))) {
|
|
@@ -167,6 +171,16 @@ export async function prepareRun(agent, input, callbacks, {
|
|
|
167
171
|
}
|
|
168
172
|
pushReal(agent, { role: "user", content: input })
|
|
169
173
|
}
|
|
174
|
+
// SESSION.md §11.1: unified per-turn env-state transient reminder (env/mode/
|
|
175
|
+
// model/resumed — R5/R8/R9/R11 one-shot coverage; changes surface next turn).
|
|
176
|
+
// R10 L1 (MULTI-INSTANCE-COLLAB §2a.4 D-L1a): peer-instance reminder right after
|
|
177
|
+
// env-state, BEFORE the time reminder — the time reminder stays LAST (prefix-cache
|
|
178
|
+
// contract). Both depth-0 only (describe the MAIN agent / its workspace peers).
|
|
179
|
+
if (depth === 0) {
|
|
180
|
+
pushEnvStateReminder(agent)
|
|
181
|
+
pushPeerReminder(agent)
|
|
182
|
+
}
|
|
183
|
+
|
|
170
184
|
// Time grounding for EVERY agent depth AND every resume, pushed LAST (after the user
|
|
171
185
|
// input): transient on the HUMAN line — dropped on persist; on the MACHINE line — kept
|
|
172
186
|
// (byte-identical resume for the provider prefix cache, 2026-08-16), fresh at every run start
|
|
@@ -188,7 +202,7 @@ export async function prepareRun(agent, input, callbacks, {
|
|
|
188
202
|
// task/plan tools are injected with the main loop; subagent/skill/goal/verify only at top level
|
|
189
203
|
// eng-coder subagents get advisor for mandatory design review before coding
|
|
190
204
|
const { planTool, subagentTool, taskTool, skillTool, goalTool, verifyTool, recentChangesTool, timerTool, advisorTool, engTool, readHistoryTool } = await import("../agent-tools.mjs")
|
|
191
|
-
const { consultStartTool,
|
|
205
|
+
const { consultStartTool, consultStopTool } = await import("../agent-tools/consult.mjs")
|
|
192
206
|
const { CONSULT_BASE } = await import("../agent.mjs")
|
|
193
207
|
// withPool: decorate the consult_start description with the CURRENT candidate pool
|
|
194
208
|
// so the model knows which models it can pick (CLI parity with the plugin). The
|
|
@@ -275,9 +289,11 @@ export async function prepareRun(agent, input, callbacks, {
|
|
|
275
289
|
// consult 工具仅在配置时注册(consultModels 空池时注册会让模型调用后吃一个错误回合)——
|
|
276
290
|
// §19: escalate 已并入常驻 subagent 的 action:"escalate"(无空池注册问题——动作在
|
|
277
291
|
// 池空时返回既有错误语义,工程模式 fail-closed 在 execute 内拒绝)。
|
|
292
|
+
// §25 D-R17a: consult_check 已退役(digest 自动注入是唯一消费通道)——consult 家族
|
|
293
|
+
// 只剩 2 工具(consult_start/consult_stop——setup 注册点与描述面同步清零)。
|
|
278
294
|
const consultModels = agent.config?.agent?.consultModels ?? []
|
|
279
295
|
const consultTools = consultModels.length
|
|
280
|
-
? [withPool(consultStartTool),
|
|
296
|
+
? [withPool(consultStartTool), consultStopTool]
|
|
281
297
|
: []
|
|
282
298
|
const depthOnly = depth === 0 ? [filteredSubagent, skillTool, goalTool, engTool, verifyTool, recentChangesTool, readHistoryTool, advisorTool, ...consultTools]
|
|
283
299
|
// SESSION.md §9 D-S2: read_history is depth-0 ONLY — a subagent querying "the session"
|
|
@@ -106,25 +106,45 @@ export function stripEventTokensForCapture(text) {
|
|
|
106
106
|
* - onToolOutput 带**已加前缀**的 name 走父 onToolOutput(name 形如
|
|
107
107
|
* "coder#1/bash",消费端剥前缀路由进对应区块;chunk 对象/裸串原样透传)。
|
|
108
108
|
* 父回调缺省时不包装(headless 嵌入)。
|
|
109
|
+
* §27 R23 D-R23c1:包装产物在 onToken 上留 `_relayPrefix` 标记——同步收尾段据此
|
|
110
|
+
* 判定"ctx.callbacks 已是嵌套 wrapper"(本 spawn 处于更深一层——eng-coder 内
|
|
111
|
+
* explore)→ emitNestedChildEvent 补发射内层完成事件(T-R23c.2b 断言源)。
|
|
109
112
|
*/
|
|
110
113
|
export function wrapChildCallbacks(relayPrefix, parentCallbacks = {}) {
|
|
114
|
+
const mark = (fn) => { fn._relayPrefix = relayPrefix; return fn }
|
|
111
115
|
const wrapped = {
|
|
112
116
|
onToken: parentCallbacks.onToken
|
|
113
|
-
? (t) => parentCallbacks.onToken(relayPrefix + stripEventToken(String(t)))
|
|
117
|
+
? mark((t) => parentCallbacks.onToken(relayPrefix + stripEventToken(String(t))))
|
|
114
118
|
: null,
|
|
115
119
|
onReasoning: parentCallbacks.onReasoning
|
|
116
|
-
? (t) => parentCallbacks.onReasoning(relayPrefix + t)
|
|
120
|
+
? mark((t) => parentCallbacks.onReasoning(relayPrefix + t))
|
|
117
121
|
: null,
|
|
118
122
|
onToolCall: parentCallbacks.onToolCall
|
|
119
|
-
? (name, args) => parentCallbacks.onToolCall(relayPrefix + name, args)
|
|
123
|
+
? mark((name, args) => parentCallbacks.onToolCall(relayPrefix + name, args))
|
|
120
124
|
: null,
|
|
121
125
|
onToolOutput: parentCallbacks.onToolOutput
|
|
122
|
-
? (name, chunk) => parentCallbacks.onToolOutput(relayPrefix + name, chunk)
|
|
126
|
+
? mark((name, chunk) => parentCallbacks.onToolOutput(relayPrefix + name, chunk))
|
|
123
127
|
: null,
|
|
124
128
|
}
|
|
125
129
|
return wrapped
|
|
126
130
|
}
|
|
127
131
|
|
|
132
|
+
/**
|
|
133
|
+
* §27 R23 D-R23c1(生成侧补发射——评审 #1 🅰):sync spawn 同步收尾时若父回调已是
|
|
134
|
+
* 嵌套 wrapper(onToken 带 `_relayPrefix` 标记——即本 spawn 的父本身是子代理,如
|
|
135
|
+
* eng-coder 内 explore 审计)→ 发内层 done/stopped 事件(带完整嵌套前缀——wrapper
|
|
136
|
+
* 链自动补外层前缀)→ 主 TUI routeSubToken 路由到子块定格。非嵌套(depth-0 直连主
|
|
137
|
+
* 回调——无标记)不发——完成冻结仍走既有 onToolResult/subKey 路径(零行为变化)。
|
|
138
|
+
* @returns {boolean} true = 已发射(嵌套上下文)
|
|
139
|
+
*/
|
|
140
|
+
export function emitNestedChildEvent(ctx, relayPrefix, kind) {
|
|
141
|
+
const onToken = ctx?.callbacks?.onToken
|
|
142
|
+
if (typeof onToken?._relayPrefix !== "string" || !onToken._relayPrefix) return false
|
|
143
|
+
if (kind !== "done" && kind !== "stopped") return false
|
|
144
|
+
onToken(`${relayPrefix}⟦ev⟧${kind}\x1e0\x1e0\x1e${kind}\x1e`)
|
|
145
|
+
return true
|
|
146
|
+
}
|
|
147
|
+
|
|
128
148
|
/**
|
|
129
149
|
* 子 agent provider API key 检查:trim 后非空才保留;缺失返回 null(调用方
|
|
130
150
|
* 按各自业务语汇报错——subagent 抛出 / escalate·consult 返回 Error 文本)。
|
|
@@ -173,6 +193,11 @@ export async function runWithContinue(runner, child, input, callbacks, runOpts,
|
|
|
173
193
|
const capture = callbacks?.onToken
|
|
174
194
|
? (t) => { output += stripEventTokensForCapture(String(t)); child._capturedOutput = output; callbacks.onToken(t) }
|
|
175
195
|
: (t) => { output += stripEventTokensForCapture(String(t)); child._capturedOutput = output }
|
|
196
|
+
// §27 R23 D-R23c1(评审 🔴 修复——2026-09-07):capture 是子代理 runAgent/dispatch ctx
|
|
197
|
+
// 实际收到的 onToken——嵌套 wrapper 标记(wrapChildCallbacks `_relayPrefix`)必须随
|
|
198
|
+
// capture 透传,否则 eng-coder 内 explore 同步收尾的 emitNestedChildEvent 判定恒 false
|
|
199
|
+
// (生成侧补发射结构性不可达——T-R23c.2b 真实路径回归)。
|
|
200
|
+
if (callbacks?.onToken?._relayPrefix) capture._relayPrefix = callbacks.onToken._relayPrefix
|
|
176
201
|
for (let resume = false; ; resume = true) {
|
|
177
202
|
try {
|
|
178
203
|
return await runner(child, input, { ...callbacks, onToken: capture }, { ...runOpts, resume })
|