dsh-extra-plan 0.0.0-stage → 1.7.0

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 (56) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +179 -2
  3. package/assets/presets/extra-plan/agent.cordis.yml +580 -0
  4. package/assets/presets/extra-plan/preset-definition-extra-plan-executor.generated.yml +115 -0
  5. package/assets/presets/extra-plan/preset-definition-extra-plan-planner.generated.yml +113 -0
  6. package/assets/presets/extra-plan/preset-definition-extra-plan-prober.generated.yml +107 -0
  7. package/assets/presets/extra-plan/preset-definition-extra-plan-reviewer.generated.yml +115 -0
  8. package/assets/presets/extra-plan/preset-definition.generated.yml +335 -0
  9. package/assets/presets/extra-plan/preset.yml +2 -0
  10. package/cordis.patch.yml +7 -0
  11. package/index.js +1671 -0
  12. package/lib/agent-runtime.js +172 -0
  13. package/lib/agent-session.js +65 -0
  14. package/lib/assembly-presentation.js +267 -0
  15. package/lib/client-carrier.js +7 -0
  16. package/lib/client.js +314 -0
  17. package/lib/extra-plan-gate-tool.js +387 -0
  18. package/lib/gate-decisions.js +744 -0
  19. package/lib/gate-words.js +108 -0
  20. package/lib/live-config.js +293 -0
  21. package/lib/log-retention.js +132 -0
  22. package/lib/model-routing.js +648 -0
  23. package/lib/path-policy.js +464 -0
  24. package/lib/plan-draft-tool.js +294 -0
  25. package/lib/planner-budget.js +136 -0
  26. package/lib/preset-defaults.generated.js +17 -0
  27. package/lib/preset-settings.js +3 -0
  28. package/lib/preset-sync.js +809 -0
  29. package/lib/preset-yaml.js +438 -0
  30. package/lib/role-contract.js +11 -0
  31. package/lib/run-code-scanner.js +360 -0
  32. package/lib/run-code-static.js +621 -0
  33. package/lib/runtime-diagnostics.js +89 -0
  34. package/lib/runtime-lifecycle.js +162 -0
  35. package/lib/runtime-static.js +23 -0
  36. package/lib/save-contract.js +263 -0
  37. package/lib/save-persistence.js +223 -0
  38. package/lib/save-plan-markdown-parser.js +369 -0
  39. package/lib/save-plan-validation-diagnostics.js +49 -0
  40. package/lib/save-plan-validation.js +812 -0
  41. package/lib/save-probe-validation.js +173 -0
  42. package/lib/save-source-verification.js +195 -0
  43. package/lib/save-tool-factories.js +270 -0
  44. package/lib/sdk-text-cache.js +161 -0
  45. package/lib/settings-contract.js +191 -0
  46. package/lib/settings.js +369 -0
  47. package/lib/shell-mutation.js +484 -0
  48. package/lib/usage-ledger-background.js +214 -0
  49. package/lib/usage-ledger-worker.js +116 -0
  50. package/lib/usage-ledger.js +1393 -0
  51. package/locale/en.json +6 -0
  52. package/locale/settings/en.json +6 -0
  53. package/locale/settings/zh.json +6 -0
  54. package/locale/zh.json +6 -0
  55. package/package.json +56 -4
  56. package/scripts/generate-runtime-defaults.mjs +796 -0
