@thincoder/core 0.11.1 → 0.11.3

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 (382) hide show
  1. package/CHANGELOG.md +64 -2
  2. package/advisor/compaction.mjs +7 -5
  3. package/advisor/convergence.mjs +34 -3
  4. package/advisor/history.mjs +24 -11
  5. package/advisor/loop.mjs +49 -12
  6. package/advisor/messages.mjs +114 -33
  7. package/advisor/project-context.mjs +171 -42
  8. package/advisor/run.mjs +24 -10
  9. package/advisor.mjs +36 -46
  10. package/agent/batch-attribution.mjs +87 -0
  11. package/agent/batch-changed-surface.mjs +129 -0
  12. package/agent/chat-call.mjs +14 -9
  13. package/agent/completion.mjs +70 -41
  14. package/agent/continue-decision.mjs +14 -8
  15. package/agent/digest-account.mjs +133 -59
  16. package/agent/dispatch-gates.mjs +6 -0
  17. package/agent/dispatch-run.mjs +1 -1
  18. package/agent/dispatch.mjs +10 -4
  19. package/agent/family-tools.mjs +37 -23
  20. package/agent/helpers.mjs +139 -73
  21. package/agent/image-heal.mjs +18 -4
  22. package/agent/offload.mjs +25 -29
  23. package/agent/post-turn.mjs +36 -35
  24. package/agent/record-results.mjs +39 -7
  25. package/agent/run-stages.mjs +132 -52
  26. package/agent/run-start.mjs +150 -78
  27. package/agent/setup-reminders.mjs +194 -91
  28. package/agent/setup.mjs +219 -140
  29. package/agent/spawn-child.mjs +40 -3
  30. package/agent/suspension.mjs +43 -15
  31. package/agent/timers.mjs +9 -4
  32. package/agent/turn-domain-text.mjs +105 -0
  33. package/agent/turn-loop.mjs +84 -27
  34. package/agent/turn-projection.mjs +286 -0
  35. package/agent/turn-task-state.mjs +274 -0
  36. package/agent/turn-tool-process.mjs +163 -0
  37. package/agent/write-gate-ledger.mjs +569 -0
  38. package/agent/write-gate.mjs +29 -352
  39. package/agent-tools/advisor-async.mjs +35 -172
  40. package/agent-tools/advisor-launch.mjs +178 -0
  41. package/agent-tools/advisor-settle.mjs +28 -1
  42. package/agent-tools/advisor.mjs +37 -48
  43. package/agent-tools/async-discard.mjs +7 -2
  44. package/agent-tools/async-settle.mjs +18 -12
  45. package/agent-tools/audit-block.mjs +6 -6
  46. package/agent-tools/bash-async.mjs +5 -2
  47. package/agent-tools/batch-closeout.mjs +223 -35
  48. package/agent-tools/batch-gate.mjs +142 -342
  49. package/agent-tools/batch-ledger-bind.mjs +240 -20
  50. package/agent-tools/batch-ledger-view.mjs +109 -0
  51. package/agent-tools/batch-lifecycle.mjs +197 -48
  52. package/agent-tools/batch-paths.mjs +29 -8
  53. package/agent-tools/batch-read.mjs +151 -4
  54. package/agent-tools/batch-record-write.mjs +417 -0
  55. package/agent-tools/batch-regions.mjs +215 -0
  56. package/agent-tools/batch-reopen.mjs +23 -11
  57. package/agent-tools/batch-segment-vocab.mjs +459 -0
  58. package/agent-tools/batch-skeleton.mjs +196 -239
  59. package/agent-tools/batch-supersede.mjs +232 -0
  60. package/agent-tools/batch-tier-gate.mjs +214 -0
  61. package/agent-tools/batch.mjs +192 -439
  62. package/agent-tools/browser-async.mjs +5 -2
  63. package/agent-tools/consult.mjs +17 -11
  64. package/agent-tools/context.mjs +76 -33
  65. package/agent-tools/design-review-record.mjs +225 -0
  66. package/agent-tools/design-slots.mjs +1 -1
  67. package/agent-tools/design-token.mjs +279 -81
  68. package/agent-tools/digest-budget.mjs +10 -9
  69. package/agent-tools/doc-check.mjs +43 -33
  70. package/agent-tools/doc-graph.mjs +140 -0
  71. package/agent-tools/eng.mjs +12 -12
  72. package/agent-tools/escalate-async.mjs +5 -5
  73. package/agent-tools/goal.mjs +5 -2
  74. package/agent-tools/judge-domain.mjs +347 -0
  75. package/agent-tools/manifest.mjs +34 -18
  76. package/agent-tools/parent-channel.mjs +6 -3
  77. package/agent-tools/plan.mjs +11 -10
  78. package/agent-tools/read-history.mjs +112 -11
  79. package/agent-tools/review-facts.mjs +19 -6
  80. package/agent-tools/settings.mjs +23 -2
  81. package/agent-tools/skill.mjs +7 -8
  82. package/agent-tools/spawn-gates.mjs +14 -24
  83. package/agent-tools/ssh-session.mjs +8 -5
  84. package/agent-tools/ssh-text.mjs +155 -0
  85. package/agent-tools/ssh-transfer.mjs +1 -1
  86. package/agent-tools/ssh-transport.mjs +19 -148
  87. package/agent-tools/subagent-actions-query.mjs +10 -6
  88. package/agent-tools/subagent-actions.mjs +2 -2
  89. package/agent-tools/subagent-async.mjs +19 -17
  90. package/agent-tools/subagent-brief.mjs +76 -0
  91. package/agent-tools/subagent-design-token.mjs +168 -0
  92. package/agent-tools/subagent-run.mjs +1 -1
  93. package/agent-tools/subagent-scheduler.mjs +13 -13
  94. package/agent-tools/subagent-spawn.mjs +92 -112
  95. package/agent-tools/subagent.mjs +16 -28
  96. package/agent-tools/task.mjs +0 -8
  97. package/agent-tools/taskbook-block.mjs +94 -0
  98. package/agent-tools/timer.mjs +12 -8
  99. package/agent-tools/verify.mjs +13 -4
  100. package/agent-tools.mjs +7 -3
  101. package/agent.mjs +26 -7
  102. package/attachments.mjs +3 -3
  103. package/auto-think.mjs +5 -2
  104. package/browser/actions.mjs +9 -3
  105. package/browser/cdp.mjs +45 -17
  106. package/browser/launch.mjs +25 -43
  107. package/browser/pool.mjs +299 -0
  108. package/browser/queue.mjs +2 -0
  109. package/browser/session-state.mjs +450 -0
  110. package/browser/session.mjs +127 -151
  111. package/browser/snapshot.mjs +89 -0
  112. package/client-identity.mjs +1 -1
  113. package/compaction-work-state.mjs +230 -0
  114. package/compress-form.mjs +41 -6
  115. package/config-defaults.mjs +7 -3
  116. package/config-migrate.mjs +40 -0
  117. package/config-normalize.mjs +28 -2
  118. package/config-reload.mjs +59 -0
  119. package/config.mjs +110 -110
  120. package/context-degrade.mjs +93 -34
  121. package/context-echo.mjs +6 -15
  122. package/context-push.mjs +328 -31
  123. package/context.mjs +298 -170
  124. package/conventions.mjs +11 -9
  125. package/declaration.mjs +126 -22
  126. package/declared-repos.mjs +94 -0
  127. package/doc-check/doc-names.mjs +73 -0
  128. package/doc-check/doc-tokens.mjs +110 -0
  129. package/doc-check/existence.mjs +160 -0
  130. package/doc-check/index.mjs +309 -213
  131. package/doc-check/line-refs.mjs +27 -101
  132. package/doc-check/paragraph.mjs +218 -102
  133. package/doc-graph/anchors.mjs +474 -0
  134. package/doc-graph/doc-batch-face.mjs +59 -0
  135. package/doc-graph/doc-suffix.mjs +27 -0
  136. package/doc-graph/graph-tokens.mjs +160 -0
  137. package/doc-graph.mjs +778 -0
  138. package/escape.mjs +6 -5
  139. package/explore-distill.mjs +41 -8
  140. package/generate-title.mjs +10 -1
  141. package/i18n.mjs +1 -1
  142. package/instance-inbox-watch.mjs +272 -0
  143. package/instance-inbox.mjs +218 -0
  144. package/instance-registry.mjs +179 -0
  145. package/knowledge/README.md +3 -0
  146. package/knowledge/prompt-resources.md +10 -0
  147. package/ledger-close-proof.mjs +100 -49
  148. package/ledger-close.mjs +188 -0
  149. package/ledger-cmd.mjs +47 -91
  150. package/ledger-consistency.mjs +113 -0
  151. package/ledger-db.mjs +47 -15
  152. package/ledger-executors.mjs +1 -1
  153. package/ledger-tools.mjs +121 -62
  154. package/ledger-write-ops.mjs +162 -46
  155. package/ledger.mjs +1 -1
  156. package/manifest-discovery.mjs +3 -1
  157. package/manifest-schema.mjs +27 -5
  158. package/memory/docs.mjs +51 -15
  159. package/memory/file-list.mjs +6 -0
  160. package/memory/schema.mjs +2 -2
  161. package/model-specs.mjs +87 -21
  162. package/origin-guard.mjs +190 -0
  163. package/package.json +3 -1
  164. package/path-resolve.mjs +338 -57
  165. package/prompt-files.mjs +114 -2
  166. package/prompt-overlays.mjs +21 -11
  167. package/prompts/advisor-design.md +96 -36
  168. package/prompts/advisor-round1.md +48 -4
  169. package/prompts/advisor-round2.md +54 -10
  170. package/prompts/advisor-round3.md +53 -9
  171. package/prompts/common.md +99 -434
  172. package/prompts/consult-base.md +7 -4
  173. package/prompts/discipline-engineering.md +504 -295
  174. package/prompts/discipline-normal.md +106 -281
  175. package/prompts/knowledge/business-gates.md +30 -0
  176. package/prompts/knowledge/decision-quality.md +21 -0
  177. package/prompts/knowledge/doc-lookup.md +30 -0
  178. package/prompts/knowledge/document-writing.md +33 -0
  179. package/prompts/knowledge/documentation-evaluation.md +48 -0
  180. package/prompts/knowledge/evidence-discipline.md +38 -0
  181. package/prompts/knowledge/normal-coding-workflow.md +110 -0
  182. package/prompts/knowledge/normal-delivery-collaboration.md +124 -0
  183. package/prompts/knowledge/normal-work-management.md +60 -0
  184. package/prompts/knowledge/product-security.md +28 -0
  185. package/prompts/knowledge/project-records.md +73 -0
  186. package/prompts/knowledge/tool-advisor.md +29 -0
  187. package/prompts/knowledge/tool-apply-patch.md +17 -0
  188. package/prompts/knowledge/tool-bash.md +48 -0
  189. package/prompts/knowledge/tool-batch-eng-coder.md +19 -0
  190. package/prompts/knowledge/tool-batch-eng-designer.md +20 -0
  191. package/prompts/knowledge/tool-batch-review.md +18 -0
  192. package/prompts/knowledge/tool-batch.md +94 -0
  193. package/prompts/knowledge/tool-browser.md +68 -0
  194. package/prompts/knowledge/tool-code-search.md +4 -0
  195. package/prompts/knowledge/tool-consult-start.md +12 -0
  196. package/prompts/knowledge/tool-consult-stop.md +6 -0
  197. package/prompts/knowledge/tool-context.md +6 -0
  198. package/prompts/knowledge/tool-delete.md +21 -0
  199. package/prompts/knowledge/tool-doc-check.md +71 -0
  200. package/prompts/knowledge/tool-doc-graph-read.md +20 -0
  201. package/prompts/knowledge/tool-doc-graph.md +49 -0
  202. package/prompts/knowledge/tool-doc-search.md +6 -0
  203. package/prompts/knowledge/tool-edit.md +41 -0
  204. package/prompts/knowledge/tool-eng.md +2 -0
  205. package/prompts/knowledge/tool-execute.md +21 -0
  206. package/prompts/knowledge/tool-fetch.md +18 -0
  207. package/prompts/knowledge/tool-file-ops.md +21 -0
  208. package/prompts/knowledge/tool-get-current-time.md +7 -0
  209. package/prompts/knowledge/tool-git-read.md +21 -0
  210. package/prompts/knowledge/tool-git.md +29 -0
  211. package/prompts/knowledge/tool-glob.md +17 -0
  212. package/prompts/knowledge/tool-goal.md +8 -0
  213. package/prompts/knowledge/tool-grep.md +21 -0
  214. package/prompts/knowledge/tool-hashline-edit.md +16 -0
  215. package/prompts/knowledge/tool-insert-after.md +17 -0
  216. package/prompts/knowledge/tool-instance-list.md +6 -0
  217. package/prompts/knowledge/tool-instance-send.md +10 -0
  218. package/prompts/knowledge/tool-knowledge.md +18 -0
  219. package/prompts/knowledge/tool-ledger-read.md +28 -0
  220. package/prompts/knowledge/tool-ledger.md +46 -0
  221. package/prompts/knowledge/tool-lint.md +16 -0
  222. package/prompts/knowledge/tool-ls.md +15 -0
  223. package/prompts/knowledge/tool-lsp.md +11 -0
  224. package/prompts/knowledge/tool-main-history.md +2 -0
  225. package/prompts/knowledge/tool-manifest-read.md +14 -0
  226. package/prompts/knowledge/tool-manifest.md +34 -0
  227. package/prompts/knowledge/tool-memory-read.md +20 -0
  228. package/prompts/knowledge/tool-memory.md +19 -0
  229. package/prompts/knowledge/tool-notify-parent.md +12 -0
  230. package/prompts/knowledge/tool-operations.md +102 -0
  231. package/prompts/knowledge/tool-peer-instances.md +2 -0
  232. package/prompts/knowledge/tool-plan.md +5 -0
  233. package/prompts/knowledge/tool-process-read.md +13 -0
  234. package/prompts/knowledge/tool-process.md +15 -0
  235. package/prompts/knowledge/tool-question.md +16 -0
  236. package/prompts/knowledge/tool-read-history-batch.md +22 -0
  237. package/prompts/knowledge/tool-read-history.md +35 -0
  238. package/prompts/knowledge/tool-read-image.md +11 -0
  239. package/prompts/knowledge/tool-read.md +22 -0
  240. package/prompts/knowledge/tool-recent-changes.md +6 -0
  241. package/prompts/knowledge/tool-repo-outline.md +4 -0
  242. package/prompts/knowledge/tool-settings-read.md +12 -0
  243. package/prompts/knowledge/tool-settings.md +17 -0
  244. package/prompts/knowledge/tool-skill.md +6 -0
  245. package/prompts/knowledge/tool-ssh.md +74 -0
  246. package/prompts/knowledge/tool-subagent.md +57 -0
  247. package/prompts/knowledge/tool-task.md +14 -0
  248. package/prompts/knowledge/tool-team-ledger-read.md +11 -0
  249. package/prompts/knowledge/tool-team-ledger.md +15 -0
  250. package/prompts/knowledge/tool-timer.md +23 -0
  251. package/prompts/knowledge/tool-tree.md +16 -0
  252. package/prompts/knowledge/tool-verify.md +19 -0
  253. package/prompts/knowledge/tool-wait-for.md +25 -0
  254. package/prompts/knowledge/tool-websearch.md +19 -0
  255. package/prompts/knowledge/tool-write.md +12 -0
  256. package/prompts/knowledge/upstream-protocol.md +45 -0
  257. package/prompts/persona-coder.md +1 -3
  258. package/prompts/persona-eng-coder.md +24 -6
  259. package/prompts/persona-eng-designer.md +150 -171
  260. package/prompts/persona-engineering.md +531 -442
  261. package/prompts/persona-explore.md +1 -3
  262. package/prompts/persona-normal.md +17 -9
  263. package/prompts/persona-plan.md +5 -3
  264. package/prompts/persona-tester.md +0 -2
  265. package/prompts/subagent-base.md +2 -2
  266. package/provider/anthropic.mjs +10 -6
  267. package/provider/core.mjs +8 -5
  268. package/provider/errors.mjs +63 -4
  269. package/provider/google.mjs +29 -10
  270. package/provider/reasoning-echo.mjs +16 -0
  271. package/provider/responses.mjs +7 -3
  272. package/provider/sse.mjs +11 -6
  273. package/provider-flows.mjs +2 -2
  274. package/rules.mjs +11 -10
  275. package/session-index-build.mjs +1 -1
  276. package/session-index-pass.mjs +1 -1
  277. package/session-index-query.mjs +1 -1
  278. package/session-index.mjs +1 -1
  279. package/session-lifecycle.mjs +131 -42
  280. package/session-slot-write.mjs +38 -6
  281. package/session.mjs +30 -11
  282. package/shell-identity.mjs +129 -22
  283. package/skip-dirs.mjs +26 -2
  284. package/team-ledger.mjs +34 -30
  285. package/text-budget.mjs +1 -1
  286. package/think-off.mjs +27 -0
  287. package/token-ttl.mjs +74 -5
  288. package/token-window.mjs +371 -47
  289. package/tool-docs/advisor.md +2 -27
  290. package/tool-docs/apply_patch.md +1 -15
  291. package/tool-docs/bash.md +2 -43
  292. package/tool-docs/batch-eng-coder.md +3 -0
  293. package/tool-docs/batch-eng-designer.md +3 -0
  294. package/tool-docs/batch-review.md +3 -0
  295. package/tool-docs/batch.md +2 -84
  296. package/tool-docs/browser.md +2 -49
  297. package/tool-docs/code_search.md +2 -2
  298. package/tool-docs/consult_start.md +2 -8
  299. package/tool-docs/consult_stop.md +2 -4
  300. package/tool-docs/context.md +1 -5
  301. package/tool-docs/delete.md +2 -17
  302. package/tool-docs/doc_check.md +2 -107
  303. package/tool-docs/doc_graph-read.md +3 -0
  304. package/tool-docs/doc_graph.md +3 -0
  305. package/tool-docs/doc_search.md +2 -4
  306. package/tool-docs/edit.md +1 -38
  307. package/tool-docs/eng.md +3 -1
  308. package/tool-docs/execute.md +2 -18
  309. package/tool-docs/fetch.md +2 -14
  310. package/tool-docs/file_ops.md +2 -18
  311. package/tool-docs/get_current_time.md +1 -6
  312. package/tool-docs/git-read.md +3 -0
  313. package/tool-docs/git.md +2 -35
  314. package/tool-docs/glob.md +2 -10
  315. package/tool-docs/goal.md +1 -6
  316. package/tool-docs/grep.md +2 -18
  317. package/tool-docs/hashline_edit.md +2 -15
  318. package/tool-docs/insert_after.md +2 -16
  319. package/tool-docs/instance_list.md +3 -0
  320. package/tool-docs/instance_send.md +3 -0
  321. package/tool-docs/knowledge.md +3 -0
  322. package/tool-docs/ledger-read.md +3 -0
  323. package/tool-docs/ledger.md +3 -8
  324. package/tool-docs/lint.md +2 -10
  325. package/tool-docs/ls.md +2 -11
  326. package/tool-docs/lsp.md +2 -9
  327. package/tool-docs/main_history.md +3 -1
  328. package/tool-docs/manifest-read.md +2 -8
  329. package/tool-docs/manifest.md +2 -35
  330. package/tool-docs/memory-read.md +3 -0
  331. package/tool-docs/memory.md +2 -20
  332. package/tool-docs/notify_parent.md +2 -13
  333. package/tool-docs/peer_instances.md +3 -1
  334. package/tool-docs/plan.md +1 -5
  335. package/tool-docs/process-read.md +3 -0
  336. package/tool-docs/process.md +2 -13
  337. package/tool-docs/question.md +3 -17
  338. package/tool-docs/read.md +2 -19
  339. package/tool-docs/read_history-batch.md +3 -0
  340. package/tool-docs/read_history.md +2 -18
  341. package/tool-docs/read_image.md +2 -9
  342. package/tool-docs/recent_changes.md +2 -2
  343. package/tool-docs/repo_outline.md +2 -2
  344. package/tool-docs/settings-read.md +3 -0
  345. package/tool-docs/settings.md +1 -12
  346. package/tool-docs/skill.md +2 -6
  347. package/tool-docs/ssh.md +1 -62
  348. package/tool-docs/subagent.md +2 -100
  349. package/tool-docs/task.md +1 -7
  350. package/tool-docs/team_ledger-read.md +3 -0
  351. package/tool-docs/team_ledger.md +3 -9
  352. package/tool-docs/timer.md +2 -19
  353. package/tool-docs/tree.md +2 -13
  354. package/tool-docs/verify.md +2 -12
  355. package/tool-docs/wait_for.md +2 -32
  356. package/tool-docs/websearch.md +2 -19
  357. package/tool-docs/write.md +2 -12
  358. package/tools/browser.mjs +54 -9
  359. package/tools/doc-write-gate.mjs +73 -0
  360. package/tools/edit-batch.mjs +170 -92
  361. package/tools/edit-diff.mjs +78 -62
  362. package/tools/edit-receipt.mjs +39 -0
  363. package/tools/execute.mjs +3 -3
  364. package/tools/file.mjs +28 -14
  365. package/tools/git.mjs +36 -21
  366. package/tools/index.mjs +6 -0
  367. package/tools/knowledge.mjs +143 -0
  368. package/tools/linter.mjs +3 -3
  369. package/tools/ops.mjs +5 -3
  370. package/tools/patch.mjs +124 -44
  371. package/tools/process-doc-mark.mjs +33 -4
  372. package/tools/repomap.mjs +25 -3
  373. package/tools/search.mjs +74 -26
  374. package/tools/shared.mjs +29 -27
  375. package/tools/ssh.mjs +5 -5
  376. package/tools/tree.mjs +32 -10
  377. package/tools/web-deepseek.mjs +1 -1
  378. package/tools/web.mjs +2 -2
  379. package/tools/write-gate-params.mjs +31 -0
  380. package/tools/write-path.mjs +16 -4
  381. package/window-policy.mjs +243 -0
  382. package/doc-check/anchors.mjs +0 -235
