@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
package/CHANGELOG.md CHANGED
@@ -3,6 +3,24 @@
3
3
  All notable changes to the core package are documented here.
4
4
  Format: Keep a Changelog · 中文 · 号在发布时定(CalVer——见 `docs/RELEASE.md` §4)。
5
5
 
6
+ ## [0.11.3] — 2026-11-23
7
+
8
+ ### Added
9
+
10
+ - **批档 §2 增设「目的与代价链」块**:任务书先讲为什么做、不做会亏什么、为什么不选更便宜的做法,再讲改什么。
11
+
12
+ ### Changed
13
+
14
+ - **结尾报告改两表**:交付表退役,需求点达成状态并入「本批进展」的状态列;会话总账不变。
15
+ - **提示词归属四问 → 五问**:新增「产品特定指令」一问;本仓路径、流程档名单与发布档写法退出提示词,改住项目层与纪律面。
16
+ - **`spawn-gates` 只拦 `PROJECT-MANIFEST.json`**:谓词改名 `rejectParentOwnedPaths`,`CHANGELOG.md` 不再被当作父侧流程档。
17
+ - **`TESTING.md` §11.17 删案**:不再要求提示词点名集成索引的仓内路径。
18
+
19
+ ### Fixed
20
+
21
+ - **思考模式回声键 400**:assistant 历史轮缺 `reasoning_content` 键即被上游拒;现在写面落键(有原文写原文,无原文写空串)、请求面补空串,不再退轮。
22
+ - **空 assistant 退场判据**:原本挂在「这条消息是否被改动」上,关思考打开旧会话时旧空轮仍会上街;现在按消息本身判定。
23
+
6
24
  ## [0.11.2] — 2026-11-16
7
25
 
8
26
  ### Added
@@ -10,7 +10,7 @@
10
10
  * advisor-loop-split 批:loop 的压缩检查点归位本档(`compactContextIfNeeded`——`context_limit` 尾串生成点同迁;时间线面 ⇒ `advisor/timeline.mjs`)。
11
11
  */
12
12
 
13
- import { providerSpec, outputReserve, usableWindow } from "../config.mjs" // 第 25 批:预算派生(与 loop.mjs 的 providerSpec 同源导入);`outputReserve`/`usableWindow` = 2026-10-06 预留裁定(#975)
13
+ import { requestBudget } from "../config.mjs" // 预算派生单源(`providerSpec` ∥ `outputReserve` ∥ `usableWindow` 都经 `budgetOf` 这一处合流);`requestBudget` = 模型窗口出口,含 §2.4 的夹点
14
14
  // B4(群 B 批,ADVISOR-GUARDS.md §9——F32):CJK 加权单源(provider/rate.mjs 叶子向无环)
15
15
  import { estimateText } from "../provider/rate.mjs"
16
16
 
@@ -30,11 +30,13 @@ const COMPACT_TRIGGER_RATIO = 0.8 // 压缩触发 = 判死线 × 0.8(既
30
30
 
31
31
  /** 评审上下文预算(纯函数——两档阈值可机测;provider 为 null 时退化默认规格)。
32
32
  * 基数 = **可用窗口 = 窗口 − 完成预留**(#975/用户 2026-10-06 裁定——预留坐在窗口里 ⇒
33
- * 先压缩、不许 provider 先拒:provider 口径 = 输入 + max_tokens ≤ 窗口;预留 = `outputReserve`)。 */
33
+ * 先压缩、不许 provider 先拒:provider 口径 = 输入 + max_tokens ≤ 窗口;预留 = `outputReserve`)。
34
+ * 派生走 `requestBudget`(模型窗口出口的同一次算式、同一处判据与夹点,`CONTEXT-COMPACTION.md` §2.4):
35
+ * 并立第二套处置会让这条线在配置矛盾上抛,而主链已是响应一声、夹住、放行。
36
+ * 矛盾预算上 `limit` 已被夹到 `BUDGET_FLOOR_TOKENS`,比例项随之落到 0——评审面自己按「上下文受限」收尾
37
+ * (`compactContextIfNeeded` 的 `context_limit` 尾),不抛。 */
34
38
  export function advisorContextBudget(provider) {
35
- const spec = providerSpec(provider)
36
- const usable = usableWindow(spec.context, outputReserve(provider, spec))
37
- const limit = Math.floor(usable * CONTEXT_LIMIT_RATIO)
39
+ const limit = Math.floor(requestBudget(provider).limit * CONTEXT_LIMIT_RATIO)
38
40
  return { limit, compactAt: Math.floor(limit * COMPACT_TRIGGER_RATIO) }
39
41
  }
40
42
 
@@ -3,6 +3,8 @@
3
3
  */
4
4
  import { readFileSync } from "node:fs"
5
5
  import { join } from "node:path"
6
+ // 拍平投影与位置换算:机读线按轮嵌套,响应表扫描在拍平视图上做,起点由位置换算一次。
7
+ import { flattenHistory, flatIndexOf } from "../context-push.mjs"
6
8
 
7
9
  export const ADVISOR_MD_PATH = ".thincoder/advisor.md"
8
10
  const AGENT_RESPONSE_HEADER = "| # | Action | Detail |"
