@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
@@ -1,55 +1,60 @@
1
1
  /**
2
2
  * agent/run-start.mjs — runAgent 起跑前段(2026-09-29 P2 三拆:agent.mjs runAgent 段 1
3
- * verbatim 迁入——distill 等待 ∕ pendingAsync 注入 ∕ prepareRun ∕ 复位块 ∕ 域文本 ∕ 授权注释块)。
3
+ * verbatim 迁入——distill 等待 ∥ pendingAsync 注入 ∥ prepareRun ∥ 复位块 ∥ 域文本 ∥ 授权注释块)。
4
+ * 2026-11-17 context-usage-reading 批:一个函数体装六件事 >> 折成五个具名步骤 + 一个编排体
5
+ * (`docs/core/design/CONTEXT-COMPACTION.md` §1.1「结构:留 ∥ 合 ∥ 删 ∥ 换」)。
4
6
  * 接口 = beginRun(agent, input, callbacks, opts) → 主循环装配面(`tools` 死绑定去——KD-8)。
7
+ *
8
+ * 七个函数内 `await import` 原样留在步骤内部:它们是真环,不是懒加载——`agent-tools/consult.mjs`
9
+ * 的 `import { createAgent, runAgent, excludeSubagentTools } from "../agent.mjs"` 经
10
+ * `agent.mjs → agent/run-start.mjs` 回到本档,提到档头就是静态环。
5
11
  */
6
12
  import { prepareRun } from "./setup.mjs"
7
- // 跨轮机读投影(CONTEXT-COMPACTION.md §1.1 ∥ SESSION.md §2 · 台账 #2395):安全接缝 = 本档——
8
- // 蒸馏得到之后、注入异步结果与本轮输入之前先把上一完成轮折叠掉。
9
- import { applyTurnProjection, createTurnLedger, findTurnStartIndex } from "./turn-projection.mjs"
13
+ // 轮元素起点(CONTEXT-COMPACTION §1.1):外层每个元素是一轮,起点由本档在 run 入口起——
14
+ // 与建账同一个位置、同一个条件,但写仍然走 `context-push.mjs` 的单点。
15
+ import { beginTurn, pushInject, setInject } from "../context.mjs"
16
+ // 轮记录的装配面(CONTEXT-COMPACTION.md §1.1:账本 ∥ 轮边界起点 ∥ 完成登记):本档只用账本一个符号,
17
+ // 跨轮清理挂在 `registerCompletedTurn`(轮完成登记那一刻,`agent.mjs`)。
18
+ import { createTurnLedger } from "./turn-projection.mjs"
19
+ // 域文本替换留痕(§8.6「写出来的那一份域文本不得为空」):空域文本取轮型基座这条路径要落一条事件。
20
+ import { logEvent } from "../log.mjs"
10
21
  import {
11
- restoreGuard, // digest D-S6 读侧单点(AGENT-LOOP-ASYNC-POOL.md §6.8;P2 机制层端差批 §2.18——键清单归核)
12
- AUTO_TURN_DIGEST_DOMAIN,
13
- AUTO_TURN_DIGEST_DOMAIN_ENG, // §6.15.3(F10 第三面):工程模式 digest 基座变体(task 指针改批次档 + 台账)
14
- UPSTREAM_TURN_DOMAIN, // §6.27.12.8:上行唤醒轮域文本(手动档——ask 轮不沿用 digest 域文本)
15
- TIMER_TURN_DOMAIN, // §6.30.3 D-TW4:timer 唤醒轮域文本(第三变体——到期 timer 自动开轮)
22
+ restoreGuard, // digest D-S6 读侧单点(AGENT-LOOP-ASYNC-POOL.md §1「挂起与 digest」;P2 机制层端差批 §2.18——键清单归核)
23
+ AUTO_TURN_DIGEST_DOMAIN, // AGENT-LOOP-ASYNC-POOL.md §8.6:消化轮基座(一族一版,两档共取)
24
+ UPSTREAM_TURN_DOMAIN, // AGENT-LOOP-UPSTREAM.md §6.27.12.8:上行唤醒轮域文本(ask 轮不沿用 digest 域文本)
25
+ TIMER_TURN_DOMAIN, // AGENT-LOOP-ASYNC-POOL.md §8.6 ∥ §7「timer」:timer 唤醒轮域文本(第三变体——到期 timer 自动开轮)
16
26
  } from "./helpers.mjs"