@@ -1,12 +1,14 @@
1
1
  /**
2
- * agent/suspension.mjs — 挂起 / 唤醒驱动(核内形态——AGENT-LOOP.md §2.3 #184 定案;机制面 = AGENT-LOOP-ASYNC-POOL.md §6.8)。
2
+ * agent/suspension.mjs — 挂起 / 唤醒驱动(核内形态——AGENT-LOOP.md §9.1 载体字段 #184 定案;机制面 = AGENT-LOOP-ASYNC-POOL.md §6.8)。
3
3
  *
4
4
  * 语义(两端同源,逐字承两端现行挂起驱动——CLI 侧 tui 面 / VSC 侧 extension 面,同语义移植):
5
- * 回合尾后台池仍 live → 挂起会话——池项 settle → 入 pending;pending 非空 **或存在未 drain 的
6
- * 上行 ask**(`upstreamWaiting`——F-UC7 / §6.27.12.4 ①)→ 合并消化轮 / 唤醒轮(auto-turn;旗标
7
- * `upstreamTurn` 仅供域文本选择);挂起空闲用户输入优先于消化轮。池空 + pending 空 + 无待处理
5
+ * 回合尾后台池仍 live → 挂起会话——池项 settle → 入 pending;**存在未投递的已结算结果**(已投递未
6
+ * 销账的条不是开轮源——那是账务状态,由 §8 的销账面消费)**或存在未 drain 的上行 ask**
7
+ * (`upstreamWaiting`——F-UC7 / §6.27.12.4 ①)→ 合并消化轮 / 唤醒轮(auto-turn;旗标
8
+ * `upstreamTurn` 仅供域文本选择);挂起空闲用户输入优先于消化轮。池空 + 无未投递条 + 无待处理
8
9
  * 输入 → 自然退出(idle)。退出清场:abort = 清池不注入(陈旧结果不注入);idle = 残余直注入
9
- * (结果零丢失;已投递未销账条按投递账过滤——留容器不注入,§6.31 出口缝)。
10
+ * (结果零丢失;已投递未销账条按投递账过滤——留容器不注入,§6.31 出口缝),且 idle 退出前容器内
11
+ * 已投递未销账条由升级的周期终点支结账(§8.3——四步机械动作,不开任何回合)。
10
12
  *
11
13
  * 载体注入(端差面 = 池 / pending / 标志挂谁):`ctx.carrier` = 字段集按核内异步面
12
14
  * 现行口径的对象(`_asyncSubagents` · `_asyncAdvisors` · `_consultSessions` ·
@@ -46,6 +48,9 @@
46
48
 
47
49
  import { parkAsyncPending } from "../agent-tools/async-settle.mjs"
48
50
  import { upstreamWaiting } from "../agent-tools/parent-channel.mjs"
51
+ // 开轮判据与投递门控同源(AGENT-LOOP-ASYNC-POOL.md §1「挂起与 digest」):容器里「有未投递条」
52
+ // 就是 `shouldDeliverEntry` 判要投的那条;升级四步(§8.3)两支共用同一实现。
53
+ import { shouldDeliverEntry, escalateUndigested } from "./digest-account.mjs"
49
54
 
50
55
  /** 运行中 consult children(非 stopped 会话的在飞子调用数——挂起活度/计数同源)。 */
