thincoder 0.12.62 → 0.12.63

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 (228) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/README.md +13 -12
  3. package/bin/thincoder.mjs +53 -27
  4. package/package.json +6 -5
  5. package/src/acp/bridge.mjs +35 -15
  6. package/src/acp/client-caps.mjs +86 -0
  7. package/src/acp/ext.mjs +86 -0
  8. package/src/acp/handlers-session.mjs +240 -0
  9. package/src/acp/handlers-slots.mjs +196 -0
  10. package/src/acp/login.mjs +48 -0
  11. package/src/acp/session.mjs +6 -4
  12. package/src/acp.mjs +67 -379
  13. package/src/cli/distill-command.mjs +3 -3
  14. package/src/cli/make-agent.mjs +59 -17
  15. package/src/cli/memory-command.mjs +3 -3
  16. package/src/cli/permission.mjs +4 -48
  17. package/src/cli/setup-wizard.mjs +1 -1
  18. package/src/completions.mjs +3 -1
  19. package/src/crash-reports.mjs +1 -1
  20. package/src/distill.mjs +4 -4
  21. package/src/heap-watch.mjs +1 -1
  22. package/src/prompt-injections.mjs +20 -0
  23. package/src/tui/agent-turn.mjs +40 -9
  24. package/src/tui/cmd-advisor.mjs +5 -5
  25. package/src/tui/cmd-config.mjs +8 -8
  26. package/src/tui/cmd-eng.mjs +25 -9
  27. package/src/tui/cmd-mcp.mjs +9 -8
  28. package/src/tui/cmd-model.mjs +1 -1
  29. package/src/tui/cmd-new.mjs +6 -5
  30. package/src/tui/cmd-reindex.mjs +1 -1
  31. package/src/tui/cmd-restore.mjs +2 -2
  32. package/src/tui/cmd-session.mjs +24 -1
  33. package/src/tui/cmd-skills.mjs +1 -1
  34. package/src/tui/cmd-think.mjs +22 -9
  35. package/src/tui/config-helpers.mjs +1 -1
  36. package/src/tui/display-budget.mjs +33 -11
  37. package/src/tui/index.mjs +9 -9
  38. package/src/tui/interaction.mjs +16 -7
  39. package/src/tui/key-modes.mjs +9 -4
  40. package/src/tui/ledger-surface.mjs +26 -10
  41. package/src/tui/model-catalog.mjs +4 -4
  42. package/src/tui/model-picker.mjs +8 -7
  43. package/src/tui/mouse.mjs +11 -6
  44. package/src/tui/pickers.mjs +15 -2
  45. package/src/tui/render-conversation.mjs +1 -1
  46. package/src/tui/render-frame.mjs +10 -5
  47. package/src/tui/render-loop.mjs +1 -1
  48. package/src/tui/render-segments.mjs +3 -1
  49. package/src/tui/slash-commands.mjs +1 -1
  50. package/src/tui/startup.mjs +14 -14
  51. package/src/tui/subagent-blocks.mjs +20 -3
  52. package/src/tui/subagent-freeze.mjs +73 -2
  53. package/src/tui/suspension-drive.mjs +46 -22
  54. package/src/tui/tool-events.mjs +11 -8
  55. package/src/tui/wizard.mjs +3 -3
  56. package/src/abort-provenance.mjs +0 -116
  57. package/src/advisor/citations.mjs +0 -139
  58. package/src/advisor/compaction.mjs +0 -174
  59. package/src/advisor/convergence.mjs +0 -80
  60. package/src/advisor/history.mjs +0 -77
  61. package/src/advisor/loop.mjs +0 -293
  62. package/src/advisor/messages.mjs +0 -299
  63. package/src/advisor/project-context.mjs +0 -194
  64. package/src/advisor/repos.mjs +0 -150
  65. package/src/advisor/run.mjs +0 -293
  66. package/src/advisor/truncate.mjs +0 -57
  67. package/src/advisor.mjs +0 -290
  68. package/src/agent/completion.mjs +0 -146
  69. package/src/agent/dispatch.mjs +0 -489
  70. package/src/agent/helpers.mjs +0 -384
  71. package/src/agent/post-turn.mjs +0 -70
  72. package/src/agent/record-results.mjs +0 -174
  73. package/src/agent/relay-prefix.mjs +0 -39
  74. package/src/agent/run-stages.mjs +0 -244
  75. package/src/agent/setup-reminders.mjs +0 -69
  76. package/src/agent/setup.mjs +0 -354
  77. package/src/agent/spawn-child.mjs +0 -243
  78. package/src/agent-tools/advisor-async.mjs +0 -346
  79. package/src/agent-tools/advisor-settle.mjs +0 -231
  80. package/src/agent-tools/advisor.mjs +0 -260
  81. package/src/agent-tools/async-settle.mjs +0 -204
  82. package/src/agent-tools/batch-segment.mjs +0 -195
  83. package/src/agent-tools/consult.mjs +0 -473
  84. package/src/agent-tools/design-token.mjs +0 -117
  85. package/src/agent-tools/digest-budget.mjs +0 -76
  86. package/src/agent-tools/eng.mjs +0 -67
  87. package/src/agent-tools/escalate-async.mjs +0 -295
  88. package/src/agent-tools/goal.mjs +0 -119
  89. package/src/agent-tools/plan.mjs +0 -81
  90. package/src/agent-tools/read-history.mjs +0 -309
  91. package/src/agent-tools/recent-changes.mjs +0 -24
  92. package/src/agent-tools/review-streak.mjs +0 -93
  93. package/src/agent-tools/settings.mjs +0 -265
  94. package/src/agent-tools/skill.mjs +0 -47
  95. package/src/agent-tools/subagent-actions.mjs +0 -482
  96. package/src/agent-tools/subagent-async.mjs +0 -434
  97. package/src/agent-tools/subagent-panel.mjs +0 -160
  98. package/src/agent-tools/subagent-run.mjs +0 -205
  99. package/src/agent-tools/subagent-scheduler.mjs +0 -392
  100. package/src/agent-tools/subagent-spawn.mjs +0 -459
  101. package/src/agent-tools/subagent.mjs +0 -404
  102. package/src/agent-tools/task.mjs +0 -87
  103. package/src/agent-tools/timer.mjs +0 -46
  104. package/src/agent-tools/verify.mjs +0 -271
  105. package/src/agent-tools.mjs +0 -17
  106. package/src/agent.mjs +0 -417
  107. package/src/auto-think.mjs +0 -115
  108. package/src/config-migrate.mjs +0 -70
  109. package/src/config.mjs +0 -496
  110. package/src/context.mjs +0 -392
  111. package/src/conventions.mjs +0 -223
  112. package/src/embedding.mjs +0 -120
  113. package/src/escape.mjs +0 -152
  114. package/src/expand-home.mjs +0 -16
  115. package/src/explore-distill.mjs +0 -155
  116. package/src/generate-title.mjs +0 -88
  117. package/src/git/checkpoint.mjs +0 -448
  118. package/src/git/gitmem.mjs +0 -100
  119. package/src/hooks.mjs +0 -97
  120. package/src/ledger.mjs +0 -227
  121. package/src/log.mjs +0 -195
  122. package/src/markdown.mjs +0 -106
  123. package/src/mcp/helpers.mjs +0 -51
  124. package/src/mcp/transport-http.mjs +0 -248
  125. package/src/mcp/transport-stdio.mjs +0 -140
  126. package/src/mcp/transport-ws.mjs +0 -122
  127. package/src/mcp.mjs +0 -295
  128. package/src/memory/code-index.mjs +0 -219
  129. package/src/memory/code-sync.mjs +0 -415
  130. package/src/memory/core.mjs +0 -299
  131. package/src/memory/delete.mjs +0 -236
  132. package/src/memory/docs.mjs +0 -419
  133. package/src/memory/file-walk.mjs +0 -109
  134. package/src/memory/scan.mjs +0 -95
  135. package/src/memory/schema.mjs +0 -452
  136. package/src/memory.mjs +0 -21
  137. package/src/model-ref.mjs +0 -66
  138. package/src/model-specs.mjs +0 -179
  139. package/src/peer-domains.mjs +0 -265
  140. package/src/peer-instances.mjs +0 -231
  141. package/src/prompt-overlays.mjs +0 -82
  142. package/src/prompts/advisor-design.md +0 -41
  143. package/src/prompts/advisor-round1.md +0 -41
  144. package/src/prompts/advisor-round2.md +0 -46
  145. package/src/prompts/advisor-round3.md +0 -42
  146. package/src/prompts/common.md +0 -115
  147. package/src/prompts/consult-base.md +0 -19
  148. package/src/prompts/discipline-engineering.md +0 -258
  149. package/src/prompts/discipline-normal.md +0 -185
  150. package/src/prompts/persona-coder.md +0 -21
  151. package/src/prompts/persona-eng-coder.md +0 -37
  152. package/src/prompts/persona-eng-designer.md +0 -60
  153. package/src/prompts/persona-engineering.md +0 -55
  154. package/src/prompts/persona-explore.md +0 -15
  155. package/src/prompts/persona-normal.md +0 -27
  156. package/src/prompts/persona-plan.md +0 -26
  157. package/src/provider/anthropic.mjs +0 -225
  158. package/src/provider/core.mjs +0 -476
  159. package/src/provider/errors.mjs +0 -101
  160. package/src/provider/google.mjs +0 -257
  161. package/src/provider/index.mjs +0 -7
  162. package/src/provider/list-models.mjs +0 -93
  163. package/src/provider/normalize.mjs +0 -81
  164. package/src/provider/rate.mjs +0 -108
  165. package/src/provider/responses.mjs +0 -495
  166. package/src/provider/retry.mjs +0 -88
  167. package/src/provider/sse.mjs +0 -264
  168. package/src/proxy.mjs +0 -261
  169. package/src/rules.mjs +0 -53
  170. package/src/session-gc.mjs +0 -221
  171. package/src/session-guard.mjs +0 -59
  172. package/src/session-migrate.mjs +0 -48
  173. package/src/session-rename.mjs +0 -38
  174. package/src/session-segments.mjs +0 -100
  175. package/src/session-slots.mjs +0 -492
  176. package/src/session-store.mjs +0 -441
  177. package/src/session.mjs +0 -492
  178. package/src/skills.mjs +0 -153
  179. package/src/text-budget.mjs +0 -46
  180. package/src/token-ttl.mjs +0 -274
  181. package/src/tools/apply_patch.md +0 -15
  182. package/src/tools/bash.md +0 -37
  183. package/src/tools/bash.mjs +0 -268
  184. package/src/tools/checklist-sync.mjs +0 -181
  185. package/src/tools/checklist.md +0 -13
  186. package/src/tools/checklist.mjs +0 -299
  187. package/src/tools/delete.md +0 -13
  188. package/src/tools/edit-batch.mjs +0 -191
  189. package/src/tools/edit-diff.mjs +0 -348
  190. package/src/tools/edit.md +0 -30
  191. package/src/tools/execute.md +0 -21
  192. package/src/tools/execute.mjs +0 -228
  193. package/src/tools/fetch.md +0 -12
  194. package/src/tools/file.mjs +0 -469
  195. package/src/tools/file_ops.md +0 -17
  196. package/src/tools/get_current_time.md +0 -8
  197. package/src/tools/git-checkpoint.mjs +0 -143
  198. package/src/tools/git-ext.mjs +0 -173
  199. package/src/tools/git.md +0 -54
  200. package/src/tools/git.mjs +0 -356
  201. package/src/tools/glob-dialect.mjs +0 -130
  202. package/src/tools/glob.md +0 -11
  203. package/src/tools/grep.md +0 -19
  204. package/src/tools/hashline_edit.md +0 -14
  205. package/src/tools/index.mjs +0 -36
  206. package/src/tools/insert_after.md +0 -15
  207. package/src/tools/lint.md +0 -10
  208. package/src/tools/linter.mjs +0 -128
  209. package/src/tools/ls.md +0 -12
  210. package/src/tools/lsp.md +0 -10
  211. package/src/tools/lsp.mjs +0 -316
  212. package/src/tools/ops.mjs +0 -299
  213. package/src/tools/patch.mjs +0 -282
  214. package/src/tools/process.md +0 -10
  215. package/src/tools/question.md +0 -16
  216. package/src/tools/question.mjs +0 -26
  217. package/src/tools/read.md +0 -20
  218. package/src/tools/read_image.md +0 -8
  219. package/src/tools/repomap.mjs +0 -314
  220. package/src/tools/search.mjs +0 -236
  221. package/src/tools/shared.mjs +0 -446
  222. package/src/tools/tree.md +0 -14
  223. package/src/tools/tree.mjs +0 -66
  224. package/src/tools/wait_for.md +0 -22
  225. package/src/tools/web.mjs +0 -224
  226. package/src/tools/websearch.md +0 -16
  227. package/src/tools/write.md +0 -11
  228. package/src/traces/trace-store.mjs +0 -355
