@thincoder/core 0.11.2 → 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 (198) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/advisor/compaction.mjs +7 -5
  3. package/advisor/history.mjs +24 -11
  4. package/advisor/loop.mjs +13 -8
  5. package/advisor/messages.mjs +72 -8
  6. package/advisor/run.mjs +24 -13
  7. package/advisor.mjs +7 -3
  8. package/agent/chat-call.mjs +14 -9
  9. package/agent/completion.mjs +28 -40
  10. package/agent/continue-decision.mjs +14 -8
  11. package/agent/digest-account.mjs +133 -59
  12. package/agent/dispatch-run.mjs +1 -1
  13. package/agent/dispatch.mjs +2 -1
  14. package/agent/family-tools.mjs +12 -13
  15. package/agent/helpers.mjs +17 -72
  16. package/agent/image-heal.mjs +18 -4
  17. package/agent/post-turn.mjs +13 -26
  18. package/agent/record-results.mjs +21 -6
  19. package/agent/run-stages.mjs +72 -37
  20. package/agent/run-start.mjs +148 -113
  21. package/agent/setup-reminders.mjs +187 -91
  22. package/agent/setup.mjs +204 -138
  23. package/agent/spawn-child.mjs +2 -2
  24. package/agent/suspension.mjs +43 -15
  25. package/agent/timers.mjs +4 -1
  26. package/agent/turn-domain-text.mjs +105 -0
  27. package/agent/turn-loop.mjs +54 -22
  28. package/agent/turn-projection.mjs +127 -227
  29. package/agent/turn-tool-process.mjs +32 -37
  30. package/agent-tools/advisor-async.mjs +6 -3
  31. package/agent-tools/advisor-launch.mjs +5 -5
  32. package/agent-tools/advisor.mjs +1 -1
  33. package/agent-tools/async-discard.mjs +7 -2
  34. package/agent-tools/async-settle.mjs +18 -12
  35. package/agent-tools/bash-async.mjs +5 -2
  36. package/agent-tools/batch-closeout.mjs +12 -62
  37. package/agent-tools/batch-ledger-bind.mjs +19 -8
  38. package/agent-tools/batch-lifecycle.mjs +37 -11
  39. package/agent-tools/batch-read.mjs +151 -4
  40. package/agent-tools/batch-record-write.mjs +5 -5
  41. package/agent-tools/batch-segment-vocab.mjs +84 -4
  42. package/agent-tools/batch-skeleton.mjs +18 -14
  43. package/agent-tools/batch-supersede.mjs +1 -1
  44. package/agent-tools/batch-tier-gate.mjs +36 -119
  45. package/agent-tools/batch.mjs +30 -20
  46. package/agent-tools/browser-async.mjs +5 -2
  47. package/agent-tools/consult.mjs +10 -7
  48. package/agent-tools/context.mjs +47 -31
  49. package/agent-tools/digest-budget.mjs +10 -9
  50. package/agent-tools/eng.mjs +3 -4
  51. package/agent-tools/escalate-async.mjs +3 -3
  52. package/agent-tools/goal.mjs +5 -2
  53. package/agent-tools/judge-domain.mjs +347 -0
  54. package/agent-tools/manifest.mjs +2 -2
  55. package/agent-tools/parent-channel.mjs +6 -3
  56. package/agent-tools/plan.mjs +11 -10
  57. package/agent-tools/review-facts.mjs +9 -3
  58. package/agent-tools/skill.mjs +7 -8
  59. package/agent-tools/spawn-gates.mjs +5 -16
  60. package/agent-tools/ssh-session.mjs +6 -3
  61. package/agent-tools/ssh-transfer.mjs +1 -1
  62. package/agent-tools/subagent-actions.mjs +2 -2
  63. package/agent-tools/subagent-async.mjs +11 -8
  64. package/agent-tools/subagent-scheduler.mjs +9 -9
  65. package/agent-tools/subagent-spawn.mjs +2 -2
  66. package/agent-tools/subagent.mjs +5 -18
  67. package/agent-tools/task.mjs +0 -8
  68. package/agent.mjs +15 -15
  69. package/auto-think.mjs +5 -2
  70. package/compaction-work-state.mjs +230 -0
  71. package/compress-form.mjs +41 -6
  72. package/config-defaults.mjs +5 -2
  73. package/config.mjs +53 -17
  74. package/context-degrade.mjs +79 -48
  75. package/context-echo.mjs +6 -26
  76. package/context-push.mjs +328 -31
  77. package/context.mjs +203 -141
  78. package/conventions.mjs +1 -1
  79. package/declaration.mjs +95 -17
  80. package/escape.mjs +6 -5
  81. package/explore-distill.mjs +35 -8
  82. package/generate-title.mjs +10 -1
  83. package/knowledge/prompt-resources.md +5 -1
  84. package/ledger-tools.mjs +50 -50
  85. package/ledger-write-ops.mjs +43 -16
  86. package/memory/docs.mjs +51 -15
  87. package/memory/file-list.mjs +6 -0
  88. package/model-specs.mjs +87 -21
  89. package/origin-guard.mjs +190 -0
  90. package/package.json +1 -1
  91. package/prompt-files.mjs +33 -11
  92. package/prompt-overlays.mjs +12 -5
  93. package/prompts/advisor-design.md +55 -36
  94. package/prompts/advisor-round1.md +18 -7
  95. package/prompts/advisor-round2.md +18 -7
  96. package/prompts/advisor-round3.md +18 -7
  97. package/prompts/common.md +89 -51
  98. package/prompts/consult-base.md +2 -3
  99. package/prompts/discipline-engineering.md +474 -440
  100. package/prompts/discipline-normal.md +107 -31
  101. package/prompts/knowledge/business-gates.md +23 -15
  102. package/prompts/knowledge/decision-quality.md +16 -18
  103. package/prompts/knowledge/doc-lookup.md +22 -27
  104. package/prompts/knowledge/document-writing.md +31 -49
  105. package/prompts/knowledge/documentation-evaluation.md +37 -45
  106. package/prompts/knowledge/evidence-discipline.md +36 -55
  107. package/prompts/knowledge/normal-coding-workflow.md +27 -21
  108. package/prompts/knowledge/normal-delivery-collaboration.md +33 -17
  109. package/prompts/knowledge/normal-work-management.md +10 -7
  110. package/prompts/knowledge/product-security.md +22 -17
  111. package/prompts/knowledge/project-records.md +63 -52
  112. package/prompts/knowledge/tool-apply-patch.md +12 -13
  113. package/prompts/knowledge/tool-bash.md +13 -4
  114. package/prompts/knowledge/tool-batch-eng-coder.md +13 -6
  115. package/prompts/knowledge/tool-batch-eng-designer.md +14 -6
  116. package/prompts/knowledge/tool-batch-review.md +12 -6
  117. package/prompts/knowledge/tool-batch.md +76 -62
  118. package/prompts/knowledge/tool-browser.md +45 -34
  119. package/prompts/knowledge/tool-context.md +2 -2
  120. package/prompts/knowledge/tool-delete.md +5 -1
  121. package/prompts/knowledge/tool-doc-check.md +25 -24
  122. package/prompts/knowledge/tool-doc-graph-read.md +3 -3
  123. package/prompts/knowledge/tool-doc-graph.md +15 -15
  124. package/prompts/knowledge/tool-edit.md +26 -23
  125. package/prompts/knowledge/tool-execute.md +9 -4
  126. package/prompts/knowledge/tool-fetch.md +7 -1
  127. package/prompts/knowledge/tool-file-ops.md +6 -1
  128. package/prompts/knowledge/tool-git-read.md +3 -1
  129. package/prompts/knowledge/tool-git.md +1 -1
  130. package/prompts/knowledge/tool-glob.md +3 -1
  131. package/prompts/knowledge/tool-grep.md +5 -2
  132. package/prompts/knowledge/tool-hashline-edit.md +4 -2
  133. package/prompts/knowledge/tool-insert-after.md +3 -1
  134. package/prompts/knowledge/tool-ledger-read.md +6 -13
  135. package/prompts/knowledge/tool-ledger.md +14 -10
  136. package/prompts/knowledge/tool-ls.md +2 -0
  137. package/prompts/knowledge/tool-manifest.md +10 -7
  138. package/prompts/knowledge/tool-memory.md +15 -11
  139. package/prompts/knowledge/tool-operations.md +59 -71
  140. package/prompts/knowledge/tool-plan.md +1 -2
  141. package/prompts/knowledge/tool-process.md +1 -1
  142. package/prompts/knowledge/tool-read-history.md +6 -7
  143. package/prompts/knowledge/tool-read.md +1 -0
  144. package/prompts/knowledge/tool-settings.md +6 -7
  145. package/prompts/knowledge/tool-ssh.md +37 -15
  146. package/prompts/knowledge/tool-subagent.md +37 -39
  147. package/prompts/knowledge/tool-task.md +3 -1
  148. package/prompts/knowledge/tool-team-ledger.md +5 -1
  149. package/prompts/knowledge/tool-tree.md +2 -0
  150. package/prompts/knowledge/tool-wait-for.md +16 -16
  151. package/prompts/knowledge/tool-write.md +4 -1
  152. package/prompts/knowledge/upstream-protocol.md +39 -37
  153. package/prompts/persona-coder.md +1 -3
  154. package/prompts/persona-eng-coder.md +5 -5
  155. package/prompts/persona-eng-designer.md +34 -17
  156. package/prompts/persona-engineering.md +532 -501
  157. package/prompts/persona-explore.md +0 -2
  158. package/prompts/persona-normal.md +17 -9
  159. package/prompts/persona-plan.md +0 -2
  160. package/prompts/persona-tester.md +0 -2
  161. package/prompts/subagent-base.md +0 -2
  162. package/provider/anthropic.mjs +4 -2
  163. package/provider/core.mjs +5 -3
  164. package/provider/errors.mjs +41 -7
  165. package/provider/google.mjs +5 -3
  166. package/provider/reasoning-echo.mjs +16 -0
  167. package/provider/responses.mjs +4 -2
  168. package/provider/sse.mjs +11 -6
  169. package/rules.mjs +11 -10
  170. package/session-lifecycle.mjs +115 -81
  171. package/session-slot-write.mjs +1 -1
  172. package/session.mjs +23 -20
  173. package/shell-identity.mjs +129 -22
  174. package/skip-dirs.mjs +24 -0
  175. package/team-ledger.mjs +22 -22
  176. package/text-budget.mjs +1 -1
  177. package/think-off.mjs +27 -0
  178. package/token-ttl.mjs +1 -1
  179. package/token-window.mjs +278 -88
  180. package/tool-docs/bash.md +0 -2
  181. package/tool-docs/consult_start.md +2 -2
  182. package/tool-docs/consult_stop.md +2 -2
  183. package/tools/browser.mjs +8 -8
  184. package/tools/execute.mjs +2 -2
  185. package/tools/file.mjs +17 -11
  186. package/tools/git.mjs +12 -12
  187. package/tools/ops.mjs +2 -2
  188. package/tools/patch.mjs +1 -1
  189. package/tools/process-doc-mark.mjs +33 -4
  190. package/tools/repomap.mjs +25 -3
  191. package/tools/search.mjs +74 -26
  192. package/tools/shared.mjs +4 -3
  193. package/tools/ssh.mjs +5 -5
  194. package/tools/tree.mjs +32 -10
  195. package/tools/web-deepseek.mjs +1 -1
  196. package/tools/web.mjs +2 -2
  197. package/tools/write-gate-params.mjs +3 -3
  198. package/window-policy.mjs +118 -78
