@thincoder/core 0.11.3 → 0.11.5

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 (183) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/advisor/compaction.mjs +40 -17
  3. package/advisor/loop.mjs +14 -6
  4. package/advisor/notice.mjs +1 -1
  5. package/advisor/timeline.mjs +4 -4
  6. package/agent/completion.mjs +19 -0
  7. package/agent/dispatch-gates.mjs +2 -0
  8. package/agent/dispatch.mjs +2 -2
  9. package/agent/family-tools.mjs +13 -9
  10. package/agent/helpers.mjs +10 -6
  11. package/agent/planning-step.mjs +453 -0
  12. package/agent/post-turn.mjs +70 -2
  13. package/agent/run-stages.mjs +22 -50
  14. package/agent/run-start.mjs +17 -0
  15. package/agent/setup-reminders.mjs +71 -8
  16. package/agent/setup.mjs +8 -39
  17. package/agent/spawn-child.mjs +6 -2
  18. package/agent/task-lifecycle.mjs +146 -0
  19. package/agent/turn-loop.mjs +73 -11
  20. package/agent-tools/batch-closeout.mjs +21 -34
  21. package/agent-tools/batch-gate.mjs +7 -5
  22. package/agent-tools/batch-ledger-bind.mjs +21 -1
  23. package/agent-tools/batch-lifecycle.mjs +7 -7
  24. package/agent-tools/batch-record-write.mjs +237 -280
  25. package/agent-tools/batch-supersede.mjs +3 -3
  26. package/agent-tools/batch.mjs +42 -9
  27. package/agent-tools/context.mjs +0 -13
  28. package/agent-tools/escalate-async.mjs +7 -1
  29. package/agent-tools/parent-channel.mjs +7 -6
  30. package/agent-tools/plan.mjs +103 -67
  31. package/agent-tools/review-facts.mjs +3 -3
  32. package/agent-tools/settings.mjs +2 -0
  33. package/agent-tools/spawn-gates.mjs +37 -11
  34. package/agent-tools/ssh-session.mjs +68 -25
  35. package/agent-tools/ssh-transfer.mjs +7 -2
  36. package/agent-tools/ssh-transport.mjs +2 -2
  37. package/agent-tools/ssh-vault.mjs +2 -2
  38. package/agent-tools/step.mjs +462 -0
  39. package/agent-tools/subagent-actions.mjs +6 -1
  40. package/agent-tools/subagent-run.mjs +7 -0
  41. package/agent-tools/subagent-spawn.mjs +1 -1
  42. package/agent-tools/subagent.mjs +17 -11
  43. package/agent-tools/task.mjs +178 -26
  44. package/agent-tools.mjs +1 -0
  45. package/agent.mjs +2 -0
  46. package/config-defaults.mjs +17 -1
  47. package/config-migrate.mjs +8 -5
  48. package/config.mjs +7 -0
  49. package/context.mjs +5 -4
  50. package/declaration.mjs +4 -4
  51. package/generate-title.mjs +0 -6
  52. package/i18n.mjs +4 -0
  53. package/ledger-cmd.mjs +11 -1
  54. package/ledger-tools.mjs +15 -4
  55. package/manifest-schema.mjs +1 -0
  56. package/model-context.mjs +34 -11
  57. package/model-specs.mjs +5 -2
  58. package/package.json +1 -1
  59. package/prompt-files.mjs +48 -11
  60. package/prompt-overlays.mjs +79 -8
  61. package/prompts/advisor-design.md +253 -206
  62. package/prompts/advisor-round1.md +151 -145
  63. package/prompts/advisor-round2.md +136 -130
  64. package/prompts/advisor-round3.md +140 -134
  65. package/prompts/common.md +244 -96
  66. package/prompts/consult-base.md +29 -30
  67. package/prompts/discipline-engineering.md +73 -519
  68. package/prompts/discipline-normal.md +28 -136
  69. package/prompts/knowledge/batch-before-write.md +8 -0
  70. package/prompts/knowledge/batch-cycle-register.md +15 -0
  71. package/prompts/knowledge/batch-progress-ledger.md +29 -0
  72. package/prompts/knowledge/business-gates.md +24 -24
  73. package/prompts/knowledge/decision-quality.md +8 -19
  74. package/prompts/knowledge/doc-discipline-d-rules.md +63 -0
  75. package/prompts/knowledge/doc-lookup.md +25 -24
  76. package/prompts/knowledge/document-writing.md +11 -32
  77. package/prompts/knowledge/documentation-evaluation.md +42 -42
  78. package/prompts/knowledge/eng-dispatch-ops.md +34 -0
  79. package/prompts/knowledge/eng-ledger-ops.md +26 -0
  80. package/prompts/knowledge/evidence-discipline.md +10 -32
  81. package/prompts/knowledge/normal-batch-discipline.md +13 -0
  82. package/prompts/knowledge/normal-coding-workflow.md +97 -99
  83. package/prompts/knowledge/normal-delivery-collaboration.md +107 -112
  84. package/prompts/knowledge/normal-work-management.md +44 -44
  85. package/prompts/knowledge/product-security.md +7 -26
  86. package/prompts/knowledge/project-records.md +69 -64
  87. package/prompts/knowledge/tool-advisor.md +17 -17
  88. package/prompts/knowledge/tool-apply-patch.md +14 -14
  89. package/prompts/knowledge/tool-bash.md +32 -31
  90. package/prompts/knowledge/tool-batch-eng-coder.md +19 -13
  91. package/prompts/knowledge/tool-batch-eng-designer.md +21 -14
  92. package/prompts/knowledge/tool-batch-review.md +18 -12
  93. package/prompts/knowledge/tool-batch.md +93 -85
  94. package/prompts/knowledge/tool-browser.md +59 -59
  95. package/prompts/knowledge/tool-code-search.md +2 -2
  96. package/prompts/knowledge/tool-consult-start.md +6 -6
  97. package/prompts/knowledge/tool-consult-stop.md +3 -3
  98. package/prompts/knowledge/tool-context.md +4 -4
  99. package/prompts/knowledge/tool-delete.md +16 -16
  100. package/prompts/knowledge/tool-doc-check.md +39 -39
  101. package/prompts/knowledge/tool-doc-graph-read.md +11 -11
  102. package/prompts/knowledge/tool-doc-graph.md +48 -48
  103. package/prompts/knowledge/tool-doc-search.md +3 -3
  104. package/prompts/knowledge/tool-edit.md +30 -30
  105. package/prompts/knowledge/tool-eng.md +1 -1
  106. package/prompts/knowledge/tool-execute.md +16 -16
  107. package/prompts/knowledge/tool-fetch.md +15 -15
  108. package/prompts/knowledge/tool-file-ops.md +15 -15
  109. package/prompts/knowledge/tool-get-current-time.md +3 -3
  110. package/prompts/knowledge/tool-git-read.md +15 -15
  111. package/prompts/knowledge/tool-git.md +26 -26
  112. package/prompts/knowledge/tool-glob.md +14 -14
  113. package/prompts/knowledge/tool-goal.md +5 -5
  114. package/prompts/knowledge/tool-grep.md +19 -18
  115. package/prompts/knowledge/tool-hashline-edit.md +13 -13
  116. package/prompts/knowledge/tool-insert-after.md +14 -14
  117. package/prompts/knowledge/tool-instance-list.md +3 -3
  118. package/prompts/knowledge/tool-instance-send.md +5 -5
  119. package/prompts/knowledge/tool-knowledge.md +12 -12
  120. package/prompts/knowledge/tool-ledger-read.md +20 -20
  121. package/prompts/knowledge/tool-ledger.md +44 -44
  122. package/prompts/knowledge/tool-lint.md +10 -10
  123. package/prompts/knowledge/tool-ls.md +11 -11
  124. package/prompts/knowledge/tool-lsp.md +8 -8
  125. package/prompts/knowledge/tool-main-history.md +1 -1
  126. package/prompts/knowledge/tool-manifest-read.md +7 -7
  127. package/prompts/knowledge/tool-manifest.md +43 -32
  128. package/prompts/knowledge/tool-memory-read.md +12 -12
  129. package/prompts/knowledge/tool-memory.md +14 -14
  130. package/prompts/knowledge/tool-notify-parent.md +10 -10
  131. package/prompts/knowledge/tool-operations.md +88 -88
  132. package/prompts/knowledge/tool-peek.md +10 -0
  133. package/prompts/knowledge/tool-peer-instances.md +1 -1
  134. package/prompts/knowledge/tool-plan.md +6 -3
  135. package/prompts/knowledge/tool-process-read.md +8 -8
  136. package/prompts/knowledge/tool-process.md +11 -11
  137. package/prompts/knowledge/tool-question.md +11 -13
  138. package/prompts/knowledge/tool-read-history-batch.md +13 -13
  139. package/prompts/knowledge/tool-read-history.md +19 -19
  140. package/prompts/knowledge/tool-read-image.md +8 -8
  141. package/prompts/knowledge/tool-read.md +17 -17
  142. package/prompts/knowledge/tool-recent-changes.md +4 -4
  143. package/prompts/knowledge/tool-repo-outline.md +2 -2
  144. package/prompts/knowledge/tool-settings-read.md +5 -7
  145. package/prompts/knowledge/tool-settings.md +10 -10
  146. package/prompts/knowledge/tool-skill.md +4 -4
  147. package/prompts/knowledge/tool-ssh.md +66 -66
  148. package/prompts/knowledge/tool-step.md +26 -0
  149. package/prompts/knowledge/tool-subagent.md +52 -50
  150. package/prompts/knowledge/tool-task.md +14 -11
  151. package/prompts/knowledge/tool-team-ledger-read.md +7 -7
  152. package/prompts/knowledge/tool-team-ledger.md +13 -13
  153. package/prompts/knowledge/tool-timer.md +14 -14
  154. package/prompts/knowledge/tool-tree.md +11 -11
  155. package/prompts/knowledge/tool-verify.md +11 -11
  156. package/prompts/knowledge/tool-wait-for.md +20 -20
  157. package/prompts/knowledge/tool-websearch.md +16 -14
  158. package/prompts/knowledge/tool-write.md +10 -10
  159. package/prompts/knowledge/upstream-protocol.md +37 -38
  160. package/prompts/persona-coder.md +22 -22
  161. package/prompts/persona-eng-coder.md +87 -81
  162. package/prompts/persona-eng-designer.md +173 -153
  163. package/prompts/persona-engineering.md +53 -554
  164. package/prompts/persona-explore.md +18 -15
  165. package/prompts/persona-normal.md +62 -63
  166. package/prompts/persona-plan.md +36 -32
  167. package/prompts/persona-tester.md +39 -39
  168. package/prompts/planning-next-moves.md +9 -0
  169. package/prompts/subagent-base.md +4 -16
  170. package/provider/errors.mjs +0 -24
  171. package/provider/list-models.mjs +20 -2
  172. package/session-lifecycle.mjs +4 -3
  173. package/tool-args.mjs +25 -0
  174. package/tool-docs/peek.md +3 -0
  175. package/tool-docs/plan.md +1 -1
  176. package/tool-docs/question.md +1 -1
  177. package/tool-docs/step.md +3 -0
  178. package/tools/edit-diff.mjs +4 -4
  179. package/tools/index.mjs +3 -2
  180. package/tools/peek.mjs +447 -0
  181. package/tools/question.mjs +87 -9
  182. package/tools/ssh.mjs +1 -1
  183. package/window-policy.mjs +107 -80