@@ -17,21 +19,31 @@ const DEFAULT_CRITERIA = `Review the code changes, focusing on:
17
19
  /**
18
20
  * Extract the agent's response table (| # | Action | Detail |) — the fix-claims
19
21
  * reference for convergence rounds.
20
- * Semantics: with sinceIdx, scan FORWARD from it — the review instance passes
21
- * its delivery watermark (`agent._advisorResponseAnchor`), so the table taken
22
- * is the one written after THIS review's delivery. Without sinceIdx (legacy
23
- * direct callers — no watermark), fall back to scanning BACKWARD for the most
22
+ * Semantics: with a delivery watermark, scan FORWARD from it — the review instance passes
23
+ * its delivery watermark (`agent._advisorResponseAnchor`, a line position `{ turn, msg }`),
24
+ * so the table taken is the one written after THIS review's delivery. Without a watermark
25
+ * (legacy direct callers — no watermark), fall back to scanning BACKWARD for the most
24
26
  * recent table. The agent response is a focus aid only — format drift falls
25
27
  * back to the no-response text and never drives control flow (decision
26
28
  * 2026-08-08).
27
- * @param {Array} history — message history
28
- * @param {number} [sinceIdx] — delivery watermark: start scanning forward from this index
29
+ * 机读线按轮嵌套:本函数收嵌套线,内部拍平一次(`flattenHistory`);第二参收位置 `{ turn, msg }`
30
+ * (调用点传 `agent._advisorResponseAnchor`)。键那位轮元素已不在线上(位置越过线尾——被摘要切走)
31
+ * ⇒ 起点 0:线上留下的每条都在投递之后。
32
+ * @param {Array} history — 机读线(嵌套轮)
33
+ * @param {{turn:number,msg:number}|number} [since] — 投递水位:从该位置起前向扫(旧数字形照收)
29
34
  * @returns {string|null} the response table content, or null
30
35
  */
31
- export function extractAgentResponseTable(history, sinceIdx) {
32
- const entries = Array.isArray(history) ? history : []
33
- if (sinceIdx !== undefined) {
34
- for (let i = sinceIdx; i < entries.length; i++) {
36
+ export function extractAgentResponseTable(history, since) {
37
+ const turns = Array.isArray(history) ? history : []
38
+ const entries = flattenHistory(turns)
39
+ let start
40
+ if (since && typeof since === "object") {
41
+ start = since.turn >= turns.length ? 0 : flatIndexOf(turns, since)
42
+ } else if (typeof since === "number") {
43
+ start = since
44
+ }
45
+ if (start !== undefined) {
46
+ for (let i = Math.max(0, start); i < entries.length; i++) {
35
47
  const m = entries[i]
36
48
  if (m.role !== "assistant" || typeof m.content !== "string") continue
37
49
  if (m.content.includes(AGENT_RESPONSE_HEADER)) return m.content
@@ -58,7 +70,8 @@ export function loadAdvisorMd(cwd) {
58
70
  }
59
71
  }
60
72
 
61
- /** Extract recent user↔assistant exchanges (up to maxTurns) for intent context. */
73
+ /** Extract recent user↔assistant exchanges (up to maxTurns) for intent context.
74
+ * 第二参调用面不变;`history` 收拍平视图(`flattenHistory(agent.history)`——调用点传)。 */
62
75
  export function extractConversationBackground(history, maxTurns = 3) {
63
76
  const entries = Array.isArray(history) ? history : []
64
77
  const lines = []
package/advisor/loop.mjs CHANGED
@@ -9,7 +9,7 @@
9
9
  * 并按 0.75 一次性预算提示 + 结构化超时尾收尾;守卫与限额函数在 compaction.mjs。
10
10
  */
11
11
  import { chat } from "../provider/core.mjs"
12
- import { providerSpec, assistantToolCallMessage } from "../config.mjs"
12
+ import { providerSpec, assistantEchoMessage, isThinkingRequest } from "../config.mjs"
13
13
  import { toOpenAISchema } from "../tools/index.mjs"
14
14
  import { truncateAdvisorResult } from "./truncate.mjs"
15
15
  import { batchTool } from "../agent-tools/batch.mjs"
@@ -31,6 +31,10 @@ import {
31
31
  ADVISOR_THINKING_PLACEHOLDER,
32
32
  } from "./compaction.mjs"
33
33
  import { createTimelineRecorder } from "./timeline.mjs"
34
+ // 判轨谓词 = `messages.mjs` 的 `reviewHoldsBatchWrite`(挂载判据与 Approval Signal 措辞两面共用):同一
35
+ // 事实各写一份就是两个版本、改一处漏一处的形状。工具面的执法半句另有——`agent-tools/batch-segment-vocab.mjs`
36
+ // 的 `reviewWritableSegment`(判可写段号、不含绑定),改轨判据时两处都要看。
37
+ import { reviewHoldsBatchWrite } from "./messages.mjs"
34
38
 
35
39
  const { readTool, globTool, grepTool, lsTool } = await import("../tools/index.mjs")
36
40
  const { lspTool } = await import("../tools/lsp.mjs")
@@ -65,12 +69,12 @@ function advisorCodeSearchTool(agent) {
65
69
  */
66
70
  function advisorToolsFor(agent, reviewType, batchDoc = null) {
67
71
  const tools = [readTool, globTool, grepTool, lsTool, lspTool, advisorCodeSearchTool(agent), docCheckTool, docGraphReadTool]
68
- // BATCH-RECORD.md §4.3:挂载判据 = 绑定 ∧ ¬(工程模式 ∧ 设计轨)。工程设计轨的 §3 对一切工具通道只读、
69
- // 轮次块由结算写,工具给了它也只会收到一条拒——不发(fail-closed)。代码轨与普通模式照旧追加:那两条路
70
- // 没有设计结算可代写,而收口门读的是 §3 的段级状态行(工具面批走代码轨,评审员要写 §3 就靠这一条)。
71
- // 未绑定 → 不挂载(fail-closed)。
72
- const engineering = !!agent?.config?.agent?.engineering
73
- if (batchDoc && !(engineering && reviewType !== "code")) tools.push(batchTool(batchDoc, { review: true, reviewType }))
72
+ // BATCH-RECORD.md §4.3:挂载判据 = 绑定 ∧ ¬(工程模式 ∧ 设计轨)——具名谓词在 `messages.mjs`
73
+ // (`reviewHoldsBatchWrite`,同一事实也决定运行期 Approval Signal 说哪一支)。工程设计轨的 §3 对一切
74
+ // 工具通道只读、轮次块由结算写,工具给了它也只会收到一条拒——不发(fail-closed)。代码轨与普通模式照旧
75
+ // 追加:那两条路没有设计结算可代写,而收口门读的是 §3 的段级状态行(工具面批走代码轨,评审员要写 §3
76
+ // 就靠这一条)。未绑定 → 不挂载(fail-closed)。
77
+ if (reviewHoldsBatchWrite(agent, reviewType, batchDoc)) tools.push(batchTool(batchDoc, { review: true, reviewType }))
74
78
  // 工具描述取完整档(设计 TOOLS §1):评审是独立基底,不随会话 mode 变化(requirements §9.1)。
75
79
  return { schemas: tools.map((tool) => toOpenAISchema(tool, "normal")), byName: new Map(tools.map((t) => [t.name, t])) }
76
80
  }
@@ -231,7 +235,8 @@ async function runAdvisorToolLoop(provider, messages, onOutput, signal, agent, c
231
235
  // tool-call assistant history lacks it — the observed "reasoning stops
232
236
  // after the first tool call, returns only at the final answer" symptom.
233
237
  // Mirrors the main agent's push (agent.mjs).
234
- messages.push(assistantToolCallMessage(response, providerSpec(provider)))
238
+ const echoSpec = providerSpec(provider)
239
+ messages.push(assistantEchoMessage(response, echoSpec, isThinkingRequest(provider, echoSpec), provider ?? null))
235
240
 
236
241
  // B1: the SAME LLM reply's multiple read-only
237
242
  // tool calls run in PARALLEL (Promise.all) — results are backfilled in
@@ -10,6 +10,8 @@ import { findReviewRepos, collectRepoSnapshots, collectChangedFiles } from "./re
10
10
  import { buildConvergenceBody, buildConvergenceInstructions, buildPriorReviewBlock } from "./convergence.mjs"
11
11
  import { loadAdvisorMd, extractConversationBackground, extractAgentResponseTable } from "./history.mjs"
12
12
  import { injectProjectGuide, injectDocumentMap, injectProjectStandards, NO_GIT_NOTICE } from "./project-context.mjs"
13
+ // 拍平投影:背景段收拍平视图(响应表由 `extractAgentResponseTable` 自己拍平)。
14
+ import { flattenHistory } from "../context-push.mjs"
13
15
 
14
16
  // Structural split (not an authority migration): the moved helpers stay reachable here.
15
17
  export { findGuideRoot, injectProjectGuide } from "./project-context.mjs"
@@ -38,6 +40,27 @@ export function buildObjectDeclarationBlock(object = null) {
38
40
  ].join("\n")
39
41
  }
40
42
 
43
+ /**
44
+ * 判轨谓词:挂载判据与 Approval Signal 措辞两面共用的那一半。
45
+ * 绑定是前置条件,与「模式 × 评审轨」写在同一句合取里——判据见 `docs/core/design/BATCH-RECORD.md` §4.3:
46
+ * 工程模式 ∧ 设计轨的轮次块由结算写,该轨的评审席没有 `batch` 工具;代码轨与普通模式照旧由绑定评审席位写。
47
+ * 假侧含「未绑定」:工具面对无 `batchDoc` 的设计评审直接拒发(`agent-tools/advisor.mjs` 的账链门),
48
+ * 故假侧在工具面可达的读者恒为工程设计轨;直接 API 调用方绕过工具面时,锁在假侧的那句话所说的结算与
49
+ * 批档都不存在——那一条路不走本谓词的两支措辞。
50
+ * 工具面的执法半句另有:`agent-tools/batch-segment-vocab.mjs` 的 `reviewWritableSegment`(判可写段号,
51
+ * 不含绑定)——改轨判据时两处都要看,它不是本谓词的射程。
52
+ * 三参都不给默认值:缺一即判不出,一个默认值等于替调用方选一条轨,而错的那条不报错。
53
+ * 消费者 = `advisor/loop.mjs` 的挂载判据(拿不拿得到)与 `advisor/run.mjs` 经本档两处出口的措辞(怎么用)。
54
+ * @param {Object} agent — 模式位载体(`agent.config.agent.engineering`)
55
+ * @param {string} reviewType — 评审轨(`"design"` ∥ `"code"`)
56
+ * @param {string|null} batchDoc — 本评审逐笔绑定的批次档(null/undefined = 未绑定)
57
+ * @returns {boolean} true = 该实例持有 `§3` 写通道
58
+ */
59
+ export function reviewHoldsBatchWrite(agent, reviewType, batchDoc) {
60
+ const engineering = !!agent?.config?.agent?.engineering
61
+ return !!batchDoc && !(engineering && reviewType !== "code")
62
+ }
63
+
41
64
  /**
42
65
  * Approval-signal block for design reviews (round 1 and round 2+ — AGENT-LOOP-ASYNC-POOL.md §6.10 D-24b:
43
66
  * an async fix-round continuation must be able to re-approve, so the token is
@@ -45,20 +68,52 @@ export function buildObjectDeclarationBlock(object = null) {
45
68
  * §29.1 F2a (2026-09-07): BOTH values are injected — the token AND the designId
46
69
  * (anchor sentence verbatim — Copy BOTH values). designId null (legacy direct
47
70
  * callers without a resolved instance) degrades to the token-only form.
71
+ *
72
+ * `writesSection3`(`reviewHoldsBatchWrite` 的取值)决定 §3 那一句指向谁:持有 `batch` 工具的轨
73
+ * 照它 `append`,落档失败要报;无写通道那一支的块由结算按报告里的 VERDICT 行写,句内只叫它把
74
+ * VERDICT 行写进报告(工具面可达的读者 = 工程设计轨,见 `reviewHoldsBatchWrite` 的假侧说明)。
75
+ * 两支持并存、各管一个读者——这一面随每一次设计评审发出,判不了读者,只能把两支写进句子本身
76
+ * (`docs/core/design/BATCH-RECORD.md` §4.5 第七面)。缺省即抛:默认值会替调用方选一条轨,
77
+ * 错的那条不报错,只把一个评审席不该看到的写口送到它手里。
78
+ * @param {string} designToken — 本次签发的设计凭证
79
+ * @param {string|null} designId — 设计槽 id(null → 只回显 token 的降级形)
80
+ * @param {boolean} writesSection3 — 该评审实例是否持有 `§3` 写通道(`reviewHoldsBatchWrite(...)` 的取值)
81
+ * @returns {string} the Approval Signal block
48
82
  */
49
- export function buildDesignApprovalBlock(designToken, designId) {
83
+ export function buildDesignApprovalBlock(designToken, designId, writesSection3) {
84
+ if (typeof writesSection3 !== "boolean") {
85
+ throw new TypeError("buildDesignApprovalBlock: writesSection3 must be a boolean from reviewHoldsBatchWrite(agent, reviewType, batchDoc) — the track decides whether this instance holds a `batch` tool, so it is never defaulted")
86
+ }
50
87
  const echo = designId
51
88
  ? `If — and ONLY if — no unresolved 🔴 (Critical) issue remains, end your reply with this exact token: [DESIGN-TOKEN:${designToken}] and this exact designId: ${designId}. Copy BOTH values verbatim — every character, including the colon and the digits after the uuid inside the token brackets; a shortened echo is flagged as truncated.`
52
89
  : `If — and ONLY if — no unresolved 🔴 (Critical) issue remains, end your reply with this exact token: [DESIGN-TOKEN:${designToken}]. Copy it verbatim — every character, including the colon and the digits after the uuid; a shortened echo is flagged as truncated.`
90
+ const section3Line = writesSection3
91
+ ? "Put that same verdict line on its own line inside the text you append to the batch record's §3 (`batch append`): the §3 write itself is checked the same way, and a §3 append that states no verdict — or states both — is refused before anything lands."
92
+ : "Put that same verdict line on a line of its own in your report: the settlement reads it and writes the round block into the batch record's §3 once the report lands, and the verdict line inside that block is the one you state here. A report that states no verdict still lands its block — the verdict line is then the constant explanation line 本轮无裁定行(评审未给出 VERDICT 行); a report that states both lands it just the same."
53
93
  return [
54
94
  "## Approval Signal",
55
95
  echo,
56
96
  "The verdict line is checked mechanically: without a `VERDICT: pass` line, or with a `VERDICT: changes-required` line, no token is issued even when the token is echoed.",
57
- "Put that same verdict line on its own line inside the text you append to the batch record's §3 (`batch append`): the §3 write itself is checked the same way, and a §3 append that states no verdict — or states both — is refused before anything lands.",
97
+ section3Line,
58
98
  "🟡 (Advisory) and 🔵 (Note) findings do NOT block approval — list them if present, but still include the token. If any 🔴 (Critical) issue remains unresolved, do NOT include the token. A reasoned non-fix accepted by the reviewer does not block (🔴 only — 🟡/🔵 never block approval); anything else stays unresolved.",
59
99
  ].join("\n")
60
100
  }
61
101
 
102
+ /**
103
+ * `batchBrief` 的形状判据(两个构建面共用一句):签名不给默认值,非字符串即抛并点名它。
104
+ * 一个默认值等于替调用方决定「没有简报」,而空串只能是调用方算出来的结果——未绑定的评审传空串,
105
+ * 块就不出现(`docs/core/design/ADVISOR-GUARDS.md` §2.5「参数面」)。
106
+ * @param {string} batchBrief — 调用方算好的一段(`buildBatchBrief(...)` 的返回值 ∥ 空串)
107
+ * @param {string} caller — 抛错点名用(两个构建函数各报自己)
108
+ * @returns {string} 原值
109
+ */
110
+ function requireBatchBrief(batchBrief, caller) {
111
+ if (typeof batchBrief !== "string") {
112
+ throw new TypeError(`${caller}: batchBrief must be a string — the caller computes it with buildBatchBrief(boundBatchDoc, cwd) and passes "" when no batch record is bound (an unbound review carries no ## Batch record block). It is never defaulted here: a default would pick that block for the caller.`)
113
+ }
114
+ return batchBrief
115
+ }
116
+
62
117
  /**
63
118
  * Build the user message for an advisor review session.
64
119
  * @param {Object} agent — the parent agent
@@ -68,6 +123,8 @@ export function buildDesignApprovalBlock(designToken, designId) {
68
123
  * @param {string[]|null} [documents] — design review only: explicit list of doc paths to review (requirements + design + referenced docs).
69
124
  * When set, the review input is built from this list ONLY — no git-diff change-set collection.
70
125
  * When absent, the legacy git-diff-based scope is kept (backward compatible).
126
+ * @param {string} batchBrief — the bound batch record's briefing block (`ADVISOR-GUARDS.md` §2.5), built by
127
+ * `buildBatchBrief`; "" when no record is bound (the block then does not appear). Required — no default.
71
128
  * @param {string[]|null} [paths] — code review only: explicit list of file/dir paths to review (deduped; shown under Review Scope)
72
129
  * @param {Object|null} [object] — review-object declaration (AGENT-LOOP-ASYNC-POOL.md §6.18 D-OA1/D-OA3):
73
130
  * { type, target, status, reason, exclude } — mechanically injected at the
@@ -75,20 +132,24 @@ export function buildDesignApprovalBlock(designToken, designId) {
75
132
  * @param {string|null} [designId] — F2a: injected next to the token in the
76
133
  * Approval Signal (both values — the reviewer copies both verbatim); null →
77
134
  * token-only degradation (legacy direct callers).
135
+ * @param {boolean} writesSection3 — 本评审实例是否持有 `§3` 写通道(`reviewHoldsBatchWrite` 的取值,由
136
+ * `run.mjs` 算一次传进来)。**不给默认值**:绑定值在本档手里没有,就地判只能写成常量。
78
137
  * @returns {string} the user message
79
138
  */
