thincoder 0.12.59 → 0.12.61

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.
Files changed (192) hide show
  1. package/CHANGELOG.md +62 -4
  2. package/README.md +10 -8
  3. package/bin/thincoder.mjs +99 -133
  4. package/package.json +6 -4
  5. package/src/abort-provenance.mjs +116 -0
  6. package/src/acp/bridge.mjs +45 -21
  7. package/src/acp.mjs +6 -1
  8. package/src/advisor/citations.mjs +83 -21
  9. package/src/advisor/compaction.mjs +174 -0
  10. package/src/advisor/loop.mjs +293 -0
  11. package/src/advisor/messages.mjs +59 -137
  12. package/src/advisor/project-context.mjs +194 -0
  13. package/src/advisor/repos.mjs +17 -40
  14. package/src/advisor/run.mjs +156 -359
  15. package/src/advisor/truncate.mjs +57 -0
  16. package/src/advisor.mjs +27 -7
  17. package/src/agent/completion.mjs +17 -11
  18. package/src/agent/dispatch.mjs +145 -27
  19. package/src/agent/helpers.mjs +107 -13
  20. package/src/agent/record-results.mjs +55 -11
  21. package/src/agent/relay-prefix.mjs +39 -0
  22. package/src/agent/run-stages.mjs +242 -0
  23. package/src/agent/setup-reminders.mjs +69 -0
  24. package/src/agent/setup.mjs +107 -127
  25. package/src/agent/spawn-child.mjs +55 -13
  26. package/src/agent-tools/advisor-async.mjs +346 -0
  27. package/src/agent-tools/advisor-settle.mjs +231 -0
  28. package/src/agent-tools/advisor.mjs +167 -116
  29. package/src/agent-tools/async-settle.mjs +191 -0
  30. package/src/agent-tools/batch-segment.mjs +195 -0
  31. package/src/agent-tools/consult.mjs +139 -107
  32. package/src/agent-tools/design-token.mjs +117 -0
  33. package/src/agent-tools/digest-budget.mjs +76 -0
  34. package/src/agent-tools/eng.mjs +24 -29
  35. package/src/agent-tools/escalate-async.mjs +289 -0
  36. package/src/agent-tools/read-history.mjs +166 -32
  37. package/src/agent-tools/recent-changes.mjs +2 -1
  38. package/src/agent-tools/review-streak.mjs +93 -0
  39. package/src/agent-tools/settings.mjs +137 -34
  40. package/src/agent-tools/subagent-actions.mjs +180 -133
  41. package/src/agent-tools/subagent-async.mjs +184 -177
  42. package/src/agent-tools/subagent-panel.mjs +160 -0
  43. package/src/agent-tools/subagent-run.mjs +205 -0
  44. package/src/agent-tools/subagent-scheduler.mjs +100 -27
  45. package/src/agent-tools/subagent-spawn.mjs +453 -0
  46. package/src/agent-tools/subagent.mjs +256 -578
  47. package/src/agent-tools/verify.mjs +119 -292
  48. package/src/agent-tools.mjs +1 -0
  49. package/src/agent.mjs +89 -205
  50. package/src/cli/distill-command.mjs +12 -6
  51. package/src/cli/make-agent.mjs +26 -8
  52. package/src/cli/memory-command.mjs +4 -3
  53. package/src/cli/permission.mjs +2 -2
  54. package/src/cli/setup-wizard.mjs +42 -17
  55. package/src/completions.mjs +114 -0
  56. package/src/config-migrate.mjs +70 -0
  57. package/src/config.mjs +180 -63
  58. package/src/context.mjs +5 -147
  59. package/src/conventions.mjs +223 -0
  60. package/src/crash-reports.mjs +128 -0
  61. package/src/distill.mjs +11 -11
  62. package/src/expand-home.mjs +16 -0
  63. package/src/explore-distill.mjs +155 -0
  64. package/src/generate-title.mjs +1 -1
  65. package/src/hooks.mjs +7 -3
  66. package/src/memory/code-index.mjs +9 -3
  67. package/src/memory/code-sync.mjs +72 -32
  68. package/src/memory/core.mjs +6 -193
  69. package/src/memory/delete.mjs +236 -0
  70. package/src/memory/docs.mjs +68 -54
  71. package/src/memory/file-walk.mjs +109 -0
  72. package/src/memory/schema.mjs +15 -3
  73. package/src/memory.mjs +3 -1
  74. package/src/model-ref.mjs +66 -0
  75. package/src/model-specs.mjs +42 -8
  76. package/src/peer-domains.mjs +265 -0
  77. package/src/peer-instances.mjs +231 -0
  78. package/src/prompt-overlays.mjs +82 -0
  79. package/src/prompts/advisor-design.md +18 -75
  80. package/src/prompts/advisor-round1.md +14 -67
  81. package/src/prompts/advisor-round2.md +15 -51
  82. package/src/prompts/advisor-round3.md +15 -51
  83. package/src/prompts/common.md +115 -0
  84. package/src/prompts/consult-base.md +5 -23
  85. package/src/prompts/discipline-engineering.md +217 -0
  86. package/src/prompts/discipline-normal.md +179 -0
  87. package/src/prompts/persona-coder.md +21 -0
  88. package/src/prompts/persona-eng-coder.md +37 -0
  89. package/src/prompts/persona-eng-designer.md +55 -0
  90. package/src/prompts/persona-engineering.md +54 -0
  91. package/src/prompts/persona-explore.md +15 -0
  92. package/src/prompts/persona-normal.md +27 -0
  93. package/src/prompts/persona-plan.md +26 -0
  94. package/src/provider/anthropic.mjs +4 -4
  95. package/src/provider/core.mjs +18 -98
  96. package/src/provider/errors.mjs +101 -0
  97. package/src/provider/google.mjs +5 -6
  98. package/src/provider/index.mjs +2 -1
  99. package/src/provider/list-models.mjs +93 -0
  100. package/src/provider/rate.mjs +2 -1
  101. package/src/provider/responses.mjs +5 -3
  102. package/src/provider/retry.mjs +8 -45
  103. package/src/provider/sse.mjs +3 -4
  104. package/src/proxy.mjs +9 -14
  105. package/src/session-gc.mjs +214 -0
  106. package/src/session-guard.mjs +47 -0
  107. package/src/session-rename.mjs +38 -0
  108. package/src/session-slots.mjs +188 -60
  109. package/src/session.mjs +104 -124
  110. package/src/token-ttl.mjs +274 -0
  111. package/src/tools/{system.mjs → bash.mjs} +19 -221
  112. package/src/tools/checklist-sync.mjs +181 -0
  113. package/src/tools/checklist.mjs +52 -39
  114. package/src/tools/edit-batch.mjs +109 -10
  115. package/src/tools/edit-diff.mjs +110 -27
  116. package/src/tools/edit.md +17 -12
  117. package/src/tools/execute.mjs +31 -4
  118. package/src/tools/file.mjs +41 -16
  119. package/src/tools/git.md +1 -1
  120. package/src/tools/git.mjs +23 -34
  121. package/src/tools/glob-dialect.mjs +130 -0
  122. package/src/tools/glob.md +3 -3
  123. package/src/tools/grep.md +1 -1
  124. package/src/tools/index.mjs +9 -8
  125. package/src/tools/ops.mjs +188 -3
  126. package/src/tools/patch.mjs +3 -3
  127. package/src/tools/question.md +4 -0
  128. package/src/tools/question.mjs +26 -0
  129. package/src/tools/read.md +1 -2
  130. package/src/tools/read_image.md +1 -1
  131. package/src/tools/search.mjs +236 -0
  132. package/src/tools/shared.mjs +14 -13
  133. package/src/tools/wait_for.md +22 -0
  134. package/src/tui/agent-turn.mjs +36 -228
  135. package/src/tui/ansi.mjs +2 -0
  136. package/src/tui/clipboard.mjs +7 -1
  137. package/src/tui/cmd-advisor.mjs +3 -2
  138. package/src/tui/cmd-config.mjs +142 -30
  139. package/src/tui/cmd-eng.mjs +28 -40
  140. package/src/tui/cmd-exit.mjs +6 -8
  141. package/src/tui/cmd-mcp.mjs +8 -2
  142. package/src/tui/cmd-model.mjs +14 -12
  143. package/src/tui/cmd-new.mjs +3 -2
  144. package/src/tui/cmd-reindex.mjs +7 -0
  145. package/src/tui/cmd-session.mjs +19 -4
  146. package/src/tui/cmd-submodel.mjs +8 -5
  147. package/src/tui/cmd-think.mjs +10 -10
  148. package/src/tui/cmd-undo.mjs +4 -3
  149. package/src/tui/cmd-upgrade.mjs +19 -4
  150. package/src/tui/config-helpers.mjs +28 -16
  151. package/src/tui/distill-cmd.mjs +1 -1
  152. package/src/tui/index.mjs +40 -38
  153. package/src/tui/interaction.mjs +3 -3
  154. package/src/tui/key-handler.mjs +61 -17
  155. package/src/tui/key-modes.mjs +86 -8
  156. package/src/tui/layout.mjs +18 -10
  157. package/src/tui/model-catalog.mjs +89 -0
  158. package/src/tui/model-picker.mjs +498 -0
  159. package/src/tui/mouse.mjs +52 -9
  160. package/src/tui/pickers.mjs +28 -392
  161. package/src/tui/render-frame.mjs +32 -16
  162. package/src/tui/render-loop.mjs +2 -0
  163. package/src/tui/render-segments.mjs +12 -9
  164. package/src/tui/render.mjs +37 -5
  165. package/src/tui/slash-commands.mjs +2 -2
  166. package/src/tui/startup.mjs +4 -0
  167. package/src/tui/subagent-blocks.mjs +106 -295
  168. package/src/tui/subagent-children.mjs +162 -0
  169. package/src/tui/subagent-freeze.mjs +169 -0
  170. package/src/tui/subagent-panel.mjs +24 -31
  171. package/src/tui/suspension-drive.mjs +297 -0
  172. package/src/tui/tool-args.mjs +7 -5
  173. package/src/tui/tool-display.mjs +143 -0
  174. package/src/tui/tool-events.mjs +56 -185
  175. package/src/tui/tui-lifecycle.mjs +46 -4
  176. package/src/tui/update-notice.mjs +4 -0
  177. package/src/tui/wizard.mjs +61 -21
  178. package/src/tui/wrapped-spawn.mjs +38 -0
  179. package/src/prompts/coder.md +0 -56
  180. package/src/prompts/discipline.md +0 -102
  181. package/src/prompts/eng-coder.md +0 -44
  182. package/src/prompts/engineering-sub.md +0 -34
  183. package/src/prompts/engineering.md +0 -340
  184. package/src/prompts/explore.md +0 -21
  185. package/src/prompts/main.md +0 -56
  186. package/src/prompts/methodology-template.md +0 -58
  187. package/src/prompts/plan.md +0 -16
  188. package/src/prompts/system.md +0 -63
  189. package/src/tools/pdf-parse-text.mjs +0 -497
  190. package/src/tools/pdf-parse-xref.mjs +0 -499
  191. package/src/tools/pdf.mjs +0 -155
  192. package/src/tools/read_pdf.md +0 -21