@@ -8,21 +8,11 @@
8
8
  * agent.mjs 迁入,agent.mjs 内无其他引用)。verbatim 迁移 + 签名化,语义零变。
9
9
  */
10
10
 
11
- import { compressIfNeeded } from "../context.mjs"
12
- // 写面单点(CONTEXT-COMPACTION §1.1):B 段一次性事件一律 `pushInject`(不落机读线);
13
- // 计划提醒 cadence 的跨调用水位换位置 `{ turn, msg }`。
14
- import { pushInject, flattenHistory, flatIndexOf } from "../context.mjs"
15
-
16
- /** 线尾位置(外层最后一个轮元素 + 它内层的长度)——跨调用水位的写法;空线 ⇒ 线头。 */
17
- function endPositionOf(history) {
18
- const last = Array.isArray(history) ? history.at(-1) : null
19
- if (!last) return { turn: 0, msg: 0 }
20
- return { turn: history.length - 1, msg: Array.isArray(last.messages) ? last.messages.length : 0 }
21
- }
11
+ import { compressIfNeeded, pushInject } from "../context.mjs"
22
12
  // §6.17/D-CC32 溢出守卫(兜底,非主修):预算面单源 `policyBudget`(有效窗口)∥ 再估面 contextUsage(与压缩判定同一函数)
23
13
  import { policyBudget } from "../config.mjs"
24
14
  import { contextUsage } from "../token-window.mjs"
25
- import { contextOverflowError, overheadOverflowError, budgetContradictionError } from "../provider/errors.mjs"
15
+ import { contextOverflowError, overheadOverflowError } from "../provider/errors.mjs"
26
16
  import { ensureAutoReminder, injectEngineeringReminder, ContinueError, snapshotGuard } from "./helpers.mjs"
27
17
  import { pushTimeReminder } from "./setup-reminders.mjs"
28
18
  import { cleanupConsultSessions } from "../agent-tools/consult.mjs"