80
- export function buildAdvisorUserMessage(agent, prior, reviewType, designToken = null, documents = null, paths = null, object = null, designId = null) {
81
- const body = buildAdvisorUserMessageInner(agent, prior, reviewType, designToken, documents, paths, object, designId)
139
+ export function buildAdvisorUserMessage(agent, prior, reviewType, designToken = null, documents = null, batchBrief, paths = null, object = null, designId = null, writesSection3) {
140
+ requireBatchBrief(batchBrief, "buildAdvisorUserMessage")
141
+ const body = buildAdvisorUserMessageInner(agent, prior, reviewType, designToken, documents, batchBrief, paths, object, designId, writesSection3)
82
142
  // B 构建自愈(F12/`ADVISOR-GUARDS.md §2` #1):design + token 且输出不含逐字信号 ⇒ 尾包补齐 Approval Signal。
83
143
  // 覆盖所有出口(含 code 形态分支降级态与 legacy 收敛分支)——既有分支语义零改:已在分支内
84
144
  // 注入过的路径因 `[DESIGN-TOKEN:{token}` 逐字在场而不重复追加(幂等)。
85
145
  if (reviewType !== "design" || !designToken) return body
86
146
  if (body.includes(`[DESIGN-TOKEN:${designToken}`)) return body
87
- return `${body}\n\n${buildDesignApprovalBlock(designToken, designId)}`
147
+ return `${body}\n\n${buildDesignApprovalBlock(designToken, designId, writesSection3)}`
88
148
  }
89
149
 
90
150
  /** 内层构建(无自愈尾包)。设计评审每轮走这里:首轮无 prior 参考块,轮 2+ 带 prior 参考块,其余消息形态相同。 */
91
- function buildAdvisorUserMessageInner(agent, prior, reviewType, designToken = null, documents = null, paths = null, object = null, designId = null) {
151
+ function buildAdvisorUserMessageInner(agent, prior, reviewType, designToken = null, documents = null, batchBrief, paths = null, object = null, designId = null, writesSection3) {
152
+ requireBatchBrief(batchBrief, "buildAdvisorUserMessageInner")
92
153
  // prior = the full prior review output (string) when a convergence round is
93
154
  // being built (decision 2026-08-08 — verbatim injection, model understands it).
94
155
  // Deterministic: only _advisorRound > 0 with stored output counts.
@@ -101,6 +162,9 @@ function buildAdvisorUserMessageInner(agent, prior, reviewType, designToken = nu
101
162
  // buildAdvisorFollowUp (T-OA2 — every round stays anchored).
102
163
  const declaration = buildObjectDeclarationBlock(object)
103
164
  if (declaration) parts.push(declaration)
165
+ // 批档简报(`ADVISOR-GUARDS.md` §2.5):位次 = 对象声明之后、`## Design Review` ∥ `## Review Scope` 之前
166
+ // ——读者先拿到任务书与裁定的所在(§1),再读到被判的对象正文。空串 = 未绑定,块不出现。
167
+ if (batchBrief) parts.push(batchBrief)
104
168
  const docList = Array.isArray(documents) ? documents.filter((d) => typeof d === "string" && d.trim()) : []
105
169
  const pathList = Array.isArray(paths) ? [...new Set(paths.filter((p) => typeof p === "string" && p.trim()))] : []
106
170
  // 评审范围项 = 指南 ∥ 标准层 ∥ 文档地图共用的**同一份操作数**(序 = 喂给 `findGuideRoot` 的那个序)。
@@ -198,7 +262,7 @@ function buildAdvisorUserMessageInner(agent, prior, reviewType, designToken = nu
198
262
  }
199
263
  if (designToken) {
200
264
  parts.push("")
201
- parts.push(buildDesignApprovalBlock(designToken, designId))
265
+ parts.push(buildDesignApprovalBlock(designToken, designId, writesSection3))
202
266
  }
203
267
  return parts.join("\n")
204
268
  }
@@ -246,7 +310,7 @@ function buildAdvisorUserMessageInner(agent, prior, reviewType, designToken = nu
246
310
  }
247
311
 
248
312
  // Conversation background — recent user↔assistant exchanges for intent context
249
- const background = extractConversationBackground(agent.history)
313
+ const background = extractConversationBackground(flattenHistory(agent.history))
250
314
  if (background) {
251
315
  parts.push("## Conversation Background (recent turns)")
252
316
  parts.push(background)
package/advisor/run.mjs CHANGED
@@ -6,11 +6,12 @@
6
6
  */
7
7
  import { findProvider } from "../config.mjs"
8
8
  import { prepareAdvisorMessages } from "../advisor.mjs"
9
- import { buildObjectDeclarationBlock, buildDesignApprovalBlock } from "./messages.mjs"
9
+ import { buildObjectDeclarationBlock, buildDesignApprovalBlock, reviewHoldsBatchWrite } from "./messages.mjs"
10
10
  import { appendCitationReport } from "./citations.mjs"
11
11
  import { runAdvisorToolLoop } from "./loop.mjs"
12
12
  import { estimateTokens } from "./compaction.mjs"
13
13
  import { batchDocForReview } from "../agent-tools/batch.mjs"
14
+ import { buildBatchBrief } from "../agent-tools/batch-read.mjs"
14
15
 
15
16
  // 拆分后 import 面(既有导出名逐一保面——re-export;谓词为本批新增)。
16
17
  export { ADVISOR_THINKING_PLACEHOLDER, MAX_RESULT_CHARS, renderTimeline as _renderTimeline } from "./compaction.mjs"
@@ -73,19 +74,22 @@ export function looksLikeReviewOutput(text) {
73
74
 
74
75
  /**
75
76
  * 压缩定锚简报(F13/`ADVISOR-GUARDS.md §2` #3)——**由评审参数构建**(非模型输出):对象声明 / 文档清单 /
76
- * Approval Signal 三锚;重内容(项目指南 / 方法论 / 文档地图)不入 pin(压缩的意义所在)。
77
+ * 批档简报(§2.5——与用户消息同一段文本)/ Approval Signal 三锚;重内容(项目指南 / 方法论 / 文档地图)不入 pin
78
+ * (压缩的意义所在)。
77
79
  * 形态逐字见 `ADVISOR-GUARDS.md §2` #3(首行为机械化重挂说明)。
80
+ * `batchBrief` 不给默认值:它与用户消息那一段必须逐字同值(同一次发起、一处算),默认值就是第二处。
78
81
  */
79
- function buildPinnedBrief(reviewType, documents, object, designToken, designId) {
82
+ function buildPinnedBrief(reviewType, documents, batchBrief, object, designToken, designId, writesSection3) {
80
83
  const docList = Array.isArray(documents) ? documents.filter((d) => typeof d === "string" && d.trim()) : []
81
84
  const parts = ["[review brief — re-attached after context compaction; the original review request is no longer in the context]"]
82
85
  const declaration = buildObjectDeclarationBlock(object)
83
86
  if (declaration) parts.push(declaration.trimEnd())
87
+ if (batchBrief) parts.push(batchBrief.trimEnd())
84
88
  if (docList.length > 0) {
85
89
  parts.push("## Documents to Review")
86
90
  parts.push(docList.map((d) => `- ${d} — Read this file in full`).join("\n"))
87
91
  }
88
- if (reviewType === "design" && designToken) parts.push(buildDesignApprovalBlock(designToken, designId))
92
+ if (reviewType === "design" && designToken) parts.push(buildDesignApprovalBlock(designToken, designId, writesSection3))
89
93
  return parts.join("\n\n")
90
94
  }
91
95
 
@@ -114,7 +118,20 @@ export async function runAdvisorReview(agent, reviewType, callbacks, designToken
114
118
  // Advisor always works in the agent's cwd — scope is defined by paths/documents.
115
119
  const advisorCwd = agent.cwd
116
120
 
117
- const messages = prepareAdvisorMessages(agent, reviewType, designToken, documents, paths, null, object, designId)
121
+ // BATCH-RECORD.md §4.3 批次档写通道的绑定——**与评审轨无关**:携了可读 `batchDoc` 即绑定
122
+ // (判据单源 = `docs/core/design/BATCH-LEDGER-REVIEW-UNIFY.md` §2.15)。同步路径 = 调用方(advisor
123
+ // 工具)传入的 callbacks.batchDoc(本笔发起时点的绑定值);异步路径 = 池条目 `entry.start()` 传入的
124
+ // 同一逐笔快照(条目字段 `batchDoc`,不读活的实例字段)。
125
+ // 工具面批走代码轨,评审员靠这一绑定才拿得到写 §3 的手;按轨截断 ⇒ 那一轨永远没有写通道,
126
+ // `§3` 只能编或永远挂着(用户 2026-11-01 11:43 否掉的那件事)。
127
+ // 绑定先于消息构建算一次:用户消息与定锚简报喂的是同一个判轨值,不是各算一次。
128
+ const boundBatchDoc = batchDocForReview(agent, documents, callbacks)
129
+ const writesSection3 = reviewHoldsBatchWrite(agent, reviewType, boundBatchDoc)
130
+ // 批档简报(`ADVISOR-GUARDS.md` §2.5):**一次算、两处消费**(与 `boundBatchDoc` ∥ `writesSection3` 同款)——
131
+ // 用户消息与压缩定锚简报喂同一个值;未绑定 ⇒ 空串(块不出现,这是调用方算出来的结果,不是签名替他选的默认)。
132
+ const batchBrief = buildBatchBrief(boundBatchDoc, agent.cwd)
133
+
134
+ const messages = prepareAdvisorMessages(agent, reviewType, designToken, documents, batchBrief, paths, null, object, designId, writesSection3)
118
135
 
119
136
  // B 启动断言(fail-closed——`ADVISOR-GUARDS.md §2` #2):设计评审请求内**必须**携带与本次签发 token 精确
120
137
  // 对应的 Approval Signal——构建面补不上就拒绝启动(不发"请回显一个不存在的 token"的请求)。
@@ -132,15 +149,9 @@ export async function runAdvisorReview(agent, reviewType, callbacks, designToken
132
149
  }
133
150
  }
134
151
 
135
- // BATCH-RECORD.md §4.3 批次档写通道的绑定——**与评审轨无关**:携了可读 `batchDoc` 即绑定
136
- // (判据单源 = `docs/core/design/BATCH-LEDGER-REVIEW-UNIFY.md` §2.15)。同步路径 = 调用方(advisor
137
- // 工具)传入的 callbacks.batchDoc(本笔发起时点的绑定值);异步路径 = 池条目 `entry.start()` 传入的
138
- // 同一逐笔快照(条目字段 `batchDoc`,不读活的实例字段)。
139
- // 工具面批走代码轨,评审员靠这一绑定才拿得到写 §3 的手;按轨截断 ⇒ 那一轨永远没有写通道,
140
- // `§3` 只能编或永远挂着(用户 2026-11-01 11:43 否掉的那件事)。
141
- const boundBatchDoc = batchDocForReview(agent, documents, callbacks)
152
+ // BATCH-RECORD.md §4.3 批次档写通道(上方的 `boundBatchDoc` ∥ `writesSection3`——本条与用户消息同值)。
142
153
  // F13/`ADVISOR-GUARDS.md §2` #3:压缩定锚简报(评审参数构建——压缩触发时由 compaction 重挂)。
143
- const pinned = buildPinnedBrief(reviewType, documents, object, designToken, designId)
154
+ const pinned = buildPinnedBrief(reviewType, documents, batchBrief, object, designToken, designId, writesSection3)
144
155
 
145
156
  try {
146
157
  // #934(零落笔看门狗——§6.32.6 触发接线②):评审族闸位钩子转发(callbacks 不供 `onStall` ⇒
package/advisor.mjs CHANGED
@@ -183,14 +183,18 @@ export { escapeLiteralEscapes }
183
183
  * @param {string} [reviewType] — "design" or "code" (已由工具层类型门定轨——此处无缺省;F30)
184
184
  * @param {string|null} [designToken] — design-review approval token (design only)
185
185
  * @param {string[]|null} [documents] — design review only: explicit list of doc paths to review (passed through to buildAdvisorUserMessage)
186
+ * @param {string} batchBrief — 本次绑定批档的简报块(`buildBatchBrief` 的返回值;未绑定 ⇒ 空串);
187
+ * 紧跟在 `documents` 之后透传给 `buildAdvisorUserMessage`(`ADVISOR-GUARDS.md` §2.5)——**不给默认值**。
186
188
  * @param {string[]|null} [paths] — code review only: explicit list of file/dir paths to review
187
189
  * @param {Object|null} [object] — review-object declaration (AGENT-LOOP-ASYNC-POOL.md §6.18 D-OA1): passed through
188
190
  * to the user-message builders; mechanically injected at the start of every review
189
191
  * round (round 1 design/code + round 2+ follow-up). Absent → legacy behavior.
190
192
  * @param {string|null} [designId] — F2a: injected next to the design token in
191
193
  * the Approval Signal (round 1 + round 2+ — both values, verbatim anchor).
194
+ * @param {boolean} writesSection3 — 本评审实例是否持有 `§3` 写通道(`reviewHoldsBatchWrite` 的取值,由
195
+ * `advisor/run.mjs` 算一次传进来);透传给同档两处 `buildAdvisorUserMessage`。**不给默认值**。
192
196
  */
193
- export function prepareAdvisorMessages(agent, reviewType, designToken = null, documents = null, paths = null, priorParam = null, object = null, designId = null) {
197
+ export function prepareAdvisorMessages(agent, reviewType, designToken = null, documents = null, batchBrief, paths = null, priorParam = null, object = null, designId = null, writesSection3) {
194
198
  // Deterministic convergence state (decision 2026-08-08): round 2+ requires
195
199
  // _advisorRound > 0 AND a stored prior review output. No history parsing.
196
200
  // priorParam (direct callers) wins over the stored output — same derivation
@@ -206,7 +210,7 @@ export function prepareAdvisorMessages(agent, reviewType, designToken = null, do
206
210
  if (reviewType === "design") {
207
211
  return [
208
212
  { role: "system", content: buildAdvisorSystemPrompt(agent, prior, reviewType) },
209
- { role: "user", content: escapeLiteralEscapes(buildAdvisorUserMessage(agent, prior, reviewType, designToken, documents, paths, object, designId)) },
213
+ { role: "user", content: escapeLiteralEscapes(buildAdvisorUserMessage(agent, prior, reviewType, designToken, documents, batchBrief, paths, object, designId, writesSection3)) },
210
214
  ]
211
215
  }
212
216
 
@@ -232,7 +236,7 @@ export function prepareAdvisorMessages(agent, reviewType, designToken = null, do
232
236
  agent._advisorRound = 0
233
237
  }
234
238
  // Mutations exist → KEEP the round (attempts keep advancing through retries).
235
- const user = buildAdvisorUserMessage(agent, prior, reviewType, designToken, documents, paths, object, designId)
239
+ const user = buildAdvisorUserMessage(agent, prior, reviewType, designToken, documents, batchBrief, paths, object, designId, writesSection3)
236
240
  return [
237
241
  { role: "system", content: buildAdvisorSystemPrompt(agent, prior, reviewType) },
238
242
  {
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import { chat } from "../provider/index.mjs"
8
8
  import { healImageRejection, clearImageFailStreak } from "./image-heal.mjs"
9
+ import { assembleRequestMessages, pushInject, pushRecord } from "../context.mjs"
9
10
 
10
11
  /** 流式输出门(§2.5 #78 并入——VSC 三态门,纯函数可直驱测试):depth 0 恒通;
11
12
  * consult 子代理豁免(其输出进会诊面板);其余经 `streamOutput` 显式选择进入。 */
@@ -16,14 +17,16 @@ export function streamOutputAllowed(depth, role, streamOutput = false) {
16
17
  export async function callModelTurn(agent, {
17
18
  systemPrompt, toolSchemas, streamOutput, callbacks, signal, streamRuleFired, autoTurn, depth, turn,
18
19
  }) {
19
- const messages = [{ role: "system", content: systemPrompt }, ...agent.history]
20
- let response
21
-
22
20
  // Auto-think: classify difficulty and set reasoning effort on turn 0; silent on failure.
21
+ // 分类与应用必须先于首次正式请求装配:assembleRequestMessages 要读分类后的 reasoningEffort。
23
22
  if (agent.config?.agent?.autoThink && turn === 0) {
24
23
  const { classifyAndApply } = await import("../auto-think.mjs")
25
24
  await classifyAndApply(agent, turn).catch(() => {})
26
25
  }
26
+ const toolsDeclared = Array.isArray(toolSchemas) && toolSchemas.length > 0
27
+ // 首送与图片自愈重发共用同一请求构造形,工具声明判据也来自同一份 toolSchemas。
28
+ const messages = assembleRequestMessages(agent, { systemPrompt, toolsDeclared })
29
+ let response
27
30
 
28
31
  // 发送选项(首送 ∥ §6.26 自愈重发共用——两送除 messages 外逐字同参)
29
32
  const sendOpts = {
@@ -60,19 +63,21 @@ export async function callModelTurn(agent, {
60
63
  // Inject into history; the outer loop recreates the controller and resumes.
61
64
  if (e.name === "AbortError" && signal?.reason?.interrupt) {
62
65
  const msg = `[User interrupt: ${signal.reason.message}]`
63
- // Dedup: if already handled during tool execution (interrupt branch below),
64
- // don't push a duplicate — the outer loop still recreates the controller.
65
- if (agent.history.at(-1)?.content !== msg) {
66
- agent.history.push({ role: "user", content: msg })
66
+ // 去重:工具执行中断那一支已投过同一条时不再入队。判据读待发队尾条——
67
+ // 注入不在 `agent.history` 上(嵌套线上 `.content` 恒 `undefined`,读它去重恒不命中)。
68
+ const queue = Array.isArray(agent._pendingInject) ? agent._pendingInject : []
69
+ if (queue.at(-1)?.content !== msg) {
70
+ pushInject(agent, { role: "user", content: msg })
71
+ pushRecord(agent, { role: "user", content: msg })
67
72
  }
68
73
  }
69
74
  // §6.26 图片拒绝自愈(判定 ∥ 剥除 ∥ 注记 ∥ 记账 = agent/image-heal.mjs 单源):
70
75
  // 未愈 ⇒ 原错照抛(非图像错误零误伤);已愈 ⇒ 载荷已修(历史无图 + 机读注记)单次重发。
71
76
  const { healed } = healImageRejection(agent, e)
72
77
  if (!healed) throw e
73
- // 重建消息(§6.26 步 4——剥除后的 agent.history 含注记):再发一次(非重试——同请求
78
+ // 重建消息(§6.26 步 4——剥除后的机读线含自愈注记):再发一次(非重试——同请求
74
79
  // 重发对图像拒绝恒无效);再败 ⇒ 本行抛新错(不循环、不二次剥除,历史保持已剥除态)。
75
- response = await chat(agent.provider, { messages: [{ role: "system", content: systemPrompt }, ...agent.history], ...sendOpts })
80
+ response = await chat(agent.provider, { messages: assembleRequestMessages(agent, { systemPrompt, toolsDeclared }), ...sendOpts })
76
81
  }
77
82
  // §6.26 清零调用点(记账单源 = image-heal.mjs):任一次成功调用清零(含自愈重发成功)
78
83
  clearImageFailStreak(agent)