@thincoder/core 0.11.5 → 0.12.1

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 (199) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/abort-provenance.mjs +23 -0
  3. package/advisor/citations.mjs +5 -1
  4. package/advisor/compaction.mjs +13 -10
  5. package/advisor/history.mjs +6 -1
  6. package/advisor/loop.mjs +35 -10
  7. package/advisor/messages.mjs +31 -43
  8. package/advisor/project-context.mjs +49 -45
  9. package/advisor/run.mjs +82 -26
  10. package/advisor.mjs +40 -11
  11. package/agent/assemble.mjs +5 -5
  12. package/agent/chat-call.mjs +21 -1
  13. package/agent/completion.mjs +1 -20
  14. package/agent/dispatch-gates.mjs +8 -3
  15. package/agent/dispatch-run.mjs +131 -20
  16. package/agent/dispatch.mjs +23 -22
  17. package/agent/family-tools.mjs +4 -7
  18. package/agent/goal-judge.mjs +99 -0
  19. package/agent/goal-state.mjs +96 -0
  20. package/agent/helpers.mjs +13 -4
  21. package/agent/offload.mjs +1 -1
  22. package/agent/planning-graph-guardrail.mjs +224 -0
  23. package/agent/planning-prompt.mjs +179 -0
  24. package/agent/planning-step.mjs +460 -173
  25. package/agent/post-turn.mjs +23 -33
  26. package/agent/record-results.mjs +8 -5
  27. package/agent/run-stages.mjs +18 -38
  28. package/agent/run-start.mjs +26 -19
  29. package/agent/setup-reminders.mjs +16 -14
  30. package/agent/setup.mjs +3 -2
  31. package/agent/spawn-child.mjs +17 -4
  32. package/agent/suspension.mjs +42 -21
  33. package/agent/task-lifecycle.mjs +165 -52
  34. package/agent/timers.mjs +9 -1
  35. package/agent/turn-loop.mjs +160 -69
  36. package/agent/turn-projection.mjs +26 -15
  37. package/agent/turn-task-state.mjs +4 -4
  38. package/agent/write-gate-ledger.mjs +1 -1
  39. package/agent/write-gate.mjs +14 -11
  40. package/agent-tools/advisor-async.mjs +2 -0
  41. package/agent-tools/advisor-launch.mjs +27 -13
  42. package/agent-tools/advisor-settle.mjs +19 -18
  43. package/agent-tools/advisor.mjs +90 -13
  44. package/agent-tools/bash-async.mjs +3 -3
  45. package/agent-tools/batch-ledger-bind.mjs +8 -5
  46. package/agent-tools/batch-read.mjs +42 -0
  47. package/agent-tools/batch-record-write.mjs +20 -12
  48. package/agent-tools/batch-segment-vocab.mjs +6 -4
  49. package/agent-tools/batch-skeleton.mjs +43 -12
  50. package/agent-tools/consult.mjs +5 -1
  51. package/agent-tools/context.mjs +5 -4
  52. package/agent-tools/design-slots.mjs +7 -4
  53. package/agent-tools/design-token.mjs +3 -2
  54. package/agent-tools/doc-graph.mjs +257 -95
  55. package/agent-tools/escalate-async.mjs +4 -1
  56. package/agent-tools/goal.mjs +28 -95
  57. package/agent-tools/plan.mjs +1 -1
  58. package/agent-tools/review-facts.mjs +56 -7
  59. package/agent-tools/settings.mjs +35 -1
  60. package/agent-tools/ssh-transport.mjs +23 -22
  61. package/agent-tools/step.mjs +24 -4
  62. package/agent-tools/subagent-actions.mjs +6 -2
  63. package/agent-tools/subagent-async.mjs +4 -2
  64. package/agent-tools/subagent.mjs +1 -1
  65. package/agent-tools/task.mjs +73 -65
  66. package/agent-tools.mjs +3 -3
  67. package/agent.mjs +12 -3
  68. package/auto-think.mjs +16 -3
  69. package/browser/actions.mjs +5 -1
  70. package/browser/cdp.mjs +1 -1
  71. package/browser/pool.mjs +110 -17
  72. package/compaction-work-state.mjs +103 -13
  73. package/compress-form.mjs +29 -3
  74. package/config-defaults.mjs +27 -3
  75. package/config-io.mjs +3 -14
  76. package/config-normalize.mjs +24 -4
  77. package/config-presets.mjs +40 -26
  78. package/config-warn.mjs +30 -0
  79. package/config.mjs +139 -63
  80. package/context-degrade.mjs +4 -4
  81. package/context-push.mjs +20 -9
  82. package/context.mjs +65 -20
  83. package/doc-graph/anchors.mjs +39 -40
  84. package/doc-graph/clusters.mjs +49 -0
  85. package/doc-graph/code-parsers.mjs +494 -0
  86. package/doc-graph/context-pack.mjs +392 -0
  87. package/doc-graph/dir-signals.mjs +228 -0
  88. package/doc-graph/edges.mjs +231 -0
  89. package/doc-graph/format.mjs +70 -0
  90. package/doc-graph/gc-cmd.mjs +104 -0
  91. package/doc-graph/gc.mjs +112 -0
  92. package/doc-graph/glob-work-graph.mjs +307 -0
  93. package/doc-graph/golden-set.mjs +131 -0
  94. package/doc-graph/ls-work-graph.mjs +534 -0
  95. package/doc-graph/outline.mjs +377 -0
  96. package/doc-graph/output-annotations.mjs +85 -0
  97. package/doc-graph/process-docs.mjs +68 -0
  98. package/doc-graph/read-work-graph.mjs +91 -0
  99. package/doc-graph/rebuild-cmd.mjs +75 -0
  100. package/doc-graph/resolvers.mjs +322 -0
  101. package/doc-graph/roots.mjs +86 -0
  102. package/doc-graph/schema.mjs +110 -0
  103. package/doc-graph/search-augment.mjs +418 -0
  104. package/doc-graph/store.mjs +231 -0
  105. package/doc-graph/target-resolve.mjs +352 -0
  106. package/doc-graph/walk.mjs +87 -0
  107. package/doc-graph.mjs +583 -707
  108. package/explore-distill.mjs +52 -17
  109. package/generate-title.mjs +7 -4
  110. package/ledger-close.mjs +6 -6
  111. package/ledger-cmd.mjs +3 -3
  112. package/ledger-consistency.mjs +8 -6
  113. package/ledger-db.mjs +45 -10
  114. package/ledger-migrate.mjs +25 -10
  115. package/ledger-read.mjs +1 -1
  116. package/ledger-write-ops.mjs +6 -6
  117. package/ledger.mjs +2 -2
  118. package/model-context.mjs +54 -18
  119. package/model-specs.mjs +86 -67
  120. package/package.json +1 -1
  121. package/prompt-overlays.mjs +3 -3
  122. package/prompts/advisor-round1.md +6 -5
  123. package/prompts/common.md +16 -6
  124. package/prompts/consult-base.md +2 -1
  125. package/prompts/discipline-engineering.md +1 -1
  126. package/prompts/discipline-normal.md +12 -8
  127. package/prompts/knowledge/doc-lookup.md +2 -2
  128. package/prompts/knowledge/normal-batch-discipline.md +2 -2
  129. package/prompts/knowledge/normal-delivery-collaboration.md +3 -3
  130. package/prompts/knowledge/tool-advisor.md +2 -2
  131. package/prompts/knowledge/tool-apply-patch.md +1 -1
  132. package/prompts/knowledge/tool-bash.md +2 -2
  133. package/prompts/knowledge/tool-batch.md +4 -4
  134. package/prompts/knowledge/tool-glob.md +9 -2
  135. package/prompts/knowledge/tool-goal.md +9 -6
  136. package/prompts/knowledge/tool-grep.md +7 -2
  137. package/prompts/knowledge/tool-ls.md +11 -5
  138. package/prompts/knowledge/tool-lsp.md +1 -1
  139. package/prompts/knowledge/tool-operations.md +3 -2
  140. package/prompts/knowledge/tool-plan.md +1 -1
  141. package/prompts/knowledge/tool-read.md +7 -6
  142. package/prompts/knowledge/tool-repo-graph-read.md +12 -0
  143. package/prompts/knowledge/tool-repo-graph.md +12 -0
  144. package/prompts/knowledge/tool-step.md +1 -1
  145. package/prompts/knowledge/tool-subagent.md +2 -2
  146. package/prompts/knowledge/tool-task.md +10 -9
  147. package/prompts/knowledge/tool-tree.md +7 -1
  148. package/prompts/persona-eng-coder.md +1 -1
  149. package/prompts/persona-eng-designer.md +1 -1
  150. package/prompts/persona-engineering.md +2 -1
  151. package/prompts/persona-explore.md +1 -1
  152. package/prompts/persona-normal.md +7 -6
  153. package/prompts/persona-plan.md +2 -2
  154. package/prompts/planning-next-moves.md +7 -8
  155. package/provider/anthropic.mjs +53 -51
  156. package/provider/core.mjs +85 -34
  157. package/provider/errors.mjs +33 -10
  158. package/provider/google.mjs +244 -37
  159. package/provider/list-models.mjs +28 -14
  160. package/provider/responses-request.mjs +15 -9
  161. package/provider/responses.mjs +10 -8
  162. package/provider/sse.mjs +3 -6
  163. package/proxy-transport.mjs +228 -119
  164. package/rules-file.mjs +79 -0
  165. package/rules.mjs +13 -51
  166. package/session-lifecycle.mjs +32 -20
  167. package/team-ledger.mjs +7 -7
  168. package/think-off.mjs +37 -18
  169. package/token-window.mjs +48 -31
  170. package/tool-args.mjs +8 -8
  171. package/tool-docs/bash.md +1 -1
  172. package/tool-docs/glob.md +3 -1
  173. package/tool-docs/goal.md +2 -2
  174. package/tool-docs/grep.md +3 -1
  175. package/tool-docs/ls.md +7 -1
  176. package/tool-docs/read.md +1 -1
  177. package/tool-docs/repo_graph-read.md +3 -0
  178. package/tool-docs/repo_graph.md +3 -0
  179. package/tool-docs/tree.md +1 -1
  180. package/tools/bash.mjs +53 -8
  181. package/tools/browser.mjs +4 -4
  182. package/tools/file.mjs +34 -7
  183. package/tools/glob-dialect.mjs +57 -7
  184. package/tools/index.mjs +3 -7
  185. package/tools/patch.mjs +8 -7
  186. package/tools/process-doc-mark.mjs +13 -0
  187. package/tools/search.mjs +152 -37
  188. package/tools/shared.mjs +6 -0
  189. package/tools/tree.mjs +211 -8
  190. package/window-policy.mjs +205 -126
  191. package/prompts/knowledge/tool-doc-graph-read.md +0 -20
  192. package/prompts/knowledge/tool-doc-graph.md +0 -49
  193. package/prompts/knowledge/tool-peek.md +0 -10
  194. package/prompts/knowledge/tool-repo-outline.md +0 -4
  195. package/tool-docs/doc_graph-read.md +0 -3
  196. package/tool-docs/doc_graph.md +0 -3
  197. package/tool-docs/peek.md +0 -3
  198. package/tool-docs/repo_outline.md +0 -3
  199. package/tools/peek.mjs +0 -447