@@ -128,8 +118,9 @@ export async function runCompactionCheck(agent, ctx) {
128
118
  // 其余全同(同 splitHistory / 同尾部预算 / 同摘要链 / 同回注 / 同基线失效)。
129
119
  const pending = agent._pendingCompact
130
120
  agent._pendingCompact = null
121
+ let compacted = false
131
122
  try {
132
- let compacted = await compressIfNeeded(
123
+ compacted = await compressIfNeeded(
133
124
  agent, threshold, callbacks,
134
125
  pending ? { ...compactionOverhead, force: true, focus: pending.focus } : compactionOverhead,
135
126
  signal,
@@ -137,16 +128,13 @@ export async function runCompactionCheck(agent, ctx) {
137
128
  if (!compacted && pending) {
138
129
  // 强制面无可压:固定开销单独越线 ⇒ 回执报与守卫同一个原因(`CONTEXT-COMPACTION.md` §5),
139
130
  // 否则 = 短历史无中段。两种 no-op 的处置不同,回执不能同一句。
140
- const { compactNoopNote, compactOverheadNote, compactContradictionNote } = await import("../agent-tools/context.mjs")
131
+ const { compactNoopNote, compactOverheadNote } = await import("../agent-tools/context.mjs")
141
132
  const forced = contextUsage(agent, compactionOverhead)
142
133
  const budget = policyBudget(agent.provider)
143
- // 矛盾格排在非对话面越线之前(`CONTEXT-COMPACTION.md` §2.4):夹住态上 `forced.fixedFloor > budget.limit`
144
- // 恒成立,先跑那一支会把原因报成 `overhead_exceeds_limit`(讲「压不掉非对话面」),真实原因被挡在后面。
145
- const note = budget.contradiction
146
- ? compactContradictionNote(budget.contradiction)
147
- : forced.fixedFloor > budget.limit
148
- ? compactOverheadNote(forced, budget.limit, budget.window)
149
- : compactNoopNote()
134
+ // 非对话面越线时报「压不掉非对话面」(`CONTEXT-COMPACTION.md` §5)。
135
+ const note = forced.fixedFloor > budget.limit
136
+ ? compactOverheadNote(forced, budget.limit, budget.window)
137
+ : compactNoopNote()
150
138
  pushInject(agent, { role: "user", content: note })
151
139
  compacted = await compressIfNeeded(agent, threshold, callbacks, compactionOverhead, signal)
152
140
  }
@@ -158,11 +146,13 @@ export async function runCompactionCheck(agent, ctx) {
158
146
  const { compactFailureNote } = await import("../agent-tools/context.mjs")
159
147
  pushInject(agent, { role: "user", content: compactFailureNote(errText(compressError), agent._compressFailures) })
160
148
  }
149
+ compacted = false
161
150
  }
162
151
 
163
152
  // 溢出守卫(CONTEXT-COMPACTION.md §6.17 / D-CC32——兜底,非主修;本缝 = catch 闭合后、返回前)。
164
153
  // 判据 / 强压 / 再判 / 抛三实数 全住 `enforceContextFit`——与 §6.17.1 链三的自适应面**同一个原子**(零复制)。
165
154
  await enforceContextFit(agent, ctx)
155
+ return Boolean(compacted)
166
156
  }
167
157
 
168
158
  /**
@@ -177,13 +167,10 @@ export async function runCompactionCheck(agent, ctx) {
177
167
  export async function enforceContextFit(agent, ctx, { forceCompact = false } = {}) {
178
168
  const { threshold, callbacks, compactionOverhead, signal } = ctx
179
169
  // 判据 = prompt 估算 > `budget.limit`(**无档次门**——`limit = window − reserve`,恒为正数、恒可判;
180
- // 派生不成立时它已被夹到 `BUDGET_FLOOR_TOKENS`,见 §2.4)。**判据不用 maxTokens**:未发时为 undefined ⇒ NaN ⇒ 守卫静默失效(§6.17)。
170
+ // 派生链没有无解格(`reserve` 已封顶)。**判据不用 maxTokens**:未发时为 undefined ⇒ NaN ⇒ 守卫静默失效(§6.17)。
181
171
  // 预算取**有效窗口**(`CONTEXT-COMPACTION.md` §2.2「stats、守卫和压缩使用同一预算对象」):有效窗口恒等于
182
172
  // 模型窗口,守卫与压缩线同一把尺,否则只降阈值不动 limit = 「早压缩但仍放行到模型窗口」,与上界相反。
183
173
  const budget = policyBudget(agent.provider)
184
- // 矛盾格(`CONTEXT-COMPACTION.md` §2.4):先于非对话面越线判——夹住态上 `fixedFloor > limit` 恒成立,
185
- // 先跑那一支会把原因报成 `overhead_exceeds_limit`。矛盾预算压多少次都装不下,不进强压(零摘要请求)。
186
- if (budget.contradiction) throw budgetContradictionError(agent.provider, budget)
187
174
  let usage = contextUsage(agent, compactionOverhead)
188
175
  // 非对话面单独越线(#2398 · `CONTEXT-COMPACTION.md` §5):history 归零后 `total` 仍等于那六项 ⇒ 压缩无解,
189
176
  // 在强压**之前**抛 typed error(`forceCompact` 同样拦:强制压缩跳得过阈值,跳不过这条);报文取六项分段(§5.2)。
@@ -224,8 +211,6 @@ export async function enforceContextFit(agent, ctx, { forceCompact = false } = {
224
211
  export async function preflightWindowFit(agent, ctx) {
225
212
  const { threshold, callbacks, compactionOverhead, signal } = ctx
226
213
  const budget = policyBudget(agent.provider)
227
- // 矛盾格(`CONTEXT-COMPACTION.md` §2.4):同一个 typed error,比 `fixedFloor > limit` 那一支先判。
228
- if (budget.contradiction) throw budgetContradictionError(agent.provider, budget)
229
214
  let usage = contextUsage(agent, compactionOverhead)
230
215
  if (!(usage.total > budget.limit)) return false
231
216
  if (usage.fixedFloor > budget.limit) throw overheadOverflowError(agent.provider, budget, usage)
@@ -254,25 +239,11 @@ export async function preflightWindowFit(agent, ctx) {
254
239
  */
255
240
  export async function injectTurnReminders(agent, ctx) {
256
241
  const { depth } = ctx
257
- // Plan-mode reminder cadence: re-inject constraint reminders while plan mode is active
258
- // (sparse every 2 turns, full every 5 / on new user message) so the restriction never fades.
259
- if (agent.planMode) {
260
- // 注入不在线上 ⇒ 「最后一条是用户输入」与改前同义(拍平视图的最后一条)。
261
- const flat = flattenHistory(agent.history)
262
- const lastMsg = flat.at(-1)
263
- const realUserMsg = lastMsg?.role === "user"
264
- && typeof lastMsg.content === "string"
265
- && !lastMsg.content.startsWith("[System reminder:")
266
- && !lastMsg.content.startsWith("[User interrupt:")
267
- // 水位 = 位置 `{ turn, msg }`(上一次提醒落线处);与当前线尾比拍平序。
268
- const since = agent._planReminderAtLen ? flatIndexOf(agent.history, agent._planReminderAtLen) : 0
269
- const newUserSince = realUserMsg && flat.length > since
270
- const { planReminderForTurn } = await import("../agent-tools/plan.mjs")
271
- const reminder = planReminderForTurn(agent, newUserSince)
272
- if (reminder) {
273
- agent._planReminderAtLen = endPositionOf(agent.history)
274
- pushInject(agent, { role: "user", content: reminder })
275
- }
242
+ // 稳态 `plan` 槽同步(单源 = `agent-tools/plan.mjs` `syncPlanSlot`):开启时写入 `PLAN_MODE_POLICY`
243
+ // (幂等,不再每 2/5 轮往消息流刷 reminder 击穿前缀缓存),关闭时清槽;分叉 `step` 维持冻结。
244
+ if (!agent._forkedStep) {
245
+ const { syncPlanSlot } = await import("../agent-tools/plan.mjs")
246
+ syncPlanSlot(agent)
276
247
  }
277
248
 
278
249
  // Engineering-mode status injection on every new user message (design-before-code
@@ -281,10 +252,11 @@ export async function injectTurnReminders(agent, ctx) {
281
252
  // 在 run 起点与压缩后刷新,不再每回合重写。
282
253
  if (depth === 0) injectEngineeringReminder(agent)
283
254
 
284
- // `time` 格每回合覆写(`CONTEXT-COMPACTION.md` §1.1 格位表「每回合一次」):本格对每个
285
- // 深度都写——「当前时间」对子代理同样是这一回合的事实(`prepareRun` 的 run 起点那一笔已给了首份)。
286
- // 写入方单点 = `setup-reminders.mjs` 的 `pushTimeReminder`。
287
- pushTimeReminder(agent)
255
+ // `time` 格节拍(`CONTEXT-COMPACTION.md` §1.1 格位表):`prepareRun` 在每次新用户 run 起点
256
+ // 已写入当前时间;同一次 run 内第 2..N 轮工具调用时,末尾 user 消息位于本轮全部工具轨迹之前,
257
+ // 原地改写 `time` 会每轮击穿 KV Prefix Cache,故此处仅在格为空时补齐(`ifMissing: true`)。
258
+ // `step` 分叉(`_forkedStep === true`,`STEP-FORK.md` §2.4)维持完全冻结。
259
+ if (!agent._forkedStep) pushTimeReminder(agent, { ifMissing: true })
288
260
  }
289
261
 
290
262
  /**
@@ -13,6 +13,7 @@ import { prepareRun } from "./setup.mjs"
13
13
  // 轮元素起点(CONTEXT-COMPACTION §1.1):外层每个元素是一轮,起点由本档在 run 入口起——
14
14
  // 与建账同一个位置、同一个条件,但写仍然走 `context-push.mjs` 的单点。
15
15
  import { beginTurn, pushInject, setInject } from "../context.mjs"
16
+ import { clearCompletedTasks } from "./task-lifecycle.mjs"
16
17
  // 轮记录的装配面(CONTEXT-COMPACTION.md §1.1:账本 ∥ 轮边界起点 ∥ 完成登记):本档只用账本一个符号,
17
18
  // 跨轮清理挂在 `registerCompletedTurn`(轮完成登记那一刻,`agent.mjs`)。
18
19
  import { createTurnLedger } from "./turn-projection.mjs"
@@ -47,6 +48,8 @@ function beginTurnRecord(agent, input, { resume, autoTurn }) {
47
48
  /** 步骤三:已结算异步结果的投递(AGENT-LOOP-ASYNC-POOL.md §9「两种投递时点」 D-S3——每次 run 的 prepareRun 之前;
48
49
  * 用户轮与自动轮同判)。 */
49
50
  async function deliverSettledAsync(agent, { autoTurn, upstreamTurn, timerTurn }) {
51
+ // 本回合刚投递的异步 advisor 评审轨迹(供 planning-step 在消化轮首轮单列触发评审结论核实规划)
52
+ agent._deliveredAdvisorReviews = []
50
53
  // ASYNC-RESULT-CONTAINER.md D2 (2026-09-08):pending 单容器 `_pendingAsyncResults`
51
54
  // +role——四族(subagent/advisor/escalate/consult)统一停靠;注入器按 role 分发
52
55
  // (consult → injectConsultResult;其余 → injectAsyncResult——族分支同 CONSULTATION.md §6.2 D-R17a/b)
@@ -74,6 +77,9 @@ async function deliverSettledAsync(agent, { autoTurn, upstreamTurn, timerTurn })
74
77
  if (!shouldDeliverEntry(e, autoTurn)) continue
75
78
  if (e.role === "consult") await injectConsultResult(agent, e)
76
79
  else await injectAsyncResult(agent, e)
80
+ if (e.role === "advisor" && !e.error && !e.cancelled && !(typeof e.report === "string" && /^\s*Advisor:\s*review failure/i.test(e.report))) {
81
+ agent._deliveredAdvisorReviews.push({ id: e.id, reviewType: e.reviewType ?? null })
82
+ }
77
83
  e._daDelivered = true
78
84
  releaseChildHold(e) // 仅释放 `childAgent`——`report` 保留至销账 / 升级(升级终局披露需原文)
79
85
  }
@@ -105,6 +111,9 @@ async function deliverSettledAsync(agent, { autoTurn, upstreamTurn, timerTurn })
105
111
  for (const e of taken) {
106
112
  if (e.role === "consult") await injectConsultResult(agent, e)
107
113
  else await injectAsyncResult(agent, e)
114
+ if (e.role === "advisor" && !e.error && !e.cancelled && !(typeof e.report === "string" && /^\s*Advisor:\s*review failure/i.test(e.report))) {
115
+ agent._deliveredAdvisorReviews.push({ id: e.id, reviewType: e.reviewType ?? null })
116
+ }
108
117
  releaseSettledEntry(e)
109
118
  }
110
119
  }
@@ -158,6 +167,14 @@ function resetRunBookkeeping(agent, { resume, autoTurn, upstreamTurn, timerTurn
158
167
  // 只在链起点复位——续跑(resume:true)不重置、不回退(编号帧公式见 helpers.mjs
159
168
  // turnFrame)。与下方 mutation/guard 复位同条件同点(全档唯一复位点)。
160
169
  agent._turnSeq = 0
170
+ // §7.4(AGENT-LOOP.md):task 运行期陈旧/收尾计数在链起点复位(续跑保留);
171
+ // 新用户回合起点顺手清扫已全员 `done` 的旧清单(例如会话恢复或自动回合遗留)。
172
+ agent._turnsSinceTaskUpdate = 0
173
+ agent._taskStaleNudgeSent = false
174
+ agent._taskClosePushbacks = 0
175
+ if (!(autoTurn || upstreamTurn || timerTurn)) {
176
+ clearCompletedTasks(agent)
177
+ }
161
178
  // AGENT-LOOP-ASYNC-POOL.md §8.8「清扫判据与合法差异」: an auto-turn's guard marks are inherited by the next USER run (not
162
179
  // reset) so auto-turn changes never escape the guard silently.
163
180
  const g = agent._inheritedGuard
@@ -44,21 +44,24 @@ import { backendMode, deepseekChannel } from "../tools/web-deepseek.mjs"
44
44
  import { resolveEnvRefs } from "../env-ref.mjs"
45
45
  // A 段当前状态的唯一写入口与会话头块的唯一写入口都住 `context-push.mjs`(`CONTEXT-COMPACTION.md`「注入的三段:按存活期分」∥「会话头块」):本档写 `time` ∥ `peer`
46
46
  // ∥ `editor` 三格与 `_sessionHead` 一段,写即覆盖——不再扫 `agent.history` 摘旧行 / 按内容比同文。
47
- import { setInject, setSessionHead } from "../context-push.mjs"
47
+ import { INJECT_SLOTS, setInject, setSessionHead } from "../context-push.mjs"
48
48
 
49
- /** Local time, second precision, for the per-turn transient reminder. */
49
+ const TIME_SLOT_INDEX = INJECT_SLOTS.indexOf("time")
50
+
51
+ /** Local time, minute precision, for the per-run transient reminder (avoids sub-minute cache churn). */
50
52
  function timeNowLocal() {
51
- return new Date().toLocaleString("sv-SE")
53
+ return new Date().toLocaleString("sv-SE").slice(0, 16)
52
54
  }
53
55
 
54
56
  /**
55
57
  * `time` 格的写入方(一格一个写入方;写入节拍单源 = `docs/core/design/CONTEXT-COMPACTION.md` §1.1 格位表
56
- * 「每回合一次:每请求读到的是这一请求的时间」)。两个调用点都走本函数:
57
- * `agent/setup.mjs` 的 `prepareRun`(run 起点——只调 `prepareRun` 的路径仍有时间行)∥
58
- * `agent/run-stages.mjs` 的 `injectTurnReminders`(回合头——覆盖为这一回合的时间)。
59
- * 成本:`assembleRequestMessages` 每请求按格现取,本格并进请求尾部那一块 ⇒ 每回合换值不破前缀缓存。
58
+ * 「每 run 起点一次;同 run 内多轮工具调用保持冻结以保 KV Prefix Cache,仅格空时由回合头兜底补齐」)。
59
+ * 两个调用点都走本函数:`agent/setup.mjs` 的 `prepareRun`(run 起点无条件写最新时间)∥
60
+ * `agent/run-stages.mjs` 的 `injectTurnReminders`(传 `{ ifMissing: true }`,仅在格为空时补齐,
61
+ * 避免同一 run 内第 2..N 轮工具调用反复改写末尾 user 消息而击穿整段工具轨迹前缀缓存)。
60
62
  */
61
- export function pushTimeReminder(agent) {
63
+ export function pushTimeReminder(agent, { ifMissing = false } = {}) {
64
+ if (ifMissing && agent?._inject?.[TIME_SLOT_INDEX]?.content) return
62
65
  setInject(agent, "time", `[System reminder: current time is ${timeNowLocal()} (local; timezone ${Intl.DateTimeFormat().resolvedOptions().timeZone || "local"})].`)
63
66
  }
64
67
 
@@ -205,6 +208,40 @@ export async function sessionOutlineOf(agent) {
205
208
  // 网页搜索面(`docs/core/design/CONTEXT-COMPACTION.md`「网页搜索面那一行」):判据全取这一趟的活工具表与配置,
206
209
  // 不读盘、不探网、不改任何工具的可用性。名称判据是启发式,行文因此是提示、不是门。
207
210
  const MCP_SEARCH_NAME_RE = /search|web|reader|crawl/i
211
+ const MCP_SEARCH_PREFERRED_RE = /search/i
212
+
213
+ /** 判定某工具是否属于联网检索/抓页工具(内置 `websearch`/`fetch` ∥ 命中 `MCP_SEARCH_NAME_RE` 的 MCP 工具)。 */
214
+ export function isWebSearchTool(tool) {
215
+ const name = typeof tool === "string" ? tool : tool?.name
216
+ if (typeof name !== "string" || !name) return false
217
+ if (name === "websearch" || name === "fetch") return true
218
+ const hasMcp = typeof tool === "object" && typeof tool?._mcpName === "string" && tool._mcpName.trim() !== ""
219
+ return hasMcp && MCP_SEARCH_NAME_RE.test(name)
220
+ }
221
+
222
+ /**
223
+ * 从活工具表挑选推荐优先使用的联网搜索工具名(MCP 搜索工具优先于内置 `websearch`):
224
+ * ① 首个带 `_mcpName` 且名含 `/search/i` 的工具(如 `glm-websearch_web_search_prime`);
225
+ * ② 否则若挂有内置 `websearch`,返回 `"websearch"`;
226
+ * ③ 否则首个命中 `MCP_SEARCH_NAME_RE` 的 MCP 工具;
227
+ * ④ 都没有则返回 `null`(环境无可用联网检索工具)。
228
+ */
229
+ export function preferredWebSearchTool(tools) {
230
+ const list = Array.isArray(tools) ? tools : []
231
+ let fallbackMcp = null
232
+ let hasBuiltin = false
233
+ for (const tool of list) {
234
+ const name = tool?.name
235
+ if (typeof name !== "string" || !name) continue
236
+ if (name === "websearch") { hasBuiltin = true; continue }
237
+ const hasMcp = typeof tool?._mcpName === "string" && tool._mcpName.trim() !== ""
238
+ if (!hasMcp) continue
239
+ if (MCP_SEARCH_PREFERRED_RE.test(name)) return name
240
+ if (!fallbackMcp && MCP_SEARCH_NAME_RE.test(name)) fallbackMcp = name
241
+ }
242
+ if (hasBuiltin) return "websearch"
243
+ return fallbackMcp
244
+ }
208
245
 
209
246
  /**
210
247
  * `websearch` 后端的第二档(Tavily):键的读法与 `tools/web.mjs` 的 `fetchTavily` 同一个(`resolveEnvRefs(config?.websearch?.apiKey)`,
@@ -267,6 +304,30 @@ export function searchFaceLine({ tools, config } = {}) {
267
304
  return `· Web search: MCP: ${mcp} · websearch(${websearch}) fetch(${fetch})`
268
305
  }
269
306
 
307
+ const DOC_ROOT_HEAD_KEYS = ["requirements", "design", "standards", "batches"]
308
+
309
+ /**
310
+ * 项目文档层根路径行(会话头块伴随 `· project state:` 的纯信息行,零额外 IO):
311
+ * 紧跟 `projectStateLine` 之后调用,直接读已由 `refreshManifest` 刷新的 `agent.manifest.docRoot`,
312
+ * 仅列非空声明的 `requirements` ∥ `design` ∥ `standards` ∥ `batches`,缺项省略;全部为空返回 null。
313
+ * @param {object} agent
314
+ * @returns {string|null}
315
+ */
316
+ export function docRootLine(agent) {
317
+ const dr = agent?.manifest?.docRoot
318
+ if (!dr || typeof dr !== "object") return null
319
+ const parts = []
320
+ for (const key of DOC_ROOT_HEAD_KEYS) {
321
+ const val = dr[key]
322
+ if (typeof val === "string" && val.trim()) parts.push(`${key}=${val.trim()}`)
323
+ else if (Array.isArray(val)) {
324
+ const items = val.map((v) => (typeof v === "string" ? v.trim() : "")).filter(Boolean)
325
+ if (items.length) parts.push(`${key}=${items.join(", ")}`)
326
+ }
327
+ }
328
+ return parts.length ? `· docRoot: ${parts.join(" · ")}` : null
329
+ }
330
+
270
331
  /**
271
332
  * 会话头块的写入方单点(`CONTEXT-COMPACTION.md`「会话头块」):现读八项拼成一段文本,
272
333
  * 交 `setSessionHead` 整段替换 `agent._sessionHead`(不进人读线、不进记录存储、不进会话存储)。
@@ -298,6 +359,8 @@ export function pushSessionHeadBlock(agent, { outline } = {}) {
298
359
  lines.push(searchFaceLine({ tools: agent?.tools, config: agent?.config }))
299
360
  const projectState = projectStateLine(agent)
300
361
  if (projectState) lines.push(`· project state: ${projectState.slice(MANIFEST_LINE_PREFIX.length).replace(/\.?\]$/, "")}`)
362
+ const docRoot = docRootLine(agent)
363
+ if (docRoot) lines.push(docRoot)
301
364
  if (outline) lines.push("· project dependency outline:", `${OUTLINE_INJECT_PREFIX}\n${outline}`)
302
365
  setSessionHead(agent, `${lines.join("\n")}]`)
303
366
  return true
package/agent/setup.mjs CHANGED
@@ -18,12 +18,10 @@ import { assembleFamilyTools } from "./family-tools.mjs"
18
18
  import { normalizeOrigin } from "../memory/origin.mjs"
19
19
  import { searchOrigins } from "../memory/code-search.mjs"
20
20
  import { INDEX_ORIGIN_ROW_WARN } from "../memory/schema.mjs"
21
- import { policyBudget, resolveCompactThreshold, resolveWorkMode, setConfigWorkMode } from "../config.mjs"
21
+ import { resolveCompactThreshold, resolveWorkMode, setConfigWorkMode } from "../config.mjs"
22
22
  // 权威层集合由声明派生(正文单源 = `docs/core/design/DOC-SYSTEM.md` §3.1;本档不持成员名单)。
23
23
  import { declarationForTarget, docLayers } from "../conventions.mjs"
24
24
  import { safeSliceUTF16 } from "../text-budget.mjs"
25
- // §2.4 的响一声:核日志一行(`ev = "budget:contradiction"`)——通道单源仍是 `log.mjs`,本批只新增一个事件名。
26
- import { logEvent } from "../log.mjs"
27
25
 
28
26
  const DOC_SEARCH_LIMIT = 5
29
27
  const DOC_CHUNK_PREVIEW_LEN = 300
@@ -78,34 +76,9 @@ function authorityLayersOf(origins) {
78
76
  return out
79
77
  }
80
78
 
81
- /** 预算矛盾的三个数(§2.4 的提醒与日志同源):矛盾只剩一格——`reserve ≥ window`,报文点 window ∥ reserve ∥ 差值。
82
- * 旧的比例余量形状(「窗口装得下输出、装不下注入余量」)随比例余量退场,它已不是可达状态。 */
83
- function contradictionNumbers(contradiction) {
84
- const c = contradiction ?? {}
85
- return `window ${c.window} · reserve ${c.reserve} · difference ${c.usable}`
86
- }
87
-
88
- /** 响一声(`CONTEXT-COMPACTION.md` §2.4):核日志一行(带 window ∥ reserve ∥ 差值)+ 一条 B 段提醒
89
- * (点这三个数与三条出路)。同一次 run 里同一条矛盾只响一次——`budgetOf` 一次 run 被调多次
90
- * (`resolveCompactThreshold` 一次、`policyBudget` 一次,守卫面每次发送前又一次),不判重就刷屏。
91
- * 去重键 = run 标识 + window + reserve + 差值;换一次 run 重新响一次,因为配置可能已改。
92
- * 静默仍被禁止:日志、提醒、守卫拒发三件都在,改的只是「在哪儿响」——从 UI 起来之前的装载期挪到运行时。
93
- * 调用点只有 `prepareRun` 一处;导出面是给本批单测档(`docs/batches/*.test.mjs`)驱动「同一 run 连响三次」那一格用的。
94
- */
95
- export function announceBudgetContradiction(agent, contradiction) {
96
- const key = `${agent._runSeq ?? 0}|${contradiction?.window}|${contradiction?.reserve}|${contradiction?.usable}`
97
- if (agent._budgetContradictionKey === key) return
98
- agent._budgetContradictionKey = key
99
- logEvent("budget:contradiction", {
100
- window: contradiction?.window, reserve: contradiction?.reserve, delta: contradiction?.usable, run: agent._runSeq ?? 0,
101
- })
102
- pushInject(agent, {
103
- role: "user",
104
- content: `[System reminder: budget contradiction — ${contradictionNumbers(contradiction)}. No request can be sent on ` +
105
- `this channel until the configuration changes: raise the window (providers[].modelContext / a larger-context model), ` +
106
- `lower provider.maxTokens, or use a model whose maxOutput is smaller than its window. ` +
107
- `The session keeps running so the configuration can be fixed.]`,
108
- })
79
+ /** 按工具名码点(UTF-16 code-unit)确定性排序:消除插件/MCP 注册顺序抖动导致的 KV Prefix Cache 失效。 */
80
+ export function sortToolsByName(tools) {
81
+ return [...tools].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
109
82
  }
110
83
 
111
84
  /**
@@ -132,12 +105,6 @@ export async function prepareRun(agent, input, callbacks, {
132
105
  // §6.17 每 run 现算:数值在场 = 显式原样;不在场 = auto 现算(按在用 provider——切模型后下一 run 跟手)。
133
106
  // 派生值不落 agent.compactThreshold(显式键永不被改写)。auto 档走**有效窗口**(§2.1)。
134
107
  const threshold = resolveCompactThreshold(agent.config?.agent?.compactThreshold, agent.provider).value
135
- // 派生不成立的处置(`CONTEXT-COMPACTION.md` §2.4):判据点仍在这里(provider 落定之后、用户与该模型的第一条读数之前),
136
- // 但不再终止进程——响一声、夹住、放行。喂的是 `policyBudget` 那一边的**有效窗口**(§2.2.1)。
137
- // 显式 `compactThreshold` 会让上面那行跳过派生,所以本行独立走一次:`reserve ≥ window` 这一条无解在
138
- // `budgetOf` 里折成 `contradiction`,不再上传;`threshold ≤ 0` 在比例余量下不可达(§2.2)。
139
- const budget = policyBudget(agent.provider)
140
- if (budget.contradiction) announceBudgetContradiction(agent, budget.contradiction)
141
108
  // 注入开关(PROMPT-SYSTEM.md §6.24 · 台账 #1420):判据 `!== false`(缺省 = 现行为零变)——
142
109
  // 逐 run 现读 `agent.config` ⇒ `settings` 工具 ∕ `/config` 写入后本会话下一次组装即生效。
143
110
  const injectDocs = !tiny && agent.config?.agent?.injectDocs !== false
@@ -250,12 +217,13 @@ export async function prepareRun(agent, input, callbacks, {
250
217
  engineering: agent.config?.agent?.engineering === true,
251
218
  consultModels: agent.config?.agent?.consultModels ?? [],
252
219
  batchDoc: agent._batchDoc ?? null,
220
+ sync: agent._upstream?.sync === true,
253
221
  // 裁定①(P4-I · 父侧 2026-09-29):端壳装饰体透传(`assembleFamilyTools` 既有 `decorate`
254
222
  // 参数面——缺省 undefined ⇒ 核默认形态逐字零变,CLI ∕ desktop 不传即零变)。
255
223
  decorate: toolDecorate,
256
224
  })
257
- // 两段式:绑定值(基础集)→ 家族段 → caller 注入面(§2.3F 不相交义务在注入方)。
258
- const tools = [...agent.tools, ...familyTools, ...(Array.isArray(extraTools) ? extraTools : [])]
225
+ // 两段式:绑定值(基础集)→ 家族段 → caller 注入面(§2.3F 不相交义务在注入方),再按名码点排序保前缀缓存稳定。
226
+ const tools = sortToolsByName([...agent.tools, ...familyTools, ...(Array.isArray(extraTools) ? extraTools : [])])
259
227
  // 工具描述按档装配(设计 TOOLS §1):主链取会话现读的 mode;`agent._role === "consult"` 取完整档
260
228
  // ——consult 与主链共用这处装配,取会话档就等于把 requirements §9.1「独立基底不被极简装配改写」撤掉。
261
229
  const toolMode = agent._role === "consult" ? "normal" : mode
@@ -282,6 +250,7 @@ export async function prepareRun(agent, input, callbacks, {
282
250
  ? (engChildRole ?? "engineering")
283
251
  : (depth === 0 ? "normal" : agent._role ?? "normal"),
284
252
  mode,
253
+ { tools: toolByName },
285
254
  )
286
255
  // D2 警告通道 = 既有 setup 警告通道(history 注入)——不新增机制。深度 0 才注入
287
256
  // (子代理警告不打扰主会话历史——旧工程警告块同款深度门)。
@@ -118,9 +118,13 @@ export function allocRelay(parent, label) {
118
118
  /**
119
119
  * relay **出生声明段**:`[model]` 元数据 token 发射(显示层据此更新区块头部,不进内容流)。
120
120
  * `[model]` 文法单源本函数——异步支同形字面在 `subagent-run.mjs`(观察项,未并)。
121
+ * 可选第 4 参 `title`(`step` 分叉微步短标题):非空时以 `\x1e` 尾附(`[model]<model>\x1e<title>`);
122
+ * 缺省或为空时逐字节保持原形 `[model]<model>`(既有消费面零变)。
121
123
  */
122
- export function emitRelayModel(emit, relayPrefix, model) {
123
- emit?.(relayPrefix + "[model]" + (model ?? ""))
124
+ export function emitRelayModel(emit, relayPrefix, model, title = "") {
125
+ const cleanTitle = typeof title === "string" ? title.replace(/\s+/g, " ").trim() : ""
126
+ const suffix = cleanTitle ? `\x1e${cleanTitle}` : ""
127
+ emit?.(relayPrefix + "[model]" + (model ?? "") + suffix)
124
128
  }
125
129
 
126
130
  /**
@@ -0,0 +1,146 @@
1
+ /**
2
+ * agent/task-lifecycle.mjs — 任务清单运行期提醒、收尾闭环与完工清理的单源纯逻辑。
3
+ *
4
+ * 三层治理(零外部 import,供 `planning-step.mjs` / `post-turn.mjs` / `completion.mjs` / `turn-loop.mjs` / `run-start.mjs` 共用):
5
+ * 1. 执行期可见性与陈旧轻推:`buildPlanningTaskHint` + `evaluateTaskStaleNudge`(连续 N 轮未更新且有未闭项 ⇒ B 段一次性轻推,更新后重臂);
6
+ * 2. 交卷前有界收尾推回:`shouldPushbackUnclosedTasks`(至多 1 次/run;仅当存在 `in_progress` 或更新后又推进过工具轮时触发,
7
+ * 允许刻意记录 `pending` 后立即交接,不打断在途异步池 / timer 等待态);
8
+ * 3. 完工自动清理:`clearCompletedTasks`(全员 `done` 时于正常收尾或新用户回合起点清空 `agent.tasks` 并经 `_onTaskUpdate([])` 同步四端)。
9
+ */
10
+
11
+ export const TASK_STALE_NUDGE_AT = 5
12
+ export const MAX_TASK_CLOSE_PUSHBACKS = 1
13
+
14
+ function clipTitle(title, maxLen = 60) {
15
+ const s = String(title ?? "").replace(/\s+/g, " ").trim()
16
+ if (s.length <= maxLen) return s
17
+ return `${s.slice(0, maxLen - 1)}…`
18
+ }
19
+
20
+ /**
21
+ * 汇总任务清单计数与紧凑未闭项摘要(1-based 编号与 `task` 工具的 `complete`/`start` 对齐)。
22
+ * @param {Array<{title?:string, status?:string}>} tasks
23
+ * @param {{maxOpen?:number}} [opts]
24
+ */
25
+ export function summarizeTaskList(tasks, { maxOpen = 4 } = {}) {
26
+ const list = Array.isArray(tasks) ? tasks : []
27
+ let done = 0
28
+ let inProgress = 0
29
+ let pending = 0
30
+ const openParts = []
31
+
32
+ for (let i = 0; i < list.length; i++) {
33
+ const item = list[i]
34
+ const status = item?.status ?? "pending"
35
+ if (status === "done") {
36
+ done += 1
37
+ continue
38
+ }
39
+ if (status === "in_progress") inProgress += 1
40
+ else pending += 1
41
+ if (openParts.length < maxOpen) {
42
+ openParts.push(`#${i + 1} [${status}] ${clipTitle(item?.title)}`)
43
+ }
44
+ }
45
+
46
+ const open = inProgress + pending
47
+ const hidden = open - openParts.length
48
+ const summary = hidden > 0
49
+ ? `${openParts.join("; ")}; …+${hidden} more`
50
+ : openParts.join("; ")
51
+
52
+ return {
53
+ total: list.length,
54
+ done,
55
+ open,
56
+ inProgress,
57
+ pending,
58
+ allDone: list.length > 0 && open === 0,
59
+ summary,
60
+ }
61
+ }
62
+
63
+ /** 构造规划步尾注中的当前任务清单提示行;无未闭项时返回空串。 */
64
+ export function buildPlanningTaskHint(tasks, turnsSinceTaskUpdate = 0) {
65
+ const info = summarizeTaskList(tasks)
66
+ if (info.open === 0) return ""
67
+ const stale = Math.max(0, Number(turnsSinceTaskUpdate) || 0)
68
+ const staleNote = stale > 0 ? `,距上次更新已过 ${stale} 轮` : ""
69
+ return `\n当前任务清单(${info.done}/${info.total} done${staleNote}):${info.summary} —— 若某步已完成或即将收尾,请在下一步顺手用 \`task\` 同步状态(\`complete\`/\`start\`)或 \`task({ clear: true })\` 清空。`
70
+ }
71
+
72
+ /**
73
+ * 每工具轮末评估是否注入一次任务清单陈旧轻推(纯状态更新 + 返回注入串 | `null`)。
74
+ * 规则:仅 `depth === 0` 且非工程模式;有未闭项且连续 `threshold` 轮未调 `task` 时发 1 条,
75
+ * 发后静默直至下一次 `task` 更新或清单清空后重臂。
76
+ */
77
+ export function evaluateTaskStaleNudge(agent, { depth = 0, results = [], threshold = TASK_STALE_NUDGE_AT } = {}) {
78
+ if (!agent || depth !== 0 || agent.config?.agent?.engineering === true) return null
79
+ const info = summarizeTaskList(agent.tasks)
80
+ if (info.open === 0) {
81
+ agent._turnsSinceTaskUpdate = 0
82
+ agent._taskStaleNudgeSent = false
83
+ return null
84
+ }
85
+ const list = Array.isArray(results) ? results : []
86
+ if (list.length === 0) return null
87
+ if (list.some((r) => r?.toolCall?.name === "task")) {
88
+ agent._turnsSinceTaskUpdate = 0
89
+ agent._taskStaleNudgeSent = false
90
+ return null
91
+ }
92
+
93
+ const turns = (agent._turnsSinceTaskUpdate ?? 0) + 1
94
+ agent._turnsSinceTaskUpdate = turns
95
+ if (agent._taskStaleNudgeSent || turns < threshold) return null
96
+
97
+ agent._taskStaleNudgeSent = true
98
+ return `[System reminder: task list has not been updated for ${turns} tool turns (${info.done}/${info.total} done, ${info.open} open: ${info.summary}). Sync progress now if the active step finished or shifted — e.g. \`task({ complete: ["1"], start: "2" })\`, or \`task({ clear: true })\` once all work is done.]`
99
+ }
100
+
101
+ /**
102
+ * 交卷前检查是否仍有未闭且已陈旧的任务清单,决定是否做一次有界收尾推回(每 run 至多 1 次)。
103
+ * 不触发面:`depth > 0` / 工程模式 / 自动回合 / 异步池在飞 / 存在在途 `timer` / 刚用 `task` 刻意留下的纯 `pending` 交接清单。
104
+ */
105
+ export function shouldPushbackUnclosedTasks(agent, { depth = 0, taskPushbacks = 0, poolActive = false } = {}) {
106
+ if (!agent || depth !== 0 || agent.config?.agent?.engineering === true || agent._inAutoTurn === true) {
107
+ return { pushback: false, reminder: null }
108
+ }
109
+ if (taskPushbacks >= MAX_TASK_CLOSE_PUSHBACKS) {
110
+ return { pushback: false, reminder: null }
111
+ }
112
+ if (poolActive || (Array.isArray(agent._pendingTimers) && agent._pendingTimers.length > 0)) {
113
+ return { pushback: false, reminder: null }
114
+ }
115
+
116
+ const info = summarizeTaskList(agent.tasks)
117
+ if (info.open === 0) {
118
+ return { pushback: false, reminder: null }
119
+ }
120
+ // 允许刚调完 `task` 且仅留 `pending` 项(无 `in_progress`、之后未再跑工具轮)的刻意交接,不额外拖轮次。
121
+ if (info.inProgress === 0 && (agent._turnsSinceTaskUpdate ?? 0) === 0) {
122
+ return { pushback: false, reminder: null }
123
+ }
124
+
125
+ return {
126
+ pushback: true,
127
+ reminder:
128
+ `[System reminder: your task list still has ${info.open} unclosed item(s) (${info.summary}). ` +
129
+ `Before finishing: if all work is done, clear the list with \`task({ clear: true })\` or mark completed items \`done\`; ` +
130
+ `if any item is genuinely unfinished or blocked, update its status accurately and state what remains in your reply.]`,
131
+ }
132
+ }
133
+
134
+ /**
135
+ * 若任务清单全部为 `done`,清空 `agent.tasks` 并经 `_onTaskUpdate([])` 同步四端面板与徽标。
136
+ * @returns {boolean} 是否实际执行了清理
137
+ */
138
+ export function clearCompletedTasks(agent) {
139
+ if (!agent || !Array.isArray(agent.tasks) || agent.tasks.length === 0) return false
140
+ if (!agent.tasks.every((t) => t?.status === "done")) return false
141
+ agent.tasks = []
142
+ agent._turnsSinceTaskUpdate = 0
143
+ agent._taskStaleNudgeSent = false
144
+ agent._onTaskUpdate?.([])
145
+ return true
146
+ }