@@ -1,205 +0,0 @@
1
- /**
2
- * subagent-run.mjs — async spawn 执行器 executeAsyncSpawn(2026-09-05 module-split:
3
- * subagent.mjs 726 > 500 硬限——execute 的 async 分支 verbatim 迁入(闭包变量参数化:
4
- * parent/ctx/role/args + buildSpawnChild 产物),语义零变——subagent.mjs execute 调
5
- * 用(只此一处);§20 补位/排队刷新仍来自 subagent-scheduler.mjs。
6
- */
7
-
8
- import { ASYNC_POOL_LIMITS, poolDomainOf, poolLimitsFor, runningPoolCount } from "./subagent-async.mjs"
9
- import { runChildPipeline } from "./subagent-async.mjs"
10
- import { logEvent } from "../log.mjs"
11
- import { deathLine } from "../abort-provenance.mjs"
12
- import { pushReal } from "../context.mjs"
13
- import {
14
- describeBlockers, refreshQueuedTokens,
15
- } from "./subagent-scheduler.mjs"
16
- // ASYNC-RESULT-CONTAINER.md D3/D6:settle 公共收尾单点 + child signal 构建单点
17
- import { buildChildSignal, settleAsyncEntry } from "./async-settle.mjs"
18
-
19
- /**
20
- * SUBAGENT-OBSERVE-SEND D2:注入队列回合边界消费核心——把 entry._injected 全部消息按普通
21
- * user 回合推入子代理历史(pushReal → 下轮 chat 即含该指令)并清空队列。独立导出供测试
22
- * 直接锁该接缝(AC2——"子下回合边界收到并作普通 user 指令"的历史落点)。consumeInjected
23
- * 闭包即调用本函数。N2:不打断在跑工具——本函数只在回合边界(agent.mjs 循环头)被调。
24
- * @returns {number} 本次投递条数(空队列 0)
25
- */
26
- export function drainInjectedQueue(entry, agent) {
27
- const q = entry?._injected
28
- if (!Array.isArray(q) || q.length === 0) return 0
29
- const msgs = q.splice(0)
30
- for (const m of msgs) pushReal(agent, { role: "user", content: String(m) })
31
- return msgs.length
32
- }
33
-
34
- /**
35
- * Async branch (AGENT-LOOP.md §15 D-A1/D-A6): spawn without waiting.
36
- * The child runs the EXACT blocking pipeline (runChildPipeline — relay /
37
- * turn-cap / permission / MIN_REPORT_CHARS / mergeChildMutations all unchanged),
38
- * but the parent does not await it: the promise is parked in _asyncSubagents and
39
- * consumed by the auto channel (§19.8 — turn-end collection / suspension digest;
40
- * the check action is gone). Slot queue (§11.1 D-24a/R14 — 分域): the entry carries a
41
- * pool domain (_pool = poolDomainOf(role)); running count < limit[its domain]
42
- * (agent.poolLimits — default engCoder 4 / other 4) → start now; ≥ → enqueue
43
- * (status "queued", position = queue index) — never rejected, never requiring the
44
- * model to batch. Domains never block each other (engCoder pool full ≠ explore queued).
45
- * @returns {string} JSON ack {id, role, status: running|queued[, position][, waiting][, reason]}
46
- */
47
- export function executeAsyncSpawn(parent, ctx, role, args, child, input, childOpts, childRunOpts, relayPrefix, childProvider, files, dependsOn) {
48
- if ((ctx.depth ?? 0) > 0) {
49
- throw new Error("async spawn only available at the top level")
50
- }
51
- parent._asyncSubagents ??= new Map()
52
- parent._asyncQueue ??= []
53
- const id = parent._subAgentCounter
54
- const entry = {
55
- id, role, relayPrefix,
56
- // §11.1 D-24a/R14:池域字段(域判定单一事实源——poolDomainOf——role 枚举见
57
- // subagent.mjs ROLES;未知角色归 other)——running 计数/补位按域过滤。
58
- _pool: poolDomainOf(role),
59
- status: "queued", // 下面按等待态/槽位重定(避免两处判断漂移)
60
- position: undefined,
61
- report: null, error: null, done: false, cancelled: false,
62
- promise: null, _settle: null, _settleSeq: 0,
63
- // §19.5 D-M5 可决策字段(status 数据装配锚点):model 在 spawn 时记录;
64
- // startedAt 在 ACTUAL start(queued 等待不计 elapsed);turn/maxTurns 由
65
- // 下方 onToken 拦截层从子代理 ⟦ev⟧turn 事件镜像(T-M18 正确性断言)。
66
- model: childProvider?.model ?? null,
67
- startedAt: null,
68
- turn: 0, maxTurns: 0,
69
- // §19.5 D-M6 (round2 #2):条目级 AbortController——cancel 定向 abort 本
70
- // 条目(runAgent signal 链);Ctrl+C 全停语义不变(基信号 abort 逐链传播)。
71
- controller: null,
72
- // §20 D-SD2 域元数据(AGENT-LOOP.md §20):running ∪ queued 条目全带——
73
- // _files(归一化绝对路径)/ _dependsOn(字符串 id)——冲突检测与补位判据
74
- // 的事实源;无调度参数 spawn 两字段皆空(legacy——不参与冲突检测——零改动)。
75
- _files: files,
76
- _dependsOn: dependsOn,
77
- _lastQueuedSig: null, // ⟦ev⟧queued 去重 sig(refreshQueuedTokens)
78
- // SUBAGENT-OBSERVE-SEND D2:父侧 send 注入队列——父 action:'send' push 消息,子
79
- // 回合边界经 consumeInjected 回调消费(drain + pushReal 成 user 回合);settle 收尾
80
- // 时仍残留 = 未投递(消息入队后子在下一回合边界前 settle)→ 附 settle 报告提示。
81
- _injected: [],
82
- }
83
- // §20 D-SD3 准入落点:等待态(依赖未满足/域冲突/depc)→ queued(waiting-deps——
84
- // 不占槽不启动——即使槽空);纯槽满(kind slot)→ 按域计数判定(§11.1 D-24a:
85
- // runningIn(domain) < limit(domain)——跨域互不阻塞——每次入池判定时读配置)。
86
- const blockers = describeBlockers(parent, entry)
87
- if (blockers.kind === "slot") {
88
- const limits = poolLimitsFor(parent) // 运行期读 + 校验(非法键回退默认——T-24a4)
89
- entry.status = runningPoolCount(parent, entry._pool) >= (limits[entry._pool] ?? ASYNC_POOL_LIMITS[entry._pool])
90
- ? "queued" : "running"
91
- } else {
92
- entry.status = "queued" // waiting-deps / dependency-cancelled——slot 空也不启动
93
- }
94
- // The settle signal — resolves when the run chain settles (never rejects).
95
- entry.promise = new Promise((res) => { entry._settle = res })
96
- // §19.5 D-M6:条目 controller 链到会话/回合基信号(_sessionSignal 优先——
97
- // §17 挂起会话内 children 持会话 signal,digest 自身 Ctrl+C 不误伤)。
98
- // D6 buildChildSignal 单点(ASYNC-RESULT-CONTAINER.md)。
99
- const ctrl = new AbortController()
100
- entry.controller = ctrl
101
- const baseSignal = buildChildSignal(parent, ctx)
102
- if (baseSignal) {
103
- // §20.3 站点 #10(第 24 批):hop 逐跳保 reason
104
- if (baseSignal.aborted) ctrl.abort(baseSignal.reason)
105
- else baseSignal.addEventListener("abort", () => ctrl.abort(baseSignal.reason), { once: true })
106
- }
107
- // §19.5 D-M5:turn 镜像拦截层(callbacks 包装层——在既有
108
- // wrapChildCallbacks 之外再包一层,只解析 ⟦ev⟧turn 更新条目,其余原样转发)。
109
- const trackOpts = { ...childOpts }
110
- const parentOnToken = trackOpts.onToken
111
- if (parentOnToken) {
112
- trackOpts.onToken = (t) => {
113
- const ev = String(t).match(/^⟦ev⟧turn\x1e(\d+)\x1e(\d+)\x1e/)
114
- if (ev) {
115
- entry.turn = Number(ev[1]) || 0
116
- entry.maxTurns = Number(ev[2]) || 0
117
- }
118
- return parentOnToken(t)
119
- }
120
- // §27 R23 D-R23c1:嵌套 wrapper 标记随镜像层透传(wrapChildCallbacks 产物带
121
- // _relayPrefix——本层重包后丢失会让异步子代理(默认 async——depth-0)内嵌 spawn
122
- // 的生成侧补发射失效(emitNestedChildEvent 判据)——同步复制标记保语义)。
123
- trackOpts.onToken._relayPrefix = parentOnToken._relayPrefix ?? null
124
- }
125
- entry.start = () => {
126
- entry.status = "running"
127
- entry.position = undefined
128
- entry.startedAt = Date.now()
129
- // §19.5.6 D-SF1(round3 #1):绑定子代理对象引用——绑定时刻 = 实际启动时
130
- // (queued 条目 spawn-ack 时刻尚无子代理对象——§20 D-SD3b);绑定对象 = 子代理
131
- // 对象(不是 _touchedFiles 数组引用——per-run 记账在 prepareRun 重置——数组
132
- // 引用会陈旧——对象引用保证 status 查询时实时读——杀前一刻最新)。
133
- entry.childAgent = child
134
- // SUBAGENT-OBSERVE-SEND D2:子侧输入源贯通(设计"硬缺口"闭合)——把"注入队列消费
135
- // 回调"经 childRunOpts 塞进 runAgent opts(runChildPipeline → runWithContinue →
136
- // runAgent),子回合边界(agent.mjs 每轮开头的 consumeInjected?.() 点)消费
137
- // entry._injected → pushReal 成 user 回合进子历史——当作普通用户指令处理。回调闭包
138
- // 持 entry + child;空队列 no-op(每轮尝试——零开销)。N2:不打断在跑工具——入队
139
- // 消息只在下一回合边界(当前工具完成后的下轮 chat 前)进上下文。
140
- const consumeInjected = (ag) => { drainInjectedQueue(entry, ag ?? child) }
141
- // §19.5 D-M7b ①: async 标记事件——零字段 ⟦ev⟧async token(sync 不发)。
142
- // 锚点 = 实际启动(与 [model] 同步——queued 入队不 paint,补位启动才发);
143
- // 先于 [model] 发出——区块创建即知 sub.async(routeSubToken 解析——
144
- // ⏹ 门控与头标 async 的判定源)。父级直接 emit(depth-0 专属路径——
145
- // 不经子代理文本 strip 白名单——与 ⟦ev⟧stopped/settled 同族)。
146
- ctx.callbacks?.onToken?.(relayPrefix + "⟦ev⟧async\x1e")
147
- // Deferred [model] emit: the TUI block is created at ACTUAL start.
148
- ctx.callbacks?.onToken?.(relayPrefix + "[model]" + (childProvider.model ?? ""))
149
- // Turn-cap on background children NEVER pops the continue panel (D-A3):
150
- // §15 D-A3 exception (2026-09-02 unified rule, AGENT-LOOP.md §2): in an
151
- // engineering && AUTO session the child auto-resumes — the user authorized
152
- // unattended runs, no one is at the panel. Every other tier auto-declines
153
- // and the partial-work report carries the cap reason. §18 D-E2 relies on
154
- // this exception as the turn-cap fallback for the default-async eng-coder
155
- // delivery (the internal protocol does not raise the 100-turn cap).
156
- runChildPipeline(child, input, trackOpts, { ...childRunOpts, signal: entry.controller.signal, consumeInjected }, {
157
- parent, role, args,
158
- askContinue: () => Promise.resolve(Boolean(parent.config?.agent?.engineering && parent.autoApprove)),
159
- })
160
- .then((report) => { entry.report = report })
161
- // §20.3 第 3 条合成器(第 24 批):原 message 前缀逐字保留 + 来源后缀
162
- .catch((err) => { entry.error = deathLine(err, entry.controller?.signal) })
163
- .finally(() => {
164
- // SUBAGENT-OBSERVE-SEND D3(send→settle 竞态):settle 收尾时 _injected 仍残留
165
- // = 消息入队后子代理在下一回合边界前 settle——未投递——附 settle 报告/错误提示
166
- // (防父误以为引导已落地)。error 路径附 error;报告路径附 report 尾。
167
- const undelivered = Array.isArray(entry._injected) ? entry._injected.length : 0
168
- if (undelivered > 0) {
169
- const note = `\n[note: ${undelivered} message(s) queued via subagent action:'send' were NOT delivered — the subagent settled before its next turn boundary; re-spawn with the direction if it still applies.]`
170
- if (entry.error != null) entry.error += note
171
- else entry.report = `${entry.report ?? ""}${note}`
172
- entry._injected = [] // 子已 settle——消费面终——清空防重复提示(提示已随报告携带)
173
- }
174
- // settle 公共收尾单点(ASYNC-RESULT-CONTAINER.md D3——settleAsyncEntry):日志三连
175
- // (ev:cancelled/child:done|error/ev:settled)/cancelled 分支(出池+墓碑+⟦ev⟧stopped
176
- // +提醒)/挂起分流(pending 单容器+出池——统一守卫 !parentAborted——D4)/公共尾部
177
- // (settleSeq/_settle/唤醒 waiter + 腾槽补位——helper 尾部恒补——见 async-settle.mjs)。
178
- settleAsyncEntry(parent, entry, {
179
- pool: parent._asyncSubagents,
180
- ctx,
181
- })
182
- })
183
- }
184
- parent._asyncSubagents.set(String(id), entry)
185
- // LOGGING(LOGGING.md):child:spawn(async——注册即事件;status 记 queued/running 分流;
186
- // 实际启动由补位 start() 触发——运行中由子内 llm/tool 事件可见)
187
- logEvent("child:spawn", { role, id: `${role}#${id}`, kind: "async", status: entry.status, ms: 0 })
188
- if (entry.status === "queued") {
189
- parent._asyncQueue.push(entry)
190
- entry.position = parent._asyncQueue.length
191
- // §20 D-SD3b:排队 spawn 返回即建面板 waiting 块(⟦ev⟧queued 事件——spawn 侧
192
- // 发——TUI routeSubToken 消费建块/更新头;启动后 ⟦ev⟧async 转 running——同 key
193
- // 不重建)。refreshQueuedTokens 同时校正既有排队条目的位置/等待态头。
194
- refreshQueuedTokens(parent, ctx.callbacks?.onToken)
195
- const blk = describeBlockers(parent, entry)
196
- const out = { id: String(id), role, status: "queued", position: entry.position }
197
- if (blk.kind !== "slot") {
198
- out.waiting = blk.kind === "depc" ? "dependency-cancelled" : "waiting-deps"
199
- out.reason = blk.detail
200
- }
201
- return JSON.stringify(out)
202
- }
203
- entry.start()
204
- return JSON.stringify({ id: String(id), role, status: "running" })
205
- }
@@ -1,392 +0,0 @@
1
- /**
2
- * subagent-scheduler.mjs — §20 子 agent 任务调度器 + 文件域组(2026-09-05 自
3
- * subagent-async.mjs 拆分——Module Split Policy §20.9——纯迁移零行为变化——
4
- * AGENT-LOOP.md §20 D-SD1..SD5 + §21.1 D-SL1 环形死锁修正)。
5
- * 内容:normalizeFileList / filesOverlap / effectiveFiles(SCHEDULER-DYNAMIC-DOMAIN
6
- * 动态域——声明 ∪ running touched)/ depInfo / describeBlockers / detectStall(§21.1
7
- * P-SL2 停滞机械检测)/ queueRunnable / assertNoDepCycle / dependentLabels /
8
- * refreshQueuedTokens / maybeRefillAsync。
9
- * ASYNC_POOL_LIMITS/poolLimitsFor/runningPoolCount 回引自 subagent-async.mjs(主体保有——
10
- * 仅调用期使用——与主体对此处调度符号的回引构成惰性环——无求值期依赖)。
11
- */
12
- import { basename, isAbsolute, relative, resolve } from "node:path"
13
- import { existsSync, statSync } from "node:fs"
14
- import { poolLimitsFor, runningPoolCount, ASYNC_POOL_LIMITS } from "./subagent-async.mjs"
15
- // ASYNC-RESULT-CONTAINER.md D1:池 accessor——async-settle.mjs 反向 import 本模块
16
- // (dependentLabels)构成同款惰性环(函数级绑定——无求值期依赖)。
17
- import { getAsyncPool } from "./async-settle.mjs"
18
-
19
- // ═══════════════════════════════════════════════════════════════════════════
20
- // §20 子 agent 任务调度器(AGENT-LOOP.md §20——D-SD1..SD5 + 20.4 处置注)
21
- // 池条目域元数据(D-SD2:entry._files/_dependsOn——running ∪ queued 全带)、准入
22
- // (D-SD3:域冲突/依赖未满足 → queued 等位)、补位扫描(D-SD4:最早可启动——
23
- // 依赖全满足 + 域无冲突——waiting 越行不阻塞 slot 位)、释放规则(D-SD5——round2
24
- // #3 锁定默认:依赖取消/失败 → 依赖者留 queued 标 dependency cancelled——仅父显式
25
- // 处置或 AUTO 自动启动)、终态墓碑(round1 #8/T-SD14:自动通道注入消费与取消写墓碑——
26
- // consumed 视为满足;非 consumed unknown id 才拒)。状态全部派生不存储(单点事实)。
27
- // ═══════════════════════════════════════════════════════════════════════════
28
-
29
- /** 文件域归一化(round1 #5——路径归一化再交集):相对 cwd 解析为绝对路径 + 去重;
30
- * 非字符串/空项静默跳过(声明错误 = false-negative 明示风险——v1 边界)。
31
- * §20.8 D-F1.1(2026-09-04):目录声明检测——fail-closed——尾斜杠形态 / 指向既有目录
32
- * → throw(含路径——错误字符串英文定稿)——目录声明静默绕过冲突检测的通道闭合;
33
- * 调用方(subagent.mjs spawn 入口)catch → 错误即工具结果(模型可见——无静默)。
34
- * 已知限制(§20.8 未编号段——评审 #4):不存在的目录声明(无尾斜杠 + 目录未创建)仍通过——不处理。
35
- * §28 R26 F-R26b(2026-09-07):父侧维护文件黑名单——归一化后 basename 全名匹配 +
36
- * 大小写不敏感(todo.md/changelog.md/checklist.md 精确 + checklist* 前缀家族——路径任意
37
- * 层含 docs/、根、.thincoder/)——命中 → throw(fail-closed——先于调度器准入——无排队
38
- * 残留——错误即工具结果);提示列出全部违规条目——英文模板逐字定稿(AGENT-LOOP.md §28)。 */
39
- export function normalizeFileList(files, cwd) {
40
- const out = []
41
- const violations = [] // §28 R26 F-R26b:父侧维护文件命中(保留声明原样——提示可读)
42
- for (const f of Array.isArray(files) ? files : []) {
43
- if (typeof f !== "string" || !f.trim()) continue
44
- if (f.trimEnd().endsWith("/") || f.trimEnd().endsWith("\\")) { // 2.7 批:尾随空格目录声明("test/ ")同拒
45
- throw new Error(`files must be file-level paths — directory declarations are not supported: ${f}`)
46
- }
47
- const abs = resolve(cwd ?? process.cwd(), f)
48
- if (existsSync(abs) && statSync(abs).isDirectory()) {
49
- throw new Error(`files must be file-level paths — directory declarations are not supported: ${f}`)
50
- }
51
- // 黑名单 basename 推导前做分隔符归一(\ → /——反斜杠变体跨平台同拒——
52
- // win32 resolve 本就兼容双分隔符——POSIX 需显式归一——advisor 🔵2 处置)
53
- const base = basename(resolve(cwd ?? process.cwd(), f.replace(/\\/g, "/"))).toLowerCase()
54
- if (base === "todo.md" || base === "changelog.md" || base.startsWith("checklist")) violations.push(f)
55
- if (!out.includes(abs)) out.push(abs)
56
- }
57
- if (violations.length > 0) {
58
- throw new Error(violations
59
- .map((f) => `Parent-side maintained file ${f} must not be listed in files — reconciliation is the parent's duty; use the design-doc path if you need to edit a design doc`)
60
- .join("\n"))
61
- }
62
- return out
63
- }
64
-
65
- /** 文件域相等比较键:Windows 大小写不敏感(vs Uri.fsPath 小写盘符差异同族——
66
- * normalizeCwd 先例)——src/x vs ./src/X 在 win32 是同一文件。 */
67
- const fileKey = (p) => (process.platform === "win32" ? p.toLowerCase() : p)
68
-
69
- /** 两文件域首个共同文件(比较键)——无交集 null。 */
70
- export function filesOverlap(a, b) {
71
- if (!a?.length || !b?.length) return null
72
- const keys = new Set(b.map(fileKey))
73
- const hit = a.map(fileKey).find((k) => keys.has(k))
74
- return hit ?? null
75
- }
76
-
77
- /** 冲突文件的显示形态(优先相对 cwd——面板/返回文本可读)。 */
78
- function showFile(parent, key) {
79
- const cwd = parent.cwd ?? process.cwd()
80
- const rel = relative(cwd, key)
81
- return rel && !rel.startsWith("..") && !isAbsolute(rel) ? rel : key
82
- }
83
-
84
- /** 有效文件域(SCHEDULER-DYNAMIC-DOMAIN 2026-09-09——动态域 = 声明 ∪ 运行中实际写入):
85
- * running 且已绑 childAgent → 声明域 ∪ childAgent._touchedFiles(写工具批提交实时记录
86
- * ——绝对路径与 normalizeFileList 同源——fileKey/filesOverlap 键空间零改动);去重按
87
- * fileKey。queued 无 childAgent(start 才绑——VSC 首 onAgentTurn 才绑)——天然只声明域
88
- * (`?.` null 安全——既有无 childAgent 用例零行为变化)。 */
89
- export function effectiveFiles(e) {
90
- const declared = e._files ?? []
91
- if (e.status !== "running" || !e.childAgent) return declared
92
- const out = [...declared]
93
- const seen = new Set(declared.map(fileKey))
94
- for (const f of e.childAgent._touchedFiles ?? []) {
95
- const k = fileKey(f)
96
- if (!seen.has(k)) { seen.add(k); out.push(f) }
97
- }
98
- return out
99
- }
100
-
101
- /**
102
- * §20 依赖终态查询(单点事实——池条目 / pending(挂起期 settle 移交——注入前)/
103
- * 终态墓碑(自动通道注入消费——consumed;取消/失败——D-SD5 分支)):
104
- * - ok = settle 成功(报告已产出)/ consumed(自动通道注入消费——T-SD14 视为满足)
105
- * - pending = running/queued 未终态(等启动/等完成)
106
- * - failed / cancelled = 终态但非成功——依赖者走 dependency cancelled 分支(round2 #3)
107
- * - unknown = 从未存在(spawn 时明确错误——非 consumed 的 unknown 拒——T-SD10)
108
- */
109
- export function depInfo(parent, id) {
110
- const key = String(id)
111
- const e = getAsyncPool(parent, "subagent")?.get(key)
112
- if (e) {
113
- if (e.cancelled) return { state: "cancelled", role: e.role }
114
- if (e.done) return e.error != null ? { state: "failed", role: e.role } : { state: "ok", role: e.role }
115
- return { state: "pending", role: e.role }
116
- }
117
- // ASYNC-RESULT-CONTAINER.md D2:pending 单容器(四族统一停靠——依赖目标挂起期 settle
118
- // 移交也在此——注入前视为已消费)。
119
- const pend = (parent._pendingAsyncResults ?? []).find((x) => String(x.id) === key)
120
- if (pend) return pend.error != null ? { state: "failed", role: pend.role } : { state: "ok", role: pend.role }
121
- const t = parent._asyncTombstones?.get(key)
122
- if (t) return { state: t.status === "cancelled" || t.status === "failed" ? t.status : "ok", role: t.role }
123
- return { state: "unknown", role: null }
124
- }
125
-
126
- /** §20 等待态派生(无存储——refill/status/面板/spawn 返回同一事实源)。kind:
127
- * - slot = 无阻塞(依赖全满足 + 域无冲突)——纯槽满等位(可启动——等 slot)
128
- * - wait = 依赖未完成 / 域冲突(running ∪ queued——D-SD3 同界——self 除外)
129
- * - depc = 依赖取消/失败(round2 #3——非 AUTO 锁住——需父显式处置;AUTO 视为可启动)
130
- * detail 为状态行共享文本(面板 waiting for 标注 / status reason / spawn reason)。 */
131
- export function describeBlockers(parent, entry) {
132
- const wait = []
133
- const depc = []
134
- for (const depId of entry._dependsOn ?? []) {
135
- const info = depInfo(parent, String(depId))
136
- if (info.state === "pending" || info.state === "unknown") {
137
- wait.push(`${info.role ?? "sub"}#${depId}(依赖未完成)`)
138
- } else if (info.state === "cancelled" || info.state === "failed") {
139
- if (parent.autoApprove) continue // AUTO 档自动启动(D-SD5——父不在场由 digest 决策)
140
- depc.push(`${info.role ?? "sub"}#${depId}`)
141
- }
142
- }
143
- const myFiles = entry._files ?? []
144
- if (myFiles.length > 0) {
145
- for (const e of parent._asyncSubagents?.values() ?? []) {
146
- if (e === entry) continue
147
- if (e.status !== "running" && e.status !== "queued") continue
148
- // SCHEDULER-DYNAMIC-DOMAIN(2026-09-09):他条目域 = effectiveFiles(e)(声明 ∪
149
- // running 实际 touched);命中仅来自 touched(∉ 声明域)→ 加注"运行中实际写入"
150
- // ——纯声明命中文案不回归(评审 #7 重叠优先级:声明∩touched 同文件不加注)。
151
- const hitDeclared = filesOverlap(myFiles, e._files ?? [])
152
- const hit = hitDeclared ?? filesOverlap(myFiles, effectiveFiles(e))
153
- if (!hit) continue
154
- // §21.1 D-SL1.2(环形死锁修正——与 queueRunnable 同界——展示一致):后入
155
- // 者(spawn 序晚于我——数字 id 比较)不列——只列"会真正阻断我的"(running
156
- // 任意序 + 先入 queued);列后入者 = 误导"等一个其实等不到的人"。
157
- if (e.status === "queued" && Number(e.id) > Number(entry.id)) continue
158
- wait.push(`${e.role}#${e.id}(域冲突 ${showFile(parent, hit)}${hitDeclared ? "" : "(运行中实际写入)"})`)
159
- }
160
- }
161
- // 长列表裁剪(块头宽度预算——细节 status 可查全量)
162
- const cut = (arr) => (arr.length > 3 ? [...arr.slice(0, 3), `…(共 ${arr.length} 项)`] : arr)
163
- if (depc.length > 0) {
164
- const body = cut(depc).join("、")
165
- return { kind: "depc", detail: wait.length > 0 ? `dependency cancelled: ${body};${cut(wait).join("、")}` : `dependency cancelled: ${body} — waiting for your decision (cancel this task to release, or AUTO starts it)` }
166
- }
167
- if (wait.length > 0) return { kind: "wait", detail: `waiting for: ${cut(wait).join("、")}` }
168
- return { kind: "slot", detail: "" }
169
- }
170
-
171
- /** §21.1 P-SL2(D-SL2——混合边环形等待停滞机械检测——AGENT-LOOP.md §21.1 扩展注):
172
- * 判据(收窄——零误报优先——宁可漏报不可误打断):池内 running = 0 && queued ≥ 2 &&
173
- * 无 dependency-cancelled 标记条目 && 每 queued 的 blocker(files 冲突者 + 未 settle
174
- * 依赖目标——与 describeBlockers/queueRunnable 同界——"真正会阻断我的"语义:files 只
175
- * 算 running 任意序 + 先入 queued(D-SL1.1 序判定);依赖 pending = 池内未终态)⊆
176
- * queued 集且非空(闭包无外逃 + 无 runnable 漏网)→ 停滞。返回 { chains }(每 queued
177
- * 条目一条阻塞链——沿首个 blocker 走到首个重复节点(闭环)——每节点自带"等谁 + 为何等"
178
- * 理由注(`X(reason) → Y` 形态——X 等 Y 因 reason);不满足 → null。
179
- * 不报(F-SL2.2 收窄判据):running 锚点存在(依赖链/文件串行正常排队);depc 滞留
180
- * (外部决策可解——§20 NF-SD 滞留有意——cancel 先入者即释放);单 queued;blocker
181
- * 外逃(unknown 依赖目标/池外条目);blocker 空(runnable——settle/cancel 驱动 refill
182
- * 会启动——非停滞)。自然流程中 wait 边恒指向先入者(依赖必须先前 spawn——unknown 拒 +
183
- * 文件冲突只阻断后入者——id 序)——混合环仅人工注入可构造(T-SD5 同族防御断言)——
184
- * 但状态既可能成环即机械可检——不依赖可达性论证。maybeRefillAsync 空转处不调用:refill
185
- * 嵌在 settle/cancel 链上无模型可见输出通道(抛错即破坏池操作)——status 视图(actions
186
- * 模块)即 F-SL2 的报错/标记落点(§19.8:check 守卫随 check 删除)。 */
187
- export const STALL_NOTE = "cancel one task in the loop (action:'cancel') to break the cycle, then re-spawn it (AGENT-LOOP.md §21.1 P-SL2)"
188
-
189
- export function detectStall(parent) {
190
- const map = parent._asyncSubagents
191
- if (!(map instanceof Map) || map.size === 0) return null
192
- const all = [...map.values()]
193
- if (all.some((e) => e.status === "running")) return null // ① running 锚点——正常排队不报
194
- const queued = all.filter((e) => e.status === "queued" && !e.cancelled)
195
- if (queued.length < 2) return null // ② 单 queued——非停滞不报
196
- // ③ 每 queued 的结构化 blocker 表(阻塞边 + 理由——镜像 describeBlockers 同界:
197
- // 依赖 pending/unknown 阻断(cancelled/failed 非 AUTO = depc 标记——整池不报);
198
- // files 冲突 running 任意序 + 先入 queued——后入者不阻断(D-SL1.1 同判)。
199
- const edgesOf = new Map()
200
- for (const q of queued) {
201
- const list = []
202
- for (const depId of q._dependsOn ?? []) {
203
- const st = depInfo(parent, String(depId)).state
204
- if (st === "pending") {
205
- list.push({ to: map.get(String(depId)), reason: `dependsOn ${String(depId)}` })
206
- } else if (st === "unknown") {
207
- return null // 依赖目标池外(unknown)——外逃 blocker——不报(保守)
208
- } else if (!parent.autoApprove) {
209
- return null // dep-cancelled/failed 标记条目——外部决策可解——不报(F-SL2.2)
210
- }
211
- }
212
- const myFiles = q._files ?? []
213
- if (myFiles.length > 0) {
214
- for (const e of all) {
215
- if (e === q) continue
216
- if (e.status !== "running" && e.status !== "queued") continue
217
- const hit = filesOverlap(myFiles, effectiveFiles(e)) // 动态域(running 锚点守卫下零增量——读法同界防御一致)
218
- if (!hit) continue
219
- if (e.status === "queued" && Number(e.id) > Number(q.id)) continue // 后入不阻断
220
- list.push({ to: e, reason: `files ${showFile(parent, hit)}——先入者` })
221
- }
222
- }
223
- if (list.length === 0) return null // ④ 无 blocker = runnable——refill 会启动——非停滞
224
- edgesOf.set(q, list)
225
- }
226
- // ⑤ 闭包无外逃:任一 blocker 落 queued 集外(含 cancelled/池外异常形态)→ 不报
227
- for (const list of edgesOf.values()) {
228
- for (const b of list) {
229
- if (b.to == null || !queued.includes(b.to)) return null
230
- }
231
- }
232
- // 链组装:每 queued 条目一条——沿首个 blocker 走到首个重复节点(闭环)——每节点
233
- // 自带"我等谁 + 为何等"段(`X(reason) → Y`——本节点 blocker 理由注于本节点旁——
234
- // 读取无歧义:X 等 Y 因为 reason——dependsOn 边不误读为目标属性——§21.1 扩展注
235
- // 示例同信息形态——闭环以起始节点重复闭合(末节点不再注——闭合自明)。
236
- const chains = []
237
- for (const start of queued) {
238
- const seen = []
239
- let cur = start
240
- for (;;) {
241
- seen.push(cur)
242
- const next = edgesOf.get(cur)?.[0]?.to
243
- if (!next) break // 防御:预检保证不达(每节点 blocker 非空闭包内)
244
- if (seen.includes(next)) { seen.push(next); break } // 闭环:重复节点入链闭合
245
- cur = next
246
- }
247
- const frags = []
248
- for (let i = 0; i < seen.length; i++) {
249
- const edge = i < seen.length - 1 ? edgesOf.get(seen[i])?.[0] : null // 末节点=闭环重复——不再注
250
- frags.push(`${seen[i].role}#${seen[i].id}${edge ? `(${edge.reason})` : ""}`)
251
- }
252
- chains.push({ task: start, text: frags.join(" → ") })
253
- }
254
- return { chains }
255
- }
256
-
257
-
258
- /** §20 D-SD4 补位判据:依赖全满足(AUTO 下 depc 放行)+ 域无冲突(running 任意序 +
259
- * queued 先入者——§21.1 D-SL1.1 序判定:同文件串行 = 先入者先启动、后入者等先入者
260
- * ——不自锁;先入者启动后以 running 身份继续挡住后入者——self 除外)。
261
- * 已知限制(§21.1 评审 #4——与 §20 NF-SD 同语义——滞留有意义不静默):先入者被
262
- * depc 锁定时(依赖取消/失败且非 AUTO——永不自动启动),后入者滞留等它——cancel
263
- * 先入者即释放(父显式可清;AUTO 档 depc 视为可启动——不滞留)。 */
264
- export function queueRunnable(parent, entry) {
265
- for (const depId of entry._dependsOn ?? []) {
266
- const state = depInfo(parent, String(depId)).state
267
- if (state === "pending" || state === "unknown") return false
268
- if ((state === "cancelled" || state === "failed") && !parent.autoApprove) return false
269
- }
270
- const myFiles = entry._files ?? []
271
- if (myFiles.length > 0) {
272
- for (const e of parent._asyncSubagents?.values() ?? []) {
273
- if (e === entry) continue
274
- if (e.status !== "running" && e.status !== "queued") continue
275
- if (!filesOverlap(myFiles, effectiveFiles(e))) continue // 动态域:声明 ∪ running touched
276
- // §21.1 D-SL1.1 序判定:queued 仅"先入者"(spawn 序早于我——数字 id 比较)阻断;
277
- // 后入者不阻断——先入者先启动——两个 queued 同文件不再互等(环形死锁修正)。
278
- // 防御(评审 #3——id 形态):池条目 id 为数字递增(_subAgentCounter——已核实);
279
- // 异常形态 Number() 得 NaN → 比较 false → 不跳过 → 保守阻断(宁可多等——
280
- // 不冒险并发——防 NaN 误放行)。
281
- if (e.status === "queued" && Number(e.id) > Number(entry.id)) continue // 后入者不阻断——先入者先启动
282
- return false
283
- }
284
- }
285
- return true
286
- }
287
-
288
- /** §20 D-SD5 环防御(round2 #5——自然流程不可达:unknown id 拒 + spawn 序天然无环——
289
- * 仅人工向池注入可构造——防御断言定位):从新 spawn 的依赖集出发沿池内条目
290
- * _dependsOn 边做路径 DFS——路径上重复访问(可达环)→ 拒绝(A→B→A 永不自启——
291
- * 错误明确——T-SD5)。运行/排队条目皆可成环节点;池小(≤4 槽 + 有限队列)深度有限。 */
292
- export function assertNoDepCycle(parent, dependsOn) {
293
- const edges = new Map()
294
- for (const e of parent._asyncSubagents?.values() ?? []) {
295
- if (e.status === "running" || e.status === "queued") {
296
- edges.set(String(e.id), (e._dependsOn ?? []).map(String))
297
- }
298
- }
299
- const onPath = new Set()
300
- const visit = (id) => {
301
- if (onPath.has(id)) {
302
- throw new Error(`subagent dependsOn cycle detected: ${[...onPath, id].join(" → ")} — entries in a dependency loop can never start; cancel the dependents and restructure the chain (AGENT-LOOP.md §20 D-SD5)`)
303
- }
304
- onPath.add(id)
305
- for (const dep of edges.get(id) ?? []) visit(dep)
306
- onPath.delete(id)
307
- }
308
- for (const d of dependsOn) visit(String(d))
309
- }
310
-
311
- /** 依赖某 id 的 queued 条目显示标签(D-SD5 提醒/标注——依赖者列表)。 */
312
- export function dependentLabels(parent, depId) {
313
- const key = String(depId)
314
- const out = []
315
- for (const e of parent._asyncQueue ?? []) {
316
- if ((e._dependsOn ?? []).some((d) => String(d) === key)) out.push(`${e.role}#${e.id}`)
317
- }
318
- return out
319
- }
320
-
321
- /** §20 D-SD3b 排队态面板刷新(⟦ev⟧queued 事件族——TUI routeSubToken 消费):对全部
322
- * queued 条目重算等待态并发射变化(去重 sig——kind/position/detail 全变才发)——
323
- * 调用点 = 一切队列突变与等待态变迁(spawn 入队 / settle 后补位与依赖转移 / cancel
324
- * 出队 / 自动通道消费)。position = 队列序(D-A1 既有——cancel 前移同源)。 */
325
- export function refreshQueuedTokens(parent, onToken) {
326
- if (typeof onToken !== "function") return
327
- const queue = parent._asyncQueue ?? []
328
- for (let i = 0; i < queue.length; i++) {
329
- const e = queue[i]
330
- const blk = describeBlockers(parent, e)
331
- const sig = `${blk.kind}\x1e${i + 1}\x1e${blk.detail}`
332
- if (e._lastQueuedSig === sig) continue
333
- e._lastQueuedSig = sig
334
- try {
335
- onToken(`${e.relayPrefix}⟦ev⟧queued\x1e${blk.kind}\x1e${i + 1}\x1equeued\x1e${blk.detail}`)
336
- } catch { /* relay 失败不影响池状态 */ }
337
- }
338
- }
339
-
340
- /**
341
- * Slot-queue refill (AGENT-LOOP.md §15 D-A1/D-A6 + §20 D-SD4 + §11.1 D-24a/R14 分域):
342
- * start queue heads while a running slot is free — called from every settle
343
- * (completion frees a slot) and from the turn-end collection's refill loop. §20:
344
- * 队列现可混合 waiting-deps 与 slot-queued——扫描选"依赖全满足 + 域无冲突"的最早
345
- * 条目启动(waiting 越行不阻塞槽位;多任务同时解除按 queued 序逐个启动)。
346
- * §11.1 D-24a(R14):槽位判定按域——条目 _pool 域内 running 数 < 该域上限才启动
347
- * (同域仍 4——纯单域队列行为与旧 shift 完全一致;跨域总量 8——各域独立腾槽,
348
- * 互不阻塞)。配置每次补位时读(poolLimitsFor——变更即生效下个补位)。
349
- */
350
- export function maybeRefillAsync(parent) {
351
- const queue = parent._asyncQueue ?? []
352
- for (;;) {
353
- let pick = -1
354
- for (let i = 0; i < queue.length; i++) {
355
- const e = queue[i]
356
- if (!queueRunnable(parent, e)) continue
357
- const pool = e._pool ?? "other" // 缺域字段(手工/旧条目)按 other——既有测试语义不变
358
- if (runningPoolCount(parent, pool) >= (poolLimitsFor(parent)[pool] ?? ASYNC_POOL_LIMITS[pool])) continue
359
- pick = i
360
- break
361
- }
362
- if (pick < 0) return
363
- queue.splice(pick, 1)[0].start()
364
- }
365
- }
366
-
367
- /**
368
- * 分配下一子代理 id——池活续号兜底(SUBAGENT-ID-COUNTER-AGENT,2026-09-09——双端同构
369
- * 机制:VSC 端载体自 history expando 移本体并接本函数;CLI 端计数器一直挂 agent 本体
370
- * (`_subAgentCounter`——per-run reset 清单不含——跨 run/跨压缩存活),本函数补齐
371
- * poolMax 兜底:计数器丢失面(AUTO 撞上限续跑/挂起驱动的重建形态)不再复用仍在
372
- * 跑/排队的条目 id——map.set 覆盖旧条目 = 静默丢报告 + status/cancel 错址)。优先级
373
- * next = max(counter ?? 0, poolMax) + 1——取号后 counter 同步(首取号初始化)。id 作用
374
- * 域 = 进程内(不做槽持久化——reload 后池清块消失,新进程从 1 无冲突——设计范围边界)。
375
- * spawn(subagent-spawn.mjs async 分支)、escalate(escalate-async.mjs)、async-advisor
376
- * 池(advisor-async.mjs——§11.2 跨池共号)共用;executeAsyncSpawn 直读 counter(分配与
377
- * 消费同步——无 await 间隙)。CLI 两池键均为字符串(set(String(id))——解析分支防御保留)。
378
- * @returns {number} 全池唯一的下一 id(单调——进程内)
379
- */
380
- export function nextSubagentId(parent) {
381
- let poolMax = 0
382
- for (const pool of [parent?._asyncSubagents, parent?._asyncAdvisors]) {
383
- if (!pool || pool.size === 0) continue
384
- for (const k of pool.keys()) {
385
- const n = typeof k === "number" ? k : Number.parseInt(k, 10)
386
- if (Number.isFinite(n) && n > poolMax) poolMax = n
387
- }
388
- }
389
- const next = Math.max(parent?._subAgentCounter ?? 0, poolMax) + 1
390
- parent._subAgentCounter = next
391
- return next
392
- }