@@ -16,13 +16,19 @@
16
16
  * invalidate verify only (user decision 2026-08-08: reviews trigger on
17
17
  * code mutations, not environment changes).
18
18
  * - advisor calls always advance _advisorRound (convergence budget counts
19
- * attempts, not successes).
19
+ * attempts, not successes). §15 F16 (2026-09-11 第 13 批): the SYNC
20
+ * called-mark is gated by the single incomplete-tail predicate
21
+ * (advisorIncompleteMarker) — a truncated-then-settled CODE review must not
22
+ * count as covered (the guard re-pushes); design reviews keep the mark
23
+ * (no code face — settle-side `failureVerdict` parity).
20
24
  * - Mutations feed _touchedFiles and fire-and-forget memory reindex.
21
25
  */
22
26
  import { pushReal } from "../context.mjs"
23
27
  import { specForModel } from "../config.mjs"
24
28
  import { FILE_MUTATORS } from "./helpers.mjs"
25
- import { join } from "node:path"
29
+ import { resolve } from "node:path"
30
+ import { advisorRuns, stripApprovedSuffix } from "../agent-tools/advisor-async.mjs"
31
+ import { looksLikeReviewOutput, advisorIncompleteMarker } from "../advisor/run.mjs"
26
32
 
27
33
  let _reindexFile = null
