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