17
27
 
18
- export async function beginRun(agent, input, callbacks, {
19
- depth = 0, signal, overrideTurns, resume = false, autoTurn = false, upstreamTurn = false, timerTurn = false,
20
- extraTools = null, injections = null, turnDomainText = null, toolDecorate = undefined,
21
- } = {}) {
22
- // Previous run's async exploration distillation must settle before this run pushes
23
- // input (SEND-STALL-DISTILL §2.2 N1) — await first, or its history replace wipes it.
24
- if (agent._pendingDistill) {
25
- const p = agent._pendingDistill
26
- agent._pendingDistill = null
27
- await p
28
- }
29
- // ── 跨轮机读投影(CONTEXT-COMPACTION.md §1.1 · 台账 #2395)──
30
- // 安全接缝三条理由(设计 §2):①上一轮已完成且已登记(`_turnPending`)⇒ 把它的原始机读过程
31
- // 折叠为「用户请求 ∥ 最终回复 ∥ 任务状态」;②投影在 `await _pendingDistill` **之后**——蒸馏会
32
- // 异步替换 `agent.history`,先等待才作用在最终数组上,不被后到的替换覆盖;③投影在注入异步结果
33
- // 与本轮输入**之前**——本轮得到的工具过程原样完整(轮内第二次请求照旧看得见)。
34
- applyTurnProjection(agent)
35
- // 本轮原始段起点(续跑沿用链起点——链是同一轮):**用户输入消息**所在位——输入之前的运行注入
36
- // (环境行 ∥ 文档与记忆注入 ∥ 异步结果)属于上下文,不随折叠消失。尚未推到输入(续跑)⇒ 不动。
37
- if (!resume) agent._turnStartLen = null
38
- // 账本:续跑沿用同一本(链内各段一笔账);新回合重开一本(中止 ∥ 异常后也不沿用旧账)。
39
- // 自动 / 上行 / 定时轮不伪造用户请求(设计 §2;三类均无用户输入)。
28
+ /** 步骤一:上一轮的异步探索蒸馏必须落地,再推本轮输入(SEND-STALL-DISTILL §2.2 N1)——
29
+ * 不 await 就会在 prepareRun 推输入之后被历史替换抹掉。 */
30
+ async function settlePendingDistill(agent) {
31
+ if (!agent._pendingDistill) return
32
+ const p = agent._pendingDistill
33
+ agent._pendingDistill = null
34
+ await p
35
+ }
36
+
37
+ /** 步骤二:轮元素起点 ∥ 轮账本——轮界与账界是同一件事(同一个位置、同一个条件)。
38
+ * 新回合起一个轮元素;续跑沿用链上那一个;续跑而外层为空 ⇒ 入口同样起一个。
39
+ * 自动 / 上行 / 定时轮不伪造用户请求(设计 §2;三类均无用户输入),账本照建。 */
40
+ function beginTurnRecord(agent, input, { resume, autoTurn }) {
41
+ if (!resume || !Array.isArray(agent.history) || agent.history.length === 0) beginTurn(agent)
40
42
  if (!resume) {
41
- agent._turnLedger = createTurnLedger({ input, autoTurn: autoTurn || upstreamTurn || timerTurn, goal: agent.goal ?? null })
43
+ agent._turnLedger = createTurnLedger({ input, autoTurn, goal: agent.goal ?? null })
42
44
  }
43
- // AGENT-LOOP-ASYNC-POOL.md §6.8 D-S3: suspension-settled async results inject before EVERY run's prepareRun
44
- // (user + auto-turn); spliced = consumed. collectSettledAsync owns a different
45
- // container, so no double-inject across the two consumption points.
45
+ }
46
+
47
+ /** 步骤三:已结算异步结果的投递(AGENT-LOOP-ASYNC-POOL.md §9「两种投递时点」 D-S3——每次 run 的 prepareRun 之前;
48
+ * 用户轮与自动轮同判)。 */
49
+ async function deliverSettledAsync(agent, { autoTurn, upstreamTurn, timerTurn }) {
46
50
  // ASYNC-RESULT-CONTAINER.md D2 (2026-09-08):pending 单容器 `_pendingAsyncResults`
47
51
  // +role——四族(subagent/advisor/escalate/consult)统一停靠;注入器按 role 分发
48
52
  // (consult → injectConsultResult;其余 → injectAsyncResult——族分支同 CONSULTATION.md §6.2 D-R17a/b)
49
53
  // ——单容器一处清,不再逐族三段。
50
54
  // §6.31 消化账务(批 digest-accounting · 2026-10-05 · 台账 #930):**投递 ≠ 销账**——
51
55
  // 会话态(`_daSession`)投递留容器(覆盖才离容器 / 未见账计一个未签收轮、达 `DA_MISS_LIMIT` 升级——
52
- // 投递恒一次,无重投回路:批 digest-retry-amplify · 台账 #1850);fallback
56
+ // 投递恒一次,无重投回路:批 digest-retry-amplify · 台账 #1850;`deferred` 与沉默同判——只计未签收轮、
57
+ // 不换第二次投递,内容靠满上限的升级终局披露回会话(§9.1));fallback
53
58
  // (headless / 直连 runAgent)缺省条逐字沿用取尽语义(先离容后注入 ∥ `releaseSettledEntry` 面;
54
59
  // 零账目动作——不销账 / 不重投),已投递未销账条同判据跳过且留容器(§6.31 出口缝② · 父侧裁定 2026-10-05)。
55
60
  const pendingAsync = agent._pendingAsyncResults
@@ -62,8 +67,9 @@ export async function beginRun(agent, input, callbacks, {
62
67
  const { injectConsultResult } = await import("../agent-tools/consult.mjs")
63
68
  const digestRound = isDigestRound({ autoTurn, upstreamTurn, timerTurn })
64
69
  // 投递门控单门(§6.31.4 · 投递恒一次):首投**仅系统轮**(`autoTurn`——用户回合零注入),
65
- // 已投递条恒跳过;注入后**留容器**(不 splice)。
66
- // 注入抛错 ⇒ 未投条目(`_daDelivered` 未置)留容器待下轮——收窄既有「splice 先取尽」的丢失窗。
70
+ // 已投递的条恒跳过;注入后**留容器**(不 splice)。
71
+ // 注入抛错 ⇒ 未投条目(`_daDelivered` 未置)留容器待下轮——
72
+ // 收窄既有「splice 先取尽」的丢失窗。
67
73
  for (const e of [...pendingAsync]) {
68
74
  if (!shouldDeliverEntry(e, autoTurn)) continue
69
75
  if (e.role === "consult") await injectConsultResult(agent, e)
@@ -72,18 +78,18 @@ export async function beginRun(agent, input, callbacks, {
72
78
  releaseChildHold(e) // 仅释放 `childAgent`——`report` 保留至销账 / 升级(升级终局披露需原文)
73
79
  }
74
80
  // 账目要求行(§6.31.3):仅会话态消化轮且未销账清单非空时注入(先投递后拼清单——
75
- // 含本回合首投);两档同发(手动 / AUTO);transient(机器线独有)。
81
+ // 含本回合首投);两档同发(手动 / AUTO);B 段一次性事件(进待发队,不落机读线)。
76
82
  if (digestRound) {
77
83
  const ids = pendingAsync.filter((e) => e._daDelivered === true).map((e) => e.id)
78
84
  if (ids.length > 0) {
79
- agent.history.push({ role: "user", content: digestAccountRequirement(ids), transient: true })
85
+ pushInject(agent, { role: "user", content: digestAccountRequirement(ids) })
80
86
  }
81
87
  }
82
88
  }
83
89
  } else if (pendingAsync?.length) {
84
90
  const { injectAsyncResult } = await import("../agent-tools/subagent.mjs")
85
91
  const { injectConsultResult } = await import("../agent-tools/consult.mjs")
86
- // TUI-OOM-ROOTCAUSE(AGENT-LOOP.md §6.15 消费点②——run 起始 pending 注入):
92
+ // TUI-OOM-ROOTCAUSE(AGENT-LOOP.md §9 消费点②——run 起始 pending 注入):
87
93
  // 注入完成后释放条目对子代理对象的持有(childAgent/report 置空——幂等 helper)。
88
94
  // §6.31 出口缝②(#44 披露①扩散面 · 父侧裁定 2026-10-05):fallback 支同判据延伸——
89
95
  // 注入前按投递账分区:已投递未销账条(`_daDelivered === true`——内容已在历史)不注入且
@@ -102,28 +108,44 @@ export async function beginRun(agent, input, callbacks, {
102
108
  releaseSettledEntry(e)
103
109
  }
104
110
  }
105
- agent._inAutoTurn = autoTurn // spawn gate for manual-tier digests (AGENT-LOOP-ASYNC-POOL.md §6.8 D-S6/N3;上行唤醒轮同持 autoTurn——§6.27.12.4 ①)
106
- // 投影段起点的搜索下界(台账 #2395):本次 `prepareRun` 将要推入的区间起点——
107
- // 只在本次推入的消息里找输入(不会误取上一轮的同文请求)。
108
- const prePrepareLen = agent.history.length
109
- const { maxTurns, threshold, toolSchemas, toolByName, systemPrompt } = await prepareRun(
110
- // G1/G2(施工②):prompt 装配收口 prepareRun 内部(assemblePrompt——prompt-overlays.mjs
111
- // 槽位常量,与子代理角色常量同源——单一权威锚 D1);本调用不再携带 prompt 常量。
112
- agent, input, callbacks,
113
- { depth, signal, overrideTurns, resume: resume || autoTurn, extraTools, injections, toolDecorate },
114
- )
111
+ }
115
112
 
116
- // Exploration-distillation boundary (CONTEXT-COMPACTION §5): prepareRun already
117
- // pushed input + injections — appended from here counts as "this run's" work.
118
- agent._runStartHistoryLen = agent.history.length
119
- // 跨轮机读投影的段起点(台账 #2395):本轮输入消息的下标——`prepareRun` 已把输入与其后的
120
- // 回合注入推进历史,投影的「本轮原始段」就从那条输入开始(输入之前的运行注入留在机读线)。
121
- if (!Number.isInteger(agent._turnStartLen)) {
122
- agent._turnStartLen = resume ? agent.history.length : findTurnStartIndex(agent.history, input, prePrepareLen)
113
+ /** 步骤四:域文本与端 overlay 写 A 段两格——run 入口**无条件写一次**,两条 `setInject` 都执行,
114
+ * 差别只在取值(上一轮自动回合的两格不得原文跟到这一轮)。
115
+ * AGENT-LOOP-ASYNC-POOL.md §8.6: 域文本 = 本轮的输入(为什么开始、接着做什么)——一族一版、两档共取,
116
+ * 档位只决定审批如何呈递,不进文本选择。
117
+ * AGENT-LOOP-UPSTREAM.md §6.27.12.4 ②: an up-stream wake turn answers a RUNNING subagent waiting for
118
+ * the reply — it states its own trigger source, not the digest turn's.
119
+ * AGENT-LOOP-ASYNC-POOL.md §8.6 ∥ §7「timer」: timer wake turn (third auto-turn variant) —— 到期 timer
120
+ * 自动开轮,仅作域文本选择(`upstreamTurn` 优先不回归:ask 轮是「有人在等回复」,比 timer 轮更紧)。 */
121
+ async function pushTurnDomainText(agent, { autoTurn, upstreamTurn, timerTurn, turnDomainText, turnOverlayText, resume }) {
122
+ // 取基座的门 = 非续跑 ∧ 自动轮族(AGENT-LOOP-ASYNC-POOL.md §8.6「起跑期的门」)。
123
+ // 它决定的是「取不取基座」,不是「写不写这一格」:`setInject` 在下面无条件执行,门关写 null。
124
+ let text = null
125
+ if ((autoTurn || upstreamTurn) && !resume) {
126
+ // AGENT-LOOP-ASYNC-POOL.md §8.6「组合点」与「唯一调用点」两段:端壳经 `opts.turnDomainText` 供
127
+ // 域文本(组合点 = 端 `turn-domains.mjs` composeTurnDomain;端 overlay 另住 `run-overlay` 格);
128
+ // 缺省(null)⇒ 核基座逐字零变(选择序不变)。AUTO 档同取。
129
+ const domainBase = upstreamTurn ? UPSTREAM_TURN_DOMAIN : timerTurn ? TIMER_TURN_DOMAIN : AUTO_TURN_DIGEST_DOMAIN
130
+ // §8.6「写出来的那一份域文本不得为空」:核侧不依赖端壳自觉——空串 / 纯空白域文本取同轮型基座并留痕。
131
+ // 替换被记录,不是静默默认;现行三个生产来源都不传空串,这一支是规则自己落点上的防御面。
132
+ if (typeof turnDomainText === "string" && turnDomainText.trim() === "") {
133
+ const turnType = upstreamTurn ? "upstream" : timerTurn ? "timer" : "digest"
134
+ logEvent("ev:turn-domain-empty-text", { turnType })
135
+ text = domainBase
136
+ } else {
137
+ text = turnDomainText ?? domainBase
138
+ }
123
139
  }
140
+ setInject(agent, "turn-domain", text)
141
+ // 端 overlay 住另一格、不看上面那道门:它描述「结果拿到之后怎么呈递」,整个 run 都成立。
142
+ // 端给了非空串就写它(续跑段端逐段携带同一串,写与不写同值);端不供(CLI ∥ 桌面 ∥ 用户回合)写 null。
143
+ setInject(agent, "run-overlay", typeof turnOverlayText === "string" && turnOverlayText.length > 0 ? turnOverlayText : null)
144
+ }
124
145
 
125
- // Per-run bookkeeping reset — PRESERVED on `resume` (ContinueError continuation):
126
- // mutation/guard continuity and the convergence budget must survive a continuation.
146
+ /** 步骤五:每 run 记账复位——PRESERVED on `resume` (ContinueError continuation):
147
+ * mutation/guard continuity and the convergence budget must survive a continuation. */
148
+ function resetRunBookkeeping(agent, { resume, autoTurn, upstreamTurn, timerTurn }) {
127
149
  // §2.3 链内段数(TURN-CAP-CONTINUE.md §4):首段 1、每次续跑 +1——复位条件同 `_turnSeq`
128
150
  // (链起点复位、续跑不回退);消费面 = 检查点 ask 载荷 / 池条目留痕二元。
129
151
  agent._continueSegments = resume ? (agent._continueSegments ?? 1) + 1 : 1
@@ -131,60 +153,73 @@ export async function beginRun(agent, input, callbacks, {
131
153
  // 续跑新段——与 `_continueSegments` 同点);段内累加,采集点在回合环(与 `_turnSeq` 同源面)。
132
154
  agent._zeroWriteTurns = 0
133
155
  agent._segmentTurns = 0 // #934 B 面读数分母(§6.32.4):同点复位——同段同源(分子 ≤ 分母)
134
- if (!resume) {
135
- // 第 19 批(TURN-ACROSS-SEGMENTS——设计 TURN-CAP-CONTINUE.md §4):链内累计编号
136
- // 只在链起点复位——续跑(resume:true)不重置、不回退(编号帧公式见 helpers.mjs
137
- // turnFrame)。与下方 mutation/guard 复位同条件同点(全档唯一复位点)。
138
- agent._turnSeq = 0
139
- // AGENT-LOOP-ASYNC-POOL.md §6.8 D-S6: an auto-turn's guard marks are inherited by the next USER run (not
140
- // reset) so auto-turn changes never escape the guard silently.
141
- const g = agent._inheritedGuard
142
- if (g) {
143
- restoreGuard(agent, g)
144
- agent._inheritedGuard = null
145
- } else {
146
- agent._mutatedThisRun = false
147
- agent._verifiedThisRun = false
148
- agent._verifyPassed = undefined
149
- agent._calledAdvisorThisRun = false
150
- agent._touchedFiles = []
151
- // #934(零落笔看门狗——AGENT-LOOP-UPSTREAM.md §6.32.6 载体重置):streak / 闩与
152
- // `_touchedFiles = []`(本块)同点复位——链起点;续跑(resume)不执行 ⇒ 「连续」
153
- // 跨段存活(锚与分支差别注见 §6.32.2 ①)。
154
- agent._zeroWriteStreak = 0
155
- agent._zeroWriteAlerted = false
156
- agent._verifyRetries = 0
157
- agent._advisorRound = 0
158
- // ADVISOR-CONVERGENCE.md §6.4 B 复位点 1(穷举两处之一):新用户回合起点 · 无继承时——回到完整预算。
159
- // 「非自动回合」合取:digest / timer / upstream 三类自动回合同样不带 `resume`(同样进本块),
160
- // 但它们落在周期中间而非起点——不清零,否则「用户回合 → 自动回合 → 用户回合」每段重新拿满 5 条,
161
- // 上限被自动回合吃掉。自动回合留下的值经 `INHERITED_GUARD_KEYS` 回填(`if (g)` 支)。
162
- if (!(autoTurn || upstreamTurn || timerTurn)) {
163
- agent._advisorReminders = 0
164
- agent._advisorHonestySent = false
165
- }
166
- agent._advisorSession = null // advisor session is per-run: discard when the task ends, next task starts fresh
167
- agent._emptyRetries = 0 // empty-response retry budget is per-run: a fresh user turn restarts from zero
168
- agent._compressFailures = 0 // compaction summary-failure counter is per-run: a fresh user turn restarts from zero
169
- // §6.6(AGENT-LOOP.md)两个载体与 `_emptyRetries` 同点复位(链起点):`wrote` 判据(`_batchWrites`)与注入帽计数
170
- // (`_designTurnNotices`)均按整流累计读——续跑不重置,否则「已落过盘」与「已告知过」的痕迹会被抹掉。
171
- agent._batchWrites = 0
172
- agent._designTurnNotices = 0
173
- // F-CC2(§6.16.2):模型主动压缩的排队槽也是回合级——上一回合末尾未被安全点消费的请求不得跨回合生效
174
- agent._pendingCompact = null
175
- }
156
+ if (resume) return
157
+ // 第 19 批(TURN-ACROSS-SEGMENTS——设计 TURN-CAP-CONTINUE.md §4):链内累计编号
158
+ // 只在链起点复位——续跑(resume:true)不重置、不回退(编号帧公式见 helpers.mjs
159
+ // turnFrame)。与下方 mutation/guard 复位同条件同点(全档唯一复位点)。
160
+ agent._turnSeq = 0
161
+ // AGENT-LOOP-ASYNC-POOL.md §8.8「清扫判据与合法差异」: an auto-turn's guard marks are inherited by the next USER run (not
162
+ // reset) so auto-turn changes never escape the guard silently.
163
+ const g = agent._inheritedGuard
164
+ if (g) {
165
+ restoreGuard(agent, g)
166
+ agent._inheritedGuard = null
167
+ return
176
168
  }
177
- // digest D-S6 manual tier(AGENT-LOOP-ASYNC-POOL.md §6.8): action-domain reminder (system-driven turn — organize only).
178
- // §6.27.12.4 ②: an up-stream wake turn answers a RUNNING subagent waiting for the reply — it
179
- // must not reuse the digest text ("no one is waiting" is the opposite of the truth).
180
- // §6.30.3 D-TW4: timer wake turn (third auto-turn variant) — 到期 timer 自动开轮,仅作域文本选择
181
- // (`upstreamTurn` 优先不回归:ask 轮是「有人在等回复」,比 timer 轮更紧)。
182
- if ((autoTurn || upstreamTurn) && !agent.autoApprove) {
183
- // §2.5-A3(P4-I):端壳经 `opts.turnDomainText` 供「核基座 + 端 overlay」组合串(组合点 =
184
- // 端 `turn-domains.mjs` composeTurnDomain);缺省(null)⇒ 核基座逐字零变(选择序不变)。
185
- const domainBase = upstreamTurn ? UPSTREAM_TURN_DOMAIN : timerTurn ? TIMER_TURN_DOMAIN : (agent.config?.agent?.engineering === true ? AUTO_TURN_DIGEST_DOMAIN_ENG : AUTO_TURN_DIGEST_DOMAIN)
186
- agent.history.push({ role: "user", content: turnDomainText ?? domainBase, transient: true })
169
+ agent._mutatedThisRun = false
170
+ agent._verifiedThisRun = false
171
+ agent._verifyPassed = undefined
172
+ agent._calledAdvisorThisRun = false
173
+ agent._touchedFiles = []
174
+ // #934(零落笔看门狗——AGENT-LOOP-UPSTREAM.md §6.32.6 载体重置):streak / 闩与
175
+ // `_touchedFiles = []`(本块)同点复位——链起点;续跑(resume)不执行 ⇒ 「连续」
176
+ // 跨段存活(锚与分支差别注见 §6.32.2 ①)。
177
+ agent._zeroWriteStreak = 0
178
+ agent._zeroWriteAlerted = false
179
+ agent._verifyRetries = 0
180
+ agent._advisorRound = 0
181
+ // ADVISOR-CONVERGENCE.md §6.4 B 复位点 1(穷举两处之一):新用户回合起点 · 无继承时——回到完整预算。
182
+ // 「非自动回合」合取:digest / timer / upstream 三类自动回合同样不带 `resume`(同样进本块),
183
+ // 但它们落在周期中间而非起点——不清零,否则「用户回合 → 自动回合 → 用户回合」每段重新拿满 5 条,
184
+ // 上限被自动回合吃掉。自动回合留下的值经 `INHERITED_GUARD_KEYS` 回填(`if (g)` 支)。
185
+ if (!(autoTurn || upstreamTurn || timerTurn)) {
186
+ agent._advisorReminders = 0
187
+ agent._advisorHonestySent = false
187
188
  }
189
+ agent._advisorSession = null // advisor session is per-run: discard when the task ends, next task starts fresh
190
+ agent._emptyRetries = 0 // empty-response retry budget is per-run: a fresh user turn restarts from zero
191
+ agent._compressFailures = 0 // compaction summary-failure counter is per-run: a fresh user turn restarts from zero
192
+ // §7.1(AGENT-LOOP.md)两个载体与 `_emptyRetries` 同点复位(链起点):`wrote` 判据(`_batchWrites`)与注入帽计数
193
+ // (`_designTurnNotices`)均按整流累计读——续跑不重置,否则「已落过盘」与「已告知过」的痕迹会被抹掉。
194
+ agent._batchWrites = 0
195
+ agent._designTurnNotices = 0
196
+ // F-CC2(§6.16.2):模型主动压缩的排队槽也是回合级——上一回合末尾未被安全点消费的请求不得跨回合生效
197
+ agent._pendingCompact = null
198
+ }
199
+
200
+ export async function beginRun(agent, input, callbacks, opts = {}) {
201
+ const {
202
+ depth = 0, signal, overrideTurns, resume = false, autoTurn = false, upstreamTurn = false, timerTurn = false,
203
+ extraTools = null, injections = null, turnDomainText = null, turnOverlayText = null, toolDecorate = undefined,
204
+ } = opts
205
+ // ── 编排体:五步依次,先后在这里一眼读得出 ─────────────────────────────
206
+ await settlePendingDistill(agent)
207
+ beginTurnRecord(agent, input, { resume, autoTurn: autoTurn || upstreamTurn || timerTurn })
208
+ await deliverSettledAsync(agent, { autoTurn, upstreamTurn, timerTurn })
209
+ agent._inAutoTurn = autoTurn // 显示与轨迹标记(AGENT-LOOP-ASYNC-POOL.md §8.7——不参与任何准入判定;上行唤醒轮同持 autoTurn——§6.27.12.4 ①)
210
+ const { maxTurns, threshold, toolSchemas, toolByName, systemPrompt } = await prepareRun(
211
+ // G1/G2(施工②):prompt 装配收口 prepareRun 内部(assemblePrompt——prompt-overlays.mjs
212
+ // 槽位常量,与子代理角色常量同源——单一权威锚 D1);本调用不再携带 prompt 常量。
213
+ agent, input, callbacks,
214
+ { depth, signal, overrideTurns, resume: resume || autoTurn, extraTools, injections, toolDecorate },
215
+ )
216
+ // Exploration-distillation boundary (CONTEXT-COMPACTION §5): prepareRun already pushed input +
217
+ // injections — appended from here counts as "this run's" work。核侧不另立起点载体(§1.1):
218
+ // 一次 run 就是外层最后一个轮元素,探索蒸馏的射程 = 那个元素的内层。
219
+ // 跨轮机读投影的段起点:本轮 = 外层最后一个轮元素(`registerCompletedTurn` 现读结构)——轮的位置由结构给出,
220
+ // 不另存一个下标载体。
221
+ resetRunBookkeeping(agent, { resume, autoTurn, upstreamTurn, timerTurn })
222
+ await pushTurnDomainText(agent, { autoTurn, upstreamTurn, timerTurn, turnDomainText, turnOverlayText, resume })
188
223
  // eng-coder authorization (_engDesignReviewed) is eng-coder-only: set by subagent-spawn.mjs
189
224
  // (spawn gate) / design-token.mjs (design review pass) BEFORE the child runAgent — the
190
225
  // depth-0 parent never reads or writes it (the parent gate reads anyLiveDesignSlot; the
@@ -193,4 +228,4 @@ export async function beginRun(agent, input, callbacks, {
193
228
  // eng-coder spawn) — persisted to the session slot at settle time (DESIGN-TOKEN-
194
229
  // SETTLEMENT D1); lifecycle: issued on a passing review, consumed by consume-design / TTL.
195
230
  return { maxTurns, threshold, toolSchemas, toolByName, systemPrompt }
196
- }
231
+ }