51
56
  function consultRunningChildren(carrier) {
@@ -56,9 +61,19 @@ function consultRunningChildren(carrier) {
56
61
  return n
57
62
  }
58
63
 
59
- /** 后台池存活判据(D-S2/F5 口径——CLI 为准):running/queued 的池条目,或已 settle 未注入
60
- * (pending 非空 = D-S3「未注入」),或运行中 consult children(会诊跨回合)。回合尾与每次
61
- * 轮末都评估退出。**#9 三域并入**:`_bgTasks`(后台 bash 任务)在途亦为 live——settle 经
64
+ /** 未投递的已结算结果判据(AGENT-LOOP-ASYNC-POOL.md §1「开轮的起因是一个事件」——开轮与退出读同一
65
+ * 处实现):容器里存在一条门控会投的条(`shouldDeliverEntry`,`autoTurn` 传真是问「系统轮有没有东西
66
+ * 要投」),才算事件。已投递未销账的条不在此列:它只剩账务意义,由 §8 的销账面与 §8.3 的升级消费。
67
+ * 载体零预设:容器不是数组 ⇒ 没有可投的条(不抛——「没有容器」不等于「会话崩」)。 */
68
+ function hasUndeliveredEntry(carrier) {
69
+ const pending = carrier?._pendingAsyncResults
70
+ if (!Array.isArray(pending)) return false
71
+ return pending.some((e) => shouldDeliverEntry(e, true))
72
+ }
73
+
74
+ /** 后台池存活判据(D-S2/F5 口径——CLI 为准):running/queued 的池条目,或存在未投递条(判据
75
+ * 同开轮 = `hasUndeliveredEntry`——已投递未销账的条不算活,那是账务状态不是事件),或运行中
76
+ * consult children(会诊跨回合)。回合尾与每次轮末都评估退出。**#9 三域并入**:`_bgTasks`(后台 bash 任务)在途亦为 live——settle 经
62
77
  * pending 停靠驱动消化轮(`bash-async.mjs` 恒停靠);**批 browser-async-fix 第四域**:
63
78
  * `_browserTasks` 同判(`browser-async.mjs` 恒停靠)。 */
64
79
  export function poolLive(carrier) {
@@ -67,7 +82,7 @@ export function poolLive(carrier) {
67
82
  const bg = carrier?._bgTasks
68
83
  const br = carrier?._browserTasks
69
84
  return (sub && sub.size > 0) || (adv && adv.size > 0) || (bg && bg.size > 0) || (br && br.size > 0)
70
- || (carrier?._pendingAsyncResults?.length ?? 0) > 0
85
+ || hasUndeliveredEntry(carrier)
71
86
  || consultRunningChildren(carrier) > 0
72
87
  }
73
88
 
@@ -209,9 +224,9 @@ function waitForSettleOrWake(carrier, abortSignal, latch, { deadline = null, tim
209
224
  *
210
225
  * 状态机行表(承 AGENT-LOOP-ASYNC-POOL.md §6.8 行表):
211
226
  * 1. 用户输入优先(D-S5):pendingInput 非空 → 以该消息开普通回合(`_suspended=false`);
212
- * 2. pending 非空 或 存在未 drain 的 ask(`upstreamWaiting`)→ 合并消化轮 / 唤醒轮(auto-turn;
227
+ * 2. 存在未投递条 或 存在未 drain 的 ask(`upstreamWaiting`)→ 合并消化轮 / 唤醒轮(auto-turn;
213
228
  * 注入由宿主 runTurn 首行完成——单注入点);
214
- * 3. 池空(无 running / queued / 未注入)→ 自然退出;
229
+ * 3. 池空(无 running / queued / 未投递条)→ 自然退出;
215
230
  * 4. 等下一 settle / 宿主唤醒(handle.wake)/ timer 到期(opt-in——兑现真 ⇒ timer 轮)。
216
231
  * 每轮消化 / 用户回合后:hooks.reclaim(consumed) 逐条回收(不等池空)——恒达窗形(子代理面板批 ·
217
232
  * 2026-10-04):正常 ∥ Abort-continue ∥ 异常抛三径同达,退出残差另经 `finishSuspension` 返回面补发
@@ -268,16 +283,18 @@ export function startSuspension(ctx) {
268
283
  continue
269
284
  }
270
285
  }
271
- // 2. pending 非空 或 未 drain 的 ask → 合并消化轮 / 上行唤醒轮(单注入点由 runTurn
286
+ // 2. 存在未投递条 或 未 drain 的 ask → 合并消化轮 / 上行唤醒轮(单注入点由 runTurn
272
287
  // 首行完成:pending 经 run 起始注入器,ask 经回合头 `drainChildUpstream`)。
288
+ // 判据 = `hasUndeliveredEntry`(与投递门控同源、与第 3 步退出判据同一处实现):容器里只余
289
+ // 已投递未销账条不开轮——那是账务状态,不是事件。
273
290
  const upstream = upstreamWaiting(carrier) // §6.27.12.4 ①:第二开轮源(谓词必须先于第 3 步退出判)
274
- if ((carrier._pendingAsyncResults?.length ?? 0) > 0 || upstream) {
291
+ if (hasUndeliveredEntry(carrier) || upstream) {
275
292
  const afterRun = consumedByRun()
276
293
  hooks.onDigest?.("start", backgroundCounts(carrier))
277
294
  try {
278
295
  await runTurn("", { autoTurn: true, upstreamTurn: upstream })
279
296
  } catch (e) {
280
- // 消化轮自身的回合级中止不是会话停止——记边界后重入循环(池空 / pending 空自然退出)。
297
+ // 消化轮自身的回合级中止不是会话停止——记边界后重入循环(池空 / 无未投递条自然退出)。
281
298
  if (e?.name === "AbortError" && !abortSignal?.aborted) {
282
299
  hooks.onDigest?.("end", backgroundCounts(carrier))
283
300
  continue
@@ -308,7 +325,7 @@ export function startSuspension(ctx) {
308
325
  await runTurn("", { autoTurn: true, timerTurn: true })
309
326
  } catch (e) {
310
327
  // timer 轮自身的回合级中止不是会话停止——容纳并重入循环(timer 轮不发 digest 边界 ⇒
311
- // 中止路径零边界、不补发轮后序钩子;池空 / pending 空自然退出——与消化支同判,§6.30.10)。
328
+ // 中止路径零边界、不补发轮后序钩子;池空 / 无未投递条自然退出——与消化支同判,§6.30.10)。
312
329
  if (e?.name === "AbortError" && !abortSignal?.aborted) continue
313
330
  throw e
314
331
  } finally {
@@ -329,6 +346,17 @@ export function startSuspension(ctx) {
329
346
  // abort 以 AbortError 抛出、循环顶检查不会再执行——不合并会把清场误走 idle 注入)。
330
347
  const abortedNow = aborted || Boolean(abortSignal?.aborted)
331
348
  aborted = abortedNow
349
+ // §8.3 周期终点支(账务周期的终点):idle 退出前把容器里已投递未销账的条结账——四步
350
+ // (账本 → 提醒 → 离容器 → 终局披露)全是机械动作,不开任何回合;会话沉寂之后不再有消化轮,
351
+ // 保底不能押在「下一轮碰巧发生」上。中止径不适用(中止按 `## 6. 中止丢弃` 清账)。
352
+ if (!abortedNow) {
353
+ const pendingNow = carrier._pendingAsyncResults
354
+ await escalateUndigested(
355
+ carrier,
356
+ "idle",
357
+ Array.isArray(pendingNow) ? pendingNow.filter((e) => e?._daDelivered === true) : [],
358
+ )
359
+ }
332
360
  const flushed = await finishSuspension(carrier, { aborted: abortedNow, injectResidual })
333
361
  // 残差离容补发(子代理面板批 · 2026-10-04 · §2.2——C2 零发射口):补发面 = 离容全量
334
362
  // (抛错径同覆);与 freezeAll 双探针幂等(归档/记录恰一次住幂等层)。
package/agent/timers.mjs CHANGED
@@ -19,6 +19,7 @@
19
19
  * `fireTimerWake` = 火策略(非空闲零动作 ∕ 零交付零开轮)。端面表壳留端(桌面键面 ∕ `ev:timer` 出词;
20
20
  * VSC ∕ CLI 自持副本已随 B3 迁移轮退场(2026-09-29——双写窗口收口),本档 = 单源)。
21
21
  */
22
+ import { pushInject, pushRecord } from "../context.mjs"
22
23
 
23
24
  /** 在途条数帽(§6.30.3 门三件②成本闸):超限 ⇒ timer 工具**显式拒**(不静默丢 / 不静默清;
24
25
  * 形态先例 = 队满「拒 + 提示 + 保留」)。与 CLI 排队容量 `QUEUED_MAX_ITEMS`(8)同值同形。 */
@@ -94,13 +95,17 @@ export function takeExpiredTimers(agent, now = Date.now()) {
94
95
  return expired
95
96
  }
96
97
 
97
- /** 历史注入单点(逐字形态 = 既有注入单源):逐条 `[System reminder: ⏰ timer — <message>]` 落历史,
98
- * 返回注入的原文(显示面复用同一串——零第二份字面)。 */
98
+ /** 历史注入单点(逐字形态 = 既有注入单源):逐条 `[System reminder: timer — <message>]` 落历史,
99
+ * 返回注入的原文(显示面复用同一串——零第二份字面)。
100
+ * **字符面(AGENT-LOOP-ASYNC-POOL.md §6.30.3)**:前缀段全落在 `/^[\x20-\x7E]+$/`(至 `timer —` 之前)——
101
+ * 缺字形的图标字符不入本行(该行以 `C.warn` 进 CLI 会话流,用户在终端直接读到)。 */
99
102
  export function injectTimerReminders(agent, entries) {
100
103
  const lines = []
101
104
  for (const t of entries ?? []) {
102
- const line = `[System reminder: ⏰ timer — ${t.message}]`
103
- agent.history.push({ role: "user", content: line })
105
+ const line = `[System reminder: timer — ${t.message}]`
106
+ // 计时器提醒是 B 段:进待发队给模型看;持久写入只落人读线(机读线零触)。
107
+ pushInject(agent, { role: "user", content: line })
108
+ pushRecord(agent, { role: "user", content: line })
104
109
  lines.push(line)
105
110
  }
106
111
  return lines
@@ -0,0 +1,105 @@
1
+ /**
2
+ * agent/turn-domain-text.mjs — 回合域文本与工程模式提醒一族(文本单源)。
3
+ *
4
+ * 2026-11-19 拆档(`docs/batches/2026-11-19-engineering-task-consult.md` §2):本族自
5
+ * `agent/helpers.mjs` 整体迁出——helpers.mjs 越过 CODE-TIER §2 的设计时线。处置沿用 2026-09-05
6
+ * 同族先例:原档再出口,导入面零改(`agent/helpers.mjs` → `agent.mjs` → eng.mjs / cmd-eng.mjs /
7
+ * 测试,八处消费者一个 import 都不动)。
8
+ *
9
+ * 机制单源 = `docs/core/design/AGENT-LOOP-ASYNC-POOL.md` §8.6「自动回合域文本」:域文本承载这一轮的
10
+ * 输入(为什么开始、接着做什么),一族一版、两档共取——档位只决定审批如何呈递,不决定这一轮能
11
+ * 做什么,也不进文本选择。工程模式与普通模式、手动档与 AUTO 档取到的都是同一篇。
12
+ */
13
+ import { pushInject, setInject } from "../context.mjs"
14
+
15
+ /** Engineering mode reminder — shared with eng.mjs tool. */
16
+ export const ENG_ON_REMINDER =
17
+ "[System reminder: engineering mode is ON (session-scoped) — design-before-code enforced. " +
18
+ "Workflow: Requirements doc → Design doc → advisor(type='design') → " +
19
+ "user approval → eng-coder implementation. Code changes go through eng-coder " +
20
+ "subagents only. Advisor calls are NOT per-turn-mandatory — call only at " +
21
+ "flow nodes or when the user asks.]"
22
+
23
+ /** Engineering mode OFF reminder — shared with the eng tool and the injector. */
24
+ export const ENG_OFF_REMINDER =
25
+ "[System reminder: engineering mode is now OFF — standard discipline applies. " +
26
+ "Changes go through the normal workflow: you may edit files directly, advisor/verify " +
27
+ "guards apply per config.]"
28
+
29
+ /** Auto-turn digest domain — the finished reports are this turn's input. One version for both
30
+ * approval tiers: tiny / normal / engineering and manual / AUTO read the same text.
31
+ * Mechanism = AGENT-LOOP-ASYNC-POOL.md §8.6; injected at the run start of an auto-turn run. */
32
+ export const AUTO_TURN_DIGEST_DOMAIN =
33
+ "[System reminder: auto-turn — background async subagents finished while there was no user message, so their reports are this turn's input (shown in the finished-report reminders above). This turn is an ordinary agent loop: read each finished report, ack it per the digest-account line when one is present, and then carry on with the in-flight work those reports interrupted.]"
34
+
35
+ /** Up-stream wake-turn domain (AGENT-LOOP-UPSTREAM.md §6.27.12.8): a running subagent sent
36
+ * an in-flight message and is waiting for the reply — the wake turn's trigger source differs from
37
+ * the digest turn's, so it says its own.
38
+ * Verbatim from the design doc (single line — no newlines). Content basis = the mechanism doc; landing = eng-coder. */
39
+ export const UPSTREAM_TURN_DOMAIN =
40
+ "[System reminder: auto-turn — a running subagent sent you an in-flight message (shown below). No user message is waiting. Decide it now and reply with subagent action:'send' (id + message) — the child consumes the reply at its next turn boundary and keeps working on the unaffected parts; if the message needs no answer, say so in one line and move on. If finished subagent reports are also present above, digest them as usual in the same turn, then carry on with the work in flight.]"
41
+
42
+ /** Timer wake-turn domain (AGENT-LOOP-ASYNC-POOL.md §8.6「自动回合域文本」· §7「timer」): a pending
43
+ * timer expired while the session was idle and the end's latch opened this turn automatically —
44
+ * neither the digest domain (reports delivered) nor the up-stream domain
45
+ * (a subagent waiting for a reply) fits: the timer's own semantics is "act on what the
46
+ * timer was for". Verbatim from the mechanism doc (single line — no newlines).
47
+ * Content basis = the mechanism doc; landing = eng-coder. */
48
+ export const TIMER_TURN_DOMAIN =
49
+ "[System reminder: auto-turn — a timer you set earlier has expired (reminder above). No user message is waiting. Act on what the timer was for now: pull the data or run the check rather than continuing to reason in the abstract. Wrap up as soon as the action is done or blocked.]"
50
+
51
+ /** Digest-accounting requirement line (AGENT-LOOP-ASYNC-POOL.md §8.2 · batch digest-accounting ·
52
+ * 2026-10-05):消化轮账目要求——两档同发(手动 / AUTO),域文本一族一版;域文本说「这一轮为什么
53
+ * 开始、接着做什么」,要求行说「怎么签收」⇒ 要求行独立常量承载(两件事,不互相包含)。两个占位 = 未销账 id 清单 `<ids>` ∥ 未签收上限 `<limit>`
54
+ * (动态代换 = digest-account.mjs `digestAccountRequirement`;上限数的一处真身 = 该档 `DA_MISS_LIMIT`——
55
+ * 本档反向 import 它成环);注入面 = transient(机器线独有)。Verbatim from the mechanism doc
56
+ * (single line — no newlines). Content basis = the mechanism doc; landing = eng-coder. */
57
+ export const DIGEST_ACCOUNT_DOMAIN =
58
+ "[System reminder: digest accounting — for each report listed below as still open, emit exactly one line: \"[digest-ack #<id>] digested — <key points>\" (handled) or \"[digest-ack #<id>] deferred — <reason>\" (not handled). Only \"digested\" closes the account. \"deferred\" leaves it open: the report is delivered again in the next system turn, and each digest round that still leaves it unhandled counts toward escalation — after <limit> such rounds it is escalated with a visible reminder and one final delivery. Still open: <ids>. Do not omit any.]"
59
+
60
+ /** 域文本那一格的存活期,判据一(`docs/core/design/AGENT-LOOP-ASYNC-POOL.md` §8.6「回合头的判据一」):
61
+ * 这一格只活一个请求——从第二个请求起(`turn ≥ 1`)一律清 `turn-domain`,三族同判。投递物进 B 段、
62
+ * 第一个请求之后就离场,域文本进 A 段格、每个请求都在场;不清就成了「指着上方那份已经不在了的东西说话」。
63
+ * **只清不写**:run 起点写的是核基座或端域文本,端 overlay 另住 `run-overlay` 格(`AGENT-LOOP-ASYNC-POOL.md`
64
+ * §8.6「两格:域文本与端 overlay」)——本条只写 `turn-domain`,两条写入路径因此不重叠。
65
+ * @param {object} agent 主 agent(A 段 `_inject` 载体)
66
+ * @param {number} turn 本回合在 run 内的序号(必填,无缺省;非数 ⇒ 抛——缺它会静默不清)
67
+ */
68
+ export function clearTurnDomainIfEmpty(agent, turn) {
69
+ if (typeof turn !== "number") {
70
+ throw new Error("clearTurnDomainIfEmpty: turn(本回合在 run 内的序号)必填且必为数——缺它这一格就静默不清,第一个请求之后模型仍在读指向上方投递物的域文本")
71
+ }
72
+ if (turn < 1) return
73
+ setInject(agent, "turn-domain", null)
74
+ }
75
+
76
+ /** 域文本那一格的存活期,判据二(`docs/core/design/AGENT-LOOP-ASYNC-POOL.md` §8.6「回合头的判据二」,
77
+ * 上行一侧的事实住 `docs/core/design/AGENT-LOOP-UPSTREAM.md` §5.1):域文本只对 drain 投到的那一个
78
+ * 回合成立——投到(`delivered > 0`)⇒ 一格不动;未投到(`delivered === 0`)⇒ 清 `turn-domain` 格。
79
+ * 只有上行族有 drain,消化与 timer 两族不经过本条,也不给它们伪造一个件数。
80
+ * **本条不判 `turn`**:调用点在回合头,`turn ≥ 1` 时判据一已先把这一格清成 `null`,再判一次写的是同一个值——
81
+ * 两条判据因此不各立一份 turn 口径(缺省一个入参就是替调用方决定它判什么)。
82
+ * **只清不写**:同判据一,两条写入路径不重叠——只写 `turn-domain`,端 overlay 那一格不在本条射程内。
83
+ * @param {object} agent 主 agent(A 段 `_inject` 载体)
84
+ * @param {number} delivered 本回合 `drainChildUpstream` 的消费条数(必填,无缺省;非数 ⇒ 抛)
85
+ */
86
+ export function clearUpstreamDomainIfEmpty(agent, delivered) {
87
+ if (typeof delivered !== "number") {
88
+ throw new Error("clearUpstreamDomainIfEmpty: delivered(本回合 drain 的消费条数)必填且必为数——缺它会静默不清,指空位的旧文本就在请求里留下")
89
+ }
90
+ if (delivered !== 0) return
91
+ setInject(agent, "turn-domain", null)
92
+ }
93
+
94
+ /** Engineering-mode status injection — one reminder on EVERY transition (2026-08-25:
95
+ * OFF is announced too — the model must know the gates lifted; silence after /eng-off
96
+ * left it guessing. Covers TUI /eng, resume, and any path bypassing the eng tool.)
97
+ * 翻转是事件不是状态(§1.1 注入三段):归 B 段待发队,下一轮看到就够;`mode` 格只留 AUTO 行,
98
+ * 模式本身每回合由 `env` 格带出,不因翻转提示离开 A 而丢。 */
99
+ export function injectEngineeringReminder(agent) {
100
+ const eng = agent.config?.agent?.engineering ?? false
101
+ if (eng !== agent._lastEngState) {
102
+ pushInject(agent, { role: "user", content: eng ? ENG_ON_REMINDER : ENG_OFF_REMINDER, transient: true })
103
+ }
104
+ agent._lastEngState = eng
105
+ }
@@ -5,26 +5,34 @@
5
5
  * 接口 = runTurnLoop(agent, ctx);控制流零转换(`continue` ∕ `return cr.content` ∕ `throw` 全留环内)。
6
6
  */
7
7
  import { resolve } from "node:path"
8
- import { pushReal, summarizeRunExplorations } from "../context.mjs"
8
+ import { pushReal, pushInject, pushRecord, flattenHistory, summarizeRunExplorations } from "../context.mjs"
9
9
  import { abortError, annotateAbort } from "../abort-provenance.mjs"
10
- import { specForModel, assistantToolCallMessage } from "../config.mjs"
10
+ import { specForModel, assistantEchoMessage, assistantTextMessage, isThinkingRequest } from "../config.mjs"
11
11
  import { executeToolCalls } from "./dispatch.mjs"
12
12
  import { recordToolResults } from "./record-results.mjs"
13
+ /** 正文收尾入线(#2647):回声键在写历史那一刻落键——有原文写原文,无原文在思考模式下写空串。 */
14
+ function pushAssistantText(agent, response) {
15
+ const spec = specForModel(agent.provider?.model)
16
+ pushReal(agent, assistantTextMessage(response, spec, isThinkingRequest(agent.provider ?? null, spec), agent.provider ?? null))
17
+ }
18
+ // 归属表(收口取材的判据一):中断分支的记账点与常路同笔——两处 `_touchedFiles.push` 都写归属。
19
+ import { recordAttribution } from "./batch-attribution.mjs"
13
20
  import { injectPostTurn } from "./post-turn.mjs"
21
+ import { clearTurnDomainIfEmpty, clearUpstreamDomainIfEmpty } from "./turn-domain-text.mjs"
14
22
  import { handleCompletion, isSubstantiveResponse } from "./completion.mjs"
15
- import { runCompactionCheck, enforceContextFit, injectTurnReminders, injectResponseReminders } from "./run-stages.mjs"
16
- import { recordTokenSample } from "../token-window.mjs"
23
+ import { runCompactionCheck, enforceContextFit, preflightWindowFit, injectTurnReminders, injectResponseReminders } from "./run-stages.mjs"
24
+ import { recordTokenSample, faceEstimate } from "../token-window.mjs"
17
25
  import { callModelTurn } from "./chat-call.mjs"
18
26
  import {
19
27
  turnFrame, // 第 19 批(TURN-ACROSS-SEGMENTS):跨段累计编号帧(设计 TURN-CAP-CONTINUE.md §4)
20
28
  ContinueError,
21
29
  FILE_MUTATORS, toolTouchPaths,
22
- wroteSince, // #934(§6.32.2 ① 判据式):写序是否推进——轮顶 ∥ 撞帽收尾两处判据点共用
30
+ wroteSince, // #934(§6.32.2 ① 判据式):写序是否推进——轮顶 ∥ 撞帽收尾 ∥ advisor 预算复位(§6.4 A)三处判据点共用
23
31
  } from "./helpers.mjs"
24
32
 
25
33
  export async function runTurnLoop(agent, {
26
34
  maxTurns, threshold, toolSchemas, toolByName, systemPrompt,
27
- depth, signal, autoTurn, suspDriven, streamOutput,
35
+ depth, signal, autoTurn, upstreamTurn, suspDriven, streamOutput,
28
36
  consumeInjected, consumeQueuedInput, callbacks, distillSignal,
29
37
  }) {
30
38
  let guardPushbacks = 0
@@ -49,6 +57,11 @@ export async function runTurnLoop(agent, {
49
57
  // `context` 工具的 stats 报**同一口径**(不自行重算第二口径;VSC checkAndCompact 同款暂存)。
50
58
  agent._ctxBasis = { threshold, overhead: compactionOverhead }
51
59
 
60
+ // 切换预判(`CONTEXT-COMPACTION.md` §5.2):run 装配之后、第一个回合之前——模型切换 ∥ `providers[].context`
61
+ // 调小 ∥ `reasoningEffort` 变更这三条来路都让 `limit` 变小,而 `agent.history` 一条没少。预判点因此就是
62
+ // 装备点(参数按 run 现算),一处覆盖三条来路,不必为每条各立钩子。越线 ⇒ 跑与安全点同一条处置链。
63
+ await preflightWindowFit(agent, { threshold, callbacks, compactionOverhead, recentCallSigs, signal })
64
+
52
65
  // §6.17.1 链三(越窗 400 自适应):单回合调用外包一层 catch——服务端说越窗 ⇒ 强制压一次 + 重试同一回合一次。
53
66
  // 排除面:`stage ∈ {compress, distill}` 的请求**不经本函数**(压缩机与蒸馏各自直调 `chat`,续写子请求的
54
67
  // 失败已在 `provider/core.mjs` 折进 `_warnings`)⇒ 本 catch 只接回合请求的 typed 越窗,不存在「已流出再重放」。
@@ -87,7 +100,7 @@ export async function runTurnLoop(agent, {
87
100
  agent._mutSeqMark = agent._mutationSeq
88
101
 
89
102
  for (let turn = 0; turn < maxTurns; turn++) {
90
- // #793(核面小修批——AGENT-LOOP.md §6.2 环边界中止前置 ∥ 需求 F5):环头检查点——中止恒以
103
+ // #793(核面小修批——AGENT-LOOP.md §3 环边界中止前置 ∥ 需求 F5):环头检查点——中止恒以
91
104
  // AbortError 收束、不开启新轮(环头注入族 / 压缩 / 模型调用零触)。
92
105
  if (signal?.aborted) throw abortError(signal, "agent", "turn-head")
93
106
  // 第 19 批(TURN-ACROSS-SEGMENTS——设计 TURN-CAP-CONTINUE.md §4):编号帧——
@@ -134,13 +147,21 @@ export async function runTurnLoop(agent, {
134
147
  // 子代理在飞消息(子 → 父;§6.27):空队列 no-op;非空 ⇒ 恰一条合并 user 消息注入。
135
148
  // 批 async-delivery-formalize(§6.34.2 行 2):驱动面收窄「交付轮轮首」(`turn === 0` ∧ `autoTurn`——
136
149
  // 用户回合零 drain);回退面(`!suspDriven`)逐字保持(每轮每步)。
137
- if (!suspDriven || (turn === 0 && autoTurn === true)) drainChildUpstream(agent)
150
+ // 域文本那一格的存活期 = 它描述的那一次投递(`AGENT-LOOP-ASYNC-POOL.md` §8.6「自动回合域文本」):
151
+ // 投递物进 B 段、第一个请求之后即离场;域文本进 A 段格、每个请求都在场。两条判据在同一个回合头
152
+ // 各判一件事,只清不写(写仍在起跑期一处)——输入不同的两条判据因此不成一条。
153
+ // 判据一(三族一律,只读 `turn`):从第二个请求起清格,投递物那时已经不在了。
154
+ // 判据二(上行族独有,只读 `delivered`):第一个请求 drain 投 0 条清格;投到的保留 run 起点那一份(端域文本 ∥ 核基座,
155
+ // 端 overlay 另住 `run-overlay` 格、不在本条射程内)——上行域文本与它描述的投递同寿(`AGENT-LOOP-UPSTREAM.md` §5.1)。
156
+ const delivered = (!suspDriven || (turn === 0 && autoTurn === true)) ? drainChildUpstream(agent) : 0
157
+ if (autoTurn) clearTurnDomainIfEmpty(agent, turn)
158
+ if (upstreamTurn) clearUpstreamDomainIfEmpty(agent, delivered)
138
159
  // ③ 用户 → 主会话投递(步边界 pickup——queue-visible 批 fix 轮 2026-09-24 · F16):循环头
139
160
  // 回合边界缝(核只给缝、不给策略——取批 / pushReal / 呈现归端侧闭包);缺省 null,系统轮不传
140
161
  // (`AGENT-LOOP-ASYNC-POOL.md` §6.8「步边界 pickup」· 适用面 = 用户回合)。
141
162
  consumeQueuedInput?.(agent)
142
163
 
143
- const lastRole = agent.history.at(-1)?.role
164
+ const lastRole = flattenHistory(agent.history).at(-1)?.role
144
165
  if (lastRole === "user" || lastRole === "tool") {
145
166
  // 2026-09-05 实践轮:压缩检查/降级计数提为 runCompactionCheck(agent/run-stages.mjs——
146
167
  // CLI 对位 VS run-stages)——循环骨架此处只剩检查调用(recentCallSigs 对象引用回流)。
@@ -154,10 +175,11 @@ export async function runTurnLoop(agent, {
154
175
  systemPrompt, toolSchemas, streamOutput, callbacks, signal, streamRuleFired, autoTurn, depth, turn,
155
176
  })
156
177
 
157
- // 空响应预算复位(AGENT-LOOP.md §6.5① · D-AL28):本轮响应**有实质** ⇒ 计数清 0(实质 = 有正文
178
+ // 空响应预算复位(AGENT-LOOP.md §6 完成守卫 · D-AL28):本轮响应**有实质** ⇒ 计数清 0(实质 = 有正文
158
179
  // 或带工具调用;判据单源 = completion.mjs `isSubstantiveResponse`)。落位 = 本轮响应存在的第一处、
159
180
  // 也是四支路(下方流规则 abort ∥ 用户中断 ∥ 工具批 ∥ 零工具)发散前的最后一处——落进任一分支都会漏其余三支。
160
- // 与下方 `guardPushbacks = 0`(工具批执行处)分工:那处复位的是 verify ∥ advisor 推回预算、只看「有工具批」;
181
+ // 与下方工具批执行处的推回预算复位分工:那处复位 verify ∥ advisor 两面——verify 面看「有工具批」、
182
+ // advisor 面看「本批写序推进」(§6.4 A:成功的文件写 ∥ 子代理合并才算进展,读文件不算);
161
183
  // 本处复位空响应预算、看「有实质」——正文本身已是实质,不必等工具批。
162
184
  if (isSubstantiveResponse(response)) agent._emptyRetries = 0
163
185
 
@@ -184,10 +206,10 @@ export async function runTurnLoop(agent, {
184
206
  // message as a reminder, retry from the same context.
185
207
  if (response.ruleTriggered) {
186
208
  if (response.content) {
187
- pushReal(agent, { role: "assistant", content: response.content })
209
+ pushAssistantText(agent, response)
188
210
  }
189
211
  const label = response.ruleName ? ` — stream rule "${response.ruleName}"` : ""
190
- agent.history.push({
212
+ pushInject(agent, {
191
213
  role: "user",
192
214
  content: `[System reminder${label}: ${response.ruleMessage}]`,
193
215
  })
@@ -202,9 +224,13 @@ export async function runTurnLoop(agent, {
202
224
  // message, then signal the outer loop to recreate the controller and resume.
203
225
  if (response.interrupted) {
204
226
  if (response.content) {
205
- pushReal(agent, { role: "assistant", content: response.content })
227
+ pushAssistantText(agent, response)
206
228
  }
207
- agent.history.push({
229
+ pushInject(agent, {
230
+ role: "user",
231
+ content: `[User interrupt: ${response.interruptMessage}]`,
232
+ })
233
+ pushRecord(agent, {
208
234
  role: "user",
209
235
  content: `[User interrupt: ${response.interruptMessage}]`,
210
236
  })
@@ -222,7 +248,19 @@ export async function runTurnLoop(agent, {
222
248
  agent._usageTurns = (agent._usageTurns ?? 0) + 1
223
249
  if (response.usage.prompt_tokens != null) {
224
250
  agent._lastPromptTokens = response.usage.prompt_tokens
225
- agent._usageAtLen = agent.history.length
251
+ // 基线位置 = 真值覆盖到的**最后一个位置**,写成「最后一个轮元素 + 它此刻的内层长度」。
252
+ // 不能写 `{ turn: agent.history.length, msg: 0 }`:`flatIndexOf` 对 `turn === 轮元素数` 是拿
253
+ // 各轮内层之和现算的,而真值之后的消息恰恰追加进**最后一个轮元素的内层**(`pushReal` 追加到
254
+ // `agent.history.at(-1).messages`)——那个位置会跟着追加前移,后缀恒空,工具结果一条都补不上
255
+ // (§2.5「两轮调用之间追加的消息计进尾部估算」)。同形写法见 `agent/run-stages.mjs` 的 `endPositionOf`。
256
+ const lastTurn = Array.isArray(agent.history) ? agent.history.at(-1) : null
257
+ agent._usageAt = lastTurn
258
+ ? { turn: agent.history.length - 1, msg: Array.isArray(lastTurn.messages) ? lastTurn.messages.length : 0 }
259
+ : { turn: 0, msg: 0 }
260
+ // 真值那一刻的非对话面(§2.5):与 `_lastPromptTokens` 同一个写点、同一个条件——两个字段
261
+ // 一起写、一起置 null。此刹 `_retained` ∥ `_inject` ∥ `_pendingInject` 仍是那条请求发出去时的样子
262
+ // (清待发队在回合结束时),所以这个基线就是真值里已含的非对话面,`fixed` 与它的差就是这段时间的增量。
263
+ agent._usageFixedBase = faceEstimate(agent, agent._ctxBasis?.overhead ?? compactionOverhead).fixed
226
264
  }
227
265
  // §6.17 估算自校准:服务端真值 ÷ 输入侧估算(`estimated` = 发送面净判同一个 estPrompt)
228
266
  recordTokenSample(agent, agent.provider, response.estimated, response.usage)
@@ -254,7 +292,9 @@ export async function runTurnLoop(agent, {
254
292
  // abort after chat completes, before committing history: don't commit a half-finished turn
255
293
  if (signal?.aborted) throw abortError(signal, "agent", "post-chat")
256
294
 
257
- pushReal(agent, assistantToolCallMessage(response, specForModel(agent.provider.model)))
295
+ // 回声键的写法归构造点,模式归 `isThinkingRequest`(单源 = think-off.mjs):调用点只把两者交给它。
296
+ const echoSpec = specForModel(agent.provider.model)
297
+ pushReal(agent, assistantEchoMessage(response, echoSpec, isThinkingRequest(agent.provider, echoSpec), agent.provider ?? null))
258
298
 
259
299
  const results = await executeToolCalls(agent, toolByName, response.toolCalls, callbacks, depth, signal)
260
300
 
@@ -277,19 +317,22 @@ export async function runTurnLoop(agent, {
277
317
  try {
278
318
  const args = JSON.parse(toolCall.arguments)
279
319
  const paths = toolTouchPaths(tool, args)
320
+ const touched = []
280
321
  for (const p of paths) {
281
322
  const abs = resolve(agent.cwd, p)
282
323
  if (!agent._touchedFiles.includes(abs)) agent._touchedFiles.push(abs)
324
+ touched.push(abs)
283
325
  }
326
+ recordAttribution(agent, touched, agent._batchDoc)
284
327
  } catch { /* 畸形 args 不影响记账(touchedFiles 尽力而为) */ }
285
328
  }
286
- // The assistant tool_calls were committed above — synthesize placeholder tool
287
- // results BEFORE the interrupt message (strict providers 400 on dangling
288
- // tool_calls; consult P1, 2026-08-30).
289
- for (const tc of response.toolCalls) {
290
- agent.history.push({ role: "tool", tool_call_id: tc.id, content: "[Tool execution interrupted — results discarded]" })
291
- }
292
- agent.history.push({
329
+ // 中断占位 `tool` 结果不入线:它们是配对占位,由发送层 `normalizeToolPairing` 按结构补
330
+ // (§1.1 注入三段:机制合成的消息一条都不落 `agent.history`)。
331
+ pushInject(agent, {
332
+ role: "user",
333
+ content: `[User interrupt: ${signal.reason.message}]`,
334
+ })
335
+ pushRecord(agent, {
293
336
  role: "user",
294
337
  content: `[User interrupt: ${signal.reason.message}]`,
295
338
  })
@@ -297,9 +340,23 @@ export async function runTurnLoop(agent, {
297
340
  continue
298
341
  }
299
342
 
300
- // Model is executing tools → real work: reset guard pushback counters
343
+ // Model is executing tools.
344
+ // verify 面:任一工具批即回满(`guardPushbacks = 0` 字面与行为逐字不变——批失败时同样清零,本批未动)。
301
345
  guardPushbacks = 0
302
- advisorPushbacks = 0
346
+ // advisor 面(ADVISOR-CONVERGENCE.md §6.4 A):预算只在被审对象真的变了时回满——判据 = 本批写序
347
+ // 推进了(`wroteSince`,与零落笔看门狗同源;`_mutSeqMark` 轮头前移、此处批后比一次)。写序唯一推进面
348
+ // = `noteMutations`,两个写者:成功的文件写工具(`dispatch-gates.mjs` 的 `noteExecutedMutation`,带
349
+ // 非 `Error:` 前缀门)与子代理代码合并(`mergeChildMutations`)——故合入也算进展,不另立判据。
350
+ // 读文件 / 查代码 / bash / git 一概不复位:它们对被审代码零改变,复位就把「同一条提醒给 N 次机会」
351
+ // 变成无限次(实测形态 = 模型读一次文件、提醒来一条,无限重复)。
352
+ // 到顶诚实提醒的一次性位与本预算同点复位(两行手拉手——§1 20:39 裁定):有新进展 ⇒ 该次交付重新需要
353
+ // 一句诚实声明;若在这里只复位预算、不复位位,则「发过诚实提醒 → 又改代码 → 再收尾」会静默放行
354
+ // (未评审即交付不吭声),而那正是本批要堵的形状。`agent._advisorReminders` **不**随进展复位——
355
+ // 它是未评审周期的上限计数(层 2 的 5 条),复位它等于把周期上限取消。
356
+ if (wroteSince(agent, agent._mutSeqMark)) {
357
+ advisorPushbacks = 0
358
+ agent._advisorHonestySent = false
359
+ }
303
360
 
304
361
  // Commit tool results (pairing, multimodal deferral, mutation accounting, reindex)
305
362
  await recordToolResults(agent, toolByName, results)
@@ -310,7 +367,7 @@ export async function runTurnLoop(agent, {
310
367
  // #417(撞帽载荷「本段零落盘轮数」):收尾轮(撞帽轮)单结——与环内同一谓词(不另作 alert ∥ streak
311
368
  // 判定,链尾无下一轮可推报);轮顶计数只覆盖到倒数第二轮(maxTurns ≤ 0 时环未跑,不虚计)。
312
369
  if (maxTurns > 0 && !wroteSince(agent, agent._mutSeqMark)) agent._zeroWriteTurns += 1
313
- // #793(核面小修批——AGENT-LOOP.md §6.2 环边界中止前置 ∥ 需求 F5):环尾检查点——中止恒以
370
+ // #793(核面小修批——AGENT-LOOP.md §3 环边界中止前置 ∥ 需求 F5):环尾检查点——中止恒以
314
371
  // AbortError 收束(不落 ContinueError——用户 Stop 优先于继续提示;消费契约 = 外层按 reason 判定)。
315
372
  if (signal?.aborted) throw abortError(signal, "agent", "turn-tail")
316
373
  throw new ContinueError(maxTurns)