@@ -51,6 +51,7 @@ import { upstreamWaiting } from "../agent-tools/parent-channel.mjs"
51
51
  // 开轮判据与投递门控同源(AGENT-LOOP-ASYNC-POOL.md §1「挂起与 digest」):容器里「有未投递条」
52
52
  // 就是 `shouldDeliverEntry` 判要投的那条;升级四步(§8.3)两支共用同一实现。
53
53
  import { shouldDeliverEntry, escalateUndigested } from "./digest-account.mjs"
54
+ import { MAX_TIMEOUT_MS } from "./timers.mjs"
54
55
 
55
56
  /** 运行中 consult children(非 stopped 会话的在飞子调用数——挂起活度/计数同源)。 */
56
57
  function consultRunningChildren(carrier) {
@@ -88,9 +89,9 @@ export function poolLive(carrier) {
88
89
 
89
90
  /** D-S3 ③ 记账清扫:回合边界竞态落下的已 settle 项(settle 回调未及移交——发生在回合刚结束、
90
91
  * `_suspended` 尚未置位的窗口)补入 pending。幂等:`parkAsyncPending` 置 `_inPending` 防重复,
91
- * 键按条目实际 key 删除(两端 key 形态不同——对载体零预设)。 */
92
+ * 键按条目实际 key 删除(两端 key 形态不同——对载体零预设)。覆盖全部四池(subagent / advisor / bg / browser)。 */
92
93
  export function sweepSettledToPending(carrier) {
93
- for (const key of ["_asyncSubagents", "_asyncAdvisors"]) {
94
+ for (const key of ["_asyncSubagents", "_asyncAdvisors", "_bgTasks", "_browserTasks"]) {
94
95
  const map = carrier?.[key]
95
96
  if (!(map instanceof Map) || map.size === 0) continue
96
97
  for (const [k, e] of [...map.entries()]) {
@@ -103,10 +104,11 @@ export function sweepSettledToPending(carrier) {
103
104
  }
104
105
 
105
106
  /** 后台计数(D-S8——宿主状态行 / 消息族的数据面):{ running, queued, pending, done }。
106
- * `done` = 回合尾留池的 settled 未消费项(挂起首轮 sweep 前的可见窗口)。 */
107
+ * `done` = 回合尾留池的 settled 未消费项(挂起首轮 sweep 前的可见窗口)。
108
+ * 口径与 `poolLive` 一致:涵盖 subagent / advisor / bg / browser 四池与 consult。 */
107
109
  export function backgroundCounts(carrier) {
108
110
  const entries = []
109
- for (const key of ["_asyncSubagents", "_asyncAdvisors"]) {
111
+ for (const key of ["_asyncSubagents", "_asyncAdvisors", "_bgTasks", "_browserTasks"]) {
110
112
  const map = carrier?.[key]
111
113
  if (map instanceof Map) entries.push(...map.values())
112
114
  }
@@ -209,11 +211,17 @@ function waitForSettleOrWake(carrier, abortSignal, latch, { deadline = null, tim
209
211
  const onTimer = () => finish("timer")
210
212
  ;(carrier._asyncWaiters ??= []).push(onSettle)
211
213
  latch.wake = () => finish("wake")
212
- // opt-in deadline(§6.30.10 等待第四态):无在途 / 未传 ⇒ 零注册(等待仍三态)。宿主不变式 = 到期即出列 / 关即 null(否则「已到期 ∧ 交付假」会 0ms 反复重注册)。
213
- if (deadline != null) {
214
- handle = timer(onTimer, Math.max(0, deadline - Date.now()))
214
+ // opt-in deadline(§6.30.10 等待第四态):无在途 / 未传 ⇒ 零注册(等待仍三态)。
215
+ // 超过 Node.js 32 位 setTimeout 上限时分段接力,防止溢出成 1ms 立刻误触发。
216
+ const armTimer = () => {
217
+ if (finished || deadline == null) return
218
+ const delay = Math.max(0, deadline - Date.now())
219
+ handle = delay > MAX_TIMEOUT_MS
220
+ ? timer(() => { handle = null; armTimer() }, MAX_TIMEOUT_MS)
221
+ : timer(onTimer, delay)
215
222
  try { handle?.unref?.() } catch { /* unref 失败不阻断 */ }
216
223
  }
224
+ if (deadline != null) armTimer()
217
225
  if (abortSignal?.aborted) { onAbort(); return }
218
226
  abortSignal?.addEventListener("abort", onAbort, { once: true })
219
227
  })
@@ -259,6 +267,7 @@ export function startSuspension(ctx) {
259
267
  carrier._daSession = true
260
268
  hooks.onCounts?.(backgroundCounts(carrier))
261
269
  let aborted = false
270
+ let failed = false
262
271
  try {
263
272
  while (true) {
264
273
  if (abortSignal?.aborted) { aborted = true; break }
@@ -291,21 +300,27 @@ export function startSuspension(ctx) {
291
300
  if (hasUndeliveredEntry(carrier) || upstream) {
292
301
  const afterRun = consumedByRun()
293
302
  hooks.onDigest?.("start", backgroundCounts(carrier))
303
+ let digestEnded = false
304
+ const endDigest = () => {
305
+ if (digestEnded) return
306
+ digestEnded = true
307
+ hooks.onDigest?.("end", backgroundCounts(carrier))
308
+ }
294
309
  try {
295
310
  await runTurn("", { autoTurn: true, upstreamTurn: upstream })
296
311
  } catch (e) {
297
312
  // 消化轮自身的回合级中止不是会话停止——记边界后重入循环(池空 / 无未投递条自然退出)。
298
313
  if (e?.name === "AbortError" && !abortSignal?.aborted) {
299
- hooks.onDigest?.("end", backgroundCounts(carrier))
314
+ endDigest()
300
315
  continue
301
316
  }
302
317
  throw e
303
318
  } finally {
304
319
  // 回收恒达窗(子代理面板批 · 2026-10-04 · §2.2):正常 ∥ Abort-continue ∥ 异常抛三径同达;
305
- // 中止径 catch 的 `onDigest("end")` 先行(continue 触 finally——既有语义序保持)。
320
+ // 中止径 catch 的 `onDigest("end")` 先行,普通异常径也在此成对关闭 digest 边界。
306
321
  hooks.reclaim?.(afterRun())
322
+ endDigest()
307
323
  }
308
- hooks.onDigest?.("end", backgroundCounts(carrier))
309
324
  hooks.onCounts?.(backgroundCounts(carrier))
310
325
  continue
311
326
  }
@@ -336,6 +351,9 @@ export function startSuspension(ctx) {
336
351
  continue
337
352
  }
338
353
  }
354
+ } catch (e) {
355
+ failed = true
356
+ throw e
339
357
  } finally {
340
358
  if (!finished) {
341
359
  finished = true
@@ -346,10 +364,9 @@ export function startSuspension(ctx) {
346
364
  // abort 以 AbortError 抛出、循环顶检查不会再执行——不合并会把清场误走 idle 注入)。
347
365
  const abortedNow = aborted || Boolean(abortSignal?.aborted)
348
366
  aborted = abortedNow
349
- // §8.3 周期终点支(账务周期的终点):idle 退出前把容器里已投递未销账的条结账——四步
350
- // (账本 → 提醒 → 离容器 → 终局披露)全是机械动作,不开任何回合;会话沉寂之后不再有消化轮,
351
- // 保底不能押在「下一轮碰巧发生」上。中止径不适用(中止按 `## 6. 中止丢弃` 清账)。
352
- if (!abortedNow) {
367
+ // §8.3 周期终点支(账务周期的终点):仅真正正常 idle 退出前把容器里已投递未销账的条结账——
368
+ // 非中止异常退出(如网络错 / 鉴权错)不属于 idle 周期终点,不误触发 idle 升级,保留容器待恢复。
369
+ if (!abortedNow && !failed) {
353
370
  const pendingNow = carrier._pendingAsyncResults
354
371
  await escalateUndigested(
355
372
  carrier,
@@ -357,13 +374,17 @@ export function startSuspension(ctx) {
357
374
  Array.isArray(pendingNow) ? pendingNow.filter((e) => e?._daDelivered === true) : [],
358
375
  )
359
376
  }
360
- const flushed = await finishSuspension(carrier, { aborted: abortedNow, injectResidual })
361
- // 残差离容补发(子代理面板批 · 2026-10-04 · §2.2——C2 零发射口):补发面 = 离容全量
362
- // (抛错径同覆);与 freezeAll 双探针幂等(归档/记录恰一次住幂等层)。
363
- hooks.reclaim?.(flushed.left)
364
- hooks.freezeAll?.()
365
- // 注入器首错重抛(fail-loud 保持——清场两探针已行毕)。
366
- if (flushed.error != null) throw flushed.error
377
+ if (abortedNow || !failed) {
378
+ const flushed = await finishSuspension(carrier, { aborted: abortedNow, injectResidual })
379
+ // 残差离容补发(子代理面板批 · 2026-10-04 · §2.2——C2 零发射口):补发面 = 离容全量
380
+ // (抛错径同覆);与 freezeAll 双探针幂等(归档/记录恰一次住幂等层)。
381
+ hooks.reclaim?.(flushed.left)
382
+ hooks.freezeAll?.()
383
+ // 注入器首错重抛(fail-loud 保持——清场两探针已行毕)。
384
+ if (flushed.error != null) throw flushed.error
385
+ } else {
386
+ hooks.freezeAll?.()
387
+ }
367
388
  }
368
389
  }
369
390
  return { reason: aborted ? "aborted" : "idle", residualInput: pendingInput.splice(0) }
@@ -1,15 +1,21 @@
1
1
  /**
2
- * agent/task-lifecycle.mjs — 任务清单运行期提醒、收尾闭环与完工清理的单源纯逻辑。
2
+ * agent/task-lifecycle.mjs — 任务清单规划步协同同步与完工清理的单源纯逻辑。
3
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([])` 同步四端)。
4
+ * 四项职责(零外部 import,供 `planning-step.mjs` / `post-turn.mjs` / `turn-loop.mjs` / `run-start.mjs` / `agent-tools/task.mjs` 共用):
5
+ * 1. 未更新轮数记账:`advanceTaskUpdateTurns`(仅维护 `agent._turnsSinceTaskUpdate` 供规划步判断是否陈旧,不向消息流注入任何打扰提醒);
6
+ * 2. 规划步协同同步:`buildPlanningTaskHint` + `createTaskSyncStreamFilter` + `extractAndApplyPlanningTaskSync`
7
+ * (规划步全程禁止调用任何工具;清单非空时由模型按需在规划文本末尾附 `<task_sync>{...}</task_sync>`,
8
+ * 流式渲染与注入均自动剥离该标签并静默调用 `task` 更新内存态与四端 UI,跨多轮任务可视情况保留或继续,绝不机械清空);
9
+ * 3. 完工自动清理:`clearCompletedTasks`(全员 `done` 时于正常收尾或新用户回合起点清空 `agent.tasks` 并经 `_onTaskUpdate([])` 同步四端);
10
+ * 4. 正常收尾:未闭项按实际状态保留,不构造 sweep 提醒或额外模型轮。
9
11
  */
10
12
 
11
- export const TASK_STALE_NUDGE_AT = 5
12
- export const MAX_TASK_CLOSE_PUSHBACKS = 1
13
+ export const MAX_PLANNING_TASK_CALLS = 3
14
+
15
+ const OPEN_TAG = "<task_sync>"
16
+ const CLOSE_TAG = "</task_sync>"
17
+ const TASK_SYNC_BLOCK_RE = /<task_sync>\s*([\s\S]*?)\s*<\/task_sync>/gi
18
+ const TASK_SYNC_DANGLING_RE = /<task_sync>[\s\S]*$/i
13
19
 
14
20
  function clipTitle(title, maxLen = 60) {
15
21
  const s = String(title ?? "").replace(/\s+/g, " ").trim()
@@ -17,6 +23,19 @@ function clipTitle(title, maxLen = 60) {
17
23
  return `${s.slice(0, maxLen - 1)}…`
18
24
  }
19
25
 
26
+ function parseTaskSyncPayload(raw) {
27
+ let s = String(raw ?? "").trim()
28
+ if (!s) return null
29
+ const fenced = /^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(s)
30
+ if (fenced) s = fenced[1].trim()
31
+ try {
32
+ const parsed = JSON.parse(s)
33
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null
34
+ } catch {
35
+ return null
36
+ }
37
+ }
38
+
20
39
  /**
21
40
  * 汇总任务清单计数与紧凑未闭项摘要(1-based 编号与 `task` 工具的 `complete`/`start` 对齐)。
22
41
  * @param {Array<{title?:string, status?:string}>} tasks
@@ -60,77 +79,172 @@ export function summarizeTaskList(tasks, { maxOpen = 4 } = {}) {
60
79
  }
61
80
  }
62
81
 
63
- /** 构造规划步尾注中的当前任务清单提示行;无未闭项时返回空串。 */
64
- export function buildPlanningTaskHint(tasks, turnsSinceTaskUpdate = 0) {
82
+ /**
83
+ * 构造规划步尾注中的当前任务清单提示行;清单为空时返回空串。
84
+ * - 当 `canSyncTask` 为真(主会话普通模式且活工具表含 `task`)时,引导规划步在末尾按需附 `<task_sync>{...}</task_sync>` 标签,
85
+ * 严禁通过工具调用发射任何 tool_calls;
86
+ * - 强调跨多轮任务可继续保留或推进、仅在确实完结或切题时清空/重置,绝不机械清空。
87
+ */
88
+ export function buildPlanningTaskHint(tasks, turnsSinceTaskUpdate = 0, { trigger = "", canSyncTask = false } = {}) {
65
89
  const info = summarizeTaskList(tasks)
66
- if (info.open === 0) return ""
90
+ if (info.total === 0) return ""
67
91
  const stale = Math.max(0, Number(turnsSinceTaskUpdate) || 0)
68
92
  const staleNote = stale > 0 ? `,距上次更新已过 ${stale} 轮` : ""
69
- return `\n当前任务清单(${info.done}/${info.total} done${staleNote}):${info.summary} —— 若某步已完成或即将收尾,请在下一步顺手用 \`task\` 同步状态(\`complete\`/\`start\`)或 \`task({ clear: true })\` 清空。`
93
+
94
+ if (info.allDone) {
95
+ if (!canSyncTask) return ""
96
+ return `\n当前任务清单(${info.done}/${info.total} 已全部 done):若无后续延续步骤,可在规划笔记末尾另起一行输出 \`<task_sync>{"clear":true}</task_sync>\` 静默清空(仍禁止调用任何工具);若要展开新一阶段,可输出 \`<task_sync>{"items":[...]}\</task_sync>\`。`
97
+ }
98
+
99
+ if (!canSyncTask) {
100
+ return `\n当前任务清单(${info.done}/${info.total} done${staleNote}):${info.summary}。`
101
+ }
102
+
103
+ if (trigger === "start") {
104
+ return `\n当前任务清单(${info.done}/${info.total} done${staleNote}):${info.summary} —— 请结合本轮用户输入视情况决定:若是跨多轮继续推进同一任务,可保持不动或在规划笔记末尾另起一行附 \`<task_sync>{"complete":["1"],"start":"2"}</task_sync>\` 同步进度;若旧清单已完结或本轮切换为无关新任务,可附 \`<task_sync>{"clear":true}</task_sync>\` 清空或 \`{"items":[...]}\` 重建(切勿机械清空未完成的跨轮任务,且严禁调用任何工具)。`
105
+ }
106
+
107
+ return `\n当前任务清单(${info.done}/${info.total} done${staleNote}):${info.summary} —— 若某步已完成、状态落后于实际进展或全部完工,可在规划笔记末尾另起一行附 \`<task_sync>{"complete":["1"],"start":"2"}</task_sync>\` 或 \`<task_sync>{"clear":true}</task_sync>\` 静默同步(支持 \`complete\`/\`start\`/\`items\`/\`clear\`,严禁调用任何工具);若任务尚在进行且状态准确,则不输出该标签。`
70
108
  }
71
109
 
72
110
  /**
73
- * 每工具轮末评估是否注入一次任务清单陈旧轻推(纯状态更新 + 返回注入串 | `null`)。
74
- * 规则:仅 `depth === 0` 且非工程模式;有未闭项且连续 `threshold` 轮未调 `task` 时发 1 条,
75
- * 发后静默直至下一次 `task` 更新或清单清空后重臂。
111
+ * 每工具轮末维护 `agent._turnsSinceTaskUpdate`(纯状态记账,不注入任何系统提醒)。
112
+ * 供下一次规划步感知清单多久未更新;无未闭项或本轮已调 `task` 时清零。
76
113
  */
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
114
+ export function advanceTaskUpdateTurns(agent, { depth = 0, results = [] } = {}) {
115
+ if (!agent || depth !== 0 || agent.config?.agent?.engineering === true) return 0
79
116
  const info = summarizeTaskList(agent.tasks)
80
117
  if (info.open === 0) {
81
118
  agent._turnsSinceTaskUpdate = 0
82
- agent._taskStaleNudgeSent = false
83
- return null
119
+ return 0
84
120
  }
85
121
  const list = Array.isArray(results) ? results : []
86
- if (list.length === 0) return null
122
+ if (list.length === 0) return agent._turnsSinceTaskUpdate ?? 0
87
123
  if (list.some((r) => r?.toolCall?.name === "task")) {
88
124
  agent._turnsSinceTaskUpdate = 0
89
- agent._taskStaleNudgeSent = false
90
- return null
125
+ return 0
91
126
  }
92
-
93
127
  const turns = (agent._turnsSinceTaskUpdate ?? 0) + 1
94
128
  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.]`
129
+ return turns
99
130
  }
100
131
 
101
132
  /**
102
- * 交卷前检查是否仍有未闭且已陈旧的任务清单,决定是否做一次有界收尾推回(每 run 至多 1 次)。
103
- * 不触发面:`depth > 0` / 工程模式 / 自动回合 / 异步池在飞 / 存在在途 `timer` / 刚用 `task` 刻意留下的纯 `pending` 交接清单。
133
+ * 流式过滤规划步正文中的 `<task_sync>...</task_sync>` 机器标签,避免原始 JSON 闪现到三端规划块。
134
+ * 任意分片粒度(含单字符分片)均安全;未闭合尾部在 `flush()` 时丢弃。
104
135
  */
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
- }
136
+ export function createTaskSyncStreamFilter(emit) {
137
+ let inTag = false
138
+ let buf = ""
115
139
 
116
- const info = summarizeTaskList(agent.tasks)
117
- if (info.open === 0) {
118
- return { pushback: false, reminder: null }
140
+ return {
141
+ push(chunk) {
142
+ if (!chunk) return
143
+ buf += chunk
144
+ while (buf.length > 0) {
145
+ if (!inTag) {
146
+ const idx = buf.toLowerCase().indexOf(OPEN_TAG)
147
+ if (idx !== -1) {
148
+ if (idx > 0) emit(buf.slice(0, idx))
149
+ buf = buf.slice(idx + OPEN_TAG.length)
150
+ inTag = true
151
+ continue
152
+ }
153
+ const lastLt = buf.lastIndexOf("<")
154
+ if (lastLt !== -1 && buf.length - lastLt < OPEN_TAG.length && OPEN_TAG.startsWith(buf.slice(lastLt).toLowerCase())) {
155
+ if (lastLt > 0) emit(buf.slice(0, lastLt))
156
+ buf = buf.slice(lastLt)
157
+ break
158
+ }
159
+ emit(buf)
160
+ buf = ""
161
+ break
162
+ } else {
163
+ const idx = buf.toLowerCase().indexOf(CLOSE_TAG)
164
+ if (idx !== -1) {
165
+ buf = buf.slice(idx + CLOSE_TAG.length)
166
+ inTag = false
167
+ continue
168
+ }
169
+ if (buf.length >= CLOSE_TAG.length) {
170
+ buf = buf.slice(-(CLOSE_TAG.length - 1))
171
+ }
172
+ break
173
+ }
174
+ }
175
+ },
176
+ flush() {
177
+ if (!inTag && buf) emit(buf)
178
+ buf = ""
179
+ },
119
180
  }
120
- // 允许刚调完 `task` 且仅留 `pending` 项(无 `in_progress`、之后未再跑工具轮)的刻意交接,不额外拖轮次。
121
- if (info.inProgress === 0 && (agent._turnsSinceTaskUpdate ?? 0) === 0) {
122
- return { pushback: false, reminder: null }
181
+ }
182
+
183
+ /**
184
+ * 从规划步文本中剥离 `<task_sync>...</task_sync>` 标签,并在主会话普通模式下静默调用 `taskTool.execute` 同步状态。
185
+ * - 不写入 `agent.history`,以 `fromPlanning: true` 标记规划步内部更新;
186
+ * - 工程模式、子代理或无 `taskTool` 时仍剥离标签但不执行任何状态变更;
187
+ * - 解析失败或执行异常优雅降级,不阻断规划步与主循环。
188
+ * @returns {Promise<{ cleanedText: string, synced: boolean, applied: number, ignored: number, receipt: string }>}
189
+ */
190
+ export async function extractAndApplyPlanningTaskSync(agent, text, { taskTool = null, depth = 0, signal } = {}) {
191
+ const raw = typeof text === "string" ? text : ""
192
+ const payloads = []
193
+ let cleaned = raw.replace(TASK_SYNC_BLOCK_RE, (_m, inner) => {
194
+ payloads.push(inner)
195
+ return ""
196
+ })
197
+ cleaned = cleaned.replace(TASK_SYNC_DANGLING_RE, "").trim()
198
+
199
+ const canExec = Boolean(
200
+ agent
201
+ && taskTool
202
+ && typeof taskTool.execute === "function"
203
+ && depth === 0
204
+ && agent.config?.agent?.engineering !== true,
205
+ )
206
+ if (!canExec || payloads.length === 0) {
207
+ return { cleanedText: cleaned, synced: false, applied: 0, ignored: payloads.length, receipt: "" }
123
208
  }
124
209
 
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.]`,
210
+ let applied = 0
211
+ let ignored = 0
212
+ let lastReceipt = ""
213
+
214
+ for (const rawInner of payloads) {
215
+ if (applied >= MAX_PLANNING_TASK_CALLS) {
216
+ ignored += 1
217
+ continue
218
+ }
219
+ const args = parseTaskSyncPayload(rawInner)
220
+ if (!args) {
221
+ ignored += 1
222
+ continue
223
+ }
224
+ try {
225
+ const out = await taskTool.execute(args, {
226
+ agent,
227
+ depth,
228
+ signal,
229
+ cwd: agent.cwd,
230
+ fromPlanning: true,
231
+ })
232
+ const msg = typeof out === "string" ? out.trim() : ""
233
+ if (msg && !msg.startsWith("Error:")) {
234
+ applied += 1
235
+ lastReceipt = msg.split("\n")[0].trim()
236
+ } else {
237
+ ignored += 1
238
+ }
239
+ } catch {
240
+ ignored += 1
241
+ }
131
242
  }
243
+
244
+ return { cleanedText: cleaned, synced: applied > 0, applied, ignored, receipt: lastReceipt }
132
245
  }
133
246
 
247
+
134
248
  /**
135
249
  * 若任务清单全部为 `done`,清空 `agent.tasks` 并经 `_onTaskUpdate([])` 同步四端面板与徽标。
136
250
  * @returns {boolean} 是否实际执行了清理
@@ -140,7 +254,6 @@ export function clearCompletedTasks(agent) {
140
254
  if (!agent.tasks.every((t) => t?.status === "done")) return false
141
255
  agent.tasks = []
142
256
  agent._turnsSinceTaskUpdate = 0
143
- agent._taskStaleNudgeSent = false
144
257
  agent._onTaskUpdate?.([])
145
258
  return true
146
259
  }
package/agent/timers.mjs CHANGED
@@ -29,6 +29,9 @@ export const TIMER_MAX_PENDING = 8
29
29
  * 核重排面不设界(防御 = 非有限正数 ⇒ `nextFireAt` 返 `null` 照消费——下限校验在工具面)。 */
30
30
  export const TIMER_MIN_EVERY_MS = 60_000
31
31
 
32
+ /** Node.js `setTimeout` 32 位有符号延迟上限(~24.85 天):超过此值会溢出为 1ms 立刻触发,需分片接力。 */
33
+ export const MAX_TIMEOUT_MS = 2_147_483_647
34
+
32
35
  /** 日历式 `HH:MM` 形判据(防御面——工具面为唯一生产者,两处同形)。 */
33
36
  const DAILY_RE = /^(?:[01]\d|2[0-3]):[0-5]\d$/
34
37
 
@@ -145,7 +148,12 @@ export function createTimerWatch({ getAgent, onFire, timer = setTimeout, clear =
145
148
  if (deadline == null) { disarm(); return null } // 无在途 / 开关关 / 无载体——撤旧,零注册
146
149
  disarm() // 单槽:重复武装 = 撤旧立新(延迟按最近到期重算)
147
150
  const delay = Math.max(0, deadline - now())
148
- handle = timer(() => { handle = null; onFire?.() }, delay)
151
+ if (delay > MAX_TIMEOUT_MS) {
152
+ // 超出 32 位 setTimeout 上限:挂一段接力定时,到点仅重同步,避免溢出成 1ms 提前触发或自旋。
153
+ handle = timer(() => { handle = null; sync() }, MAX_TIMEOUT_MS)
154
+ } else {
155
+ handle = timer(() => { handle = null; onFire?.() }, delay)
156
+ }
149
157
  try { handle?.unref?.() } catch { /* unref 失败不阻断(一次性闩自然退出) */ }
150
158
  return delay
151
159
  }