@@ -0,0 +1,744 @@
1
+ // plugins 根入口的纯决策与 run_code 聚合;无反向 index.js 依赖。
2
+ import { sessionEvents } from './agent-session.js'
3
+ import { budgetExceeded, budgetExhaustedReason, toolCallsSinceUser, DEFAULT_EXPLORE_BUDGET } from './planner-budget.js'
4
+ import { runCodeTextOf, createRunCodeStatic } from './run-code-static.js'
5
+ import { pwshMutationEvidence, bashMutationEvidence } from './shell-mutation.js'
6
+
7
+ const ASK_TOOL = 'ask_user_question'
8
+ const isDispatchStart = (t) => t === 'tool/ptc-dispatch-start'
9
+ const isDispatch = (t) => t === 'tool/ptc-dispatch'
10
+ const GATE_TOOL = 'extra_plan_gate'
11
+
12
+ // deny 提示模板(与闸门验词同源:引用本次 apply 的 gateRuntime,改词表则提示自动跟随)
13
+ function routeDenyReason(toolLabel, state, gateRuntime) {
14
+ if (state && state.route === 'plan') {
15
+ return `规划态下主会话不可写文件:${toolLabel}。探查请走 save_probe,写文件请等方案就绪后走执行者委派`
16
+ }
17
+ if (state && state.route === 'executor') {
18
+ return `执行者态下主会话不直做写入:${toolLabel}。路线已确认「${gateRuntime.words.routeExecutor}」,请通过 subagent 委派执行者执行`
19
+ }
20
+ return `路由未确认:${toolLabel}。只读探查可随时进行。创建/修改/删除文件${gateRuntime.confirm.route},用户选定路线后才可动手`
21
+ }
22
+ // 越界操作指引:沿用 routeDenyReason 既有口径,仅在其后追加一句(不另造文案风格)。
23
+ // 对应改造前 shell 写命令分支的第二级判定——非直行态禁止工作区内自写,但允许带 sandbox_permissions 做工作区外写入。
24
+ const OUT_OF_SCOPE_WRITE_HINT = '。工作区内写入请走 subagent 委派执行者;越界操作(工作区外写入)可带 sandbox_permissions 参数与 justification 重试'
25
+ function planDenyReason(action, state, gateRuntime) {
26
+ if (state && state.route === 'main') {
27
+ return `直行态下不可规划:${action}。「${gateRuntime.words.routeMain}」已选,请直接使用 write/edit/pwsh/bash 等工具动手完成任务`
28
+ }
29
+ if (state && state.route === 'plan' && state.purpose !== 'refine' && state.purpose !== 'redo') {
30
+ return `规划目的尚未确认:${action}。${gateRuntime.confirm.purpose},答复后再调用 ${action}`
31
+ }
32
+ if (state && state.route === 'plan' && state.clarified === false) {
33
+ return `澄清问答尚未完成:${action}。请先调用 extra_plan_gate 并传入 gate = clarify 做澄清问答(1-3 个关键问题,给候选选项),完成后再调用 ${action}`
34
+ }
35
+ return `子代理未放行:${action}。${gateRuntime.confirm.route},意图澄清问答后再调用 ${action}`
36
+ }
37
+ function executorDenyReason(action, state, gateRuntime) {
38
+ return `执行类委派未放行:${action}。请先调用 extra_plan_gate 并传入 gate = route,让用户选择「${gateRuntime.words.routeExecutor}」后再委派执行者`
39
+ }
40
+
41
+ // 当前宿主事件只保留 PTC dispatch 形状;旧 code-dispatch 运行分支已删除。
42
+
43
+ // shell mutation 辅助函数由 lib/shell-mutation.js 提供;下方 import 保持公开 decisions 绑定。
44
+
45
+
46
+
47
+ // ── 纯判定函数(模块顶层;经 decisions 导出供场景测试直接复用,防复制漂移) ──
48
+
49
+ // 会话事件快照的唯一来源 = lib/agent-session.js;本模块不复制子代理识别逻辑。
50
+
51
+ // 委派角色判定由下方从 lib/agent-runtime.js 导入。
52
+ // anchored 引导阶段判定:会话尚未落盘任何 tool/call 事件。
53
+ function filterBootstrapContextDecision(decision, gated) {
54
+ if (gated !== true || decision === null || typeof decision !== 'object' || decision.kind !== 'enter' || !Array.isArray(decision.messages)) return decision
55
+ const messages = decision.messages.filter((message) => {
56
+ if (message === null || typeof message !== 'object' || message.source === null || typeof message.source !== 'object') return true
57
+ return message.source.kind !== 'agent-instructions' && message.source.kind !== 'skill-catalog'
58
+ })
59
+ return messages.length === decision.messages.length ? decision : { ...decision, messages }
60
+ }
61
+
62
+ function projectedSkillCatalogSignature(message) {
63
+ if (message === null || typeof message !== 'object' || message.source === null || typeof message.source !== 'object' || message.source.kind !== 'skill-catalog' || !Array.isArray(message.source.entries)) return undefined
64
+ const entries = []
65
+ for (const entry of message.source.entries) {
66
+ if (entry === null || typeof entry !== 'object' || typeof entry.name !== 'string' || entry.name === '' || typeof entry.description !== 'string') return undefined
67
+ entries.push([entry.name, entry.description])
68
+ }
69
+ return JSON.stringify(entries)
70
+ }
71
+
72
+ function jsonShapeSignature(value, active = new Set()) {
73
+ if (value === null) return 'null'
74
+ if (typeof value === 'string') return JSON.stringify(value)
75
+ if (typeof value === 'boolean') return value ? 'true' : 'false'
76
+ if (typeof value === 'number') return Number.isFinite(value) ? String(value) : undefined
77
+ if (typeof value !== 'object') return undefined
78
+ if (active.has(value)) return undefined
79
+ active.add(value)
80
+ try {
81
+ if (Array.isArray(value)) {
82
+ const items = []
83
+ for (const item of value) {
84
+ const signature = jsonShapeSignature(item, active)
85
+ if (signature === undefined) return undefined
86
+ items.push(signature)
87
+ }
88
+ return '[' + items.join(',') + ']'
89
+ }
90
+ const prototype = Object.getPrototypeOf(value)
91
+ if (prototype !== Object.prototype && prototype !== null) return undefined
92
+ const parts = []
93
+ for (const key of Object.keys(value).sort()) {
94
+ const signature = jsonShapeSignature(value[key], active)
95
+ if (signature === undefined) return undefined
96
+ parts.push(JSON.stringify(key) + ':' + signature)
97
+ }
98
+ return '{' + parts.join(',') + '}'
99
+ } catch {
100
+ return undefined
101
+ } finally {
102
+ active.delete(value)
103
+ }
104
+ }
105
+
106
+ function projectedAgentInstructionsSignature(message) {
107
+ if (message === null || typeof message !== 'object' || message.source === null || typeof message.source !== 'object' || message.source.kind !== 'agent-instructions') return undefined
108
+ if (!Array.isArray(message.content) || message.content.length === 0) return undefined
109
+ return jsonShapeSignature(message.content)
110
+ }
111
+
112
+ function projectedContextSignature(message) {
113
+ if (message === null || typeof message !== 'object' || message.source === null || typeof message.source !== 'object') return undefined
114
+ const kind = message.source.kind
115
+ const signature = kind === 'agent-instructions'
116
+ ? projectedAgentInstructionsSignature(message)
117
+ : kind === 'skill-catalog' ? projectedSkillCatalogSignature(message) : undefined
118
+ return signature === undefined ? undefined : { kind, signature }
119
+ }
120
+
121
+ function dedupeProjectedContextDecision(decision, visibleMessages) {
122
+ if (decision === null || typeof decision !== 'object' || decision.kind !== 'enter' || !Array.isArray(decision.messages)) return decision
123
+ const baselines = new Map()
124
+ if (Array.isArray(visibleMessages)) {
125
+ for (const message of visibleMessages) {
126
+ const projected = projectedContextSignature(message)
127
+ if (projected !== undefined) baselines.set(projected.kind, projected.signature)
128
+ }
129
+ }
130
+ let changed = false
131
+ const messages = []
132
+ for (const message of decision.messages) {
133
+ const projected = projectedContextSignature(message)
134
+ if (projected !== undefined && baselines.get(projected.kind) === projected.signature) {
135
+ changed = true
136
+ continue
137
+ }
138
+ messages.push(message)
139
+ if (projected !== undefined) baselines.set(projected.kind, projected.signature)
140
+ }
141
+ return changed ? { ...decision, messages } : decision
142
+ }
143
+ // 首轮相位判定:会话尚未落盘任何 tool/call 事件即「引导期」。
144
+ // 改造8(账本与弃用迁移)后签名带 events:异步钩子必须传自己已预取的 lease.events
145
+ // (observeSession 的不可变快照),走 events 通道、不再经宿主的同步快照通道;
146
+ // events 未传或非法(既有夹具、仍走同步快照的调用方)才在 sessionEvents 内部回落到同步快照兜底。
147
+ function isBootstrapPhase(agent, events) {
148
+ if (agent === undefined || agent === null) return false
149
+ const session = agent.session
150
+ if (session === undefined || session === null) return false
151
+ const source = sessionEvents(session, events)
152
+ return !source.some((event) => {
153
+ if (event === null || typeof event !== 'object') return false
154
+ return event.type === 'tool/call' || (Array.isArray(event.type) && event.type.includes('tool/call'))
155
+ })
156
+ }
157
+
158
+ // shell 命令解码与 mutation 匹配由 lib/shell-mutation.js 提供。
159
+
160
+
161
+ // 免计瀑布预算的工具白名单(planner 预算计数与 pre-execute 闸门豁免共用)。
162
+ const FREE_TOOLS = new Set(['save_plan', 'edit_plan_draft'])
163
+
164
+ // ContentBlock 数组首条 text 块的文本(无 text 块 → '')
165
+ function firstTextOfBlocks(blocks) {
166
+ if (!Array.isArray(blocks)) return ''
167
+ for (const block of blocks) {
168
+ if (block !== null && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string') return block.text
169
+ }
170
+ return ''
171
+ }
172
+
173
+ function resetStageState(state) {
174
+ state.purpose = 'none'
175
+ state.clarified = false
176
+ }
177
+
178
+ function resetRouteState(state) {
179
+ state.route = 'none'
180
+ resetStageState(state)
181
+ }
182
+
183
+ function applyGateOutcome(state, gate, result) {
184
+ // outcome 口径:answered 推进状态;cancelled 清空闸门状态(route/purpose/clarified 全复位,
185
+ // 与改造前对「用户取消」的处理一致);skipped(未作答)与 channel-error(提问通道故障)不改动既有字段。
186
+ // clarify 仅当 route=plan 且 purpose∈{refine,redo} 时由 answered 置位(与 purpose 分支的 route 前置同口径)。
187
+ if (result === null || typeof result !== 'object') return
188
+ const outcome = result.outcome
189
+ if (outcome === 'cancelled') {
190
+ resetRouteState(state)
191
+ return
192
+ }
193
+ if (outcome !== 'answered') return
194
+ if (gate === 'route') {
195
+ // route 覆盖式写入;每次 route 闸门作答都无条件清空 purpose 与 clarified(与改造前一致)。
196
+ const route = result.route
197
+ if (route !== 'main' && route !== 'executor' && route !== 'plan' && route !== 'none') return
198
+ resetStageState(state)
199
+ state.route = route
200
+ return
201
+ }
202
+ if (gate === 'purpose') {
203
+ // purpose 只在规划路线上成立,写入的同时把澄清态复位。
204
+ if (state.route !== 'plan') return
205
+ const purpose = result.purpose
206
+ if (purpose !== 'refine' && purpose !== 'redo') return
207
+ state.purpose = purpose
208
+ state.clarified = false
209
+ return
210
+ }
211
+ if (gate === 'clarify' && state.route === 'plan' && (state.purpose === 'refine' || state.purpose === 'redo')) state.clarified = true
212
+ }
213
+
214
+ // 三锚点状态机(纯函数,自最近一条人类消息起的事件推导):
215
+ // route: 'none' | 'main' | 'executor' | 'plan'(用户选「暂不推进」→ 回 'none',保持未确认)
216
+ // purpose: 'none' | 'refine' | 'redo'(purposeRefine → refine / purposeRedo → redo)
217
+ // clarified: 是否有完成的澄清问答(clarify 闸门 answered 且 route=plan 且 purpose∈{refine,redo} 时置 true,换路线时随阶段态一起清空)
218
+ // 唯一推进源是 extra_plan_gate 的 tool/call 与 tool/result(含 run_code 内嵌套的 ptc-dispatch 形态):
219
+ // 调用参数取 gate,结果文本解析 JSON 后取 outcome 与 route/purpose,交 applyGateOutcome 处理:
220
+ // answered 按 gate 推进(clarify 仅当 route=plan 且 purpose∈{refine,redo} 时置位 clarified);cancelled 清空闸门状态(route/purpose/clarified 全复位);
221
+ // skipped(未作答)与 channel-error(提问通道故障)均不改动既有字段。
222
+ // 普通 ask_user_question 不再参与状态推导。
223
+ function deriveFlowState(events, gateRuntime) {
224
+ const state = { route: 'none', clarified: false, purpose: 'none' }
225
+ if (!Array.isArray(events)) return state
226
+ let lastHuman = -1
227
+ for (let i = events.length - 1; i >= 0; i -= 1) {
228
+ const e = events[i]
229
+ if (e !== null && typeof e === 'object' && e.type === 'user/message' &&
230
+ e.data !== null && typeof e.data === 'object' &&
231
+ e.data.source !== null && typeof e.data.source === 'object' &&
232
+ e.data.source.kind === 'user') {
233
+ lastHuman = i
234
+ break
235
+ }
236
+ }
237
+ if (lastHuman === -1) return state
238
+ const calls = new Map() // callId / subCallId → gate(route、purpose、clarify)
239
+ // 调用参数取 gate:arguments 可能是 JSON 字符串,也可能是已解析对象。
240
+ const gateOfArgs = (args) => {
241
+ let parsed = null
242
+ if (typeof args === 'string' && args.length > 0) {
243
+ try { parsed = JSON.parse(args) } catch (error) { return null }
244
+ } else if (args !== null && typeof args === 'object') {
245
+ parsed = args
246
+ }
247
+ if (parsed === null || typeof parsed !== 'object') return null
248
+ return typeof parsed.gate === 'string' ? parsed.gate : null
249
+ }
250
+ // 结果文本取 JSON:闸门工具的返回值整体序列化在首个 text 块里,解析失败即跳过。
251
+ const resultOfBlocks = (blocks) => {
252
+ const text = firstTextOfBlocks(blocks)
253
+ if (typeof text !== 'string' || text === '') return null
254
+ let parsed = null
255
+ try { parsed = JSON.parse(text) } catch (error) { return null }
256
+ return parsed !== null && typeof parsed === 'object' ? parsed : null
257
+ }
258
+ for (let i = lastHuman + 1; i < events.length; i += 1) {
259
+ const e = events[i]
260
+ if (e === null || typeof e !== 'object') continue
261
+ if (e.data === null || typeof e.data !== 'object') continue
262
+ // 形态一:普通直呼——tool/call 登记 gate,tool/result 交回结果。
263
+ if (e.type === 'tool/call') {
264
+ if (e.data.name !== GATE_TOOL || typeof e.data.callId !== 'string') continue
265
+ const gate = gateOfArgs(e.data.arguments)
266
+ if (gate !== null) calls.set(e.data.callId, gate)
267
+ continue
268
+ }
269
+ if (e.type === 'tool/result') {
270
+ const message = e.data.message
271
+ if (message === null || typeof message !== 'object' || typeof message.toolCallId !== 'string') continue
272
+ if (!calls.has(message.toolCallId)) continue
273
+ applyGateOutcome(state, calls.get(message.toolCallId), resultOfBlocks(message.content))
274
+ continue
275
+ }
276
+ // 形态二:run_code 内嵌套调用——tool/ptc-dispatch-start 登记 gate,tool/ptc-dispatch 交回结果。
277
+ if (isDispatchStart(e.type)) {
278
+ if (e.data.name !== GATE_TOOL || typeof e.data.subCallId !== 'string') continue
279
+ const gate = gateOfArgs(e.data.arguments)
280
+ if (gate !== null) calls.set(e.data.subCallId, gate)
281
+ continue
282
+ }
283
+ if (isDispatch(e.type)) {
284
+ if (typeof e.data.subCallId !== 'string' || !calls.has(e.data.subCallId)) continue
285
+ applyGateOutcome(state, calls.get(e.data.subCallId), resultOfBlocks(e.data.content))
286
+ }
287
+ }
288
+ return state
289
+ }
290
+
291
+
292
+ // save_plan/save_probe 合同、校验与渲染已拆至 lib。
293
+
294
+ // 工具集判定(真实工具集 tools.schemas,restrict 后非折叠;目录判定保留为 schemas 不可得时的回落)。
295
+ // 元素支持两种形状:字符串工具名、{ name } 对象(装配目录/工具集均为对象形状)。
296
+ function catalogHasWriteTools(tools) {
297
+ if (!Array.isArray(tools)) return false
298
+ return tools.some((tool) =>
299
+ (typeof tool === 'string' && (tool === 'write' || tool === 'edit')) ||
300
+ (tool !== null && typeof tool === 'object' && (tool.name === 'write' || tool.name === 'edit')))
301
+ }
302
+
303
+ // 只读子代理回退判定:供真实 schemas 不可得且目录未折叠时使用;目录非空且不含 write/edit,不等同角色权限。
304
+ function isReadOnlyChildByCatalog(tools) {
305
+ return Array.isArray(tools) && tools.length > 0 && !catalogHasWriteTools(tools)
306
+ }
307
+
308
+ // 工具集判定:真实工具集(tools.schemas,restrict 后非折叠)是否含 write/edit——
309
+ // 含 write/edit=可写(executor),无 write/edit=只读(probe/reviewer)。
310
+ // 形状约定与 catalogHasWriteTools 同(字符串元素 / { name } 对象);非数组 → false。
311
+ function schemasHasWriteTools(schemas) { return catalogHasWriteTools(schemas) }
312
+
313
+ // 工具集判定:真实工具集是否含指定工具名(save_probe 信号:仅主会话与认领的 probe 子代理注册)。
314
+ // 形状约定同上;非数组 → false。
315
+ function schemasHasTool(schemas, toolName) {
316
+ if (!Array.isArray(schemas)) return false
317
+ return schemas.some((tool) =>
318
+ (typeof tool === 'string' && tool === toolName) ||
319
+ (tool !== null && typeof tool === 'object' && tool.name === toolName))
320
+ }
321
+
322
+ // ptc 折叠目录判定:ptc 模式下 wireSchemas 塌缩为仅 [run_code]——折叠点在被装配的
323
+ // @deepseek-ai/dsh-tool-executor-ptc 包的 schemas 声明(本仓只按包名描述,不记宿主固定行号)。
324
+ // 判定口径与 catalogIsCollapsed 逐条对应:工具集非数组或长度不为 1 → 不折叠;唯一元素是 run_code
325
+ // (字符串或对象 {name:'run_code'})即视为折叠,即「仅剩 run_code 即视为折叠」。折叠时目录信号不可用
326
+ // (executor/reviewer/probe 目录同为 [run_code],目录无 write/edit 不代表只读角色)→ 只读判定改用真实
327
+ // 工具集(schemas(agent) 不受折叠影响):含 write/edit=可写(executor),无 write/edit=只读(probe/reviewer),
328
+ // reviewer 的 write/edit 由目录层 deny 兜底。
329
+ function catalogIsCollapsed(tools) {
330
+ if (!Array.isArray(tools) || tools.length !== 1) return false
331
+ const only = tools[0]
332
+ return (typeof only === 'string' && only === 'run_code') ||
333
+ (only !== null && typeof only === 'object' && only.name === 'run_code')
334
+ }
335
+
336
+ // ① subagent_probe 分支:明确按 main/planner/child 角色单点判定。
337
+ // T5:探查者仅主会话可委派——planner 与其它 child 都必须在运行时第二道防线拒绝,
338
+ // 直呼/listener 和 run_code 组判定统一走本函数,避免 toolFilter 漏洞造成递归委派。
339
+ // planner 文案必须引导「申请继续探查」;其它 child 保持只读角色文案。
340
+ function subagentProbeGateReason(exec, role) {
341
+ const roleKind = typeof role === 'string' ? role : role !== undefined && role !== null && typeof role.kind === 'string' ? role.kind : 'child'
342
+ if (roleKind === 'planner') {
343
+ return '规划子代理不得委派探查者:subagent_probe 仅主会话可用(探查者属主会话的探查能力)。请用 read/glob/grep 自行核对;确有缺口时输出「申请继续探查:<待查项> — <原因>」,由主会话派探查者并把线索文件路径转达给你(toolFilter 之外的第二道防线)'
344
+ }
345
+ if (roleKind !== 'main') {
346
+ return '只读子代理不得委派探查者:subagent_probe 仅主会话可用;请保持当前角色的只读边界'
347
+ }
348
+ // 委派工具参数表里已无后台标志(dsh-tool-subagent 只暴露 cwd/description/prompt 与
349
+ // 可选模型项):委派恒为立即返回 subagentId 加完成通知,原「必须后台」断言不再成立,
350
+ // 后台约束上移到宿主层,本闸门只保留名称级放行。
351
+ return null
352
+ }
353
+
354
+ // shell 写命令的只读角色拒绝文案(B3 收敛:唯一实现,planner/探查者/验收复核者 × pwsh/bash 共六格;
355
+ // 六格基础拒句与重构前逐字一致,固定依据后缀由 withShellEvidence 统一追加。只处理 pwsh/bash 且确实命中既有 mutation 判定的调用;role 只接受
356
+ // planner/probe/reviewer,其余(含未知角色、非 shell 工具、只读命令)一律返回 null。
357
+ // write/edit 分支与本函数无关,各自 GateReason 内逐字保留。
358
+ function withShellEvidence(reason, name, evidence) {
359
+ if (evidence === null) return reason
360
+ const hit = evidence.value === '' ? '' : ' 命中 ' + evidence.value
361
+ return reason + ';触发依据:' + name + ' ' + evidence.rule + hit
362
+ }
363
+
364
+ function shellMutationReason(role, exec) {
365
+ let label = null
366
+ if (role === 'planner') label = '规划子代理'
367
+ else if (role === 'probe') label = '探查者'
368
+ else if (role === 'reviewer') label = '验收复核者'
369
+ if (label === null) return null
370
+ if (exec === undefined || exec === null) return null
371
+ if (exec.name === 'pwsh') {
372
+ const evidence = pwshMutationEvidence(exec)
373
+ return evidence === null ? null : withShellEvidence(label + '只读:pwsh 仅限只读探查命令,禁止创建/修改/删除文件', 'pwsh', evidence)
374
+ }
375
+ if (exec.name === 'bash') {
376
+ const evidence = bashMutationEvidence(exec)
377
+ return evidence === null ? null : withShellEvidence(label + '只读:bash 仅限只读探查命令,禁止创建/修改/删除文件', 'bash', evidence)
378
+ }
379
+ return null
380
+ }
381
+
382
+ // 子代理控制工具硬闸:仅主会话可用;保持纯函数以供直呼与 run_code 组判定复用。
383
+ function childControlGateReason(exec) {
384
+ const name = exec !== undefined && exec !== null && typeof exec.name === 'string' ? exec.name : ''
385
+ if (name !== 'send_message') return null
386
+ return '子代理禁止调用 send_message:仅主会话可用'
387
+ }
388
+
389
+ // ② planner 分支(plannerGateReason;自 apply 内提取的纯部分):write/edit → shell 写命令
390
+ // (shellMutationReason)→ job_output → 预算;不含 run_code(由调用方处理)。
391
+ function plannerGateReason(exec, events, exploreBudget, jobOutputCallCounters) {
392
+ const controlReason = childControlGateReason(exec)
393
+ if (controlReason !== null) return controlReason
394
+ if (exec.name === 'write' || exec.name === 'edit') {
395
+ return '规划子代理只读:方案经 save_plan 落盘,其余写入一律禁止(toolFilter 之外的第二道防线)'
396
+ }
397
+ const shellReason = shellMutationReason('planner', exec)
398
+ if (shellReason !== null) return shellReason
399
+ if (exec.name === 'job_output') return jobOutputGateReason(exec, jobOutputCallCounters)
400
+ if (!FREE_TOOLS.has(exec.name) && !isRunCodeSubCall(exec)) {
401
+ const used = toolCallsSinceUser(events !== undefined ? events : [], FREE_TOOLS)
402
+ if (budgetExceeded(used + 1, exploreBudget)) {
403
+ return budgetExhaustedReason(Math.min(used, exploreBudget), exploreBudget)
404
+ }
405
+ }
406
+ return null
407
+ }
408
+
409
+ // ③ child 只读块(childReadonlyGateReason;自 apply 内提取的纯部分):write/edit → shell 写命令
410
+ // (shellMutationReason,probe 布尔选角色)→ job_output;不含 run_code。
411
+ function childReadonlyGateReason(exec, probe, jobOutputCallCounters) {
412
+ const controlReason = childControlGateReason(exec)
413
+ if (controlReason !== null) return controlReason
414
+ if (exec.name === 'write' || exec.name === 'edit') {
415
+ return probe ? '探查者只读:探查不修改任何文件,write/edit 一律禁止(工具目录判定)' : '验收复核者只读:验收复核不修改任何文件,write/edit 一律禁止(工具目录判定)'
416
+ }
417
+ const shellReason = shellMutationReason(probe ? 'probe' : 'reviewer', exec)
418
+ if (shellReason !== null) return shellReason
419
+ if (exec.name === 'job_output') return jobOutputGateReason(exec, jobOutputCallCounters)
420
+ return null
421
+ }
422
+
423
+ // job_output 全角色闸门(v0.1.10):wait:true 禁令 + 同 job 查重(自原 mainGateReason 分支逐字搬移,
424
+ // 闸门 1/2 文案逐字不变);counters undefined/null 或 vExec 无 agent(组判定成员)时
425
+ // 跳过查重、wait 检查照常。本函数只读查重,写入侧唯一位点是 recordJobOutputCall(B3 收敛)。
426
+ function jobOutputGateReason(exec, jobOutputCallCounters) {
427
+ const args = exec !== undefined && exec !== null ? exec.arguments : undefined
428
+ // 闸门 1:禁止 wait: true 前台等待(参数不可解析时跳过,运行时瀑布兜底)
429
+ if (args !== undefined && args !== null && typeof args === 'object' && args.wait === true) {
430
+ return 'job_output 禁止带 wait: true 前台等待。请省略 wait 参数或设 wait: false,job 完成后会收到通知'
431
+ }
432
+ // 闸门 2:禁止同一 jobId 连续调用(防轮询)——内存计数器替代 events 推导。
433
+ // 只读查重(写入由 recordJobOutputCall 在放行路径执行,时序等价);组判定成员无会话上下文时
434
+ // 跳过(运行时瀑布兜底)。
435
+ if (args !== undefined && args !== null && typeof args === 'object' && typeof args.job_id === 'string') {
436
+ const execAgent = exec !== undefined && exec !== null ? exec.agent : undefined
437
+ const header = execAgent !== undefined && execAgent !== null && execAgent.session !== undefined && execAgent.session !== null ? execAgent.session.header : undefined
438
+ const sessId = header !== undefined && header !== null ? header.id : undefined
439
+ const counters = jobOutputCallCounters
440
+ if (typeof sessId === 'string' && counters !== undefined && counters !== null) {
441
+ const perSession = counters.get(sessId)
442
+ if (perSession !== undefined && perSession !== null && perSession.has(args.job_id)) {
443
+ return `job_output 禁止对同一 job 重复调用。job "${args.job_id}" 在本轮已调用过,请等待子代理返回结果,禁止提前收尾、结束`
444
+ }
445
+ }
446
+ }
447
+ return null
448
+ }
449
+
450
+ // job_output 放行后的计数器记录(B3 收敛:唯一实现;planner、只读 child、主会话三处共用,
451
+ // 执行者仍完全豁免)。仅当工具名恰为 job_output、job_id 为字符串、sessionId 为字符串且
452
+ // counters 可用时惰性建 session Map 并写 jobId→1;任一条件不满足即返回 false 且零副作用。
453
+ // 返回值仅供场景测试断言状态迁移,运行时调用方忽略。
454
+ function recordJobOutputCall(agent, exec, counters) {
455
+ if (exec === undefined || exec === null || exec.name !== 'job_output') return false
456
+ const args = exec.arguments
457
+ if (args === undefined || args === null || typeof args !== 'object' || typeof args.job_id !== 'string') return false
458
+ const header = agent !== undefined && agent !== null && agent.session !== undefined && agent.session !== null ? agent.session.header : undefined
459
+ const sessId = header !== undefined && header !== null ? header.id : undefined
460
+ if (typeof sessId !== 'string') return false
461
+ if (counters === undefined || counters === null) return false
462
+ let perSession = counters.get(sessId)
463
+ if (perSession === undefined) { perSession = new Map(); counters.set(sessId, perSession) }
464
+ perSession.set(args.job_id, 1)
465
+ return true
466
+ }
467
+
468
+ // job_list/list_agents 主会话防轮询闸门(v0.4.0):同锚点周期内第二次调用拒绝(首次放行)。
469
+ // 无参数键,按调用行为计数:pollGuardCounters 为 Map<sessionId, Set<'job_list'|'list_agents'>>。
470
+ // 只读查重;写入侧唯一位点是 recordPollGuardCall(B3 收敛同款);vExec 无 agent(组判定成员)时
471
+ // 跳过查重(运行时瀑布重入兜底,与 jobOutputGateReason 同口径)。
472
+ function pollGuardGateReason(exec, pollGuardCounters) {
473
+ const name = exec !== undefined && exec !== null && typeof exec.name === 'string' ? exec.name : ''
474
+ if (name !== 'job_list' && name !== 'list_agents') return null
475
+ const execAgent = exec !== undefined && exec !== null ? exec.agent : undefined
476
+ const header = execAgent !== undefined && execAgent !== null && execAgent.session !== undefined && execAgent.session !== null ? execAgent.session.header : undefined
477
+ const sessId = header !== undefined && header !== null ? header.id : undefined
478
+ if (typeof sessId === 'string' && pollGuardCounters !== undefined && pollGuardCounters !== null) {
479
+ const called = pollGuardCounters.get(sessId)
480
+ if (called !== undefined && called !== null && called.has(name)) {
481
+ return '禁止轮询子代理状态,停止操作并等待子代理通知'
482
+ }
483
+ }
484
+ return null
485
+ }
486
+ // job_list/list_agents 放行后的计数器记录(唯一写入位点;仅主会话路径调用)。
487
+ function recordPollGuardCall(agent, exec, counters) {
488
+ if (exec === undefined || exec === null) return false
489
+ if (exec.name !== 'job_list' && exec.name !== 'list_agents') return false
490
+ const header = agent !== undefined && agent !== null && agent.session !== undefined && agent.session !== null ? agent.session.header : undefined
491
+ const sessId = header !== undefined && header !== null ? header.id : undefined
492
+ if (typeof sessId !== 'string') return false
493
+ if (counters === undefined || counters === null) return false
494
+ let called = counters.get(sessId)
495
+ if (called === undefined) { called = new Set(); counters.set(sessId, called) }
496
+ called.add(exec.name)
497
+ return true
498
+ }
499
+
500
+ // 仅报告本 apply 的回退计数。精确角色认领不消费此计数,不能据它判断宿主任务状态。
501
+ function probeDisposalWarning(remaining) {
502
+ if (!Number.isInteger(remaining) || remaining <= 0) return null
503
+ return '委派方会话销毁时,仍有 ' + remaining + ' 个记录未通过计数回退路径认领;该计数不能判断探查者是否已启动或后台任务是否已取消。'
504
+ }
505
+
506
+ // ④ 主会话段(mainGateReason;自 apply 内提取的纯部分,分支顺序逐字同序):
507
+ // ask → write/edit → cordis 2 只读 → pwsh/bash → planToolName
508
+ // → save_probe 分支保持不变(route=plan + purpose∈{refine,redo} + clarified)
509
+ // → subagent 族 → run_code(调 runCodeGroupDenyReason,depth+1)
510
+ // → job_output(wait 检查 + 计数器查重,只读不写入;set 由 recordJobOutputCall 在放行路径执行)→ null。
511
+ // save_plan 已移除路由态限制:无显式分支,由本函数兜底 return null 任意路由态放行
512
+ // (受限规划工件:仅写 cwd/.extra-plan 固定形状 Markdown,内容闸门与规划子代理同一实现)。
513
+ // gateCtx: { events, planToolName, jobOutputCallCounters, pollGuardCounters, runCodeDepth, runcodeCatchGate, getAgents(可选), messageTargetIdOf(arguments)(可选), gateRuntime }(gateRuntime 必填)。
514
+ function mainGateReason(state, exec, gateCtx) {
515
+ const ctx = gateCtx !== undefined && gateCtx !== null ? gateCtx : {}
516
+ const gateRuntime = ctx.gateRuntime
517
+ if (gateRuntime === undefined || gateRuntime === null) {
518
+ throw new Error('extra-plan: mainGateReason 需要本次 apply 的 gateRuntime(config.gateWords);helper 不得自建默认词表')
519
+ }
520
+ const events = ctx.events !== undefined && ctx.events !== null ? ctx.events : []
521
+ const planToolName = typeof ctx.planToolName === 'string' && ctx.planToolName !== '' ? ctx.planToolName : 'subagent_plan'
522
+ state = state !== undefined && state !== null ? state : { route: 'none', clarified: false, purpose: 'none' }
523
+ const name = exec !== undefined && exec !== null && typeof exec.name === 'string' ? exec.name : ''
524
+ if (name === ASK_TOOL) {
525
+ // 1b:普通 ask_user_question 的选项标签推断与结构校验整体退场(选项由 extra_plan_gate 生成);
526
+ // 主会话侧的闸门判定已前移到 extra_plan_gate 工具,这里直接放行以免旧路径形成死锁。
527
+ return null
528
+ }
529
+ if (name === 'write' || name === 'edit') {
530
+ // route 非 main 即拒:main 才允许主会话直接动手,plan 走规划子代理,executor 走执行者委派。
531
+ if (state.route !== 'main') {
532
+ return routeDenyReason('write/edit', state, gateRuntime)
533
+ }
534
+ return null
535
+ }
536
+ // cordis(官方工具集,只读引用):当前支持两个只读工具。
537
+ if (name === 'cordis_inspect_list' || name === 'cordis_inspect_query') {
538
+ return null
539
+ }
540
+ const shellEvidence = name === 'pwsh' ? pwshMutationEvidence(exec) : name === 'bash' ? bashMutationEvidence(exec) : null
541
+ if (shellEvidence !== null) {
542
+ const shellLabel = name
543
+ // 越界特例的等价映射(对应改造前的两级串行判定):
544
+ // 第一级 = 路线是否已确认:route=none(未确认)一律拒绝、且不追加越界指引,避免误导为可绕过;
545
+ // 第二级 = 已确认路线(executor/plan):带 sandbox_permissions 字符串才是「工作区外写入」放行
546
+ // (宿主审批闸在其后),不带则拒绝并在 routeDenyReason 口径后追加越界指引。
547
+ if (state.route !== 'main') {
548
+ if (state.route === 'none') {
549
+ return withShellEvidence(routeDenyReason(shellLabel, state, gateRuntime), shellLabel, shellEvidence)
550
+ }
551
+ const shellArgs = exec !== undefined && exec !== null ? exec.arguments : undefined
552
+ if (shellArgs !== undefined && shellArgs !== null && typeof shellArgs === 'object' && typeof shellArgs.sandbox_permissions === 'string') {
553
+ return null
554
+ }
555
+ return withShellEvidence(routeDenyReason(shellLabel, state, gateRuntime) + OUT_OF_SCOPE_WRITE_HINT, shellLabel, shellEvidence)
556
+ }
557
+ return null
558
+ }
559
+ if (name === planToolName || name === 'save_probe') {
560
+ if (state.route !== 'plan' || state.clarified !== true || (state.purpose !== 'refine' && state.purpose !== 'redo')) {
561
+ return planDenyReason(name, state, gateRuntime)
562
+ }
563
+ // 委派工具参数表里已无后台标志:规划子代理的续轮由宿主 continuable 后端固定为
564
+ // 立即返回加通知,前台等待不存在,故只保留路由态判定。
565
+ return null
566
+ }
567
+ if (name === 'subagent' || name === 'subagent_fork' || name === 'workflow' || name === 'ralph' || name === 'subagent_review') {
568
+ if (state.route !== 'executor') {
569
+ return executorDenyReason(name, state, gateRuntime)
570
+ }
571
+ // 委派工具参数表里已无后台标志:subagent/subagent_review 恒为立即返回 subagentId
572
+ // 加完成通知,后台约束在宿主层,本处只保留路线判定。
573
+ return null
574
+ }
575
+ // 主会话向 running 目标的 send_message 拒绝;job_list/list_agents 同锚点防轮询。
576
+ if (name === 'send_message') {
577
+ // 主会话调用者:目标 running → 拒;idle/未驻留/agents 服务不可用 → 放行
578
+ // (未驻留或已回收目标由宿主 coldResume NOT_RESUMABLE 自拒)。
579
+ if (typeof ctx.getAgents === 'function') {
580
+ const agents = ctx.getAgents()
581
+ if (agents !== undefined && agents !== null && typeof agents.get === 'function') {
582
+ const smArgs = exec !== undefined && exec !== null ? exec.arguments : undefined
583
+ // DSH_CURRENT_RC2:可选回调优先读取新 agent 名称/路径的本轮解析ID;删除边界仅限最新路径 agent 与 resolveName 适配(rc.2 与 rc.3 共用),须另行授权,不含共享安全核心。
584
+ // DSH_COMPAT_RC1:新参数未提供时读取旧 agent_id Session ID;删除边界仅限 rc.1 旧参数兼容,须另行授权,不含共享安全核心。
585
+ const targetId = typeof ctx.messageTargetIdOf === 'function'
586
+ ? ctx.messageTargetIdOf(smArgs)
587
+ : smArgs !== undefined && smArgs !== null && typeof smArgs === 'object' && typeof smArgs.agent_id === 'string' ? smArgs.agent_id : null
588
+ if (typeof targetId === 'string') {
589
+ const target = agents.get(targetId)
590
+ if (target !== undefined && target !== null && target.status === 'running') {
591
+ return '子代理running中,禁止打扰'
592
+ }
593
+ }
594
+ }
595
+ }
596
+ return null
597
+ }
598
+ if (name === 'job_list' || name === 'list_agents') return pollGuardGateReason(exec, ctx.pollGuardCounters)
599
+ if (name === 'run_code') {
600
+ return runCodeGroupDenyReason(state, exec, { kind: 'main' }, { events, planToolName, jobOutputCallCounters: ctx.jobOutputCallCounters, pollGuardCounters: ctx.pollGuardCounters, getAgents: ctx.getAgents, messageTargetIdOf: ctx.messageTargetIdOf, runcodeCatchGate: ctx.runcodeCatchGate, runCodeDepth: (typeof ctx.runCodeDepth === 'number' ? ctx.runCodeDepth : 0) + 1, gateRuntime })
601
+ }
602
+ if (name === 'job_output') return jobOutputGateReason(exec, ctx.jobOutputCallCounters)
603
+ return null
604
+ }
605
+
606
+ // 组判定:run_code 拆解 → 逐成员走「与直呼完全相同的闸门」→ 聚合拒绝。
607
+ // state:主会话 flow state(role.kind==='main' 时必传;其它角色忽略);缺省归一化为
608
+ // { route:'none', clarified:false, purpose:'none' }。
609
+ // role:{ kind:'main' } | { kind:'planner' } | { kind:'child', readOnly:boolean, probe:boolean }。
610
+ // gateCtx: { events, planToolName, jobOutputCallCounters, pollGuardCounters, runCodeDepth, runcodeCatchGate, getAgents(可选), messageTargetIdOf(arguments)(可选), gateRuntime }(gateRuntime 必填)。
611
+ // 缺省:events:[]、planToolName:'subagent_plan'、jobOutputCallCounters:new Map()、pollGuardCounters:new Map()、
612
+ // exploreBudget:DEFAULT_EXPLORE_BUDGET、runCodeDepth:0、runcodeCatchGate:false;getAgents 不设缺省(undefined 即 fail-open 放行);
613
+ // gateRuntime 必须由调用方显式传入(词表唯一值源是 config.gateWords,helper 无默认词表)。
614
+ // 多调用容错硬闸门:成员逐项判定之后、聚合之前执行 runCodeCatchGateReason(教学式文案)。
615
+ // 返回 null=放行;非 null=聚合拒绝文案。
616
+ function runCodeGroupDenyReason(state, exec, role, gateCtx) {
617
+ const ctx = {
618
+ events: [],
619
+ planToolName: 'subagent_plan',
620
+ jobOutputCallCounters: new Map(),
621
+ pollGuardCounters: new Map(),
622
+ exploreBudget: DEFAULT_EXPLORE_BUDGET,
623
+ runCodeDepth: 0,
624
+ runcodeCatchGate: false,
625
+ ...(gateCtx !== undefined && gateCtx !== null ? gateCtx : {}),
626
+ }
627
+ const st = state !== undefined && state !== null
628
+ ? state
629
+ : { route: 'none', clarified: false, purpose: 'none' }
630
+ const r = role !== undefined && role !== null && typeof role === 'object' && typeof role.kind === 'string' ? role : { kind: 'main' }
631
+ const roleKind = r.kind
632
+ const members = []
633
+ const denies = []
634
+ const visit = (codeArg, depth) => {
635
+ // ask 返回值硬闸门只接入主会话;嵌套超出既有展开深度的部分仍由实际 pre-execute 重入兜底。
636
+ const askReason = roleKind === 'main' ? askOrGateReturnGateReason(codeArg) : null
637
+ const decomposed = decomposeRunCode(codeArg)
638
+ if (askReason !== null) {
639
+ const askMember = { kind: 'ask-gate', name: ASK_TOOL, argsParsed: true, args: {}, argsText: '' }
640
+ denies.push({ member: askMember, reason: askReason })
641
+ }
642
+ for (const member of decomposed.members) {
643
+ // 嵌套 run_code 成员展平:depth>=1 或参数不可解析 → 跳过(运行时瀑布兜底);
644
+ // 否则递归拆解 member.args.code 并原位展平(子成员按 role 继续判定)。
645
+ if (member.name === 'run_code' && member.kind === 'tool') {
646
+ if (depth >= 1 || !member.argsParsed || member.args === null || typeof member.args.code !== 'string') continue
647
+ visit(member.args.code, depth + 1)
648
+ continue
649
+ }
650
+ members.push(member)
651
+ const vExec = member.kind === 'bare-write'
652
+ ? { name: 'write', bare: true, hints: member.hints, arguments: {}, sub: true }
653
+ : { name: member.name, arguments: member.argsParsed ? member.args : member.argsText, sub: true }
654
+ let reason = roleKind !== 'main' ? childControlGateReason(vExec) : null
655
+ if (reason === null && ctx.controlOnly !== true && member.name === 'subagent_probe') {
656
+ reason = subagentProbeGateReason(vExec, roleKind)
657
+ } else if (reason === null && ctx.controlOnly !== true && member.kind === 'bare-write') {
658
+ // 裸写成员按角色分流:只读角色保留 v2 共享文案(hits 拼写与既有共享文案逐字同构);
659
+ // 主会话走 write/edit 闸门(routeDenyReason 文案);
660
+ // 执行者(child 非只读)豁免。
661
+ if (roleKind === 'planner' || (roleKind === 'child' && r.readOnly === true)) {
662
+ const h = member.hints
663
+ reason = `只读角色仅允许只读探查:run_code 代码命中写模式特征 ${h.length} 处(${h.slice(0, 3).join('、')}${h.length > 3 ? ' 等' : ''})。请改用 read/glob/grep 或 shell 只读命令`
664
+ } else if (roleKind === 'main') {
665
+ reason = mainGateReason(st, vExec, ctx)
666
+ } // 执行者豁免:reason 保持 null
667
+ } else if (reason === null && ctx.controlOnly !== true && roleKind === 'planner') {
668
+ reason = plannerGateReason(vExec, ctx.events !== undefined ? ctx.events : [], ctx.exploreBudget, ctx.jobOutputCallCounters)
669
+ } else if (reason === null && ctx.controlOnly !== true && roleKind === 'child') {
670
+ reason = r.readOnly === true ? childReadonlyGateReason(vExec, r.probe === true, ctx.jobOutputCallCounters) : null
671
+ } else if (reason === null && ctx.controlOnly !== true) {
672
+ reason = mainGateReason(st, vExec, ctx)
673
+ }
674
+ if (reason !== null) denies.push({ member, reason })
675
+ }
676
+ }
677
+ visit(runCodeTextOf(exec), ctx.runCodeDepth)
678
+ if (ctx.controlOnly !== true && ctx.runcodeCatchGate === true) {
679
+ const catchReason = runCodeCatchGateReason(runCodeTextOf(exec))
680
+ if (catchReason !== null) denies.push({ member: { kind: 'catch', name: 'run_code' }, reason: catchReason })
681
+ }
682
+ if (ctx.controlOnly !== true && roleKind === 'planner') {
683
+ const siteCount = runCodeSiteCount(runCodeTextOf(exec))
684
+ if (siteCount > ctx.exploreBudget) denies.push({ member: { kind: 'cap', name: 'run_code' }, reason: `run_code 静态调用点 ${siteCount} 处超过单实例子调用上限 ${ctx.exploreBudget}(exploreBudget):请拆分多个 run_code 或减少单次调用点` })
685
+ // 新增(T2 修复):预算耗尽白名单把关——budgetExceeded(toolCallsSinceUser(events, FREE_TOOLS)+1, exploreBudget) 时,
686
+ // run_code 工具组必须成员组非空且全部 ∈ FREE_TOOLS 才放行;空组/动态访问(decomposeRunCode 置 dynamic)/
687
+ // 任何非 FREE_TOOLS 成员(含嵌套 run_code、bare-write)→ 拒绝(保守)。拒绝文案=预算耗尽原文+动态拼接白名单。
688
+ const budgetUsed = toolCallsSinceUser(ctx.events !== undefined ? ctx.events : [], FREE_TOOLS)
689
+ if (budgetExceeded(budgetUsed + 1, ctx.exploreBudget)) {
690
+ const budgetDecomposed = decomposeRunCode(runCodeTextOf(exec))
691
+ const allFree = budgetDecomposed.dynamic !== true && budgetDecomposed.members.length > 0 && budgetDecomposed.members.every((m) => FREE_TOOLS.has(m.name))
692
+ if (!allFree) {
693
+ denies.push({ member: { kind: 'budget', name: 'run_code' }, reason: budgetExhaustedReason(Math.min(budgetUsed, ctx.exploreBudget), ctx.exploreBudget) + ` 预算耗尽后 run_code 仅可调用 ${[...FREE_TOOLS].join('/')},其他工具均不放行` })
694
+ }
695
+ }
696
+ }
697
+ if (denies.length === 0) return null
698
+ return aggregateRunCodeDenyReason(members, denies)
699
+ }
700
+
701
+ // 聚合报错(统一格式,任何一次组判定拒绝均用此格式;子文案逐字不变):
702
+ // header 一行(组规模 + 触发明细计数 + 「全通过才放行」语义)+ 逐行 `- <标签>: <子文案>`;
703
+ // 标签规则:普通成员=工具名;裸写=`write(裸写特征:<hints 顿号连接>)`;ask-gate(A22 返回链闸门)=无工具标签,直接输出「- 」加子文案全文(工具名已由文案承载);
704
+ // 参数不可解析=`<工具名>(参数不可解析)`;行序=组员顺序(展平后);子文案来自闸门函数原返回值;catch/cap/budget 直接取成员 name。
705
+ function aggregateRunCodeDenyReason(members, denies) {
706
+ const lines = [`run_code 拆解预审未通过:工具组共 ${members.length} 项(去重后),${denies.length} 项触发闸门,任一触发即整体拒绝:`]
707
+ for (const d of denies) {
708
+ if (d.member.kind === 'catch') { lines.push(`- ${d.member.name}: ${d.reason}`); continue }
709
+ if (d.member.kind === 'cap') { lines.push(`- ${d.member.name}: ${d.reason}`); continue }
710
+ if (d.member.kind === 'budget') { lines.push(`- ${d.member.name}: ${d.reason}`); continue }
711
+ if (d.member.kind === 'ask-gate') { lines.push(`- ${d.reason}`); continue }
712
+ let label = d.member.name
713
+ if (d.member.kind === 'bare-write') label = `write(裸写特征:${d.member.hints.join('、')})`
714
+ else if (!d.member.argsParsed) label = `${d.member.name}(参数不可解析)`
715
+ lines.push(`- ${label}: ${d.reason}`)
716
+ }
717
+ return lines.join('\n')
718
+ }
719
+
720
+
721
+
722
+
723
+
724
+ // run_code 静态 helper 单向接线:依赖只由根的 ASK_TOOL、GATE_TOOL显式注入。
725
+ const {
726
+ decomposeRunCode,
727
+ runCodeCatchGateReason,
728
+ collectRunCodeSites,
729
+ askOrGateReturnGateReason,
730
+ runCodeSiteCount,
731
+ isRunCodeSubCall,
732
+ runCodeDispatchCapText,
733
+ } = createRunCodeStatic({ askTool: ASK_TOOL, gateTool: GATE_TOOL })
734
+
735
+ export {
736
+ FREE_TOOLS, ASK_TOOL,
737
+ routeDenyReason, planDenyReason, executorDenyReason, applyGateOutcome,
738
+ isBootstrapPhase, filterBootstrapContextDecision, dedupeProjectedContextDecision,
739
+ deriveFlowState,
740
+ catalogHasWriteTools, isReadOnlyChildByCatalog, schemasHasWriteTools, schemasHasTool, catalogIsCollapsed,
741
+ subagentProbeGateReason, shellMutationReason, childControlGateReason, plannerGateReason, childReadonlyGateReason, jobOutputGateReason, recordJobOutputCall,
742
+ pollGuardGateReason, recordPollGuardCall, probeDisposalWarning, mainGateReason, runCodeGroupDenyReason, aggregateRunCodeDenyReason,
743
+ decomposeRunCode, runCodeCatchGateReason, collectRunCodeSites, askOrGateReturnGateReason, runCodeSiteCount, isRunCodeSubCall, runCodeDispatchCapText,
744
+ }