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,648 @@
1
+ // planner 与非 planner child 的模型路由。
2
+ // 纯 helper 重新导出供测试;createModelRouting 持有每次 apply 的 WeakMap 缓存和
3
+ // 延迟 host/config getter,避免 Agent 结果跨插件实例;模块不 import index.js,
4
+ // 会话分类统一来自 agent-session.js。
5
+ import { appendFileSync } from 'node:fs'
6
+ import { createUserMessage } from '@deepseek-ai/dsh-llm'
7
+ import { isSubagentChild } from './agent-session.js'
8
+
9
+ // 显式路由判定(对齐官方 model-selection.ts L118-119 routeChanged 口径:
10
+ // provider 或 model 任一与父值不同即视为显式)。空串/undefined 视为「无选择」。
11
+ export function isExplicitRoute(rProvider, rModel, pProvider, pModel) {
12
+ const rp = typeof rProvider === 'string' && rProvider !== '' ? rProvider : undefined
13
+ const rm = typeof rModel === 'string' && rModel !== '' ? rModel : undefined
14
+ if (rp !== undefined && (rp !== pProvider || rm !== pModel)) return true
15
+ if (rm !== undefined && rm !== pModel) return true
16
+ return false
17
+ }
18
+
19
+ // 显式 effort 判定(对齐官方 L189-190):只有 resolved 存在且 ≠ 父值才算显式;
20
+ // undefined/空串(adapter 默认被 requestProposal 剥除后)不算显式。
21
+ export function isExplicitEffort(rEffort, pEffort) {
22
+ return typeof rEffort === 'string' && rEffort !== '' && rEffort !== pEffort
23
+ }
24
+
25
+ // probe(探查者)子代理模型跟随完整父链的顶层配置:沿 parentSession 链上溯,取顶层主会话
26
+ // requestHeader().config 作为 provider/model/maxTokens 注入源。链任一层断裂(get 失败、
27
+ // requestHeader 非函数或抛异常、config 为 null、depth 达 8 上限)时 source 为空;插件不构造
28
+ // 直接父回退。非严格路径返回空路由配置,严格路径阻断,不推断宿主后续继承。模块顶层纯
29
+ // 函数不引用 probeClaimFor/pendingProbeClaims/plannerModelCache/getPlannerModel/ctx 闭包变量,
30
+ // 保留该快照/来源并经 decisions 导出,供场景测试直接复用。
31
+ function requestConfigSnapshot(agent) {
32
+ if (agent === undefined || agent === null || agent.session === undefined || agent.session === null) return null
33
+ if (typeof agent.session.requestHeader !== 'function') return null
34
+ let header
35
+ try { header = agent.session.requestHeader() } catch (error) { return null }
36
+ const config = header !== undefined && header !== null && header.config !== undefined && header.config !== null ? header.config : null
37
+ if (config === null || typeof config !== 'object') return null
38
+ return {
39
+ provider: typeof config.provider === 'string' && config.provider !== '' ? config.provider : undefined,
40
+ model: typeof config.model === 'string' && config.model !== '' ? config.model : undefined,
41
+ maxTokens: typeof config.maxTokens === 'number' && config.maxTokens > 0 ? config.maxTokens : undefined,
42
+ reasoningEffort: typeof config.reasoningEffort === 'string' ? config.reasoningEffort : '',
43
+ }
44
+ }
45
+
46
+ function agentFromRegistry(agents, id) {
47
+ if (agents === undefined || agents === null || typeof agents.get !== 'function') return undefined
48
+ try { return agents.get(id) } catch (error) { return undefined }
49
+ }
50
+
51
+ // 返回直接父与顶层主会话的 owned route snapshot;链断裂时不把中间 child 当主会话。
52
+ export function resolveAgentRouteSources(agent, agents) {
53
+ const header = agent !== undefined && agent !== null && agent.session !== undefined && agent.session !== null && agent.session.header !== undefined && agent.session.header !== null ? agent.session.header : null
54
+ const parentSession = header !== null ? header.parentSession : undefined
55
+ if (typeof parentSession !== 'string') return { available: false, complete: false, direct: null, source: null }
56
+ const parent = agentFromRegistry(agents, parentSession)
57
+ const direct = requestConfigSnapshot(parent)
58
+ if (direct === null) return { available: false, complete: false, direct: null, source: null }
59
+ let source = direct
60
+ let current = parent
61
+ let complete = true
62
+ let depth = 0
63
+ // 父链上行判定走 header-only(传空 events)降级:isSubagentChild 的 header origin/delegationDepth
64
+ // 判据足以识别子代理会话(header 必带标记),事件流 descriptor 兜底不再使用。
65
+ // 不迁 observeSession:它是 async,本循环在同步上下文无法 await;而 resolveAgentRouteSources 被
66
+ // 生产入口(index.js 的 agent/request 决策面)与模块内 nonPlannerRouteSources 同步直调,
67
+ // 改 async 会破坏调用契约。故这里跳过事件流扫描。
68
+ while (isSubagentChild(current, [])) {
69
+ const currentHeader = current !== undefined && current !== null && current.session !== undefined && current.session !== null && current.session.header !== undefined && current.session.header !== null ? current.session.header : null
70
+ const upId = currentHeader !== null ? currentHeader.parentSession : undefined
71
+ if (typeof upId !== 'string') { complete = false; break }
72
+ const up = agentFromRegistry(agents, upId)
73
+ if (up === undefined) { complete = false; break }
74
+ const upConfig = requestConfigSnapshot(up)
75
+ if (upConfig === null) { complete = false; break }
76
+ current = up
77
+ source = upConfig
78
+ depth += 1
79
+ if (depth >= 8) { complete = false; break }
80
+ }
81
+ return { available: true, complete, direct, source: complete ? source : null }
82
+ }
83
+
84
+ // planner-model 可用性判定(纯函数;唯一调用方是 resolvePlannerEntry)。
85
+ // 输入:plannerModel(string,'' = 设置页显式清空 = 继承主会话模型)、provider(父会话
86
+ // provider,可能 undefined)、catalog(模型目录查询结果描述):
87
+ // { kind: 'ok', ids: [...] } 目录查询成功且清单非空
88
+ // | { kind: 'empty' } 适配器未覆写发现能力(静默返回 [])
89
+ // | { kind: 'error' } 查询抛错(如 provider 未注册 → NO_ADAPTER)
90
+ // | { kind: 'no-llm' } 取不到 llm 服务 / 未发起查询
91
+ // 输出:{ use, degraded, diag, reason }
92
+ // use = 是否用 plannerModel 覆盖 model(false = planner 继承主会话模型)
93
+ // degraded = 是否发生「静默降级」(配置的模型未被采用,供口径/回溯)
94
+ // diag = 需要落盘诊断时的 decision 值,否则 null
95
+ // reason = 判定原因(诊断留痕用)
96
+ // 规则(顺序即设计口径):
97
+ // 1. plannerModel === '' → 不覆盖(空设置表示继承),不落诊断;
98
+ // 2. plannerModel 非空且 provider 有值:
99
+ // a. 目录成功、清单非空且未命中 → 不覆盖(静默降级,diag:'inherit-parent');
100
+ // b. 清单为空 / 抛错 / 取不到 llm → 保守沿用 plannerModel(目录 advisory:
101
+ // 空清单≠不可用,防误杀未实现发现能力的适配器),diag:'keep-planner-model';
102
+ // c. 命中 → 覆盖(现行为),不落诊断;
103
+ // 3. plannerModel 非空且 provider 无值(父会话空闲等)→ 沿用 plannerModel,不落诊断。
104
+ export function decidePlannerModelUse(plannerModel, provider, catalog) {
105
+ const configured = typeof plannerModel === 'string' ? plannerModel : ''
106
+ if (configured === '') return { use: false, degraded: false, diag: null, reason: 'empty-config' }
107
+ if (typeof provider !== 'string' || provider === '') return { use: true, degraded: false, diag: null, reason: 'no-provider' }
108
+ const kind = catalog !== null && typeof catalog === 'object' && typeof catalog.kind === 'string' ? catalog.kind : 'no-llm'
109
+ if (kind === 'ok') {
110
+ const ids = Array.isArray(catalog.ids) ? catalog.ids : []
111
+ if (ids.includes(configured)) return { use: true, degraded: false, diag: null, reason: 'catalog-hit' }
112
+ return { use: false, degraded: true, diag: 'inherit-parent', reason: 'catalog-miss' }
113
+ }
114
+ if (kind === 'empty') return { use: true, degraded: false, diag: 'keep-planner-model', reason: 'catalog-empty' }
115
+ if (kind === 'error') return { use: true, degraded: false, diag: 'keep-planner-model', reason: 'catalog-error' }
116
+ return { use: true, degraded: false, diag: 'keep-planner-model', reason: 'catalog-unavailable' }
117
+ }
118
+
119
+ // True 路径的真实探针固定上限;False 路径不读取这些辅助逻辑。
120
+ export const PLANNER_PROBE_TIMEOUT_MS = 30000
121
+ // 跨 Provider 严格候选探针的并发上限(硬编码常量,不新增任何配置项、不经 cfg.* 读取):
122
+ // planner 与非 planner 候选循环共用同一个有界并发池,超出上限的候选排队等待,
123
+ // 全部候选结束后才按发起顺序收集结果并排序选择(选择结果与串行实现逐项一致)。
124
+ export const PLANNER_PROBE_CONCURRENCY = 5
125
+ export const PLANNER_BLOCKED_REASON = 'extra-plan: planner request blocked: no verified planner route'
126
+ export const NON_PLANNER_BLOCKED_REASON = 'extra-plan: non-planner request blocked: no verified non-planner route'
127
+
128
+ export function routeKey(provider, model) {
129
+ return provider + '\u0000' + model
130
+ }
131
+
132
+ function comparePlannerText(a, b) {
133
+ const left = typeof a === 'string' ? a : ''
134
+ const right = typeof b === 'string' ? b : ''
135
+ return left < right ? -1 : left > right ? 1 : 0
136
+ }
137
+
138
+ function plannerProviderRank(providerId, parentProvider) {
139
+ if (providerId === 'deepseek-official') return 2
140
+ if (typeof parentProvider === 'string' && parentProvider !== '' && providerId === parentProvider) return 1
141
+ return 0
142
+ }
143
+
144
+ export function sortPlannerCandidates(candidates, parentProvider) {
145
+ return [...candidates].sort((left, right) => {
146
+ const leftRank = plannerProviderRank(left.id, parentProvider)
147
+ const rightRank = plannerProviderRank(right.id, parentProvider)
148
+ if (leftRank !== rightRank) return leftRank - rightRank
149
+ if (leftRank === 0) {
150
+ const byName = comparePlannerText(left.name, right.name)
151
+ if (byName !== 0) return byName
152
+ }
153
+ return comparePlannerText(left.id, right.id)
154
+ })
155
+ }
156
+
157
+ // ── per-apply 工厂:planner / 非 planner 单点解析(缓存固定到 Agent 生命周期) ──
158
+ // 注入仅真依赖:6 个惰性 getter(3 个热读配置项 plannerModel/otherAgentModel/
159
+ // crossProviderPlannerModel + llm / agents / 诊断落盘路径)。
160
+ export function createModelRouting({ getPlannerModel, getOtherAgentModel, getCrossProviderPlannerModel, getLlm, getAgents, getDiagPath }) {
161
+ // ── planner 模型单点解析 ──
162
+ // plannerModelCache:planner 子代理有效模型条目缓存(key=agent)。True 路径首次入口
163
+ // 立即缓存 in-flight promise;成功 entry 与严格 rejection 都固定到该 Agent 生命周期。
164
+ const plannerModelCache = new WeakMap()
165
+ // 非 planner 专用缓存:key=单个 child Agent;成功、in-flight 与 strict rejection 均固定隔离。
166
+ const otherAgentModelCache = new WeakMap()
167
+
168
+ function plannerAbortError(signal) {
169
+ const reason = signal !== undefined && signal !== null ? signal.reason : undefined
170
+ return reason instanceof Error ? reason : new Error('extra-plan: planner probe aborted')
171
+ }
172
+
173
+ // 用一个本地 AbortController 同时覆盖 listModels、prepareCall 和完整 stream;listModels
174
+ // 没有 signal 参数,Promise.race 只解除本解析等待,不能替第三方 adapter 撤销遗留 I/O。
175
+ async function withPlannerProbeDeadline(operation, parentSignal) {
176
+ if (parentSignal !== undefined && parentSignal !== null && parentSignal.aborted) throw plannerAbortError(parentSignal)
177
+ const controller = new AbortController()
178
+ let timedOut = false
179
+ let parentAbortListener = null
180
+ if (parentSignal !== undefined && parentSignal !== null && typeof parentSignal.addEventListener === 'function') {
181
+ parentAbortListener = () => controller.abort(plannerAbortError(parentSignal))
182
+ parentSignal.addEventListener('abort', parentAbortListener, { once: true })
183
+ if (parentSignal.aborted) parentAbortListener()
184
+ }
185
+ const timeout = setTimeout(() => {
186
+ timedOut = true
187
+ controller.abort(new Error('extra-plan: planner route probe timed out'))
188
+ }, PLANNER_PROBE_TIMEOUT_MS)
189
+ let abortListener = null
190
+ const aborted = new Promise((resolve, reject) => {
191
+ abortListener = () => reject(controller.signal.reason instanceof Error ? controller.signal.reason : new Error('extra-plan: planner probe aborted'))
192
+ if (controller.signal.aborted) abortListener()
193
+ else controller.signal.addEventListener('abort', abortListener, { once: true })
194
+ })
195
+ const pending = Promise.resolve().then(() => operation(controller.signal))
196
+ pending.catch(() => {})
197
+ try {
198
+ return await Promise.race([pending, aborted])
199
+ } catch (error) {
200
+ if (parentSignal !== undefined && parentSignal !== null && parentSignal.aborted) throw plannerAbortError(parentSignal)
201
+ if (timedOut) return { timeout: true }
202
+ throw error
203
+ } finally {
204
+ clearTimeout(timeout)
205
+ if (parentAbortListener !== null && parentSignal !== undefined && parentSignal !== null && typeof parentSignal.removeEventListener === 'function') parentSignal.removeEventListener('abort', parentAbortListener)
206
+ if (abortListener !== null) controller.signal.removeEventListener('abort', abortListener)
207
+ }
208
+ }
209
+
210
+ // 候选目录检查与真实探针共用一个 deadline。checkCatalog=false 仅用于父会话 fallback,
211
+ // 因而不把 advisory listModels 误当成 fallback 成功,也允许父模型未列在目录中时验证。
212
+ async function probePlannerRoute(llm, provider, model, parentSignal, checkCatalog) {
213
+ let matched = !checkCatalog
214
+ try {
215
+ const result = await withPlannerProbeDeadline(async (signal) => {
216
+ if (checkCatalog) {
217
+ if (typeof llm.listModels !== 'function') return { matched: false, ok: false }
218
+ const models = await llm.listModels(provider)
219
+ if (!Array.isArray(models) || !models.some((item) => item !== null && typeof item === 'object' && item.id === model)) return { matched: false, ok: false }
220
+ matched = true
221
+ }
222
+ if (typeof llm.prepareCall !== 'function') return { matched, ok: false }
223
+ const prepared = await llm.prepareCall({ provider, model, maxTokens: 1 }, signal)
224
+ if (prepared === null || typeof prepared !== 'object' || typeof prepared.stream !== 'function') return { matched, ok: false }
225
+ const preparedConfig = prepared.config
226
+ if (preparedConfig === null || typeof preparedConfig !== 'object' || preparedConfig.provider !== provider || preparedConfig.model !== model) return { matched, ok: false }
227
+ const request = {
228
+ provider: preparedConfig.provider,
229
+ model: preparedConfig.model,
230
+ ...(preparedConfig.reasoningEffort === undefined ? {} : { reasoningEffort: preparedConfig.reasoningEffort }),
231
+ ...(preparedConfig.temperature === undefined ? {} : { temperature: preparedConfig.temperature }),
232
+ ...(preparedConfig.maxTokens === undefined ? {} : { maxTokens: preparedConfig.maxTokens }),
233
+ ...(preparedConfig.stop === undefined ? {} : { stop: preparedConfig.stop }),
234
+ // source 用生产者自有 kind(v4 行准入禁止旧包裹形状:kind 取旧兜底值 plugin + plugin 包名字段);与插件其余注入消息同形。
235
+ messages: [createUserMessage({ source: { kind: 'plugin:dsh-extra-plan' }, content: [{ type: 'text', text: 'OK' }] })],
236
+ signal,
237
+ }
238
+ let finishCount = 0
239
+ let finishKind = ''
240
+ for await (const chunk of prepared.stream(request)) {
241
+ if (chunk !== null && typeof chunk === 'object' && chunk.type === 'finish') {
242
+ finishCount += 1
243
+ finishKind = chunk.reason !== null && typeof chunk.reason === 'object' && typeof chunk.reason.kind === 'string' ? chunk.reason.kind : ''
244
+ }
245
+ }
246
+ return { matched, ok: finishCount === 1 && finishKind !== '' && finishKind !== 'error' && finishKind !== 'aborted' }
247
+ }, parentSignal)
248
+ if (result !== null && typeof result === 'object' && result.timeout === true) return { matched, ok: false }
249
+ return result !== null && typeof result === 'object' && typeof result.ok === 'boolean' ? result : { matched, ok: false }
250
+ } catch (error) {
251
+ if (parentSignal !== undefined && parentSignal !== null && parentSignal.aborted) throw plannerAbortError(parentSignal)
252
+ return { matched, ok: false }
253
+ }
254
+ }
255
+
256
+ // 有界并发探针池(上限 PLANNER_PROBE_CONCURRENCY):候选按入参顺序启动,超出上限的排队;
257
+ // 每个候选各自走 probePlannerRoute(各自独立 AbortController + 30s deadline,互不共享),
258
+ // 返回值与入参一一对应且按发起顺序排列(完成顺序不影响结果)——调用方因此可在全部候选结束后
259
+ // 按发起顺序写 probeOutcomes/successes 再排序,与串行实现的选择结果完全一致。
260
+ // 任一候选抛出(父 turn abort 原样传播)→ 整体 reject;其余候选的 rejection 由 Promise.all 一并接住。
261
+ async function probePlannerCandidates(llm, providerIds, model, parentSignal) {
262
+ const outcomes = new Array(providerIds.length)
263
+ let next = 0
264
+ const worker = async () => {
265
+ for (;;) {
266
+ const index = next
267
+ next += 1
268
+ if (index >= providerIds.length) return
269
+ outcomes[index] = await probePlannerRoute(llm, providerIds[index], model, parentSignal, true)
270
+ }
271
+ }
272
+ const width = Math.min(PLANNER_PROBE_CONCURRENCY, providerIds.length)
273
+ const workers = []
274
+ for (let i = 0; i < width; i += 1) workers.push(worker())
275
+ await Promise.all(workers)
276
+ return outcomes
277
+ }
278
+
279
+ function uniqueProviderCandidates(listedProviders) {
280
+ const seenProviderIds = new Set()
281
+ const candidates = []
282
+ for (const listed of listedProviders) {
283
+ if (listed === null || typeof listed !== 'object' || typeof listed.id !== 'string' || listed.id === '' || seenProviderIds.has(listed.id)) continue
284
+ seenProviderIds.add(listed.id)
285
+ candidates.push({ id: listed.id, name: typeof listed.name === 'string' ? listed.name : listed.id })
286
+ }
287
+ return candidates
288
+ }
289
+
290
+ // planner/non-planner strict 路径共用 provider 去重、并发探针与按发起顺序收集。
291
+ async function collectStrictProbeCandidates(llm, model, parentSignal) {
292
+ const probeOutcomes = new Map()
293
+ const successes = []
294
+ if (model === '' || typeof llm.listProviders !== 'function') return { probeOutcomes, successes }
295
+ let listedProviders = []
296
+ try {
297
+ const listed = await withPlannerProbeDeadline(() => llm.listProviders(), parentSignal)
298
+ if (!(listed !== null && typeof listed === 'object' && listed.timeout === true) && Array.isArray(listed)) listedProviders = listed
299
+ } catch (error) {
300
+ if (parentSignal !== undefined && parentSignal !== null && parentSignal.aborted) throw plannerAbortError(parentSignal)
301
+ }
302
+ const candidates = uniqueProviderCandidates(listedProviders)
303
+ const outcomes = await probePlannerCandidates(llm, candidates.map((candidate) => candidate.id), model, parentSignal)
304
+ for (let index = 0; index < candidates.length; index += 1) {
305
+ const outcome = outcomes[index]
306
+ if (outcome === undefined) continue
307
+ if (outcome.matched) probeOutcomes.set(routeKey(candidates[index].id, model), outcome)
308
+ if (outcome.ok) successes.push({ id: candidates[index].id, name: candidates[index].name })
309
+ }
310
+ return { probeOutcomes, successes }
311
+ }
312
+ // False/缺失/非法开关的旧单 provider 流程原样保留:只查父 provider 的 advisory 目录,
313
+ // 不枚举 provider,也不调用真实 prepareCall/stream 或严格 fallback probe。
314
+ async function resolvePlannerEntrySingleProvider(agent) {
315
+ let provider
316
+ let model
317
+ let maxTokens
318
+ try {
319
+ const targetModel = getPlannerModel(agent)
320
+ const parentSession = agent.session.header.parentSession
321
+ if (typeof parentSession === 'string') {
322
+ const agents = getAgents()
323
+ let parent
324
+ try {
325
+ parent = agents !== undefined ? agents.get(parentSession) : undefined
326
+ } catch (error) {
327
+ parent = undefined
328
+ }
329
+ const pcfg = requestConfigSnapshot(parent)
330
+ if (pcfg !== null) {
331
+ provider = pcfg.provider
332
+ model = pcfg.model
333
+ maxTokens = pcfg.maxTokens
334
+ }
335
+ }
336
+ if (targetModel !== '') {
337
+ let catalog = { kind: 'no-llm' }
338
+ const llm = getLlm()
339
+ if (llm !== undefined && llm !== null && typeof llm.listModels === 'function') {
340
+ try {
341
+ const models = await llm.listModels(provider)
342
+ const ids = Array.isArray(models)
343
+ ? models.map((m) => m !== null && typeof m === 'object' && typeof m.id === 'string' ? m.id : '').filter((id) => id !== '')
344
+ : []
345
+ catalog = ids.length === 0 ? { kind: 'empty' } : { kind: 'ok', ids }
346
+ } catch (error) {
347
+ catalog = { kind: 'error' }
348
+ }
349
+ }
350
+ const decision = decidePlannerModelUse(targetModel, provider, catalog)
351
+ if (decision.use) model = targetModel
352
+ if (decision.diag !== null) {
353
+ try {
354
+ const diagPath = getDiagPath(agent)
355
+ if (typeof diagPath !== 'string' || diagPath === '') return { provider, model, maxTokens }
356
+ appendFileSync(diagPath, JSON.stringify({
357
+ ts: new Date().toISOString(),
358
+ type: 'degrade',
359
+ sessionId: agent.session !== undefined && agent.session !== null && agent.session.header !== undefined ? agent.session.header.id : '',
360
+ provider: provider !== undefined ? provider : '',
361
+ plannerModel: targetModel,
362
+ decision: decision.diag,
363
+ reason: decision.reason,
364
+ }) + '\n', 'utf8')
365
+ } catch (error) { /* 诊断落盘失败不影响解析 */ }
366
+ }
367
+ }
368
+ } catch (error) {
369
+ // 旧兼容口径:解析异常保持已取到的值,不抛出。
370
+ }
371
+ return { provider, model, maxTokens }
372
+ }
373
+
374
+ // True 严格路径:只把已完成真实 OK probe 的排序候选或已验证父 fallback 交给 planner。
375
+ async function resolvePlannerEntryStrict(agent, parentSignal) {
376
+ let provider
377
+ let model
378
+ let maxTokens
379
+ const targetModel = getPlannerModel(agent)
380
+ try {
381
+ const parentSession = agent.session.header.parentSession
382
+ if (typeof parentSession === 'string') {
383
+ const agents = getAgents()
384
+ let parent
385
+ try {
386
+ parent = agents !== undefined ? agents.get(parentSession) : undefined
387
+ } catch (error) {
388
+ parent = undefined
389
+ }
390
+ const pcfg = requestConfigSnapshot(parent)
391
+ if (pcfg !== null) {
392
+ provider = pcfg.provider
393
+ model = pcfg.model
394
+ maxTokens = pcfg.maxTokens
395
+ }
396
+ }
397
+ } catch (error) {
398
+ // 缺失/损坏的父配置在候选全失败时由固定 strict block 统一处理。
399
+ }
400
+ // 空串等于继承主会话:父 provider/model 即最终路由,直接短路,不做 provider 枚举
401
+ // 与真实探针。父值不可用时保持原逻辑(不提前返回,PLANNER_BLOCKED_REASON 条件不变)。
402
+ // 空串短路同样先响应中断,与 resolveOtherAgentEntryStrict 的空串短路保持一致。
403
+ if (targetModel === '' && typeof provider === 'string' && provider !== '' && typeof model === 'string' && model !== '') {
404
+ if (parentSignal !== undefined && parentSignal !== null && parentSignal.aborted) throw plannerAbortError(parentSignal)
405
+ return { provider, model, maxTokens }
406
+ }
407
+ let llm
408
+ try {
409
+ llm = getLlm()
410
+ } catch (error) {
411
+ llm = undefined
412
+ }
413
+ if (llm === undefined || llm === null || typeof llm !== 'object') throw new Error(PLANNER_BLOCKED_REASON)
414
+
415
+ const { probeOutcomes, successes } = await collectStrictProbeCandidates(llm, targetModel, parentSignal)
416
+ const sorted = sortPlannerCandidates(successes, provider)
417
+ if (sorted.length > 0) return { provider: sorted[0].id, model: targetModel, maxTokens }
418
+
419
+ if (parentSignal !== undefined && parentSignal !== null && parentSignal.aborted) throw plannerAbortError(parentSignal)
420
+ if (typeof provider !== 'string' || provider === '' || typeof model !== 'string' || model === '') throw new Error(PLANNER_BLOCKED_REASON)
421
+ const fallbackKey = routeKey(provider, model)
422
+ const reused = probeOutcomes.get(fallbackKey)
423
+ const fallback = reused !== undefined ? reused : await probePlannerRoute(llm, provider, model, parentSignal, false)
424
+ if (fallback.ok) return { provider, model, maxTokens }
425
+ if (parentSignal !== undefined && parentSignal !== null && parentSignal.aborted) throw plannerAbortError(parentSignal)
426
+ throw new Error(PLANNER_BLOCKED_REASON)
427
+ }
428
+
429
+ // 单一入口的首个调用即保存 promise,避免同一 Agent 并发/续轮重复真实探针;rejection
430
+ // 也固定缓存,后续请求不会把未验证路由重新交给 DSH。
431
+ function resolvePlannerEntry(agent, parentSignal) {
432
+ const cached = plannerModelCache.get(agent)
433
+ if (cached !== undefined) return cached
434
+ const crossProvider = getCrossProviderPlannerModel(agent)
435
+ const pending = crossProvider
436
+ ? resolvePlannerEntryStrict(agent, parentSignal)
437
+ : resolvePlannerEntrySingleProvider(agent)
438
+ plannerModelCache.set(agent, pending)
439
+ return pending
440
+ }
441
+
442
+ // 非 planner 路由来源:普通 child 保留直接父 maxTokens,probe 保留顶层来源 maxTokens;
443
+ // provider/model 的 fallback 始终取完整链路解析出的顶层主会话,链断裂不冒充中间 child。
444
+ function nonPlannerRouteSources(agent) {
445
+ let agents
446
+ try { agents = getAgents() } catch (error) { agents = undefined }
447
+ return resolveAgentRouteSources(agent, agents)
448
+ }
449
+
450
+ function nonPlannerFallbackEntry(sources, probe) {
451
+ if (sources === null || sources === undefined || sources.available !== true || sources.source === null || sources.direct === null) return null
452
+ const tokenSource = probe ? sources.source : sources.direct
453
+ return {
454
+ provider: sources.source.provider,
455
+ model: sources.source.model,
456
+ maxTokens: tokenSource.maxTokens,
457
+ }
458
+ }
459
+
460
+ // cross=false/缺失/非法:只对顶层主会话 provider 做 advisory listModels;不做真实探针。
461
+ async function resolveOtherAgentEntrySingleProvider(agent, probe) {
462
+ const sources = nonPlannerRouteSources(agent)
463
+ const fallback = nonPlannerFallbackEntry(sources, probe)
464
+ const targetModel = getOtherAgentModel(agent)
465
+ if (fallback === null || targetModel === '' || fallback.provider === undefined) return fallback || {}
466
+ let llm
467
+ try { llm = getLlm() } catch (error) { llm = undefined }
468
+ if (llm === undefined || llm === null || typeof llm.listModels !== 'function') return fallback
469
+ try {
470
+ const models = await llm.listModels(fallback.provider)
471
+ if (Array.isArray(models) && models.some((item) => item !== null && typeof item === 'object' && item.id === targetModel)) {
472
+ return { ...fallback, model: targetModel }
473
+ }
474
+ } catch (error) {
475
+ // advisory 目录异常按要求静默回退顶层主会话。
476
+ }
477
+ return fallback
478
+ }
479
+
480
+ // cross=true:所有匹配 provider 并发(上限 PLANNER_PROBE_CONCURRENCY)完整 OK probe,
481
+ // 候选全部结束后按 planner 既有排序选择。
482
+ async function resolveOtherAgentEntryStrict(agent, parentSignal, probe) {
483
+ const sources = nonPlannerRouteSources(agent)
484
+ const fallback = nonPlannerFallbackEntry(sources, probe)
485
+ const targetModel = getOtherAgentModel(agent)
486
+ if (fallback === null) {
487
+ if (parentSignal !== undefined && parentSignal !== null && parentSignal.aborted) throw plannerAbortError(parentSignal)
488
+ throw new Error(NON_PLANNER_BLOCKED_REASON)
489
+ }
490
+ // 空串等于继承主会话:父 fallback 即最终路由,零网络零探针(与单 provider 路径的空串语义对齐)。
491
+ if (targetModel === '' && fallback.provider !== undefined) {
492
+ if (parentSignal !== undefined && parentSignal !== null && parentSignal.aborted) throw plannerAbortError(parentSignal)
493
+ return fallback
494
+ }
495
+ if (parentSignal !== undefined && parentSignal !== null && parentSignal.aborted) throw plannerAbortError(parentSignal)
496
+ let llm
497
+ try { llm = getLlm() } catch (error) { llm = undefined }
498
+ if (llm === undefined || llm === null || typeof llm !== 'object') {
499
+ throw new Error(NON_PLANNER_BLOCKED_REASON)
500
+ }
501
+ const { probeOutcomes, successes } = await collectStrictProbeCandidates(llm, targetModel, parentSignal)
502
+ const sorted = sortPlannerCandidates(successes, fallback.provider)
503
+ if (sorted.length > 0) return { ...fallback, provider: sorted[0].id, model: targetModel }
504
+ if (parentSignal !== undefined && parentSignal !== null && parentSignal.aborted) throw plannerAbortError(parentSignal)
505
+ if (fallback.provider === undefined || fallback.model === undefined) throw new Error(NON_PLANNER_BLOCKED_REASON)
506
+ const fallbackKey = routeKey(fallback.provider, fallback.model)
507
+ const reused = probeOutcomes.get(fallbackKey)
508
+ const fallbackOutcome = reused !== undefined ? reused : await probePlannerRoute(llm, fallback.provider, fallback.model, parentSignal, false)
509
+ if (fallbackOutcome.ok) return fallback
510
+ if (parentSignal !== undefined && parentSignal !== null && parentSignal.aborted) throw plannerAbortError(parentSignal)
511
+ throw new Error(NON_PLANNER_BLOCKED_REASON)
512
+ }
513
+
514
+ // 单一非 planner 入口:每个 child Agent 独立保存首个 in-flight promise、成功或 strict rejection。
515
+ function resolveOtherAgentEntry(agent, parentSignal, probe) {
516
+ const cached = otherAgentModelCache.get(agent)
517
+ if (cached !== undefined) return cached
518
+ const crossProvider = getCrossProviderPlannerModel(agent)
519
+ const pending = crossProvider
520
+ ? resolveOtherAgentEntryStrict(agent, parentSignal, probe)
521
+ : resolveOtherAgentEntrySingleProvider(agent, probe)
522
+ otherAgentModelCache.set(agent, pending)
523
+ return pending
524
+ }
525
+
526
+ // 验收者模型入口:plannerModel 作为验收者的规划者模型来源,空串等于继承主会话(直接回退父
527
+ // fallback,不取 llm)。reviewerRoutePendingCache/reviewerRouteSettledCache 是 per-apply 实例
528
+ // (不得提升为模块全局),按 plannerModel、crossProviderPlannerModel 真假、顶层主会话
529
+ // provider/model/maxTokens 五段拼键;pending 与 settled 隔离,条目超过 32 条时整表清空。
530
+ const reviewerRoutePendingCache = new Map()
531
+ const reviewerRouteSettledCache = new Map()
532
+
533
+ function throwIfReviewerAborted(parentSignal) {
534
+ if (parentSignal !== undefined && parentSignal !== null && parentSignal.aborted) throw plannerAbortError(parentSignal)
535
+ }
536
+
537
+ function awaitReviewerPending(pending, parentSignal, removePending) {
538
+ if (parentSignal === undefined || parentSignal === null || typeof parentSignal.addEventListener !== 'function') return pending
539
+ if (parentSignal.aborted) {
540
+ if (typeof removePending === 'function') removePending()
541
+ throw plannerAbortError(parentSignal)
542
+ }
543
+ return new Promise((resolve, reject) => {
544
+ let done = false
545
+ const cleanup = () => {
546
+ if (typeof parentSignal.removeEventListener === 'function') parentSignal.removeEventListener('abort', onAbort)
547
+ }
548
+ const onAbort = () => {
549
+ if (done) return
550
+ done = true
551
+ cleanup()
552
+ if (typeof removePending === 'function') removePending()
553
+ reject(plannerAbortError(parentSignal))
554
+ }
555
+ parentSignal.addEventListener('abort', onAbort, { once: true })
556
+ pending.then((entry) => {
557
+ if (done) return
558
+ done = true
559
+ cleanup()
560
+ resolve(entry)
561
+ }, (error) => {
562
+ if (done) return
563
+ done = true
564
+ cleanup()
565
+ reject(error)
566
+ })
567
+ if (parentSignal.aborted) onAbort()
568
+ })
569
+ }
570
+
571
+ function removeReviewerPending(cacheKey, ownerSignal, pending) {
572
+ const bucket = reviewerRoutePendingCache.get(cacheKey)
573
+ if (bucket === undefined || bucket.get(ownerSignal) !== pending) return
574
+ bucket.delete(ownerSignal)
575
+ if (bucket.size === 0) reviewerRoutePendingCache.delete(cacheKey)
576
+ }
577
+
578
+ function reviewerPendingEntryCount() {
579
+ let count = 0
580
+ for (const bucket of reviewerRoutePendingCache.values()) count += bucket.size
581
+ return count
582
+ }
583
+
584
+ async function resolveReviewerEntry(agent, parentSignal) {
585
+ throwIfReviewerAborted(parentSignal)
586
+ const sources = nonPlannerRouteSources(agent)
587
+ const fallback = nonPlannerFallbackEntry(sources, false)
588
+ const targetModel = getPlannerModel(agent)
589
+ if (targetModel === '') {
590
+ throwIfReviewerAborted(parentSignal)
591
+ return fallback || {}
592
+ }
593
+ const crossProvider = getCrossProviderPlannerModel(agent)
594
+ const parentProvider = fallback !== null && fallback.provider !== undefined ? fallback.provider : ''
595
+ const parentModel = fallback !== null && fallback.model !== undefined ? fallback.model : ''
596
+ const parentMaxTokens = fallback !== null && fallback.maxTokens !== undefined ? String(fallback.maxTokens) : ''
597
+ const cacheKey = targetModel + '|' + (crossProvider ? 'cross' : 'direct') + '|' + parentProvider + '|' + parentModel + '|' + parentMaxTokens
598
+ const ownerSignal = parentSignal !== undefined && parentSignal !== null ? parentSignal : undefined
599
+ throwIfReviewerAborted(ownerSignal)
600
+ const settled = reviewerRouteSettledCache.get(cacheKey)
601
+ if (settled !== undefined) return settled
602
+ const pendingBucket = reviewerRoutePendingCache.get(cacheKey)
603
+ const cached = pendingBucket !== undefined ? pendingBucket.get(ownerSignal) : undefined
604
+ if (cached !== undefined) {
605
+ return awaitReviewerPending(cached, parentSignal, () => removeReviewerPending(cacheKey, ownerSignal, cached))
606
+ }
607
+ throwIfReviewerAborted(ownerSignal)
608
+ // 解析失败不得把 rejection 抛给调用方:普通失败统一兜底为父 fallback,取消原样传播。
609
+ // 同一 ownerSignal 合并 in-flight;不同 signal 旁路独立解析,迟到结果不得回写新条目。
610
+ const pending = (crossProvider
611
+ ? resolvePlannerEntryStrict(agent, ownerSignal)
612
+ : resolvePlannerEntrySingleProvider(agent)
613
+ ).then((entry) => {
614
+ throwIfReviewerAborted(ownerSignal)
615
+ return {
616
+ provider: entry.provider,
617
+ model: entry.model,
618
+ maxTokens: fallback !== null ? fallback.maxTokens : entry.maxTokens,
619
+ }
620
+ }).catch(() => {
621
+ throwIfReviewerAborted(ownerSignal)
622
+ return fallback || {}
623
+ })
624
+ if (reviewerPendingEntryCount() + reviewerRouteSettledCache.size > 32) {
625
+ reviewerRoutePendingCache.clear()
626
+ reviewerRouteSettledCache.clear()
627
+ }
628
+ let ownPendingBucket = reviewerRoutePendingCache.get(cacheKey)
629
+ if (ownPendingBucket === undefined) {
630
+ ownPendingBucket = new Map()
631
+ reviewerRoutePendingCache.set(cacheKey, ownPendingBucket)
632
+ }
633
+ ownPendingBucket.set(ownerSignal, pending)
634
+ pending.then((entry) => {
635
+ const bucket = reviewerRoutePendingCache.get(cacheKey)
636
+ if (bucket === undefined || bucket.get(ownerSignal) !== pending) return
637
+ bucket.delete(ownerSignal)
638
+ if (bucket.size === 0) reviewerRoutePendingCache.delete(cacheKey)
639
+ if (ownerSignal !== undefined && ownerSignal.aborted) return
640
+ if (reviewerRouteSettledCache.has(cacheKey)) return
641
+ reviewerRouteSettledCache.set(cacheKey, entry)
642
+ }, () => {
643
+ removeReviewerPending(cacheKey, ownerSignal, pending)
644
+ })
645
+ return awaitReviewerPending(pending, parentSignal, () => removeReviewerPending(cacheKey, ownerSignal, pending))
646
+ }
647
+ return { resolvePlannerEntry, resolveOtherAgentEntry, resolveReviewerEntry }
648
+ }