28
34
 
@@ -72,6 +78,9 @@ export async function recordToolResults(agent, toolByName, results) {
72
78
  // Direct file edit — code was changed. The prior advisor review and
73
79
  // verify are stale: a review that ran before the edit no longer
74
80
  // covers the current file state.
81
+ // §29 fix A(AGENT-LOOP.md §29——2026-09-07):mutation-seq 记账已移到 dispatch
82
+ // runOne 执行成功即刻(唯一记账点——取代本批后段 + agent.mjs 中断分支——不双计)——
83
+ // 此处仅剩 guard 标志失效(顺序语义:批内同消息的 sync advisor 提交仍在其后置位)。
75
84
  agent._mutatedThisRun = true
76
85
  agent._calledAdvisorThisRun = false
77
86
  agent._verifiedThisRun = false
@@ -91,20 +100,55 @@ export async function recordToolResults(agent, toolByName, results) {
91
100
  }
92
101
  if (toolCall.name === "verify") agent._verifiedThisRun = true
93
102
  if (toolCall.name === "advisor") {
94
- agent._calledAdvisorThisRun = true
95
- // All advisor calls (code and design) share the 5-round convergence
96
- // budget each advances _advisorRound toward MAX_ADVISOR_ROUNDS.
97
- // Always advance the round the convergence protocol cares about
98
- // how many reviews have run (round 1→2→3→4→5), not how many succeeded.
99
- // A failed/interrupted review is still a review attempt and should use
100
- // the next round's prompt on retry.
101
- agent._advisorRound++
103
+ // §11.2 D-24b (settle accounting split — fix #2): an ASYNC launch returns an
104
+ // ack and settles later the settle callback owns its called/round/token
105
+ // accounting. Only the SYNC path (depth>0 / explicit async:false) accounts
106
+ // here per-review instance round++ (marker-keyed by tool call id) + the
107
+ // legacy mirror._advisorRound_ counter stays for display/back-compat.
108
+ // REFUSED launches (pool full / per-review cap) count as neither a call
109
+ // nor a completion: no called-mark (the guard must keep pushing until a
110
+ // review really runs), no round advance.
111
+ const refused = agent._advisorRefusals?.has(toolCall.id)
112
+ const asyncAck = agent._advisorAsyncAcks?.has(toolCall.id)
113
+ if (refused) {
114
+ agent._advisorRefusals.delete(toolCall.id)
115
+ } else if (asyncAck) {
116
+ agent._advisorAsyncAcks.delete(toolCall.id)
117
+ } else {
118
+ const reviewId = agent._advisorSyncCalls?.get(toolCall.id)
119
+ const run = reviewId !== undefined ? advisorRuns(agent).get(reviewId) : undefined
120
+ // F16 同步面(第 13 批 §15.2——ADVISOR-CONVERGENCE.md §15):未完成尾 + 非设计面
121
+ // (含类型不可判——run 缺失的 legacy 直调)⇒ 不置「已覆盖」(与 settle 面
122
+ // 逐条 parity;设计评审保持计入——无代码面)。
123
+ const incomplete = advisorIncompleteMarker(String(result))
124
+ if (!(incomplete && run?.reviewType !== "design")) agent._calledAdvisorThisRun = true
125
+ if (reviewId !== undefined) {
126
+ if (run) {
127
+ run.round++
128
+ agent._advisorRound = run.round
129
+ // Prior of round 2+ = the last REVIEW-LOOKING output (run.mjs parity).
130
+ // F2e (§29.1): the sync settle's engine-approved suffix (stored on the
131
+ // run by settleDesignReview) is stripped with exact truncation — the
132
+ // prior never carries the raw token / designId.
133
+ if (looksLikeReviewOutput(result)) {
134
+ run.priorOutput = stripApprovedSuffix(result, run.approvedSuffix)
135
+ }
136
+ } else {
137
+ agent._advisorRound++
138
+ }
139
+ agent._advisorSyncCalls.delete(toolCall.id)
140
+ } else {
141
+ // Direct/legacy callers without a resolution marker — plain mirror
142
+ // increment (the per-review registry never saw this call).
143
+ agent._advisorRound++
144
+ }
145
+ }
102
146
  }
103
147
  if (FILE_MUTATORS.has(toolCall.name)) {
104
148
  const args = JSON.parse(toolCall.arguments)
105
149
  const paths = tool.touchedPaths ? tool.touchedPaths(args) : [args.path]
106
150
  for (const p of paths) {
107
- const abs = join(agent.cwd, p)
151
+ const abs = resolve(agent.cwd, p)
108
152
  if (!agent._touchedFiles.includes(abs)) agent._touchedFiles.push(abs)
109
153
  if (agent.memory) {
110
154
  // Fire-and-forget: don't block the agent loop on indexing.
@@ -0,0 +1,39 @@
1
+ /**
2
+ * relay-prefix.mjs — relay 前缀(`role#id/`)文法**单一权威**(第 27 批 §12.3①——R-A2.3)。
3
+ *
4
+ * 零依赖(不 import 任何模块)——TUI(`src/tui/`)与 ACP(`src/acp/`)双向可导入,无环;
5
+ * 生成侧 `src/agent/spawn-child.mjs` 再导出(枢纽)。文法 = 自
6
+ * `src/tui/subagent-blocks.mjs` 逐字迁入(第 27 批 §12.3②——零语义改动)。
7
+ */
8
+
9
+ /** `role#id/` prefix router — hyphen included since the eng-coder fix (2026-08-21). */
10
+ export const RELAY_PREFIX_RE = /^([\w-]+)#(\d+)\//
11
+
12
+ /** 嵌套 relay 前缀通用解析(循环解析任意深度——显示契约 docs/design/TUI.md §6):
13
+ * `eng-coder#2/explore#1/read` → { head(块路由), inner[], label(inner 链——R23:
14
+ * 子块折叠键/外层 currentTool 全路径用), rest }。
15
+ * 单层 = inner[]/label ""——与既有单段匹配语义零改;无前缀 → null。 */
16
+ export function parseRelayPath(text) {
17
+ const segments = []
18
+ let rest = String(text)
19
+ for (;;) {
20
+ const m = rest.match(RELAY_PREFIX_RE)
21
+ if (!m) break
22
+ segments.push(`${m[1]}#${m[2]}`)
23
+ rest = rest.slice(m[0].length)
24
+ }
25
+ if (segments.length === 0) return null
26
+ return {
27
+ head: segments[0],
28
+ inner: segments.slice(1),
29
+ label: segments.slice(1).join("/"),
30
+ rest,
31
+ }
32
+ }
33
+
34
+ /** 构造向单一实现(本批统一的两处构造点——`makeRelay` 与 async 取号分支共用;
35
+ * 另两处字面构造(escalate/advisor async)不在本批声明面——批次档 §2 修正轮登记,如需收敛另批):
36
+ * `relayPrefixOf("coder", 3)` → `"coder#3/"`。 */
37
+ export function relayPrefixOf(label, id) {
38
+ return `${label}#${id}/`
39
+ }
@@ -0,0 +1,242 @@
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
+ // 第 30 批 D1(Stop 钩子——AGENT-LOOP.md §21):主会话 run 终止事件(触发块见 finalizeAgentTurn)
20
+ import { runHooks } from "../hooks.mjs"
21
+
22
+ /**
23
+ * 响应后置提醒注入(2026-09-05 实践轮——自 runAgent 响应处理链提取,verbatim):
24
+ * 流规则 warning(warn 动作——流已完成——去重注入,模型下轮可见)+ 异常 finish
25
+ * reason 警告(响应可能不完整/截断——reasonMap 人类化描述注入)。
26
+ */
27
+ export function injectResponseReminders(agent, response) {
28
+ // Stream rule warnings (action: "warn"): stream completed; inject de-duplicated
29
+ // warnings so the model sees them before its next response.
30
+ if (response._warnings?.length) {
31
+ const deDuplicated = [...new Map(response._warnings.map(w => [w.name || w.pattern, w])).values()]
32
+ agent.history.push({
33
+ role: "user",
34
+ content: `[System reminder — stream rule warnings from your last response:\n${deDuplicated.map(w => `- ${w.name || w.pattern}: ${w.message}`).join("\n")}]`,
35
+ })
36
+ }
37
+
38
+ // Warn on abnormal finish reasons — the response may be incomplete/truncated.
39
+ if (response.finishReason && response.finishReason !== "stop" && response.finishReason !== "tool_calls") {
40
+ const reasonMap = {
41
+ length: "output token limit reached after exhausting continuations",
42
+ insufficient_system_resource: "provider inference resources exhausted — consider retrying or switching models",
43
+ content_filter: "response blocked by provider content filtering",
44
+ }
45
+ const detail = reasonMap[response.finishReason] || `unknown reason "${response.finishReason}"`
46
+ agent.history.push({
47
+ role: "user",
48
+ content: `[System reminder: the previous turn ended abnormally — ${detail}. The assistant response that follows may be incomplete.]`,
49
+ })
50
+ }
51
+ }
52
+
53
+ /**
54
+ * 回合压缩检查(2026-09-05 实践轮——自 runAgent 主循环提取):仅安全点(history 以
55
+ * 完整交换结尾——user/tool 位)。成功:失败计数清零/计划提醒 cadence 复位/停滞检测
56
+ * 计数复位(recentCallSigs——runAgent 回合级局部——经 ctx 传对象引用)/压缩完成事件
57
+ * /AUTO 提醒重注入。失败:AbortError 透传;计数 + Q3 onCompressFail;
58
+ * COMPRESS_FAILURE_LIMIT 连续失败降级 compressFallback(确定性截断——不发 LLM)。
59
+ */
60
+ export async function runCompactionCheck(agent, ctx) {
61
+ const { threshold, callbacks, compactionOverhead, signal, recentCallSigs } = ctx
62
+ try {
63
+ if (await compressIfNeeded(agent, threshold, callbacks, compactionOverhead, signal)) {
64
+ agent._compressFailures = 0
65
+ agent._planReminderAtLen = 0 // After compression history shrinks, reset cadence so reminders resume
66
+ recentCallSigs.length = 0 // After compression history is rebuilt, reset stall detection counter
67
+ // Completion info (CONTEXT-COMPACTION §7 D-C2): { mode, tokensFreed, elapsedMs } —
68
+ // the TUI panel renders it; callers that ignore the arg keep prior onCompress semantics.
69
+ callbacks.onCompress?.(agent._lastCompressInfo ?? {})
70
+ ensureAutoReminder(agent)
71
+ }
72
+ } catch (compressError) {
73
+ // AbortError must not be swallowed: user cancellation must propagate
74
+ if (compressError?.name === "AbortError" || signal?.aborted) throw compressError
75
+ agent._compressFailures = (agent._compressFailures ?? 0) + 1
76
+ // Q3 (CONTEXT-COMPACTION §7 D-C1): a failed compression is surfaced to the panel;
77
+ // COMPRESS_FAILURE_LIMIT consecutive failures still degrade to compressFallback.
78
+ callbacks?.onCompressFail?.(compressError)
79
+ if (agent._compressFailures >= COMPRESS_FAILURE_LIMIT) {
80
+ agent._compressFailures = 0
81
+ if (compressFallback(agent)) callbacks.onCompress?.(agent._lastCompressInfo ?? {})
82
+ }
83
+ }
84
+ }
85
+
86
+ /**
87
+ * 回合注入组(2026-09-05 实践轮——自 runAgent 主循环提取):plan-mode 提醒 cadence
88
+ * (稀疏 2 轮/满 5 轮/新用户消息重置——限制不淡化)+ 工程模式状态注入(depth-0 每新
89
+ * 用户消息一次——见 injectEngineeringReminder)。verbatim——语义零变。
90
+ */
91
+ export async function injectTurnReminders(agent, ctx) {
92
+ const { depth } = ctx
93
+ // Plan-mode reminder cadence: re-inject constraint reminders while plan mode is active
94
+ // (sparse every 2 turns, full every 5 / on new user message) so the restriction never fades.
95
+ if (agent.planMode) {
96
+ const lastMsg = agent.history.at(-1)
97
+ const realUserMsg = lastMsg?.role === "user"
98
+ && typeof lastMsg.content === "string"
99
+ && !lastMsg.content.startsWith("[System reminder:")
100
+ && !lastMsg.content.startsWith("[User interrupt:")
101
+ const newUserSince = realUserMsg && agent.history.length > (agent._planReminderAtLen ?? 0)
102
+ const { planReminderForTurn } = await import("../agent-tools/plan.mjs")
103
+ const reminder = planReminderForTurn(agent, newUserSince)
104
+ if (reminder) {
105
+ agent._planReminderAtLen = agent.history.length + 1
106
+ agent.history.push({ role: "user", content: reminder, transient: true })
107
+ }
108
+ }
109
+
110
+ // Engineering-mode status injection on every new user message (design-before-code
111
+ // vs standard discipline) — see injectEngineeringReminder.
112
+ if (depth === 0) {
113
+ injectEngineeringReminder(agent)
114
+ }
115
+ }
116
+
117
+ /**
118
+ * 回合收尾(2026-09-05 实践轮——自 runAgent finally 提取,verbatim + 签名化):写足迹
119
+ * flush → Stop 钩子(第 30 批 D1——ctx.depth === 0 的主会话 run 终止事件,
120
+ * fire-and-forget)→ consult 清理(无孤儿烧 token 的 consult children)→ async 池回合尾
121
+ * 分流(Ctrl+C 清池不注入 / ContinueError 留池续跑 / 其余 collectSettledAsync)→ auto-turn
122
+ * guard 标记继承(对象字段清单——正常结束才继承;中止丢弃;ContinueError 由续跑快照)。
123
+ */
124
+ export async function finalizeAgentTurn(agent, ctx) {
125
+ const { signal, autoTurn, suspDriven, thrownError, depth } = ctx
126
+ // R10 L3(MULTI-INSTANCE-COLLAB §2a.5 D-L3a):回合末登记 flush——本回合写足迹整写
127
+ // 一次(首行执行:收尾链后续任何异常都不吞登记);无写入 → 跳过(hot 窗口自然衰减)。
128
+ flushPeerDomains(agent)
129
+ // 第 30 批 D1(Stop 钩子):主会话 run 终止 → fire-and-forget(非阻塞;失败静默——与 PostToolUse 同语义)。
130
+ // 排除用户中止(Ctrl+C / Ctrl+I——中止后 TUI 重建 controller 续跑或已显式停回合)与 AbortError 展开。
131
+ if (depth === 0 && !signal?.aborted && thrownError?.name !== "AbortError") {
132
+ runHooks("Stop", {
133
+ agent,
134
+ error: thrownError && !(thrownError instanceof ContinueError) ? thrownError : undefined,
135
+ extra: {
136
+ turn: agent._currentTurn ?? 0,
137
+ reason: thrownError instanceof ContinueError ? "maxTurns" : thrownError ? "error" : "done",
138
+ },
139
+ }).catch(() => {})
140
+ }
141
+ // R17(AGENT-LOOP.md §25 D-R17a): consultation sessions are cross-turn
142
+ // background work now — NO unconditional turn-end cleanup (the old rule aborted
143
+ // leftover consult children at every turn end because check-loop consumption was
144
+ // turn-scoped). Sessions stay alive across normal turn ends (and ContinueError
145
+ // resumes); the Ctrl+C abort branch below is the only path that aborts them
146
+ // (cleanupConsultSessions — marked stopped → no digest), and the suspension
147
+ // driver aborts them on its own abort unwind.
148
+ // Async subagent turn-end handling (AGENT-LOOP.md §15 D-A3 + §17 D-S1). Lifecycle:
149
+ // - Ctrl+C (plain abort): children were aborted with the parent signal — clear
150
+ // WITHOUT injecting stale errors (user explicitly stopped); consultation
151
+ // sessions are cross-turn background work since R17 — the abort branch is the
152
+ // ONLY normal-path place that aborts them (cleanupConsultSessions marks
153
+ // stopped → their settles never reach the digest stream).
154
+ // - Ctrl+I (interrupt): keeps the pool AND the consult sessions: the turn
155
+ // resumes with the interrupt message, children stay tracked (in a suspension
156
+ // session children hold agent._sessionSignal and a digest's own Ctrl+I must
157
+ // not orphan them).
158
+ // - ContinueError (turn cap): no wait, no injection — children keep running and
159
+ // the RESUME run's turn-end collection takes over.
160
+ // - anything else: inject the SETTLED entries only; running/queued stay in the
161
+ // pool for the suspension session (D-S1 — no allSettled turn-end wait).
162
+ if (signal?.aborted && !signal?.reason?.interrupt) {
163
+ const subPool = getAsyncPool(agent, "subagent")
164
+ const advPool = getAsyncPool(agent, "advisor")
165
+ if ((subPool?.size ?? 0) > 0 || (advPool?.size ?? 0) > 0) {
166
+ logEvent("ev:stopped", { poolN: (subPool?.size ?? 0) + (advPool?.size ?? 0), where: "turn-end-abort" })
167
+ }
168
+ subPool?.clear()
169
+ advPool?.clear()
170
+ agent._asyncQueue = []
171
+ // R17: the consult family dies with the user stop (marked stopped — no digest).
172
+ cleanupConsultSessions(agent)
173
+ // ASYNC-RESULT-CONTAINER.md D2:pending 单容器——中止丢弃 consult/escalate 族停靠
174
+ // (原 _pendingConsultResults/_pendingEscalateResults 同口径——VSC 同语义 filter);
175
+ // subagent/advisor 停靠保留(挂起期 settle 的已完成结果不随中止丢)。
176
+ agent._pendingAsyncResults = (agent._pendingAsyncResults ?? []).filter((e) => e.role !== "consult" && e.role !== "escalate")
177
+ } else if (thrownError instanceof ContinueError) {
178
+ // keep _asyncSubagents/_asyncAdvisors/_consultSessions — the resumed run continues them
179
+ } else {
180
+ const injectedAdvisor = await collectSettledAsync(agent, { suspDriven })
181
+ // §11.2 D-24b: a normally-ended USER run with no review/child activity closes
182
+ // the OPEN code instances — the converged/abandoned thread must not burn the
183
+ // 5-round cap of a later task (the next code review starts a fresh round 1).
184
+ // Digest auto-turns are exempt (their disposition precedes the fix round).
185
+ // A run whose turn-end collection just INJECTED a settled review report
186
+ // (headless, suspDriven=false) must NOT close: the model has not digested
187
+ // the findings yet — the fix round that follows still continues the thread.
188
+ if (!autoTurn && !injectedAdvisor) {
189
+ const { closeOpenCodeAdvisorRuns } = await import("../agent-tools/advisor-async.mjs")
190
+ closeOpenCodeAdvisorRuns(agent)
191
+ }
192
+ }
193
+ agent._inAutoTurn = false
194
+ // §17 D-S6: auto-turn guard marks survive into the next USER run (restored at its
195
+ // !resume reset above). Normal ends only — abort discards; ContinueError lets the
196
+ // auto-resumed run snapshot at its own end.
197
+ if (autoTurn && !(signal?.aborted && !signal?.reason?.interrupt) && !(thrownError instanceof ContinueError)) {
198
+ agent._inheritedGuard = {
199
+ _mutatedThisRun: agent._mutatedThisRun, _verifiedThisRun: agent._verifiedThisRun,
200
+ _verifyPassed: agent._verifyPassed, _calledAdvisorThisRun: agent._calledAdvisorThisRun,
201
+ _touchedFiles: agent._touchedFiles, _verifyRetries: agent._verifyRetries,
202
+ _advisorRound: agent._advisorRound,
203
+ }
204
+ }
205
+ }
206
+
207
+ /**
208
+ * Turn-end async subagent collection (AGENT-LOOP.md §17 D-S1 + §17.5 supersede):
209
+ * two modes, selected by the caller's driver context (17.5.2/17.5.4 #2):
210
+ * - suspDriven=false (fallback — headless/direct runAgent callers without a
211
+ * suspension driver): inject every entry that SETTLED during this run
212
+ * (XML-escaped report/error — child reports may carry file/webpage content;
213
+ * >64K offloaded with preview + path) and remove it from the pool. Running/
214
+ * queued STAY — no allSettled wait. Results never lost without a session.
215
+ * - suspDriven=true (the interaction layer runs suspensionSession after this
216
+ * run): NO direct inject — settled entries STAY pooled (settled not consumed)
217
+ * for the session's first sweepSettledToPending → digest turn (§17.5 — done
218
+ * 条目留池等消化轮注入;status 在 sweep 前仍从池读——17.5.2 不变面(§19.8:check 已删——自动通道为唯一消费方))。
219
+ * maybeRefillAsync runs in both modes (starts queued heads whose slot freed).
220
+ * Single ownership: entries settled inside a suspension session were moved to
221
+ * _pendingAsyncResults by the settle callback, so this only sees user-turn
222
+ * settles (no double inject — D-S3 points ①/②). The ⟦ev⟧done freeze is NOT
223
+ * emitted here — each settle callback emits it (§15 D-A3).
224
+ * 2026-09-05 实践轮:自 agent.mjs 迁入(agent.mjs 内仅 finalize 引用——随收尾同迁)。
225
+ */
226
+ async function collectSettledAsync(agent, { suspDriven = false } = {}) {
227
+ const maps = [getAsyncPool(agent, "subagent"), getAsyncPool(agent, "advisor")].filter((m) => m instanceof Map && m.size > 0)
228
+ if (maps.length === 0) return false
229
+ const { maybeRefillAsync, injectAsyncResult } = await import("../agent-tools/subagent.mjs")
230
+ maybeRefillAsync(agent) // start queued heads now that slots may have freed — no waiting
231
+ if (suspDriven) return false // §17.5: settled stays pooled — the suspension session digests it
232
+ let injectedAdvisor = false
233
+ for (const map of maps) {
234
+ for (const e of [...map.values()]) {
235
+ if (!e.done) continue // still running — stays in the pool (D-S1)
236
+ await injectAsyncResult(agent, e)
237
+ if (e.role === "advisor") injectedAdvisor = true
238
+ map.delete(String(e.id))
239
+ }
240
+ }
241
+ return injectedAdvisor
242
+ }
@@ -0,0 +1,69 @@
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), session slot (F1), restart awareness
8
+ * (R5 resumed). §11.2(2026-09-08):resumed 按会话跟踪——恢复事件由 session.mjs
9
+ * applySession 武装(agent._envResumed——载入历史非空 = 恢复);进程重启句独立走
10
+ * agent._processRestartPending(bin 启动 resume 路径设)——双信号互不绑门(N6)。
11
+ * Change awareness needs no dedicated injection — every turn carries the
12
+ * CURRENT state, so a mode/model flip shows up in the next turn's line.
13
+ * git is NOT a field here (§11.1: CLI 不重复注入 clean|dirty 摘要) — the rich
14
+ * git-context injection (branch/commits/uncommitted — helpers.mjs
15
+ * collectGitContext, wired in setup.mjs) carries it.
16
+ * Peer awareness (R10 L1) rides the same per-turn transient channel:
17
+ * pushPeerReminder injects the live co-cwd instance list when present.
18
+ */
19
+ import { END } from "../session-slots.mjs"
20
+ import { peerInstances } from "../peer-instances.mjs"
21
+
22
+ /** env-state line builder — pure, unit-testable.
23
+ * §11.2(F1):slot 字段入行——位置在 model 后 resumed 前(N3:无绑定 → 显式 null——
24
+ * 不读 manifest active 共享指针——粘性 _slot 才是"本 agent 之槽")。 */
25
+ export function envStateLine({ mode, model, slot, resumed }) {
26
+ return `[System reminder: env: ${END}, mode: ${mode}, model: ${model}, slot: ${slot}, resumed: ${resumed ? "yes" : "no"}.]`
27
+ }
28
+
29
+ /**
30
+ * Push the per-turn env-state reminder (setup.mjs calls it for depth-0 runs —
31
+ * the line describes the MAIN agent's host/mode/model/slot identity). resumed=yes
32
+ * exactly once per session restore: applySession (session.mjs) arms
33
+ * agent._envResumed when restored history is non-empty; consumed here so every
34
+ * later turn reads resumed=no(§11.2 F2——每次恢复一次;/new 与空历史槽切换不武装——
35
+ * F3 伪触发消除)。slot = 粘性 agent._slot(§11.2 N2/N3——无绑定显式 null)。
36
+ * Degrades safely: activeModel null → provider.model → "unknown" (T-E12);
37
+ * a missing config/history never throws (T-E13).
38
+ */
39
+ export function pushEnvStateReminder(agent) {
40
+ const mode = agent.config?.agent?.engineering ? "eng" : "normal"
41
+ const model = agent.activeModel ?? agent.provider?.model ?? "unknown"
42
+ const slot = agent._slot ?? null
43
+ const resumed = agent._envResumed === true
44
+ agent._envResumed = false
45
+ agent.history.push({ role: "user", content: envStateLine({ mode, model, slot, resumed }), transient: true })
46
+ }
47
+
48
+ /**
49
+ * R10 L1 peer reminder(MULTI-INSTANCE-COLLAB §2a.4 D-L1a——仿 pushEnvStateReminder
50
+ * 形态:depth-0、transient:true——注入纪律同 env-state)。有同伴(非 self > 0)才注入
51
+ * ——无同伴零开销(peerInstances 惰性 mtime 缓存保证:manifest 未变零 exec)。任何
52
+ * 感知失败静默跳过(注入绝不打断回合)。文案(设计逐字):"本目录另有 N 个活跃
53
+ * thincoder({end} pid={pid}…)——文件操作注意避让"。
54
+ */
55
+ export function pushPeerReminder(agent) {
56
+ let peers
57
+ try {
58
+ peers = peerInstances(agent.cwd).filter((p) => !p.self)
59
+ } catch {
60
+ return // 感知失败降级——不注入
61
+ }
62
+ if (peers.length === 0) return
63
+ const who = peers.map((p) => (p.end ? `${p.end} pid=${p.pid}` : `pid=${p.pid}`)).join("、")
64
+ agent.history.push({
65
+ role: "user",
66
+ content: `[System reminder: 本目录另有 ${peers.length} 个活跃 thincoder(${who})——文件操作注意避让]`,
67
+ transient: true,
68
+ })
69
+ }