@@ -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,17 +5,23 @@
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
+ }
13
18
  // 归属表(收口取材的判据一):中断分支的记账点与常路同笔——两处 `_touchedFiles.push` 都写归属。
14
19
  import { recordAttribution } from "./batch-attribution.mjs"
15
20
  import { injectPostTurn } from "./post-turn.mjs"
21
+ import { clearTurnDomainIfEmpty, clearUpstreamDomainIfEmpty } from "./turn-domain-text.mjs"
16
22
  import { handleCompletion, isSubstantiveResponse } from "./completion.mjs"
17
23
  import { runCompactionCheck, enforceContextFit, preflightWindowFit, injectTurnReminders, injectResponseReminders } from "./run-stages.mjs"
18
- import { recordTokenSample } from "../token-window.mjs"
24
+ import { recordTokenSample, faceEstimate } from "../token-window.mjs"
19
25
  import { callModelTurn } from "./chat-call.mjs"
20
26
  import {
21
27
  turnFrame, // 第 19 批(TURN-ACROSS-SEGMENTS):跨段累计编号帧(设计 TURN-CAP-CONTINUE.md §4)
@@ -26,7 +32,7 @@ import {
26
32
 
27
33
  export async function runTurnLoop(agent, {
28
34
  maxTurns, threshold, toolSchemas, toolByName, systemPrompt,
29
- depth, signal, autoTurn, suspDriven, streamOutput,
35
+ depth, signal, autoTurn, upstreamTurn, suspDriven, streamOutput,
30
36
  consumeInjected, consumeQueuedInput, callbacks, distillSignal,
31
37
  }) {
32
38
  let guardPushbacks = 0
@@ -94,7 +100,7 @@ export async function runTurnLoop(agent, {
94
100
  agent._mutSeqMark = agent._mutationSeq
95
101
 
96
102
  for (let turn = 0; turn < maxTurns; turn++) {
97
- // #793(核面小修批——AGENT-LOOP.md §6.2 环边界中止前置 ∥ 需求 F5):环头检查点——中止恒以
103
+ // #793(核面小修批——AGENT-LOOP.md §3 环边界中止前置 ∥ 需求 F5):环头检查点——中止恒以
98
104
  // AbortError 收束、不开启新轮(环头注入族 / 压缩 / 模型调用零触)。
99
105
  if (signal?.aborted) throw abortError(signal, "agent", "turn-head")
100
106
  // 第 19 批(TURN-ACROSS-SEGMENTS——设计 TURN-CAP-CONTINUE.md §4):编号帧——
@@ -141,13 +147,21 @@ export async function runTurnLoop(agent, {
141
147
  // 子代理在飞消息(子 → 父;§6.27):空队列 no-op;非空 ⇒ 恰一条合并 user 消息注入。
142
148
  // 批 async-delivery-formalize(§6.34.2 行 2):驱动面收窄「交付轮轮首」(`turn === 0` ∧ `autoTurn`——
143
149
  // 用户回合零 drain);回退面(`!suspDriven`)逐字保持(每轮每步)。
144
- 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)
145
159
  // ③ 用户 → 主会话投递(步边界 pickup——queue-visible 批 fix 轮 2026-09-24 · F16):循环头
146
160
  // 回合边界缝(核只给缝、不给策略——取批 / pushReal / 呈现归端侧闭包);缺省 null,系统轮不传
147
161
  // (`AGENT-LOOP-ASYNC-POOL.md` §6.8「步边界 pickup」· 适用面 = 用户回合)。
148
162
  consumeQueuedInput?.(agent)
149
163
 
150
- const lastRole = agent.history.at(-1)?.role
164
+ const lastRole = flattenHistory(agent.history).at(-1)?.role
151
165
  if (lastRole === "user" || lastRole === "tool") {
152
166
  // 2026-09-05 实践轮:压缩检查/降级计数提为 runCompactionCheck(agent/run-stages.mjs——
153
167
  // CLI 对位 VS run-stages)——循环骨架此处只剩检查调用(recentCallSigs 对象引用回流)。
@@ -161,7 +175,7 @@ export async function runTurnLoop(agent, {
161
175
  systemPrompt, toolSchemas, streamOutput, callbacks, signal, streamRuleFired, autoTurn, depth, turn,
162
176
  })
163
177
 
164
- // 空响应预算复位(AGENT-LOOP.md §6.5① · D-AL28):本轮响应**有实质** ⇒ 计数清 0(实质 = 有正文
178
+ // 空响应预算复位(AGENT-LOOP.md §6 完成守卫 · D-AL28):本轮响应**有实质** ⇒ 计数清 0(实质 = 有正文
165
179
  // 或带工具调用;判据单源 = completion.mjs `isSubstantiveResponse`)。落位 = 本轮响应存在的第一处、
166
180
  // 也是四支路(下方流规则 abort ∥ 用户中断 ∥ 工具批 ∥ 零工具)发散前的最后一处——落进任一分支都会漏其余三支。
167
181
  // 与下方工具批执行处的推回预算复位分工:那处复位 verify ∥ advisor 两面——verify 面看「有工具批」、
@@ -192,10 +206,10 @@ export async function runTurnLoop(agent, {
192
206
  // message as a reminder, retry from the same context.
193
207
  if (response.ruleTriggered) {
194
208
  if (response.content) {
195
- pushReal(agent, { role: "assistant", content: response.content })
209
+ pushAssistantText(agent, response)
196
210
  }
197
211
  const label = response.ruleName ? ` — stream rule "${response.ruleName}"` : ""
198
- agent.history.push({
212
+ pushInject(agent, {
199
213
  role: "user",
200
214
  content: `[System reminder${label}: ${response.ruleMessage}]`,
201
215
  })
@@ -210,9 +224,13 @@ export async function runTurnLoop(agent, {
210
224
  // message, then signal the outer loop to recreate the controller and resume.
211
225
  if (response.interrupted) {
212
226
  if (response.content) {
213
- pushReal(agent, { role: "assistant", content: response.content })
227
+ pushAssistantText(agent, response)
214
228
  }
215
- agent.history.push({
229
+ pushInject(agent, {
230
+ role: "user",
231
+ content: `[User interrupt: ${response.interruptMessage}]`,
232
+ })
233
+ pushRecord(agent, {
216
234
  role: "user",
217
235
  content: `[User interrupt: ${response.interruptMessage}]`,
218
236
  })
@@ -230,7 +248,19 @@ export async function runTurnLoop(agent, {
230
248
  agent._usageTurns = (agent._usageTurns ?? 0) + 1
231
249
  if (response.usage.prompt_tokens != null) {
232
250
  agent._lastPromptTokens = response.usage.prompt_tokens
233
- 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
234
264
  }
235
265
  // §6.17 估算自校准:服务端真值 ÷ 输入侧估算(`estimated` = 发送面净判同一个 estPrompt)
236
266
  recordTokenSample(agent, agent.provider, response.estimated, response.usage)
@@ -262,7 +292,9 @@ export async function runTurnLoop(agent, {
262
292
  // abort after chat completes, before committing history: don't commit a half-finished turn
263
293
  if (signal?.aborted) throw abortError(signal, "agent", "post-chat")
264
294
 
265
- 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))
266
298
 
267
299
  const results = await executeToolCalls(agent, toolByName, response.toolCalls, callbacks, depth, signal)
268
300
 
@@ -294,13 +326,13 @@ export async function runTurnLoop(agent, {
294
326
  recordAttribution(agent, touched, agent._batchDoc)
295
327
  } catch { /* 畸形 args 不影响记账(touchedFiles 尽力而为) */ }
296
328
  }
297
- // The assistant tool_calls were committed above — synthesize placeholder tool
298
- // results BEFORE the interrupt message (strict providers 400 on dangling
299
- // tool_calls; consult P1, 2026-08-30).
300
- for (const tc of response.toolCalls) {
301
- agent.history.push({ role: "tool", tool_call_id: tc.id, content: "[Tool execution interrupted — results discarded]" })
302
- }
303
- 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, {
304
336
  role: "user",
305
337
  content: `[User interrupt: ${signal.reason.message}]`,
306
338
  })
@@ -335,7 +367,7 @@ export async function runTurnLoop(agent, {
335
367
  // #417(撞帽载荷「本段零落盘轮数」):收尾轮(撞帽轮)单结——与环内同一谓词(不另作 alert ∥ streak
336
368
  // 判定,链尾无下一轮可推报);轮顶计数只覆盖到倒数第二轮(maxTurns ≤ 0 时环未跑,不虚计)。
337
369
  if (maxTurns > 0 && !wroteSince(agent, agent._mutSeqMark)) agent._zeroWriteTurns += 1
338
- // #793(核面小修批——AGENT-LOOP.md §6.2 环边界中止前置 ∥ 需求 F5):环尾检查点——中止恒以
370
+ // #793(核面小修批——AGENT-LOOP.md §3 环边界中止前置 ∥ 需求 F5):环尾检查点——中止恒以
339
371
  // AbortError 收束(不落 ContinueError——用户 Stop 优先于继续提示;消费契约 = 外层按 reason 判定)。
340
372
  if (signal?.aborted) throw abortError(signal, "agent", "turn-tail")
341
373
  throw new ContinueError(maxTurns)