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.
- package/LICENSE +21 -0
- package/README.md +179 -2
- package/assets/presets/extra-plan/agent.cordis.yml +580 -0
- package/assets/presets/extra-plan/preset-definition-extra-plan-executor.generated.yml +115 -0
- package/assets/presets/extra-plan/preset-definition-extra-plan-planner.generated.yml +113 -0
- package/assets/presets/extra-plan/preset-definition-extra-plan-prober.generated.yml +107 -0
- package/assets/presets/extra-plan/preset-definition-extra-plan-reviewer.generated.yml +115 -0
- package/assets/presets/extra-plan/preset-definition.generated.yml +335 -0
- package/assets/presets/extra-plan/preset.yml +2 -0
- package/cordis.patch.yml +7 -0
- package/index.js +1671 -0
- package/lib/agent-runtime.js +172 -0
- package/lib/agent-session.js +65 -0
- package/lib/assembly-presentation.js +267 -0
- package/lib/client-carrier.js +7 -0
- package/lib/client.js +314 -0
- package/lib/extra-plan-gate-tool.js +387 -0
- package/lib/gate-decisions.js +744 -0
- package/lib/gate-words.js +108 -0
- package/lib/live-config.js +293 -0
- package/lib/log-retention.js +132 -0
- package/lib/model-routing.js +648 -0
- package/lib/path-policy.js +464 -0
- package/lib/plan-draft-tool.js +294 -0
- package/lib/planner-budget.js +136 -0
- package/lib/preset-defaults.generated.js +17 -0
- package/lib/preset-settings.js +3 -0
- package/lib/preset-sync.js +809 -0
- package/lib/preset-yaml.js +438 -0
- package/lib/role-contract.js +11 -0
- package/lib/run-code-scanner.js +360 -0
- package/lib/run-code-static.js +621 -0
- package/lib/runtime-diagnostics.js +89 -0
- package/lib/runtime-lifecycle.js +162 -0
- package/lib/runtime-static.js +23 -0
- package/lib/save-contract.js +263 -0
- package/lib/save-persistence.js +223 -0
- package/lib/save-plan-markdown-parser.js +369 -0
- package/lib/save-plan-validation-diagnostics.js +49 -0
- package/lib/save-plan-validation.js +812 -0
- package/lib/save-probe-validation.js +173 -0
- package/lib/save-source-verification.js +195 -0
- package/lib/save-tool-factories.js +270 -0
- package/lib/sdk-text-cache.js +161 -0
- package/lib/settings-contract.js +191 -0
- package/lib/settings.js +369 -0
- package/lib/shell-mutation.js +484 -0
- package/lib/usage-ledger-background.js +214 -0
- package/lib/usage-ledger-worker.js +116 -0
- package/lib/usage-ledger.js +1393 -0
- package/locale/en.json +6 -0
- package/locale/settings/en.json +6 -0
- package/locale/settings/zh.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +56 -4
- package/scripts/generate-runtime-defaults.mjs +796 -0
package/index.js
ADDED
|
@@ -0,0 +1,1671 @@
|
|
|
1
|
+
// dsh-extra-plan 入口:route/purpose/clarified 三锚点、extra_plan_gate 闸门入口、子角色、A/C/M 投影、
|
|
2
|
+
// save 工件、探查预算、模型路由、按 session 隔离的 usage 与宿主事件契约。
|
|
3
|
+
// 当前本地契约紧邻决策实现;架构与历史见 pe-test/docs/ai-概览.md、ai-机制设计.md、
|
|
4
|
+
// ai-宿主耦合台账.md 及历史归档。
|
|
5
|
+
// 本模块不安装独立的规划模式;save_plan 仅是受限的工作工件例外。
|
|
6
|
+
// 配置值来自宿主 live source;此处注释不是第二个真源。
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
// F 段(HP 首轮)tool:read 的内置兜底文案(= 预设 agent.cordis.yml 的 bootstrapReadHint 示例,逐字一致)。
|
|
10
|
+
// 除代码外用中文;要点保留:工具名 read 与程序内 tools.read(...) 调用形态、file_path 必填。
|
|
11
|
+
// 参数默认值与返回形状由宿主 read 契约(dsh-tool-fs)单独承载,不写进本文案。
|
|
12
|
+
// 与宿主 read 契约的人工核对见台账 HS26。
|
|
13
|
+
const BOOTSTRAP_READ_HINT_FALLBACK = [
|
|
14
|
+
'run_code 调用 read 示例:',
|
|
15
|
+
"try {return await tools.read({file_path:'README.md'})} catch (e) {console.log(String(e))}"
|
|
16
|
+
].join('\n')
|
|
17
|
+
|
|
18
|
+
// 路由/目的 ask 的关键词唯一真源是 YAML(config.gateWords,见 agent.cordis.yml):
|
|
19
|
+
// JS 侧只有字段规格、派生与严格校验(lib/gate-words.js),没有内置词值、没有默认词表。
|
|
20
|
+
// 每次 apply 现场 createGateRuntime(cfg.gateWords) 建立本 agent scope 的词表,并作为
|
|
21
|
+
// 显式参数贯穿全部 helper、状态机与闸门(helper 不得自建默认词表、不得改走模块全局)。
|
|
22
|
+
// 供场景测试直接复用(消除"复制品"漂移)。模块顶层无副作用,纯 Node 可 import。
|
|
23
|
+
export const decisions = {
|
|
24
|
+
FREE_TOOLS,
|
|
25
|
+
PWSH_MUTATION,
|
|
26
|
+
BASH_MUTATION,
|
|
27
|
+
PWSH_BARE_WORDS,
|
|
28
|
+
BASH_BARE_WORDS,
|
|
29
|
+
bashCommandOf,
|
|
30
|
+
bashMutationMatches,
|
|
31
|
+
isSubagentChild,
|
|
32
|
+
isExplicitRoute,
|
|
33
|
+
isExplicitEffort,
|
|
34
|
+
isLiveDelegation,
|
|
35
|
+
isBootstrapPhase,
|
|
36
|
+
filterBootstrapContextDecision,
|
|
37
|
+
dedupeProjectedContextDecision,
|
|
38
|
+
pwshCommandOf,
|
|
39
|
+
pwshMutationMatches,
|
|
40
|
+
catalogHasWriteTools,
|
|
41
|
+
isReadOnlyChildByCatalog,
|
|
42
|
+
catalogIsCollapsed,
|
|
43
|
+
schemasHasWriteTools,
|
|
44
|
+
schemasHasTool,
|
|
45
|
+
deriveFlowState,
|
|
46
|
+
applyGateOutcome,
|
|
47
|
+
toolCallCount,
|
|
48
|
+
toolCallsSinceUser,
|
|
49
|
+
withPlannerPromptSuffix,
|
|
50
|
+
BUDGET_REMINDER_THRESHOLD,
|
|
51
|
+
budgetNoticeText,
|
|
52
|
+
withBudgetNotice,
|
|
53
|
+
budgetReminderText,
|
|
54
|
+
budgetReminderMessage,
|
|
55
|
+
budgetReminderSent,
|
|
56
|
+
budgetExhaustedReason,
|
|
57
|
+
budgetExceeded,
|
|
58
|
+
routeDenyReason,
|
|
59
|
+
planDenyReason,
|
|
60
|
+
executorDenyReason,
|
|
61
|
+
sanitizeTaskName,
|
|
62
|
+
timestamp,
|
|
63
|
+
renderSavePlan,
|
|
64
|
+
PROBE_LIMITS,
|
|
65
|
+
validateProbe,
|
|
66
|
+
renderSaveProbe,
|
|
67
|
+
renderProbeMarkdown,
|
|
68
|
+
extractProbeEvidenceRefs,
|
|
69
|
+
RUNCODE_MUTATION_HINTS,
|
|
70
|
+
codeMutationHints,
|
|
71
|
+
decomposeRunCode,
|
|
72
|
+
runCodeCatchGateReason,
|
|
73
|
+
collectRunCodeSites,
|
|
74
|
+
askOrGateReturnGateReason,
|
|
75
|
+
runCodeSiteCount,
|
|
76
|
+
isRunCodeSubCall,
|
|
77
|
+
runCodeDispatchCapText,
|
|
78
|
+
runCodeGroupDenyReason,
|
|
79
|
+
childControlGateReason,
|
|
80
|
+
subagentProbeGateReason,
|
|
81
|
+
shellMutationReason,
|
|
82
|
+
plannerGateReason,
|
|
83
|
+
childReadonlyGateReason,
|
|
84
|
+
mainGateReason,
|
|
85
|
+
aggregateRunCodeDenyReason,
|
|
86
|
+
jobOutputGateReason,
|
|
87
|
+
recordJobOutputCall,
|
|
88
|
+
pollGuardGateReason,
|
|
89
|
+
recordPollGuardCall,
|
|
90
|
+
probeDisposalWarning,
|
|
91
|
+
resolveAgentRouteSources,
|
|
92
|
+
decidePlannerModelUse,
|
|
93
|
+
PLANNER_PROBE_TIMEOUT_MS,
|
|
94
|
+
PLANNER_BLOCKED_REASON,
|
|
95
|
+
NON_PLANNER_BLOCKED_REASON,
|
|
96
|
+
sortPlannerCandidates,
|
|
97
|
+
CORDIS_PRESENTATION_TOOLS,
|
|
98
|
+
projectAssemblyForPresentation,
|
|
99
|
+
renderFilteredToolsSdk,
|
|
100
|
+
resolveToolsSdkRenderer,
|
|
101
|
+
sdkSchemasForRendering,
|
|
102
|
+
projectSkillCatalogDecision,
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export const name = 'extra-plan'
|
|
106
|
+
export const inject = ['systemPrompt']
|
|
107
|
+
|
|
108
|
+
import { dirname, resolve as pathResolve } from 'node:path'
|
|
109
|
+
import { createPathContext, resolveHostPath } from './lib/path-policy.js'
|
|
110
|
+
import { createRuntimeDiagnostics } from './lib/runtime-diagnostics.js'
|
|
111
|
+
import { PROBE_LIMITS, sanitizeTaskName, timestamp, renderSavePlan, renderSaveProbe, renderProbeMarkdown, extractProbeEvidenceRefs } from './lib/save-contract.js'
|
|
112
|
+
import { validateProbe } from './lib/save-probe-validation.js'
|
|
113
|
+
import { atomicCommit, atomicReplace } from './lib/save-persistence.js'
|
|
114
|
+
import { createSaveToolFactories } from './lib/save-tool-factories.js'
|
|
115
|
+
import { createPlanDraftToolFactories } from './lib/plan-draft-tool.js'
|
|
116
|
+
import { createGateToolFactories } from './lib/extra-plan-gate-tool.js'
|
|
117
|
+
import { RUNCODE_MUTATION_HINTS, codeMutationHints } from './lib/run-code-static.js'
|
|
118
|
+
import { PWSH_MUTATION, BASH_MUTATION, PWSH_BARE_WORDS, BASH_BARE_WORDS, pwshCommandOf, bashCommandOf, pwshMutationMatches, bashMutationMatches } from './lib/shell-mutation.js'
|
|
119
|
+
import { DEFAULT_SETTINGS } from './lib/preset-defaults.generated.js'
|
|
120
|
+
import { toolCallCount, toolCallsSinceUser, withPlannerPromptSuffix, BUDGET_REMINDER_THRESHOLD, budgetNoticeText, withBudgetNotice, budgetReminderText, budgetReminderMessage, budgetReminderSent, budgetExhaustedReason, budgetExceeded } from './lib/planner-budget.js'
|
|
121
|
+
import { causeChainOf } from './lib/runtime-static.js'
|
|
122
|
+
import { createAgentRuntime, isLiveDelegation } from './lib/agent-runtime.js'
|
|
123
|
+
import { sessionEvents, isSubagentChild, observeSessionLeaseOf } from './lib/agent-session.js'
|
|
124
|
+
import { createModelRouting, isExplicitRoute, isExplicitEffort, resolveAgentRouteSources, decidePlannerModelUse, PLANNER_PROBE_TIMEOUT_MS, PLANNER_BLOCKED_REASON, NON_PLANNER_BLOCKED_REASON, sortPlannerCandidates } from './lib/model-routing.js'
|
|
125
|
+
import { FREE_TOOLS, routeDenyReason, planDenyReason, executorDenyReason, applyGateOutcome, isBootstrapPhase, deriveFlowState, filterBootstrapContextDecision, dedupeProjectedContextDecision, catalogHasWriteTools, isReadOnlyChildByCatalog, schemasHasWriteTools, schemasHasTool, catalogIsCollapsed, subagentProbeGateReason, shellMutationReason, childControlGateReason, plannerGateReason, childReadonlyGateReason, jobOutputGateReason, recordJobOutputCall, pollGuardGateReason, recordPollGuardCall, probeDisposalWarning, mainGateReason, runCodeGroupDenyReason, aggregateRunCodeDenyReason, decomposeRunCode, runCodeCatchGateReason, collectRunCodeSites, askOrGateReturnGateReason, runCodeSiteCount, isRunCodeSubCall, runCodeDispatchCapText } from './lib/gate-decisions.js'
|
|
126
|
+
import { CORDIS_PRESENTATION_TOOLS, projectAssemblyForPresentation, renderFilteredToolsSdk, resolveToolsSdkRenderer, sdkSchemasForRendering, toolSdkSchemasOf, projectSkillCatalogDecision, PTC_SECTION_NAME, READ_SECTION_NAME, SDK_SECTION_NAME, sectionOf, hasSection, hasNonEmptySection } from './lib/assembly-presentation.js'
|
|
127
|
+
import { createSdkTextCache } from './lib/sdk-text-cache.js'
|
|
128
|
+
import { createRuntimeLifecycle } from './lib/runtime-lifecycle.js'
|
|
129
|
+
import { GATE_WORD_FIELDS, createGateRuntime } from './lib/gate-words.js'
|
|
130
|
+
import { PROBER_PRESET_ID } from './lib/role-contract.js'
|
|
131
|
+
import { createLiveConfig } from './lib/live-config.js'
|
|
132
|
+
import { createDeveloperMessage } from '@deepseek-ai/dsh-llm'
|
|
133
|
+
import z from '@deepseek-ai/schemastery'
|
|
134
|
+
|
|
135
|
+
const DEFAULT_DIAG_FILE = 'extra-plan-request-errors.jsonl'
|
|
136
|
+
|
|
137
|
+
// 主插件 Config 对应 id=extra-plan;lib/settings.js 的 Config 对应 id=dsh-extra-plan-settings。
|
|
138
|
+
// 二者不复用、不互相导入;settings Config 仍独立维护 11 个 volatile 字段。
|
|
139
|
+
export const Config = z.object({
|
|
140
|
+
gateWords: z.dict(z.string()).required(),
|
|
141
|
+
planTool: z.string().default('subagent_plan'),
|
|
142
|
+
savePlanDir: z.string().default('.extra-plan'),
|
|
143
|
+
plannerModel: z.string().default(DEFAULT_SETTINGS.plannerModel),
|
|
144
|
+
otherAgentModel: z.string().default(DEFAULT_SETTINGS.otherAgentModel),
|
|
145
|
+
reviewerUsesPlannerModel: z.boolean().default(DEFAULT_SETTINGS.reviewerUsesPlannerModel),
|
|
146
|
+
exploreBudget: z.number().step(1).min(1).default(DEFAULT_SETTINGS.exploreBudget),
|
|
147
|
+
plannerPromptSuffix: z.string().default(DEFAULT_SETTINGS.plannerPromptSuffix),
|
|
148
|
+
anchoredBootstrap: z.boolean().default(DEFAULT_SETTINGS.anchoredBootstrap),
|
|
149
|
+
creativeMode: z.boolean().default(DEFAULT_SETTINGS.creativeMode),
|
|
150
|
+
webFetch: z.boolean().default(DEFAULT_SETTINGS.webFetch),
|
|
151
|
+
runcodeCatchGate: z.boolean().default(DEFAULT_SETTINGS.runcodeCatchGate),
|
|
152
|
+
crossProviderPlannerModel: z.boolean().default(DEFAULT_SETTINGS.crossProviderPlannerModel),
|
|
153
|
+
bootstrapPersona: z.string().default('You are a helpful software engineer assistant.'),
|
|
154
|
+
bootstrapReadHint: z.string().default(BOOTSTRAP_READ_HINT_FALLBACK),
|
|
155
|
+
bootstrapShellTools: z.array(z.string()).default(['bash', 'pwsh']),
|
|
156
|
+
bootstrapCommonTools: z.array(z.string()).default(['read']),
|
|
157
|
+
// 已退役:无运行期消费者,仅作旧配置兼容(保留字段与默认值,旧配置文件带该键时不改变行为)。
|
|
158
|
+
usageLedger: z.object({
|
|
159
|
+
enabled: z.boolean().default(false),
|
|
160
|
+
path: z.string().default(''),
|
|
161
|
+
}).default({ enabled: false, path: '' }),
|
|
162
|
+
diagFile: z.string().default(DEFAULT_DIAG_FILE),
|
|
163
|
+
})
|
|
164
|
+
|
|
165
|
+
// ── save_probe/任意工具参数截断 → MALFORMED_RESPONSE 整轮致命的限次自愈(v0.3.1) ──────
|
|
166
|
+
// 机制:宿主 dsh-llm-deepseek 在消息流结束处对每个 tool-call 参数严格 JSON.parse,失败抛
|
|
167
|
+
// LlmError('... tool input is invalid JSON', 'MALFORMED_RESPONSE');该码不在宿主默认重试码集
|
|
168
|
+
// (DEFAULT_RETRYABLE_CODES),llm-retry 直接放行 → agent/request-error waterfall 若无人返回
|
|
169
|
+
// {kind:'retry'},本轮整体终止。参数非法时工具 execute 根本不会被调用(解析发生在宿主流层),
|
|
170
|
+
// 修复只能落在 request-error 兜底、不能落在 save_probe 工具内;失败回合工具未执行、无副作用,
|
|
171
|
+
// 重试一次是安全的。
|
|
172
|
+
// malformedRecovery 为模块级函数(须被导出供回归冒烟直呼,apply 闭包函数无法导出);
|
|
173
|
+
// per-session 重试账本 malformedRetried 按 sessionId 分桶(本插件每个会话各持一份 apply
|
|
174
|
+
// 实例,模块级 Map + sessionId 键在「模块共享/每会话独立」两种装载模型下语义一致),
|
|
175
|
+
// disposed 时按 sessionId 回收(见 agent/disposed 监听器)。
|
|
176
|
+
// 注入形状(已按当前宿主源码核实;2026-09-25 订正):developer/message 在已知事件白名单
|
|
177
|
+
// (dsh-session lib/types/known-event-types.js L36);append 必须带 surfaceOp:'append'
|
|
178
|
+
// (dsh-session lib/index.js L294-308);message 需非空 id、role='developer'、source.kind
|
|
179
|
+
// 非空字符串、content 数组(同文件 L1151-1176);纯文本 content 不得带 headerSeq(L246-256)。
|
|
180
|
+
// **原记「invariant.js 无该分支(故无需坐标)」已被宿主源码证伪**:v4 行准入要求
|
|
181
|
+
// developer/message 自带 turn/step 且均为 ≥1 的整数,宿主 append 只补 seq/time、绝不补坐标,
|
|
182
|
+
// 坐标必须由调用方给出(实机报错为 SessionFormatError: developer/message turn must be a
|
|
183
|
+
// non-negative safe integer);关系校验 companion 未挂载于活动 profile,故只需满足行准入。
|
|
184
|
+
// source 同须用生产者自有 kind,v4 禁止旧包裹形状(kind 取旧兜底值 plugin + plugin 包名字段);本插件统一 plugin:dsh-extra-plan。
|
|
185
|
+
const MALFORMED_RETRY_HINT = '你上一次的某个工具调用参数在传输中被截断,宿主侧无法把参数解析成合法 JSON,本次请求以 MALFORMED_RESPONSE 失败,该工具未执行、没有产生任何副作用。请在重试时压缩并重写该工具调用的参数:缩短长文本与证据列表、只保留核实结论必需的行号/数值/文案,确保参数是完整合法的 JSON,再原样重发同一调用。'
|
|
186
|
+
|
|
187
|
+
// sessionId → Set('turn:step'):同一回合同一步只兜底 1 次(防重试死循环)。
|
|
188
|
+
const malformedRetried = new Map()
|
|
189
|
+
|
|
190
|
+
// 判定链:① 非 MALFORMED_RESPONSE 不干预;② signal.aborted 绝不干扰用户取消;
|
|
191
|
+
// ③ agent.session.header.id 非字符串不干预;④ 同 (turn:step) 已兜底过则不重复;
|
|
192
|
+
// ⑤ 首次命中:记账 + 注入中文 developer 提示(模型在重试请求中可见),注入失败只吞掉、
|
|
193
|
+
// 不阻断自愈;⑥ 返回 { kind: 'retry' } → dsh-agent-loop 重试该步。任何意外异常一律
|
|
194
|
+
// 返回 null 透传(自愈兜底绝不放大故障)。
|
|
195
|
+
function malformedRecovery(payload) {
|
|
196
|
+
try {
|
|
197
|
+
if (payload === undefined || payload === null || typeof payload !== 'object') return null
|
|
198
|
+
const failure = payload.failure
|
|
199
|
+
if (failure === undefined || failure === null || failure.code !== 'MALFORMED_RESPONSE') return null
|
|
200
|
+
if (payload.signal !== undefined && payload.signal !== null && payload.signal.aborted) return null
|
|
201
|
+
const agent = payload.agent
|
|
202
|
+
const sessionId = agent !== undefined && agent !== null && agent.session !== undefined && agent.session !== null && agent.session.header !== undefined && agent.session.header !== null
|
|
203
|
+
? agent.session.header.id
|
|
204
|
+
: ''
|
|
205
|
+
if (typeof sessionId !== 'string' || sessionId === '') return null
|
|
206
|
+
const key = `${payload.turn}:${payload.step}`
|
|
207
|
+
let set = malformedRetried.get(sessionId)
|
|
208
|
+
if (set !== undefined && set.has(key)) return null
|
|
209
|
+
if (set === undefined) {
|
|
210
|
+
set = new Set()
|
|
211
|
+
malformedRetried.set(sessionId, set)
|
|
212
|
+
}
|
|
213
|
+
set.add(key)
|
|
214
|
+
// 坐标防御:v4 行准入要求 developer/message 自带 ≥1 的 turn/step 且宿主 append 不补坐标,
|
|
215
|
+
// 而 request-error 的 payload 在个别场景可能缺坐标或非正整数——此时跳过注入,但仍返回
|
|
216
|
+
// { kind: 'retry' },使自愈主路径不因注入条件不满足而失效。
|
|
217
|
+
if (Number.isInteger(payload.turn) && payload.turn >= 1 && Number.isInteger(payload.step) && payload.step >= 1) {
|
|
218
|
+
try {
|
|
219
|
+
const message = createDeveloperMessage({ content: [{ type: 'text', text: MALFORMED_RETRY_HINT }], source: { kind: 'plugin:dsh-extra-plan' } })
|
|
220
|
+
agent.session.append('developer/message', { turn: payload.turn, step: payload.step, message }, { surfaceOp: 'append' })
|
|
221
|
+
} catch (error) {
|
|
222
|
+
console.warn(`extra-plan: malformed retry hint append failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return { kind: 'retry' }
|
|
226
|
+
} catch (error) {
|
|
227
|
+
return null
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function safeContextGet(ctx, key) {
|
|
232
|
+
try {
|
|
233
|
+
return ctx !== undefined && ctx !== null && typeof ctx.get === 'function' ? ctx.get(key) : undefined
|
|
234
|
+
} catch (error) {
|
|
235
|
+
return undefined
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function absoluteRoot(value) {
|
|
240
|
+
if (typeof value !== 'string' || value.trim() === '') return null
|
|
241
|
+
try {
|
|
242
|
+
return createPathContext({ workspaceRoot: value }).workspaceRoot
|
|
243
|
+
} catch {
|
|
244
|
+
return null
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function rootFact(value, present) {
|
|
249
|
+
if (present !== true) return { state: 'missing', path: null }
|
|
250
|
+
const normalized = absoluteRoot(value)
|
|
251
|
+
return normalized === null ? { state: 'invalid', path: null } : { state: 'valid', path: normalized }
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function sameRoot(left, right) {
|
|
255
|
+
if (left === null || right === null) return false
|
|
256
|
+
const a = pathResolve(left)
|
|
257
|
+
const b = pathResolve(right)
|
|
258
|
+
return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function configEditorServiceOf(ctx) {
|
|
262
|
+
const editor = safeContextGet(ctx, 'configEditor')
|
|
263
|
+
return editor !== undefined && editor !== null && typeof editor.configuration === 'function' && typeof editor.edit === 'function' ? editor : null
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function documentFact(value, present) {
|
|
267
|
+
if (present !== true || value === undefined || value === null || value === '') return { state: 'missing', path: null }
|
|
268
|
+
const normalized = absoluteRoot(value)
|
|
269
|
+
return normalized === null ? { state: 'invalid', path: null } : { state: 'valid', path: normalized }
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function profileFactsOf(ctx) {
|
|
273
|
+
const profile = safeContextGet(ctx, 'profileContext')
|
|
274
|
+
const has = (key) => profile !== undefined && profile !== null && Object.prototype.hasOwnProperty.call(profile, key)
|
|
275
|
+
const profileHomeFact = rootFact(profile?.home, has('home'))
|
|
276
|
+
const profilePatchFact = rootFact(profile?.patchPath, has('patchPath'))
|
|
277
|
+
const installAnchorFact = rootFact(profile?.installAnchor, has('installAnchor'))
|
|
278
|
+
const editor = configEditorServiceOf(ctx)
|
|
279
|
+
let editorDocumentFact = { state: 'missing', path: null }
|
|
280
|
+
if (editor !== null) {
|
|
281
|
+
try { editorDocumentFact = documentFact(editor.documentPath, editor.documentPath !== undefined) } catch (error) { editorDocumentFact = { state: 'invalid', path: null } }
|
|
282
|
+
}
|
|
283
|
+
let documentState = 'missing'
|
|
284
|
+
let documentPath = null
|
|
285
|
+
let documentCapability = null
|
|
286
|
+
if (profilePatchFact.state === 'invalid' || editorDocumentFact.state === 'invalid') documentState = 'invalid'
|
|
287
|
+
else if (profilePatchFact.state === 'valid' && editorDocumentFact.state === 'valid' && !sameRoot(profilePatchFact.path, editorDocumentFact.path)) documentState = 'conflict'
|
|
288
|
+
else if (editorDocumentFact.state === 'valid') {
|
|
289
|
+
documentState = 'valid'
|
|
290
|
+
documentPath = editorDocumentFact.path
|
|
291
|
+
documentCapability = profilePatchFact.state === 'valid' ? 'profilePatch' : 'editorDocument'
|
|
292
|
+
} else if (profilePatchFact.state === 'valid') {
|
|
293
|
+
documentState = 'valid'
|
|
294
|
+
documentPath = profilePatchFact.path
|
|
295
|
+
documentCapability = 'profilePatch'
|
|
296
|
+
}
|
|
297
|
+
const homeProvider = safeContextGet(ctx, 'dshHomePath')
|
|
298
|
+
let dshHomeFact = { state: 'missing', path: null }
|
|
299
|
+
if (typeof homeProvider === 'function') {
|
|
300
|
+
try { dshHomeFact = rootFact(homeProvider(), true) } catch (error) { dshHomeFact = { state: 'invalid', path: null } }
|
|
301
|
+
}
|
|
302
|
+
const envPresent = Object.prototype.hasOwnProperty.call(process.env, 'DSH_HOME')
|
|
303
|
+
const envHomeFact = rootFact(process.env.DSH_HOME, envPresent)
|
|
304
|
+
const trustedSources = [profileHomeFact, dshHomeFact]
|
|
305
|
+
const invalidTrustedSource = trustedSources.some((item) => item.state === 'invalid')
|
|
306
|
+
const validSources = trustedSources.filter((item) => item.state === 'valid')
|
|
307
|
+
const trustedConflict = validSources.some((item) => !sameRoot(item.path, validSources[0]?.path))
|
|
308
|
+
const envConflict = validSources.length > 0 && envHomeFact.state === 'valid' && !sameRoot(envHomeFact.path, validSources[0]?.path)
|
|
309
|
+
const envInvalidWithTrustedRoot = validSources.length > 0 && envHomeFact.state === 'invalid'
|
|
310
|
+
const hostConflict = trustedConflict || envConflict
|
|
311
|
+
const hostState = invalidTrustedSource || envInvalidWithTrustedRoot ? 'invalid' : hostConflict ? 'conflict' : validSources.length === 0 ? 'missing' : 'valid'
|
|
312
|
+
const hostDataRoot = hostState === 'valid' ? validSources[0].path : null
|
|
313
|
+
return {
|
|
314
|
+
hostDataRoot,
|
|
315
|
+
hostState,
|
|
316
|
+
profilePatch: profilePatchFact.state === 'valid' ? profilePatchFact.path : null,
|
|
317
|
+
documentState,
|
|
318
|
+
documentPath,
|
|
319
|
+
documentCapability,
|
|
320
|
+
installAnchor: installAnchorFact.state === 'valid' ? installAnchorFact.path : null,
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function installAnchorOf(ctx) {
|
|
325
|
+
return profileFactsOf(ctx).installAnchor
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// 0.2.2-rc.1 修复(BUG-3):授权根重叠判定(大小写不敏感、双向包含)。
|
|
329
|
+
// 只读代码根与 W/H 任一方向重叠时必须跳过注册,否则只读能力会把工作区或数据根变成全域禁写。
|
|
330
|
+
function pathRootsOverlap(left, right) {
|
|
331
|
+
if (typeof left !== 'string' || typeof right !== 'string') return false
|
|
332
|
+
if (left === '' || right === '') return false
|
|
333
|
+
const sep = left.includes('\\') || right.includes('\\') ? '\\' : '/'
|
|
334
|
+
const a = left.replace(/[\\/]+$/, '').toLowerCase()
|
|
335
|
+
const b = right.replace(/[\\/]+$/, '').toLowerCase()
|
|
336
|
+
if (a === '' || b === '') return false
|
|
337
|
+
return a === b || a.startsWith(b + sep) || b.startsWith(a + sep)
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function pathContextFor(ctx, cwd) {
|
|
341
|
+
const facts = profileFactsOf(ctx)
|
|
342
|
+
const workspaceRoot = absoluteRoot(cwd)
|
|
343
|
+
const capabilities = {}
|
|
344
|
+
if (facts.profilePatch !== null) capabilities.profilePatch = { path: facts.profilePatch, type: 'file', access: 'write', purpose: 'config-editor' }
|
|
345
|
+
if (facts.documentCapability === 'editorDocument' && facts.documentPath !== null) capabilities.editorDocument = { path: facts.documentPath, type: 'file', access: 'read', purpose: 'config-editor' }
|
|
346
|
+
if (facts.installAnchor !== null) capabilities.installAnchor = { path: facts.installAnchor, type: 'file', access: 'read', purpose: 'install-anchor' }
|
|
347
|
+
// 0.2.2-rc.1 修复(BUG-3):宿主只读代码根(installAnchor 所在安装目录)作为 probe-reference
|
|
348
|
+
// 证据根,供探查者引用宿主源码取证。只读;与 workspaceRoot / hostDataRoot 重叠时跳过注册。
|
|
349
|
+
if (facts.installAnchor !== null) {
|
|
350
|
+
const installRootPath = dirname(facts.installAnchor)
|
|
351
|
+
const hostDataRootPath = facts.hostState === 'valid' && facts.hostDataRoot !== null ? facts.hostDataRoot : null
|
|
352
|
+
if (!pathRootsOverlap(installRootPath, workspaceRoot) && !pathRootsOverlap(installRootPath, hostDataRootPath)) {
|
|
353
|
+
capabilities.installRoot = { path: installRootPath, type: 'directory', access: 'read', purpose: 'probe-reference' }
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
const options = { hostCapabilities: capabilities }
|
|
357
|
+
if (workspaceRoot !== null) options.workspaceRoot = workspaceRoot
|
|
358
|
+
if (facts.hostState === 'valid' && facts.hostDataRoot !== null) options.hostDataRoot = facts.hostDataRoot
|
|
359
|
+
if (options.workspaceRoot === undefined && options.hostDataRoot === undefined && Object.keys(capabilities).length === 0) return null
|
|
360
|
+
try { return createPathContext(options) } catch (error) { return null }
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function resolveDocumentTargetFor(ctx, agent) {
|
|
364
|
+
const facts = profileFactsOf(ctx)
|
|
365
|
+
if (facts.documentState === 'invalid') throw new Error('配置文档事实非法,拒绝热读')
|
|
366
|
+
if (facts.documentState === 'conflict') throw new Error('配置文档事实矛盾,拒绝热读')
|
|
367
|
+
if (facts.documentPath === null || facts.documentCapability === null) return ''
|
|
368
|
+
const context = pathContextFor(ctx, sessionCwdOf(agent))
|
|
369
|
+
if (context === null) return ''
|
|
370
|
+
return resolveHostPath(context, facts.documentPath, { capability: facts.documentCapability, purpose: 'config-editor' })
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function sessionCwdOf(agent) {
|
|
374
|
+
const session = agent !== undefined && agent !== null ? agent.session : undefined
|
|
375
|
+
const header = session !== undefined && session !== null ? session.header : undefined
|
|
376
|
+
return header !== undefined && header !== null && typeof header.cwd === 'string' ? header.cwd : ''
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const { prepareDiagnosticPath, appendDiagnostic, recordAgentError } = createRuntimeDiagnostics({
|
|
380
|
+
sessionCwdOf,
|
|
381
|
+
pathContextFor,
|
|
382
|
+
profileFactsOf,
|
|
383
|
+
absoluteRoot,
|
|
384
|
+
defaultDiagnosticFile: DEFAULT_DIAG_FILE,
|
|
385
|
+
})
|
|
386
|
+
|
|
387
|
+
export { PROBE_LIMITS, extractProbeEvidenceRefs, malformedRecovery, recordAgentError }
|
|
388
|
+
|
|
389
|
+
export function apply(ctx, config) {
|
|
390
|
+
const cfg = config !== null && typeof config === 'object' ? config : {}
|
|
391
|
+
// 闸门词表(唯一值源 = 本次 apply 的 YAML config.gateWords):缺失/非法同步抛出,
|
|
392
|
+
// 阻止该预设被使用(不回退到任何内置旧词)。必须在任何工具/监听器/服务副作用之前求值。
|
|
393
|
+
const gateRuntime = createGateRuntime(cfg.gateWords)
|
|
394
|
+
// prompt variable 注册(当前 agent scope,恰好 6 个):persona 的 {{extra_plan_*}} 依赖它。
|
|
395
|
+
// provider 返回本次 apply 捕获的值(改 YAML 后普通重启即生效);effect 随 scope 释放,
|
|
396
|
+
// 不注册全局变量、不跨 apply 缓存。
|
|
397
|
+
ctx.effect(() => {
|
|
398
|
+
const disposers = []
|
|
399
|
+
for (const item of GATE_WORD_FIELDS) {
|
|
400
|
+
const dispose = ctx.systemPrompt.variable(item.variable, () => gateRuntime.words[item.field])
|
|
401
|
+
if (typeof dispose === 'function') disposers.push(dispose)
|
|
402
|
+
}
|
|
403
|
+
return () => {
|
|
404
|
+
for (const dispose of disposers) dispose()
|
|
405
|
+
}
|
|
406
|
+
})
|
|
407
|
+
const planToolName = typeof cfg.planTool === 'string' ? cfg.planTool : 'subagent_plan'
|
|
408
|
+
const savePlanDir = typeof cfg.savePlanDir === 'string' && cfg.savePlanDir !== '' ? cfg.savePlanDir : '.extra-plan'
|
|
409
|
+
const { defineSavePlan, defineSaveProbe } = createSaveToolFactories({
|
|
410
|
+
savePlanDir,
|
|
411
|
+
atomicCommit,
|
|
412
|
+
atomicReplace,
|
|
413
|
+
getPathContext: (cwd) => pathContextFor(ctx, cwd),
|
|
414
|
+
})
|
|
415
|
+
// edit_plan_draft(草稿修复工具)与 save_plan 并列接线:草稿工厂独立实例,不塞进 save 工厂内部。
|
|
416
|
+
const { defineEditPlanDraft } = createPlanDraftToolFactories({
|
|
417
|
+
savePlanDir,
|
|
418
|
+
atomicCommit,
|
|
419
|
+
atomicReplace,
|
|
420
|
+
getPathContext: (cwd) => pathContextFor(ctx, cwd),
|
|
421
|
+
})
|
|
422
|
+
// ── 配置热读:10 项设置从「apply 期一次性常量」改为「消费点现场取值」 ──────
|
|
423
|
+
// 设置页改 YAML 后同会话即时生效(无需重启);取值经 mtime+size 变更检测缓存,
|
|
424
|
+
// 文件未变时零读盘零解析,详见 lib/live-config.js。fallbackDefaults = apply 期
|
|
425
|
+
// cfg 快照:既是磁盘不可用/解析失败时的兜底,也是本实例初始值(生产上与该
|
|
426
|
+
// YAML 同源——cfg 就是该文件当时的解析结果)。
|
|
427
|
+
const liveConfig = createLiveConfig({
|
|
428
|
+
// 路径决议(T6):只消费真实ctx服务/可信profile事实生成的精确Host目标;
|
|
429
|
+
// 不把裸 configEditor.documentPath 交给通用H根,也不由普通路径形状自授能力。
|
|
430
|
+
resolveDocumentTarget: (agent) => resolveDocumentTargetFor(ctx, agent),
|
|
431
|
+
getPathContext: (agent) => pathContextFor(ctx, sessionCwdOf(agent)),
|
|
432
|
+
fallbackDefaults: {
|
|
433
|
+
plannerModel: typeof cfg.plannerModel === 'string' ? cfg.plannerModel : DEFAULT_SETTINGS.plannerModel,
|
|
434
|
+
otherAgentModel: typeof cfg.otherAgentModel === 'string' ? cfg.otherAgentModel.trim() : DEFAULT_SETTINGS.otherAgentModel,
|
|
435
|
+
reviewerUsesPlannerModel: typeof cfg.reviewerUsesPlannerModel === 'boolean' ? cfg.reviewerUsesPlannerModel : DEFAULT_SETTINGS.reviewerUsesPlannerModel,
|
|
436
|
+
exploreBudget: Number.isInteger(cfg.exploreBudget) && cfg.exploreBudget > 0 ? cfg.exploreBudget : DEFAULT_SETTINGS.exploreBudget,
|
|
437
|
+
plannerPromptSuffix: typeof cfg.plannerPromptSuffix === 'string' ? cfg.plannerPromptSuffix : DEFAULT_SETTINGS.plannerPromptSuffix,
|
|
438
|
+
anchoredBootstrap: typeof cfg.anchoredBootstrap === 'boolean' ? cfg.anchoredBootstrap : DEFAULT_SETTINGS.anchoredBootstrap,
|
|
439
|
+
creativeMode: typeof cfg.creativeMode === 'boolean' ? cfg.creativeMode : DEFAULT_SETTINGS.creativeMode,
|
|
440
|
+
webFetch: typeof cfg.webFetch === 'boolean' ? cfg.webFetch : DEFAULT_SETTINGS.webFetch,
|
|
441
|
+
runcodeCatchGate: typeof cfg.runcodeCatchGate === 'boolean' ? cfg.runcodeCatchGate : DEFAULT_SETTINGS.runcodeCatchGate,
|
|
442
|
+
crossProviderPlannerModel: typeof cfg.crossProviderPlannerModel === 'boolean' ? cfg.crossProviderPlannerModel : DEFAULT_SETTINGS.crossProviderPlannerModel,
|
|
443
|
+
},
|
|
444
|
+
})
|
|
445
|
+
// ── 10 项热读:消费点现场取值(全部加括号调用) ──
|
|
446
|
+
const plannerModel = (agent) => liveConfig.get('plannerModel', agent)
|
|
447
|
+
const otherAgentModel = (agent) => liveConfig.get('otherAgentModel', agent)
|
|
448
|
+
const reviewerUsesPlannerModel = (agent) => liveConfig.get('reviewerUsesPlannerModel', agent)
|
|
449
|
+
const exploreBudget = (agent) => liveConfig.get('exploreBudget', agent)
|
|
450
|
+
const plannerPromptSuffix = (agent) => liveConfig.get('plannerPromptSuffix', agent)
|
|
451
|
+
const bootstrapOn = (agent) => liveConfig.get('anchoredBootstrap', agent)
|
|
452
|
+
const runcodeCatchGateOn = (agent) => liveConfig.get('runcodeCatchGate', agent)
|
|
453
|
+
const crossProviderPlannerModel = (agent) => liveConfig.get('crossProviderPlannerModel', agent)
|
|
454
|
+
// creativeMode 三消费点全部改走 live-config getter(T5-5):C 隐藏集合(shouldHideCreativeCatalog)
|
|
455
|
+
// 与装配投影 hideCordis 两处现场取值,链 = settings 行 override → cfg 快照 → BUILTIN_DEFAULTS。
|
|
456
|
+
const creativeModeOn = (agent) => liveConfig.get('creativeMode', agent)
|
|
457
|
+
// webFetch 热读:运行期 restrict 逐会话生效(改值免重启),链与 creativeMode 同源(settings 行 → cfg 快照 → 内置默认)。
|
|
458
|
+
const webFetchOn = (agent) => liveConfig.get('webFetch', agent)
|
|
459
|
+
const bootstrapPersona = typeof cfg.bootstrapPersona === 'string' ? cfg.bootstrapPersona : 'You are a helpful software engineer assistant.'
|
|
460
|
+
// 变量②:F 段(HP 首轮)tool:read 的手写文案;空串/非字符串一律回退内置同文案兜底。
|
|
461
|
+
const bootstrapReadHint = typeof cfg.bootstrapReadHint === 'string' && cfg.bootstrapReadHint !== ''
|
|
462
|
+
? cfg.bootstrapReadHint
|
|
463
|
+
: BOOTSTRAP_READ_HINT_FALLBACK
|
|
464
|
+
const bootstrapShellTools = new Set(Array.isArray(cfg.bootstrapShellTools) ? cfg.bootstrapShellTools : ['bash', 'pwsh'])
|
|
465
|
+
const bootstrapCommonTools = new Set(Array.isArray(cfg.bootstrapCommonTools) ? cfg.bootstrapCommonTools : ['read'])
|
|
466
|
+
let bootstrapShellMissingWarned = false
|
|
467
|
+
const sdkTextCache = createSdkTextCache()
|
|
468
|
+
|
|
469
|
+
// 改造11:createUsageLedger 工厂已删除(它只返回 {enabled,path,pathError},且此处无消费者)。
|
|
470
|
+
// 账本默认路径经 settings root effect 由 Worker 调用 startupArchive:
|
|
471
|
+
// lib/usage-ledger.js 的 LEDGER_DIRECTORY('logs/dsh-extra-plan')与 ARCHIVE_FILE_NAME
|
|
472
|
+
// ('extra-plan-usage-ledger.jsonl')经 Host 路径授权解析为 <host 根>/logs/dsh-extra-plan/extra-plan-usage-ledger.jsonl。
|
|
473
|
+
const sandboxPolicy = ctx.get('sandboxPolicy')
|
|
474
|
+
const { isChild, isPlannerChild, isReviewerChild, toolSchemasOf, childBaseline } = createAgentRuntime({
|
|
475
|
+
getAgents: () => ctx.get('agents'),
|
|
476
|
+
sandboxPolicy,
|
|
477
|
+
warn: (...args) => console.warn(...args),
|
|
478
|
+
})
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
// ── planner / 非 planner 模型单点解析(工厂实例;缓存 per-apply) ──
|
|
482
|
+
// 见 lib/model-routing.js:plannerModelCache / otherAgentModelCache 每次 apply 各新建一份
|
|
483
|
+
// WeakMap(绝不提升为模块全局);llm/agents/诊断路径按惰性 getter 取用。
|
|
484
|
+
const { resolvePlannerEntry, resolveOtherAgentEntry, resolveReviewerEntry } = createModelRouting({
|
|
485
|
+
getPlannerModel: (agent) => plannerModel(agent),
|
|
486
|
+
getOtherAgentModel: (agent) => otherAgentModel(agent),
|
|
487
|
+
getCrossProviderPlannerModel: (agent) => crossProviderPlannerModel(agent),
|
|
488
|
+
getLlm: () => ctx.get('llm'),
|
|
489
|
+
getAgents: () => ctx.get('agents'),
|
|
490
|
+
getDiagPath: (agent) => prepareDiagnosticPath(ctx, agent, diagPath),
|
|
491
|
+
})
|
|
492
|
+
|
|
493
|
+
// ── C=1 创造模式的官方 skill 面(T5-3 取径订正)────────────────────────────
|
|
494
|
+
// 旧实现(0.1.2-rc.1~0.1.5-rc.2)在 apply 期经 agentPresets.resolve('cordis') 取 shipped
|
|
495
|
+
// 预设目录后 skills.register 两个 SKILL.md。宿主 resolve() 只返回 {id[,broken]},
|
|
496
|
+
// 恒无 path → 整块静默失效(预设挂载成功但 skill 永远不注册)。
|
|
497
|
+
// 现取径 = 静态注册:预设 skill-filesystem 行的 config.bundledSkillDir 指向
|
|
498
|
+
// @deepseek-ai/dsh-agent-preset 包内 skills/(见 agent.cordis.yml),三个 SKILL.md 随
|
|
499
|
+
// skill-filesystem 行进入本预设组合;换通道后旧 customSkillDirs 经 ctx.fs 扫 asar 抛
|
|
500
|
+
// 非 absent 错被 registry 整体跳过,故改 bundledSkillDir(trustedHost → node:fs)+ watch: false;
|
|
501
|
+
// creativeMode=false 不再靠「不注册」,而由 assembly-presentation 的 CREATIVE_SKILL_NAMES 在
|
|
502
|
+
// catalog 投影里隐藏(只去掉名字可见性:skill 仍注册,按名调用依旧可加载,不等于真隔离)。
|
|
503
|
+
|
|
504
|
+
// childBaseline/usageContextOf 与角色固定宿主模式由每次 apply 独立创建的 agent runtime 工厂提供;sandboxPolicy 仅复核当前 child 显式 override 的幂等性。
|
|
505
|
+
|
|
506
|
+
// save_plan/save_probe 的合同、校验、渲染与单次落盘由 lib 工厂提供;此处仅保留注册与生命周期接线。
|
|
507
|
+
const runtimeLifecycle = createRuntimeLifecycle({
|
|
508
|
+
defineSavePlan, defineSaveProbe, defineEditPlanDraft, isSubagentChild, isPlannerChild, toolSchemasOf,
|
|
509
|
+
isBootstrapPhase,
|
|
510
|
+
schemasHasWriteTools, isRunCodeSubCall, runCodeDispatchCapText,
|
|
511
|
+
})
|
|
512
|
+
const {
|
|
513
|
+
registerSavePlan, registerSaveProbe, registerEditPlanDraft, probeClaimFor,
|
|
514
|
+
jobOutputCallCounters, jobOutputLastAnchors, pollGuardCounters,
|
|
515
|
+
subCallCounters, toolJobsNoticesConsumed,
|
|
516
|
+
recordRunCodeDeny, takeRunCodeDenyRecords, recordProbeClaim,
|
|
517
|
+
} = runtimeLifecycle
|
|
518
|
+
const noteRunCodeSubCall = (agent, sessionId, rid) => runtimeLifecycle.noteRunCodeSubCall(sessionId, rid, exploreBudget(agent))
|
|
519
|
+
const consumeToolJobsNotice = (agent, message) => {
|
|
520
|
+
const session = agent !== null && typeof agent === 'object' && !Array.isArray(agent) ? agent.session : undefined
|
|
521
|
+
const header = session !== null && typeof session === 'object' && !Array.isArray(session) ? session.header : undefined
|
|
522
|
+
const sessionId = header !== null && typeof header === 'object' && !Array.isArray(header) ? header.id : undefined
|
|
523
|
+
if (typeof sessionId !== 'string' || sessionId === '') return false
|
|
524
|
+
if (message === null || typeof message !== 'object' || Array.isArray(message)) return false
|
|
525
|
+
if (typeof message.id !== 'string' || message.id.trim() === '') return false
|
|
526
|
+
const source = message.source
|
|
527
|
+
if (source === null || typeof source !== 'object' || Array.isArray(source)) return false
|
|
528
|
+
if (source.kind !== 'tool-jobs' || source.form !== 'notice') return false
|
|
529
|
+
if (!Array.isArray(message.content)) return false
|
|
530
|
+
let noticeText = ''
|
|
531
|
+
for (const block of message.content) {
|
|
532
|
+
if (block !== null && typeof block === 'object' && !Array.isArray(block) && block.type === 'text' && typeof block.text === 'string') {
|
|
533
|
+
noticeText = block.text
|
|
534
|
+
break
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
const match = noticeText.match(/background job (\S+)/)
|
|
538
|
+
if (match === null) return false
|
|
539
|
+
const jobId = match[1]
|
|
540
|
+
const noticeId = message.id
|
|
541
|
+
let consumed = toolJobsNoticesConsumed.get(sessionId)
|
|
542
|
+
if (consumed !== undefined && consumed.has(noticeId)) return false
|
|
543
|
+
if (consumed === undefined) {
|
|
544
|
+
consumed = new Set()
|
|
545
|
+
toolJobsNoticesConsumed.set(sessionId, consumed)
|
|
546
|
+
}
|
|
547
|
+
const perSession = jobOutputCallCounters.get(sessionId)
|
|
548
|
+
if (perSession !== undefined && perSession.has(jobId)) perSession.delete(jobId)
|
|
549
|
+
pollGuardCounters.delete(sessionId)
|
|
550
|
+
consumed.add(noticeId)
|
|
551
|
+
return true
|
|
552
|
+
}
|
|
553
|
+
ctx.on('agent/inbox/claimed', (payload) => {
|
|
554
|
+
consumeToolJobsNotice(payload?.agent, payload?.message)
|
|
555
|
+
})
|
|
556
|
+
// ── 闸门工具 extra_plan_gate 的接线(1b)──────────────────────────────
|
|
557
|
+
// 选项文案由预设词表生成(gateRuntime.words),模型不再手写 ask_user_question 的选项;
|
|
558
|
+
// 提问通道落在宿主 userQuestions 服务上(与官方 ask_user_question 同一入口),
|
|
559
|
+
// 服务侧 assertLiveRoot 对子代理回 DELEGATED_CALLER,与本文件 pre-execute 硬拒同口径。
|
|
560
|
+
function userQuestionsServiceOf(agent) {
|
|
561
|
+
try {
|
|
562
|
+
const scoped = agent !== undefined && agent !== null ? agent.ctx : undefined
|
|
563
|
+
if (scoped !== undefined && scoped !== null && typeof scoped.get === 'function') {
|
|
564
|
+
const service = scoped.get('userQuestions')
|
|
565
|
+
if (service !== undefined && service !== null && typeof service.ask === 'function') return service
|
|
566
|
+
}
|
|
567
|
+
} catch (error) {
|
|
568
|
+
// 落到 apply 级 ctx 兜底
|
|
569
|
+
}
|
|
570
|
+
try {
|
|
571
|
+
const fallback = typeof ctx.get === 'function' ? ctx.get('userQuestions') : undefined
|
|
572
|
+
if (fallback !== undefined && fallback !== null && typeof fallback.ask === 'function') return fallback
|
|
573
|
+
} catch (error) {
|
|
574
|
+
return undefined
|
|
575
|
+
}
|
|
576
|
+
return undefined
|
|
577
|
+
}
|
|
578
|
+
// 闸门提问通道:id 缺失时由本层补齐稳定 id(1a 的提问模板只给 header/question/options,
|
|
579
|
+
// 宿主答案按 id 回填);不传 wait=不绑定某个 tool call 卡片的无限等待,工具结果照常回填。
|
|
580
|
+
async function askGateUser(request) {
|
|
581
|
+
const source = request !== null && typeof request === 'object' && !Array.isArray(request) ? request : {}
|
|
582
|
+
const agent = source.agent
|
|
583
|
+
const service = userQuestionsServiceOf(agent)
|
|
584
|
+
if (service === undefined) {
|
|
585
|
+
const missing = new Error('extra-plan: userQuestions 服务不可用,extra_plan_gate 无法向用户提问')
|
|
586
|
+
missing.code = 'NO_PROVIDER'
|
|
587
|
+
throw missing
|
|
588
|
+
}
|
|
589
|
+
const questions = Array.isArray(source.questions) ? source.questions : []
|
|
590
|
+
const normalized = questions.map((question, index) => {
|
|
591
|
+
const item = question !== null && typeof question === 'object' && !Array.isArray(question) ? question : {}
|
|
592
|
+
const id = typeof item.id === 'string' && item.id !== '' ? item.id : 'extra_plan_gate_' + index
|
|
593
|
+
return { ...item, id }
|
|
594
|
+
})
|
|
595
|
+
const askRequest = { questions: normalized }
|
|
596
|
+
if (agent !== undefined && agent !== null) askRequest.agent = agent
|
|
597
|
+
if (source.signal !== undefined) askRequest.signal = source.signal
|
|
598
|
+
return await service.ask(askRequest)
|
|
599
|
+
}
|
|
600
|
+
// 闸门工具前置状态读取:每次 execute 现场取该 agent 会话的最新事件快照求三字段状态(route/purpose/clarified),供 purpose 分支在弹卡前做路线校验。
|
|
601
|
+
const gateToolFactories = createGateToolFactories({ gateRuntime, ask: askGateUser, getState: (agent) => deriveFlowState(sessionEvents(agent !== undefined && agent !== null ? agent.session : undefined), gateRuntime) })
|
|
602
|
+
const gateToolRegistered = new WeakSet()
|
|
603
|
+
// 与 registerSavePlan/registerSaveProbe 同构的 per-apply 注册:幂等、服务缺失只 warn、
|
|
604
|
+
// 绝不向 agent/created 抛出。省略 when=闸门工具不做相位屏蔽(save 工具引导期隐藏,
|
|
605
|
+
// 闸门工具必须随时可调);子代理不可见由调用点的 !isSubagentChild 条件保证。
|
|
606
|
+
function registerGateTool(agent) {
|
|
607
|
+
if (gateToolRegistered.has(agent)) return
|
|
608
|
+
const tools = toolsServiceOf(agent)
|
|
609
|
+
if (tools === undefined || tools === null || typeof tools.register !== 'function') {
|
|
610
|
+
console.warn('extra-plan: tools service unavailable — extra_plan_gate not registered')
|
|
611
|
+
return
|
|
612
|
+
}
|
|
613
|
+
try {
|
|
614
|
+
tools.register(gateToolFactories.defineGateTool(agent))
|
|
615
|
+
gateToolRegistered.add(agent)
|
|
616
|
+
} catch (error) {
|
|
617
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
618
|
+
if (error instanceof Error && message.includes('already registered')) {
|
|
619
|
+
gateToolRegistered.add(agent)
|
|
620
|
+
console.warn('extra-plan: extra_plan_gate already registered in this scope — keeping the existing tool, no retry')
|
|
621
|
+
return
|
|
622
|
+
}
|
|
623
|
+
console.error('extra-plan: extra_plan_gate registration failed: ' + message)
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
// 1) agent/created:子代理基线(角色 + 固定宿主模式);规划子代理与主会话注册 save_plan/edit_plan_draft
|
|
627
|
+
// (主会话侧任意路由态放行:受限规划工件,判定在 mainGateReason 兜底);主会话与探查子代理
|
|
628
|
+
// 注册 save_probe(scoped;创建监听与 pre-step 互补兜底)。
|
|
629
|
+
// HK1(事件与状态模型):agent/created 升为 serial——
|
|
630
|
+
// 监听器被宿主 await,任何抛出都会让会话创建失败。故整块必须吞错:内部异常只
|
|
631
|
+
// console.warn 留痕,绝不放任传播(gateRuntime 已在 apply 期求值,此处不再抛)。
|
|
632
|
+
// 0.2.2-rc.1 修复(BUG-2):宿主已禁止在 agent/request 改 provider/model/reasoningEffort,
|
|
633
|
+
// 改在创建期用 agent.model.select 完成(agent/created 为 serial 且被宿主 await,
|
|
634
|
+
// 早于首个 step 的 selection 捕获)。解析失败只留痕、不阻断会话创建。
|
|
635
|
+
async function selectChildModelOnCreate(agent, signal) {
|
|
636
|
+
try {
|
|
637
|
+
if (!isSubagentChild(agent)) return
|
|
638
|
+
const planner = isPlannerChild(agent)
|
|
639
|
+
const reviewerRoute = isReviewerChild(agent) && reviewerUsesPlannerModel(agent)
|
|
640
|
+
// 父会话当前路由与力度:显式判定与 effort 来源都取它(宿主 resolveChildAgentOptions
|
|
641
|
+
// 已把父 provider/model/effort 合成进 agent.options)。
|
|
642
|
+
let parentConfig = null
|
|
643
|
+
try {
|
|
644
|
+
const parentId = agent.session !== undefined && agent.session !== null && agent.session.header !== undefined && agent.session.header !== null
|
|
645
|
+
? agent.session.header.parentSession
|
|
646
|
+
: undefined
|
|
647
|
+
const agentsService = typeof ctx.get === 'function' ? ctx.get('agents') : undefined
|
|
648
|
+
const parent = parentId !== undefined && agentsService !== undefined && agentsService !== null ? agentsService.get(parentId) : undefined
|
|
649
|
+
const header = parent !== undefined && parent.session !== undefined && typeof parent.session.requestHeader === 'function' ? parent.session.requestHeader() : undefined
|
|
650
|
+
const pcfg = header !== undefined && header !== null && header.config !== undefined && header.config !== null ? header.config : null
|
|
651
|
+
if (pcfg !== null) parentConfig = pcfg
|
|
652
|
+
} catch (error) {
|
|
653
|
+
parentConfig = null
|
|
654
|
+
}
|
|
655
|
+
// 显式路由优先:复刻 agent/request 旧口径的 isExplicitRoute(options 与父路由不同即显式),
|
|
656
|
+
// 显式时不 select、不探目录,保持「显式选择不被覆盖」。
|
|
657
|
+
if (!planner && parentConfig !== null) {
|
|
658
|
+
const optProvider = agent.options !== undefined && agent.options !== null && typeof agent.options.provider === 'string' ? agent.options.provider : ''
|
|
659
|
+
const optModel = agent.options !== undefined && agent.options !== null && typeof agent.options.model === 'string' ? agent.options.model : ''
|
|
660
|
+
if (isExplicitRoute(optProvider, optModel, parentConfig.provider, parentConfig.model)) return
|
|
661
|
+
}
|
|
662
|
+
// probe 判定改用角色预设身份:创建期 toolSchemasOf 可能尚未就绪。
|
|
663
|
+
const presetOfAgent = agent.session !== undefined && agent.session !== null && agent.session.header !== undefined && agent.session.header !== null
|
|
664
|
+
? agent.session.header.agentPreset
|
|
665
|
+
: undefined
|
|
666
|
+
const probe = presetOfAgent === PROBER_PRESET_ID
|
|
667
|
+
let entry
|
|
668
|
+
if (planner) entry = await resolvePlannerEntry(agent, signal)
|
|
669
|
+
else if (reviewerRoute) entry = await resolveReviewerEntry(agent, signal)
|
|
670
|
+
else entry = await resolveOtherAgentEntry(agent, signal, probe)
|
|
671
|
+
if (entry === null || entry === undefined) return
|
|
672
|
+
const provider = typeof entry.provider === 'string' ? entry.provider : ''
|
|
673
|
+
const model = typeof entry.model === 'string' ? entry.model : ''
|
|
674
|
+
if (provider === '' || model === '') return
|
|
675
|
+
const selection = { provider, model }
|
|
676
|
+
// 力度继承主会话(既有「力度完全继承主会话」语义):select 一并带上,使宿主 preStep
|
|
677
|
+
// 捕获的 selection 与 agent/request 的提议一致(0.2.2-rc.1 硬校验)。
|
|
678
|
+
const optionEffort = agent.options !== undefined && agent.options !== null && typeof agent.options.reasoningEffort === 'string' ? agent.options.reasoningEffort : ''
|
|
679
|
+
const parentEffort = parentConfig !== null && typeof parentConfig.reasoningEffort === 'string' ? parentConfig.reasoningEffort : ''
|
|
680
|
+
const selectedEffort = optionEffort !== '' ? optionEffort : parentEffort
|
|
681
|
+
if (selectedEffort !== '') selection.reasoningEffort = selectedEffort
|
|
682
|
+
agent.model.select(selection)
|
|
683
|
+
} catch (error) {
|
|
684
|
+
console.warn('extra-plan: agent/created 模型选择失败(不阻断会话创建):' + (error instanceof Error ? error.message : String(error)))
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
// 0.2.2-rc.1 修复(BUG-1):宿主装配期以 provider 并集覆盖 waterfall 返回的 tools,改返回 tools 无结构效果,
|
|
689
|
+
// 故引导期工具面收窄只走 ctx.tools.restrict 通道(返回 disposer,首个 tool/call 后释放)。
|
|
690
|
+
// allow = 配置集 ∩ 可收窄名(view(agent).restrictableNames 优先、schemas 兜底);PTC 折叠与只读 child 一律不 arm。
|
|
691
|
+
// C=0 工具面裁剪(BUG-1 hideCordis):两个 cordis 展示工具的可见性同样只走 agent 作用域 restrict 通道({ deny })。
|
|
692
|
+
// deny 只列这两名:run_code 是保留传输名,restrict 会整次抛错。
|
|
693
|
+
// 两条裁剪通路(引导期 allow 收窄、C=0 deny 裁剪)共用单一存储与单一 arm/release:restrict 的唯一调用点
|
|
694
|
+
// 在 armToolRestriction 内,filter 只允许 { allow: [...] } 或 { deny: [...] } 并原样透传(不改写名单内容)。
|
|
695
|
+
// 全路径诊断落盘 <数据根>/logs/dsh-extra-plan/extra-plan-anchored.jsonl(source 区分裁剪通路、filter 落原值)。
|
|
696
|
+
const CORDIS_PRESENTATION_DENY = ['cordis_inspect_list', 'cordis_inspect_query']
|
|
697
|
+
const ANCHORED_BOOTSTRAP_SOURCE = 'anchored-bootstrap'
|
|
698
|
+
const CORDIS_PRESENTATION_SOURCE = 'cordis-presentation'
|
|
699
|
+
// web_fetch 免重启开关:deny 单名走同一条 restrict 通路(source 独立,便于诊断区分)。
|
|
700
|
+
const WEB_FETCH_SOURCE = 'web-fetch'
|
|
701
|
+
const WEB_FETCH_TOOL_NAME = 'web_fetch'
|
|
702
|
+
const WAIT_AGENT_SOURCE = 'wait-agent'
|
|
703
|
+
const WAIT_AGENT_TOOL_NAME = 'wait_agent'
|
|
704
|
+
// 单一存储:agent → (source → { disposer, filter });同 agent 同 source 已 arm 即幂等返回。
|
|
705
|
+
const toolRestrictions = new WeakMap()
|
|
706
|
+
const anchoredDiagState = new WeakMap()
|
|
707
|
+
function toolsServiceOf(agent) {
|
|
708
|
+
try {
|
|
709
|
+
const scoped = agent !== undefined && agent !== null ? agent.ctx : undefined
|
|
710
|
+
if (scoped === undefined || scoped === null) return undefined
|
|
711
|
+
if (scoped.tools !== undefined && scoped.tools !== null) return scoped.tools
|
|
712
|
+
if (typeof scoped.get === 'function') {
|
|
713
|
+
const tools = scoped.get('tools')
|
|
714
|
+
if (tools !== undefined && tools !== null) return tools
|
|
715
|
+
}
|
|
716
|
+
return undefined
|
|
717
|
+
} catch (error) {
|
|
718
|
+
return undefined
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
// 可收窄名快照:view(agent).restrictableNames 是 restrict 前的可收窄名集合(宿主 view 语义);
|
|
722
|
+
// 取不到时返回 null,由调用方按「名单无法校验」处理(restrict 对未知名整次抛错)。
|
|
723
|
+
function restrictableNamesOf(agent) {
|
|
724
|
+
const tools = toolsServiceOf(agent)
|
|
725
|
+
if (tools === undefined || tools === null || typeof tools.view !== 'function') return null
|
|
726
|
+
try {
|
|
727
|
+
const view = tools.view(agent)
|
|
728
|
+
if (view !== undefined && view !== null && view.restrictableNames instanceof Set) return view.restrictableNames
|
|
729
|
+
} catch (error) {
|
|
730
|
+
return null
|
|
731
|
+
}
|
|
732
|
+
return null
|
|
733
|
+
}
|
|
734
|
+
function restrictableSnapshotOf(agent) {
|
|
735
|
+
const names = restrictableNamesOf(agent)
|
|
736
|
+
return names === null ? null : [...names].sort()
|
|
737
|
+
}
|
|
738
|
+
// 单一存储的事务式入口:取 agent 的 source→{ disposer, filter } 槽位,缺失即建。
|
|
739
|
+
function toolRestrictionSlotOf(agent) {
|
|
740
|
+
let slot = toolRestrictions.get(agent)
|
|
741
|
+
if (slot === undefined) {
|
|
742
|
+
slot = new Map()
|
|
743
|
+
toolRestrictions.set(agent, slot)
|
|
744
|
+
}
|
|
745
|
+
return slot
|
|
746
|
+
}
|
|
747
|
+
// 两条通路共用的诊断出口(arm/release 唯一状态点):自带 try/catch 吞错(诊断失败不得影响主流程);
|
|
748
|
+
// 每个 agent/source 只保留最近 arm/release/skip 快照,仅 arm-failed/release-failed 即时落盘;
|
|
749
|
+
// source 区分裁剪通路、filter 落 allow/deny 原值(前置判据不成立时无 filter,落 null)。
|
|
750
|
+
function anchoredDiagStateOf(agent) {
|
|
751
|
+
let state = anchoredDiagState.get(agent)
|
|
752
|
+
if (state === undefined) {
|
|
753
|
+
state = {
|
|
754
|
+
first: false,
|
|
755
|
+
later: false,
|
|
756
|
+
restrictions: {
|
|
757
|
+
[ANCHORED_BOOTSTRAP_SOURCE]: { arm: null, release: null, skip: null },
|
|
758
|
+
[CORDIS_PRESENTATION_SOURCE]: { arm: null, release: null, skip: null },
|
|
759
|
+
[WEB_FETCH_SOURCE]: { arm: null, release: null, skip: null },
|
|
760
|
+
[WAIT_AGENT_SOURCE]: { arm: null, release: null, skip: null },
|
|
761
|
+
},
|
|
762
|
+
}
|
|
763
|
+
anchoredDiagState.set(agent, state)
|
|
764
|
+
}
|
|
765
|
+
return state
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
function toolRestrictionDiag(agent, source, event, filter, trigger, detail) {
|
|
769
|
+
try {
|
|
770
|
+
const state = anchoredDiagStateOf(agent)
|
|
771
|
+
const triggerText = typeof trigger === 'string' && trigger !== '' ? trigger : 'unknown'
|
|
772
|
+
const sourceText = typeof source === 'string' ? source : 'unknown'
|
|
773
|
+
const snapshot = {
|
|
774
|
+
event,
|
|
775
|
+
source: sourceText,
|
|
776
|
+
filter: filter !== undefined ? filter : null,
|
|
777
|
+
trigger: triggerText,
|
|
778
|
+
...(detail !== undefined && detail !== null ? detail : {}),
|
|
779
|
+
}
|
|
780
|
+
const sourceState = state.restrictions[sourceText]
|
|
781
|
+
if (sourceState !== undefined) {
|
|
782
|
+
const eventText = String(event)
|
|
783
|
+
if (eventText.startsWith('arm-')) sourceState.arm = snapshot
|
|
784
|
+
else if (eventText.startsWith('release-')) sourceState.release = snapshot
|
|
785
|
+
else if (eventText.startsWith('skip-')) sourceState.skip = snapshot
|
|
786
|
+
}
|
|
787
|
+
if (event !== 'arm-failed' && event !== 'release-failed') return
|
|
788
|
+
appendDiagnostic(ctx, agent, 'extra-plan-anchored.jsonl', {
|
|
789
|
+
ts: new Date().toISOString(),
|
|
790
|
+
sessionId: typeof agent?.session?.header?.id === 'string' ? agent.session.header.id : '',
|
|
791
|
+
event,
|
|
792
|
+
source: sourceText,
|
|
793
|
+
filter: filter !== undefined ? filter : null,
|
|
794
|
+
trigger: triggerText,
|
|
795
|
+
...(detail !== undefined && detail !== null ? detail : {}),
|
|
796
|
+
})
|
|
797
|
+
} catch (error) {
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
function restrictionsSnapshotOf(agent, state) {
|
|
802
|
+
const active = toolRestrictions.get(agent)
|
|
803
|
+
const snapshot = {}
|
|
804
|
+
for (const source of [ANCHORED_BOOTSTRAP_SOURCE, CORDIS_PRESENTATION_SOURCE, WEB_FETCH_SOURCE, WAIT_AGENT_SOURCE]) {
|
|
805
|
+
const entry = active !== undefined ? active.get(source) : undefined
|
|
806
|
+
const latest = state.restrictions[source]
|
|
807
|
+
snapshot[source] = {
|
|
808
|
+
active: entry !== undefined ? entry.filter : null,
|
|
809
|
+
arm: latest !== undefined ? latest.arm : null,
|
|
810
|
+
release: latest !== undefined ? latest.release : null,
|
|
811
|
+
skip: latest !== undefined ? latest.skip : null,
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
return snapshot
|
|
815
|
+
}
|
|
816
|
+
// 引导期 allow = 配置集 ∩ 可收窄名(view.restrictableNames 优先、schemas 兜底);
|
|
817
|
+
// 两者都不可用或交集为空时返回空数组,调用方不 arm 并落诊断(不回落配置集:
|
|
818
|
+
// 配置集默认含 win32 上并不存在的 bash,restrict 对未知名整次抛错)。
|
|
819
|
+
// 引导期 allow 仅由 bootstrapShellTools 与 bootstrapCommonTools 组成,不再补齐
|
|
820
|
+
// extra_plan_gate;闸门工具在首个 tool/call 后自然可见。
|
|
821
|
+
function anchoredAllowNamesOf(agent) {
|
|
822
|
+
let names = null
|
|
823
|
+
const tools = toolsServiceOf(agent)
|
|
824
|
+
if (tools !== undefined && typeof tools.view === 'function') {
|
|
825
|
+
try {
|
|
826
|
+
const view = tools.view(agent)
|
|
827
|
+
if (view !== undefined && view !== null && view.restrictableNames instanceof Set) names = view.restrictableNames
|
|
828
|
+
} catch (error) {
|
|
829
|
+
// view 取不到时退回 schemas 兜底
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
if (names === null) {
|
|
833
|
+
const schemas = toolSchemasOf(agent)
|
|
834
|
+
if (Array.isArray(schemas)) {
|
|
835
|
+
const schemaNames = new Set()
|
|
836
|
+
for (const schema of schemas) {
|
|
837
|
+
if (schema !== null && typeof schema === 'object' && typeof schema.name === 'string') schemaNames.add(schema.name)
|
|
838
|
+
}
|
|
839
|
+
names = schemaNames
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
if (names === null) return []
|
|
843
|
+
const allow = []
|
|
844
|
+
for (const name of [...bootstrapShellTools, ...bootstrapCommonTools]) {
|
|
845
|
+
if (!names.has(name)) continue
|
|
846
|
+
if (!allow.includes(name)) allow.push(name)
|
|
847
|
+
}
|
|
848
|
+
return allow
|
|
849
|
+
}
|
|
850
|
+
// 通用 arm:restrict 的唯一调用点,filter 名单校验、幂等与诊断集中于此。
|
|
851
|
+
// filter 只允许 { allow: [...] } 或 { deny: [...] },原样透传给 restrict(不改写名单内容);
|
|
852
|
+
// skip 表示前置判据不成立(只落诊断、不 arm),诊断事件恒带 source 与 filter(无 filter 时落 null)。
|
|
853
|
+
function armToolRestriction(agent, { source, filter, trigger, skip }) {
|
|
854
|
+
const allowOf = filter !== null && typeof filter === 'object' && Array.isArray(filter.allow) ? filter.allow : null
|
|
855
|
+
const denyOf = filter !== null && typeof filter === 'object' && Array.isArray(filter.deny) ? filter.deny : null
|
|
856
|
+
if (skip !== undefined && skip !== null) {
|
|
857
|
+
toolRestrictionDiag(agent, source, skip.event, filter, trigger, skip.detail)
|
|
858
|
+
return
|
|
859
|
+
}
|
|
860
|
+
if (allowOf === null && denyOf === null) {
|
|
861
|
+
console.warn('extra-plan: 工具面裁剪跳过(' + source + '):filter 形态非法,只允许 { allow } 或 { deny }')
|
|
862
|
+
toolRestrictionDiag(agent, source, 'arm-failed', filter, trigger, { reason: 'invalid-filter' })
|
|
863
|
+
return
|
|
864
|
+
}
|
|
865
|
+
const filterFields = allowOf !== null ? { allow: allowOf } : { deny: denyOf }
|
|
866
|
+
const wanted = allowOf !== null ? allowOf : denyOf
|
|
867
|
+
const slot = toolRestrictionSlotOf(agent)
|
|
868
|
+
if (slot.has(source)) {
|
|
869
|
+
toolRestrictionDiag(agent, source, 'skip-already-armed', filter, trigger, {})
|
|
870
|
+
return
|
|
871
|
+
}
|
|
872
|
+
const tools = toolsServiceOf(agent)
|
|
873
|
+
if (tools === undefined || tools === null || typeof tools.restrict !== 'function') {
|
|
874
|
+
toolRestrictionDiag(agent, source, 'skip-no-restrict', filter, trigger, {})
|
|
875
|
+
return
|
|
876
|
+
}
|
|
877
|
+
if (wanted.length === 0) {
|
|
878
|
+
toolRestrictionDiag(agent, source, 'arm-failed', filter, trigger, { ...filterFields, reason: 'empty-filter' })
|
|
879
|
+
return
|
|
880
|
+
}
|
|
881
|
+
const restrictable = restrictableNamesOf(agent)
|
|
882
|
+
const restrictableSnapshot = restrictable === null ? null : [...restrictable].sort()
|
|
883
|
+
// 缺名校验(restrict 对未知名整次抛错):allow 名单已由调用方按可收窄名求交,取不到快照时沿用
|
|
884
|
+
// 原行为继续尝试;deny 是固定平台名,取不到快照即无法确认存在,必须跳过。
|
|
885
|
+
const missing = restrictable === null
|
|
886
|
+
? (allowOf !== null ? [] : [...wanted])
|
|
887
|
+
: wanted.filter((name) => !restrictable.has(name))
|
|
888
|
+
if (missing.length > 0) {
|
|
889
|
+
console.warn('extra-plan: 工具面裁剪跳过(' + source + '):可收窄名缺 ' + missing.join(', '))
|
|
890
|
+
toolRestrictionDiag(agent, source, 'arm-failed', filter, trigger, { ...filterFields, reason: 'missing-restrictable-names', missing, restrictable: restrictableSnapshot })
|
|
891
|
+
return
|
|
892
|
+
}
|
|
893
|
+
try {
|
|
894
|
+
const disposer = tools.restrict(filter)
|
|
895
|
+
if (typeof disposer === 'function') {
|
|
896
|
+
slot.set(source, { disposer, filter })
|
|
897
|
+
toolRestrictionDiag(agent, source, 'arm-ok', filter, trigger, { ...filterFields, restrictable: restrictableSnapshot })
|
|
898
|
+
} else {
|
|
899
|
+
toolRestrictionDiag(agent, source, 'arm-failed', filter, trigger, { ...filterFields, restrictable: restrictableSnapshot, message: 'restrict returned non-function disposer' })
|
|
900
|
+
}
|
|
901
|
+
} catch (error) {
|
|
902
|
+
console.warn('extra-plan: 工具面裁剪失败(不影响会话创建):' + (error instanceof Error ? error.message : String(error)))
|
|
903
|
+
toolRestrictionDiag(agent, source, 'arm-failed', filter, trigger, { ...filterFields, restrictable: restrictableSnapshot, message: error instanceof Error ? error.message : String(error) })
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
// 通用 release:只调 disposer() 再删该项(宿主对空 filter 整次抛错,故不做任何空 filter 调用);
|
|
907
|
+
// release-ok 诊断落被释放项的 filter 原值。
|
|
908
|
+
function releaseToolRestriction(agent, source) {
|
|
909
|
+
const slot = toolRestrictions.get(agent)
|
|
910
|
+
const entry = slot !== undefined ? slot.get(source) : undefined
|
|
911
|
+
if (entry === undefined) return
|
|
912
|
+
slot.delete(source)
|
|
913
|
+
if (slot.size === 0) toolRestrictions.delete(agent)
|
|
914
|
+
try {
|
|
915
|
+
entry.disposer()
|
|
916
|
+
toolRestrictionDiag(agent, source, 'release-ok', entry.filter, 'release', {})
|
|
917
|
+
} catch (error) {
|
|
918
|
+
console.warn('extra-plan: 工具面裁剪释放失败(不影响会话):' + (error instanceof Error ? error.message : String(error)))
|
|
919
|
+
toolRestrictionDiag(agent, source, 'release-failed', entry.filter, 'release', { message: error instanceof Error ? error.message : String(error) })
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
// 引导期收窄适配:只算 filter(allow = 配置集 ∩ 可收窄名)与「不该 arm」的判据,restrict 与诊断统一交通用 arm。
|
|
923
|
+
// 判据求值异常按 arm-failed 落盘并跳过,保持「收窄失败不影响会话创建」的既有语义。
|
|
924
|
+
function anchoredBootstrapArmOptionsOf(agent, trigger) {
|
|
925
|
+
const source = ANCHORED_BOOTSTRAP_SOURCE
|
|
926
|
+
try {
|
|
927
|
+
if (!bootstrapOn(agent)) return { source, trigger, filter: null, skip: { event: 'skip-bootstrap-off', detail: {} } }
|
|
928
|
+
// 只在仍处引导期时 arm:resume 后已过首个 tool/call 的会话不再收窄。
|
|
929
|
+
if (!isBootstrapPhase(agent)) return { source, trigger, filter: null, skip: { event: 'skip-phase', detail: {} } }
|
|
930
|
+
if (isChild(agent) && !isPlannerChild(agent)) return { source, trigger, filter: null, skip: { event: 'skip-child', detail: {} } }
|
|
931
|
+
// 只在真实宿主 Session 上 arm:真实 Session 提供 append(事件落盘能力),
|
|
932
|
+
// 静态契约/工具面夹具不提供该能力,因此不会被运行期收窄污染(路线 A)。
|
|
933
|
+
const session = agent.session
|
|
934
|
+
if (session === undefined || session === null || typeof session.append !== 'function') {
|
|
935
|
+
return { source, trigger, filter: null, skip: { event: 'skip-no-session-append', detail: {} } }
|
|
936
|
+
}
|
|
937
|
+
// PTC 部署跳过:工具面折叠为仅 run_code 时收窄会砍掉嵌套绑定(不再以 ptcRuntime 服务是否存在判定)。
|
|
938
|
+
const armSchemas = toolSchemasOf(agent)
|
|
939
|
+
if (catalogIsCollapsed(armSchemas)) {
|
|
940
|
+
return { source, trigger, filter: null, skip: { event: 'skip-ptc-collapsed', detail: { reason: 'schemas collapsed to run_code' } } }
|
|
941
|
+
}
|
|
942
|
+
const allow = anchoredAllowNamesOf(agent)
|
|
943
|
+
if (allow.length === 0) {
|
|
944
|
+
return {
|
|
945
|
+
source,
|
|
946
|
+
trigger,
|
|
947
|
+
filter: { allow },
|
|
948
|
+
skip: {
|
|
949
|
+
event: 'skip-empty-allow',
|
|
950
|
+
detail: {
|
|
951
|
+
restrictable: restrictableSnapshotOf(agent),
|
|
952
|
+
schemasNames: Array.isArray(armSchemas) ? armSchemas.filter((s) => s !== null && typeof s === 'object' && typeof s.name === 'string').map((s) => s.name) : null,
|
|
953
|
+
configured: [...bootstrapShellTools, ...bootstrapCommonTools],
|
|
954
|
+
},
|
|
955
|
+
},
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
return { source, trigger, filter: { allow } }
|
|
959
|
+
} catch (error) {
|
|
960
|
+
console.warn('extra-plan: 引导期工具面收窄失败(不影响会话创建):' + (error instanceof Error ? error.message : String(error)))
|
|
961
|
+
return { source, trigger, filter: null, skip: { event: 'arm-failed', detail: { message: error instanceof Error ? error.message : String(error) } } }
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
function armAnchoredToolRestriction(agent, source) {
|
|
965
|
+
armToolRestriction(agent, anchoredBootstrapArmOptionsOf(agent, source))
|
|
966
|
+
}
|
|
967
|
+
function releaseAnchoredToolRestriction(agent) {
|
|
968
|
+
releaseToolRestriction(agent, ANCHORED_BOOTSTRAP_SOURCE)
|
|
969
|
+
}
|
|
970
|
+
// C=0 工具面裁剪适配:判据只用 !creativeModeOn(agent),不掺 bootstrapOn/相位——与引导期 allow
|
|
971
|
+
// 白名单是两条独立通路,掺相位会互相撤销(同 agent 同 source 只 arm 一次);只算 filter 后交通用 arm。
|
|
972
|
+
// C=1 不裁剪且不落诊断(与原行为一致)。
|
|
973
|
+
function armCordisPresentationRestriction(agent, source) {
|
|
974
|
+
if (creativeModeOn(agent)) return
|
|
975
|
+
armToolRestriction(agent, { source: CORDIS_PRESENTATION_SOURCE, trigger: source, filter: { deny: [...CORDIS_PRESENTATION_DENY] } })
|
|
976
|
+
}
|
|
977
|
+
// 释放只调通用 release(内部只调 disposer() 再删项):宿主空 filter 会整次抛错,故不做任何空 filter 调用。
|
|
978
|
+
function releaseCordisPresentationRestriction(agent) {
|
|
979
|
+
releaseToolRestriction(agent, CORDIS_PRESENTATION_SOURCE)
|
|
980
|
+
}
|
|
981
|
+
// web_fetch 免重启开关适配:判据只读 webFetchOn(与 settings 行热读同源),逐会话 arm deny 单名 web_fetch。
|
|
982
|
+
// 三条前置判定按序且都在通用 arm 之前完成:
|
|
983
|
+
// ① 开关为真 → 不裁剪、不落诊断(与 C=1 的 cordis 通路同口径);
|
|
984
|
+
// ② 子代理是注册级缺失(web_fetch 本就不在子代理工具面),对未注册名 arm 会让宿主 restrict 整次抛错,故直接返回;
|
|
985
|
+
// ③ 可收窄名快照取到且不含 web_fetch → 改传 skip 事件 skip-no-web-fetch-name,落 skip 而非 arm-failed,避免污染失败计数。
|
|
986
|
+
function armWebFetchRestriction(agent, source) {
|
|
987
|
+
if (webFetchOn(agent)) return
|
|
988
|
+
if (isSubagentChild(agent)) return
|
|
989
|
+
const filter = { deny: [WEB_FETCH_TOOL_NAME] }
|
|
990
|
+
const restrictable = restrictableNamesOf(agent)
|
|
991
|
+
if (restrictable !== null && !restrictable.has(WEB_FETCH_TOOL_NAME)) {
|
|
992
|
+
armToolRestriction(agent, { source: WEB_FETCH_SOURCE, trigger: source, filter, skip: { event: 'skip-no-web-fetch-name', detail: {} } })
|
|
993
|
+
return
|
|
994
|
+
}
|
|
995
|
+
armToolRestriction(agent, { source: WEB_FETCH_SOURCE, trigger: source, filter })
|
|
996
|
+
}
|
|
997
|
+
// 释放只调通用 release(内部只调 disposer() 再删项):宿主空 filter 会整次抛错,故不做任何空 filter 调用。
|
|
998
|
+
function releaseWebFetchRestriction(agent) {
|
|
999
|
+
releaseToolRestriction(agent, WEB_FETCH_SOURCE)
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
// 永久收窄当前 Agent 的注册表视图;不撤掉控制包或影响子代理完成通知。
|
|
1003
|
+
function armWaitAgentRestriction(agent, trigger) {
|
|
1004
|
+
if (!restrictableNamesOf(agent)?.has(WAIT_AGENT_TOOL_NAME)) return
|
|
1005
|
+
armToolRestriction(agent, { source: WAIT_AGENT_SOURCE, trigger, filter: { deny: [WAIT_AGENT_TOOL_NAME] } })
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
ctx.on('agent/created', async (payload) => {
|
|
1009
|
+
const agent = payload !== undefined && payload !== null ? payload.agent : undefined
|
|
1010
|
+
if (agent === undefined) return
|
|
1011
|
+
try {
|
|
1012
|
+
childBaseline(agent)
|
|
1013
|
+
if (isPlannerChild(agent) || !isSubagentChild(agent)) {
|
|
1014
|
+
registerSavePlan(agent)
|
|
1015
|
+
registerEditPlanDraft(agent)
|
|
1016
|
+
}
|
|
1017
|
+
if (!isSubagentChild(agent) || probeClaimFor(agent)) { registerSaveProbe(agent) }
|
|
1018
|
+
if (!isSubagentChild(agent)) registerGateTool(agent)
|
|
1019
|
+
} catch (error) {
|
|
1020
|
+
console.warn('extra-plan: agent/created 初始化失败(不阻断会话创建):' + (error instanceof Error ? error.message : String(error)))
|
|
1021
|
+
}
|
|
1022
|
+
// 模型选择与引导期工具面收窄各自独立吞错:注册/基线失败不得连坐这两步。
|
|
1023
|
+
await selectChildModelOnCreate(agent, payload.signal)
|
|
1024
|
+
armAnchoredToolRestriction(agent, 'agent-created')
|
|
1025
|
+
armCordisPresentationRestriction(agent, 'agent-created')
|
|
1026
|
+
armWebFetchRestriction(agent, 'agent-created')
|
|
1027
|
+
armWaitAgentRestriction(agent, 'agent-created')
|
|
1028
|
+
})
|
|
1029
|
+
|
|
1030
|
+
// 2) pre-step:消息投影;规划子代理初始任务与
|
|
1031
|
+
// 续轮转达机械拼接 plannerPromptSuffix(「任务要求 + 空行 + 配置文本」——宿主
|
|
1032
|
+
// exec.arguments 与消息对象均 deepFreeze,拼接走 pre-step 消息替换通道,
|
|
1033
|
+
// 与 agent-instructions 基线注入同通道)。
|
|
1034
|
+
// C=0:按各宿主实际装载目录,把三版本的精确隐藏名投影到模型可见 catalog;不把跨版本并集当成单根物理装载。
|
|
1035
|
+
// DSH_COMPAT_RC1:rc.1 旧隐藏名为 cordis-plugin-development、editing-cordis-compositions、
|
|
1036
|
+
// cordis-composition-reference;rc.1另含但不隐藏 agent-experience。删除边界仅限上述旧隐藏名,须另行授权,不含共享安全核心。
|
|
1037
|
+
// DSH_CURRENT_RC2:最新路径隐藏名为 dsh-doc(rc.2 与 rc.3 共用);agent-experience 不在隐藏集合。
|
|
1038
|
+
// 删除边界:最新路径隐藏名须保留,撤销兼容仍须另行授权,不含共享安全核心。
|
|
1039
|
+
// (换通道后旧 customSkillDirs 走 ctx.fs 扫 asar 会抛错;不再靠「不注册」),
|
|
1040
|
+
// 一律从模型可见 catalog 隐藏——只影响名字可见性,skill 仍注册、按名调用仍可加载。
|
|
1041
|
+
// C=1:首轮暂隐已由 filterBootstrapContextDecision 在 gated 为 true 时整条剔除 skill-catalog 消息承担;本函数只保留 C=0 全量隐藏分支。
|
|
1042
|
+
function shouldHideCreativeCatalog(agent) {
|
|
1043
|
+
return !creativeModeOn(agent)
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
// agent/pre-step 消息投影:prepend 让本处理在 tool-skill/agent-instructions 等内层完成后
|
|
1047
|
+
// 收到最终 decision;F 只过滤当前副本,L 仍由宿主自然重组。
|
|
1048
|
+
function isAnchoredContextGate(agent, events) {
|
|
1049
|
+
if (agent === undefined || agent === null) return false
|
|
1050
|
+
const planner = isPlannerChild(agent)
|
|
1051
|
+
const child = isChild(agent)
|
|
1052
|
+
return bootstrapOn(agent) && isBootstrapPhase(agent, events) && (planner || !child)
|
|
1053
|
+
}
|
|
1054
|
+
let preStepWarned = false
|
|
1055
|
+
function warnPreStepFailure(error) {
|
|
1056
|
+
if (preStepWarned) return
|
|
1057
|
+
preStepWarned = true
|
|
1058
|
+
console.warn('extra-plan: agent/pre-step 后处理失败(已尽可能保留源过滤结果):' + (error instanceof Error ? error.message : String(error)))
|
|
1059
|
+
}
|
|
1060
|
+
ctx.on('agent/pre-step', async (payload, next) => {
|
|
1061
|
+
const decision = await next()
|
|
1062
|
+
// 首轮相位判定改用 observeSession 租约快照(改造8:异步钩子不再经 deprecated 同步通道);
|
|
1063
|
+
// 租约拿不到时退化为未传 events,由 isBootstrapPhase 内部兜底,判定逻辑不变。
|
|
1064
|
+
let lease
|
|
1065
|
+
let gated
|
|
1066
|
+
let hideCreativeCatalog
|
|
1067
|
+
try {
|
|
1068
|
+
lease = await observeSessionLeaseOf(payload.agent)
|
|
1069
|
+
gated = isAnchoredContextGate(payload.agent, lease?.events)
|
|
1070
|
+
hideCreativeCatalog = shouldHideCreativeCatalog(payload.agent)
|
|
1071
|
+
} finally {
|
|
1072
|
+
if (lease !== undefined && typeof lease[Symbol.dispose] === 'function') lease[Symbol.dispose]()
|
|
1073
|
+
}
|
|
1074
|
+
// source gate 是关键边界:放在可降级的 creative/去重处理之外,失败不得发送未过滤 decision。
|
|
1075
|
+
const filtered = filterBootstrapContextDecision(decision, gated)
|
|
1076
|
+
let projected = filtered
|
|
1077
|
+
try {
|
|
1078
|
+
projected = hideCreativeCatalog ? projectSkillCatalogDecision(projected) : projected
|
|
1079
|
+
const session = payload.agent.session
|
|
1080
|
+
const visibleMessages = session !== undefined && session !== null && typeof session.deriveMessages === 'function'
|
|
1081
|
+
? session.deriveMessages()
|
|
1082
|
+
: undefined
|
|
1083
|
+
projected = dedupeProjectedContextDecision(projected, visibleMessages)
|
|
1084
|
+
return projected
|
|
1085
|
+
} catch (error) {
|
|
1086
|
+
warnPreStepFailure(error)
|
|
1087
|
+
return projected
|
|
1088
|
+
}
|
|
1089
|
+
}, { prepend: true })
|
|
1090
|
+
|
|
1091
|
+
ctx.on('agent/pre-step', async (payload, next) => {
|
|
1092
|
+
// 每次 pre-step 在 await next() 前捕获自己的 Agent;不得使用 apply 级共享引用。
|
|
1093
|
+
const agent = payload !== undefined && payload !== null ? payload.agent : undefined
|
|
1094
|
+
let initializationFailed = false
|
|
1095
|
+
if (agent !== undefined) {
|
|
1096
|
+
try {
|
|
1097
|
+
childBaseline(agent)
|
|
1098
|
+
// T3:save_plan 与 save_probe 同构——主会话侧同样在 pre-step 幂等兜底注册
|
|
1099
|
+
// (web 会话先按默认预设发布;agent/created 与本处 pre-step 互补,recompose 不重发前者时
|
|
1100
|
+
// 仍可补齐注册;registerTool 的 WeakSet 保证不重复注册)。
|
|
1101
|
+
if (isPlannerChild(agent) || !isSubagentChild(agent)) {
|
|
1102
|
+
registerSavePlan(agent)
|
|
1103
|
+
registerEditPlanDraft(agent)
|
|
1104
|
+
}
|
|
1105
|
+
if (!isSubagentChild(agent) || probeClaimFor(agent)) { registerSaveProbe(agent) }
|
|
1106
|
+
if (!isSubagentChild(agent)) registerGateTool(agent)
|
|
1107
|
+
// 引导期收窄兜底:recompose 不重发 agent/created 的会话(Web 首启)在这里补 arm。
|
|
1108
|
+
armAnchoredToolRestriction(agent, 'pre-step')
|
|
1109
|
+
armCordisPresentationRestriction(agent, 'pre-step')
|
|
1110
|
+
armWebFetchRestriction(agent, 'pre-step')
|
|
1111
|
+
armWaitAgentRestriction(agent, 'pre-step')
|
|
1112
|
+
} catch (error) {
|
|
1113
|
+
initializationFailed = true
|
|
1114
|
+
warnPreStepFailure(error)
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
const decision = await next()
|
|
1118
|
+
// 引导期兜底释放:本步已进入 L 段(会话已有 tool/call)时解除收窄,使下一步装配回到完整工具面。
|
|
1119
|
+
// 宿主 assemble 早于 pre-step,故此处释放只影响下一步;初始化失败分支同样执行,不得跳过。
|
|
1120
|
+
if (agent !== undefined) {
|
|
1121
|
+
try {
|
|
1122
|
+
const releaseLease = await observeSessionLeaseOf(agent)
|
|
1123
|
+
try {
|
|
1124
|
+
if (!isBootstrapPhase(agent, releaseLease?.events)) releaseAnchoredToolRestriction(agent)
|
|
1125
|
+
// C=1 转档释放:中途切到 C=1 时解除 cordis 展示工具 deny;判据与 arm 同源(只读 creativeModeOn)。
|
|
1126
|
+
if (creativeModeOn(agent)) releaseCordisPresentationRestriction(agent)
|
|
1127
|
+
// webFetch 开启即释放 web_fetch deny:改值后下一 pre-step 生效,无需重启宿主。
|
|
1128
|
+
if (webFetchOn(agent)) releaseWebFetchRestriction(agent)
|
|
1129
|
+
} finally {
|
|
1130
|
+
if (releaseLease !== undefined && typeof releaseLease[Symbol.dispose] === 'function') releaseLease[Symbol.dispose]()
|
|
1131
|
+
}
|
|
1132
|
+
} catch (error) {
|
|
1133
|
+
warnPreStepFailure(error)
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
if (initializationFailed) return decision
|
|
1137
|
+
try {
|
|
1138
|
+
if (decision.kind !== 'enter') return decision
|
|
1139
|
+
if (agent === undefined || !isPlannerChild(agent)) return decision
|
|
1140
|
+
if (!Array.isArray(decision.messages)) return decision
|
|
1141
|
+
let lease = await observeSessionLeaseOf(agent)
|
|
1142
|
+
try {
|
|
1143
|
+
// 预算告知(先于 suffix 拼接,suffix 为空也生效)+ 阈值提示(剩余 ≤3 且未注入过时追加一条)。
|
|
1144
|
+
const budgetNotice = budgetNoticeText(exploreBudget(agent))
|
|
1145
|
+
let messages = decision.messages.map((message) => withPlannerPromptSuffix(withBudgetNotice(message, budgetNotice), plannerPromptSuffix(agent)))
|
|
1146
|
+
// 改造8:本钩子是 async 钩子且已持有 observeSession 租约,事件一律取租约快照;
|
|
1147
|
+
// 租约不可用时记账相关逻辑(工具计数与阈值提示)显式跳过,不再回落 deprecated 同步快照通道。
|
|
1148
|
+
const leaseEvents = lease === undefined ? undefined : lease.events
|
|
1149
|
+
if (!Array.isArray(leaseEvents)) return { ...decision, messages }
|
|
1150
|
+
const used = toolCallsSinceUser(leaseEvents, FREE_TOOLS)
|
|
1151
|
+
const reminder = budgetReminderText(exploreBudget(agent) - used, exploreBudget(agent), BUDGET_REMINDER_THRESHOLD)
|
|
1152
|
+
if (reminder !== '' && !budgetReminderSent(leaseEvents, '本轮探查预算还剩 ')) {
|
|
1153
|
+
messages = [...messages, budgetReminderMessage(reminder)]
|
|
1154
|
+
}
|
|
1155
|
+
return { ...decision, messages }
|
|
1156
|
+
} finally {
|
|
1157
|
+
if (lease !== undefined && typeof lease[Symbol.dispose] === 'function') lease[Symbol.dispose]()
|
|
1158
|
+
}
|
|
1159
|
+
} catch (error) {
|
|
1160
|
+
warnPreStepFailure(error)
|
|
1161
|
+
return decision
|
|
1162
|
+
}
|
|
1163
|
+
})
|
|
1164
|
+
|
|
1165
|
+
// 2.5) 模型请求失败诊断 + MALFORMED_RESPONSE 限次自愈(v0.3.1):把 failure 的完整
|
|
1166
|
+
// cause 链逐行写进诊断文件,用于定位"save_plan 后请求流中断"的真实底层错误(TRANSPORT
|
|
1167
|
+
// 只是包装码);记账之外,对 MALFORMED_RESPONSE 做一次兜底自愈(malformedRecovery,
|
|
1168
|
+
// 见模块级注释):llm-retry 已返回 {kind:'retry'} 时原样透传(不与宿主重试叠加、不
|
|
1169
|
+
// 重复重试),否则交 malformedRecovery 判定——命中返回 retry 让 dsh-agent-loop 重试该
|
|
1170
|
+
// 步,未命中回退原 action 透传(其余失败码行为不变)。
|
|
1171
|
+
const diagPath = typeof cfg.diagFile === 'string' && cfg.diagFile !== '' ? cfg.diagFile : DEFAULT_DIAG_FILE
|
|
1172
|
+
let diagWarned = false
|
|
1173
|
+
// causeChainOf 从 lib/runtime-static.js 导入。
|
|
1174
|
+
|
|
1175
|
+
function recordRequestError(payload) {
|
|
1176
|
+
try {
|
|
1177
|
+
const row = {
|
|
1178
|
+
ts: new Date().toISOString(),
|
|
1179
|
+
sessionId: payload.agent !== undefined && payload.agent.session !== undefined ? payload.agent.session.header.id : '',
|
|
1180
|
+
role: payload.agent !== undefined ? (isPlannerChild(payload.agent) ? 'planner' : isSubagentChild(payload.agent) ? 'executor' : 'main') : 'unknown',
|
|
1181
|
+
turn: payload.turn,
|
|
1182
|
+
step: payload.step,
|
|
1183
|
+
provider: payload.provider,
|
|
1184
|
+
message: payload.failure !== undefined && payload.failure !== null && typeof payload.failure.message === 'string' ? payload.failure.message.slice(0, 400) : '',
|
|
1185
|
+
...(payload.failure !== undefined && payload.failure !== null && payload.failure.code !== undefined ? { code: String(payload.failure.code) } : {}),
|
|
1186
|
+
causeChain: causeChainOf(payload.failure, 8),
|
|
1187
|
+
}
|
|
1188
|
+
if (!appendDiagnostic(ctx, payload.agent, diagPath, row)) throw new Error('request diagnostics root unavailable')
|
|
1189
|
+
} catch (error) {
|
|
1190
|
+
if (!diagWarned) {
|
|
1191
|
+
diagWarned = true
|
|
1192
|
+
console.warn(`extra-plan: request-error diagnostics write failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
ctx.on('agent/request-error', async (payload, next) => {
|
|
1198
|
+
let action
|
|
1199
|
+
try {
|
|
1200
|
+
action = await next()
|
|
1201
|
+
} finally {
|
|
1202
|
+
recordRequestError(payload)
|
|
1203
|
+
}
|
|
1204
|
+
if (action !== undefined && action !== null && action.kind === 'retry') return action
|
|
1205
|
+
return malformedRecovery(payload) ?? action
|
|
1206
|
+
})
|
|
1207
|
+
|
|
1208
|
+
// 2.6) 回合错误取证(agent/error 为 emit、同步回调):宿主不把回合级错误写
|
|
1209
|
+
// console,由 recordAgentError 逐字落盘诊断文件供根因定位
|
|
1210
|
+
// (含子代理"腰斩"的流建立失败等 runTurn 级错误);recordAgentError 内部全吞错、
|
|
1211
|
+
// 写失败仅一次性告警,监听器绝不放大故障。
|
|
1212
|
+
ctx.on('agent/error', (payload) => recordAgentError(payload, { ctx }))
|
|
1213
|
+
|
|
1214
|
+
// 4) 会话销毁:同步状态回收 + 单会话状态回收。必须保持同步回调——agent/disposed 是
|
|
1215
|
+
// emit/void,宿主调用监听器后只对返回的 Promise 挂 catch、不等待完成。
|
|
1216
|
+
// 改造8 起没有 final usage fold:用量账本由插件启动时扫描会话日志维护(改造11 起收敛到
|
|
1217
|
+
// lib/usage-ledger.js 单文件),本监听器不读事件、不写账本,也不再持有任何 usage cursor。
|
|
1218
|
+
// 顺序不可换:① 先释放 sdkTextCache;② 保留 pendingProbeClaims 的剩余数量告警语义,再删除
|
|
1219
|
+
// 该 session 的待认领计数(含 runCodeDenyRecords 的 PTC 拒绝记录桶);③ 最后按
|
|
1220
|
+
// sessionId 依次回收 jobOutputCallCounters、jobOutputLastAnchors、toolJobsNoticesConsumed、
|
|
1221
|
+
// subCallCounters 与 malformedRetried(MALFORMED 自愈限次账本)。
|
|
1222
|
+
// 重复 disposed 幂等;其它 session 的同名 rootCallId 与计数均不受影响。
|
|
1223
|
+
ctx.on('agent/disposed', (payload) => {
|
|
1224
|
+
const agent = payload.agent
|
|
1225
|
+
anchoredDiagState.delete(agent)
|
|
1226
|
+
const sessionId = agent?.session?.header?.id
|
|
1227
|
+
if (typeof sessionId !== 'string') return
|
|
1228
|
+
try {
|
|
1229
|
+
sdkTextCache.dispose(agent)
|
|
1230
|
+
} catch (error) {
|
|
1231
|
+
console.warn('extra-plan: agent/disposed text cache cleanup failed: ' + (error instanceof Error ? error.message : String(error)))
|
|
1232
|
+
}
|
|
1233
|
+
const pending = runtimeLifecycle.pendingProbeCount(sessionId)
|
|
1234
|
+
if (Number.isInteger(pending) && pending > 0) {
|
|
1235
|
+
const warning = probeDisposalWarning(pending)
|
|
1236
|
+
if (warning !== null) console.warn(warning)
|
|
1237
|
+
}
|
|
1238
|
+
runtimeLifecycle.disposeSession(sessionId)
|
|
1239
|
+
malformedRetried.delete(sessionId)
|
|
1240
|
+
})
|
|
1241
|
+
|
|
1242
|
+
// 3) anchored 引导(默认开):主会话与规划子代理首轮极简;executor/reviewer/prober 不引导。
|
|
1243
|
+
// native 首轮保留 bootstrap shell(s)+read,sections 仅 persona;Pure PTC
|
|
1244
|
+
// 首轮保留唯一 run_code、persona 与 tool:read 手写文案——宿主 tools:ptc-only 段已按
|
|
1245
|
+
// 用户要求停用、不透传;借宿主段名覆盖 text(cfg.bootstrapReadHint),不生成完整 SDK。
|
|
1246
|
+
// 无 shell 无 run_code 跳过+警告一次。钩子常驻(bootstrapOn=false 时也注册):
|
|
1247
|
+
// 另负责按真实 schemas 优先、未折叠装配目录回退识别非 planner child 的只读分类(含 prober/reviewer),写入 per-agent
|
|
1248
|
+
// 缓存,供 pre-execute 拦截复用;bootstrapOn=false 时仍记录分类,不据此承诺 C 投影或执行隔离。
|
|
1249
|
+
const readOnlyChildren = new WeakSet()
|
|
1250
|
+
// 0.2.2-rc.1 修复(BUG-1)诊断:每个 agent 按当前 apply 的 first/later 各保留一次成功装配判定,
|
|
1251
|
+
// 用于区分「工具面被宿主并集覆盖」与「引导分支根本没进入」这两种同源症状。
|
|
1252
|
+
ctx.on('system-prompt/assemble', async (assembly, context, next) => {
|
|
1253
|
+
const result = await next()
|
|
1254
|
+
const agent = context.agent
|
|
1255
|
+
if (agent === undefined) return result
|
|
1256
|
+
const planner = isPlannerChild(agent)
|
|
1257
|
+
const child = isChild(agent)
|
|
1258
|
+
const schemas = toolSchemasOf(agent)
|
|
1259
|
+
if (child && !planner) {
|
|
1260
|
+
// 只读分类使用 registry.schemas,而不是装配返回数组;模型可见隐藏不改变执行分类。
|
|
1261
|
+
if (schemas !== undefined) {
|
|
1262
|
+
if (schemasHasWriteTools(schemas)) readOnlyChildren.delete(agent)
|
|
1263
|
+
else readOnlyChildren.add(agent)
|
|
1264
|
+
} else if (catalogIsCollapsed(result.tools)) {
|
|
1265
|
+
readOnlyChildren.delete(agent)
|
|
1266
|
+
} else if (isReadOnlyChildByCatalog(result.tools)) {
|
|
1267
|
+
readOnlyChildren.add(agent)
|
|
1268
|
+
} else {
|
|
1269
|
+
readOnlyChildren.delete(agent)
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
// 展示决策按 phase → creative → mode 分层;所有分支只返回模型可见副本。
|
|
1274
|
+
// v4 D-A:phase 决策用与 arm 同源同步判据 isBootstrapPhase(agent)(同步 sessionEvents 通道);租约只读求值仅用于 assemble-diag 取证对比(phaseLease 字段),不参与 anchoredFirst 决策;差异记录:同步快照可能滞后于租约不可变快照,但 arm 用同判据已在实机 arm-ok 生效,同源即对齐。
|
|
1275
|
+
const phase = isBootstrapPhase(agent) ? 'first' : 'later'
|
|
1276
|
+
let phaseLease = null
|
|
1277
|
+
try {
|
|
1278
|
+
const lease = await observeSessionLeaseOf(agent)
|
|
1279
|
+
phaseLease = isBootstrapPhase(agent, lease?.events) ? 'first' : 'later'
|
|
1280
|
+
if (lease !== undefined && typeof lease[Symbol.dispose] === 'function') lease[Symbol.dispose]()
|
|
1281
|
+
} catch (error) {
|
|
1282
|
+
phaseLease = 'unavailable'
|
|
1283
|
+
}
|
|
1284
|
+
const role = planner ? 'planner' : child ? 'executor' : 'main'
|
|
1285
|
+
// 呈现模式二值化:唯一来源是宿主装配结果里的 tools:ptc-only 段,由实际挂载的 ptc 执行器注入,其余 native。
|
|
1286
|
+
const mode = hasNonEmptySection(result.sections, PTC_SECTION_NAME) ? 'ptc' : 'native'
|
|
1287
|
+
const anchoredFirst = bootstrapOn(agent) && phase === 'first' && (role === 'main' || role === 'planner')
|
|
1288
|
+
const anchoredPtc = anchoredFirst && mode === 'ptc'
|
|
1289
|
+
let presented = result
|
|
1290
|
+
if (anchoredPtc) {
|
|
1291
|
+
// HP0/HP1:PTC 首轮只保留传输、persona 与手写 read 文案(覆盖 tool:read 的 text);不先生成完整 SDK。
|
|
1292
|
+
presented = projectAssemblyForPresentation(result, schemas, {
|
|
1293
|
+
hideCordis: !creativeModeOn(agent),
|
|
1294
|
+
ptcOnly: true,
|
|
1295
|
+
keepSectionNames: new Set([PTC_SECTION_NAME, READ_SECTION_NAME]),
|
|
1296
|
+
})
|
|
1297
|
+
} else if (!creativeModeOn(agent)) {
|
|
1298
|
+
let sdkText
|
|
1299
|
+
// F/native 随后只返回 bootstrap shell(s)+read,不能为被剥离的完整 SDK 预热。
|
|
1300
|
+
if (!anchoredFirst && hasSection(result.sections, SDK_SECTION_NAME)) {
|
|
1301
|
+
let language = 'typescript'
|
|
1302
|
+
try {
|
|
1303
|
+
// ptcRuntime 服务由 @deepseek-ai/dsh-ptc-runtime-node 提供(宿主 patch 行 id: ptc-runtime)。
|
|
1304
|
+
const runtime = typeof ctx.get === 'function' ? ctx.get('ptcRuntime') : undefined
|
|
1305
|
+
if (runtime !== undefined && runtime !== null && typeof runtime.language === 'string') language = runtime.language
|
|
1306
|
+
} catch (error) { /* 缺少 ptcRuntime 时按测试/兼容默认使用 TypeScript renderer */ }
|
|
1307
|
+
try {
|
|
1308
|
+
const effectiveSchemas = toolSdkSchemasOf(agent) ?? schemas
|
|
1309
|
+
const rendererInput = sdkSchemasForRendering(effectiveSchemas)
|
|
1310
|
+
const renderer = await resolveToolsSdkRenderer(language, installAnchorOf(ctx))
|
|
1311
|
+
sdkText = await sdkTextCache.getOrCreate(agent, rendererInput, language, renderer)
|
|
1312
|
+
} catch (error) {
|
|
1313
|
+
console.warn('extra-plan: filtered tools:sdk render failed (' + (error instanceof Error ? error.message : String(error)) + ')')
|
|
1314
|
+
// 渲染失败时清空 SDK 段:assembly-presentation.js 仅在 typeof sdkText === 'string' 时替换 tools:sdk 文本,不清空会保留宿主未过滤原文(含 cordis_inspect_list/query 声明)
|
|
1315
|
+
sdkText = ''
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
presented = projectAssemblyForPresentation(result, schemas, { sdkText, hideCordis: !creativeModeOn(agent), ptcOnly: mode === 'ptc' })
|
|
1319
|
+
} else if (mode === 'ptc') {
|
|
1320
|
+
// Pure PTC 的保留传输始终是唯一顶层工具;其余 binding 只在嵌套 SDK 中出现。
|
|
1321
|
+
presented = projectAssemblyForPresentation(result, schemas, { hideCordis: false, ptcOnly: true })
|
|
1322
|
+
} else {
|
|
1323
|
+
// C=1/native:不主动隐藏 Cordis 或替换 SDK;仅剥离已退役 tool:cordis 段,
|
|
1324
|
+
// 两个展示工具保留在 SDK 原文中;展示投影不等于运行隔离,C=0 适用分支负责过滤/重渲(失败清空)。
|
|
1325
|
+
presented = projectAssemblyForPresentation(result, schemas, { hideCordis: false })
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
// v4 assemble-diag:当前 apply 内同一 Agent 的首次实际 F/L 各自最多成功落盘一次。
|
|
1329
|
+
// phaseSync=决策用同步判据;phaseLease=租约只读求值(仅取证对比,不参与 anchoredFirst 决策);phaseSource=决策来源。
|
|
1330
|
+
|
|
1331
|
+
const hasTools = Array.isArray(presented.tools) && presented.tools.length > 0
|
|
1332
|
+
let narrowed = null
|
|
1333
|
+
if (anchoredFirst && hasTools) {
|
|
1334
|
+
const shells = presented.tools.filter((tool) => tool !== null && typeof tool === 'object' && bootstrapShellTools.has(tool.name))
|
|
1335
|
+
const runCodes = presented.tools.filter((tool) => tool !== null && typeof tool === 'object' && tool.name === 'run_code')
|
|
1336
|
+
if (shells.length === 0 && runCodes.length === 0) {
|
|
1337
|
+
if (!bootstrapShellMissingWarned) {
|
|
1338
|
+
bootstrapShellMissingWarned = true
|
|
1339
|
+
console.warn('extra-plan: anchoredBootstrap enabled but neither a bootstrap shell nor run_code is present in the catalog — bootstrap skipped for this assembly')
|
|
1340
|
+
}
|
|
1341
|
+
} else {
|
|
1342
|
+
const keep = new Set([...shells.map((tool) => tool.name), ...(shells.length === 0 ? runCodes.map((tool) => tool.name) : []), ...bootstrapCommonTools])
|
|
1343
|
+
const bootstrapped = presented.tools.filter((tool) => tool !== null && typeof tool === 'object' && keep.has(tool.name))
|
|
1344
|
+
if (anchoredPtc) {
|
|
1345
|
+
const readSection = sectionOf(presented.sections, READ_SECTION_NAME)
|
|
1346
|
+
narrowed = { sections: [{ name: 'extra-plan-bootstrap', text: bootstrapPersona }, ...(readSection === undefined ? [{ name: READ_SECTION_NAME, text: bootstrapReadHint }] : [{ ...readSection, text: bootstrapReadHint }])], contexts: [], tools: bootstrapped }
|
|
1347
|
+
} else {
|
|
1348
|
+
narrowed = { sections: [{ name: 'extra-plan-bootstrap', text: bootstrapPersona }], contexts: [], tools: bootstrapped }
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
} else if (anchoredFirst && !hasTools && anchoredPtc) {
|
|
1352
|
+
narrowed = { sections: [{ name: 'extra-plan-bootstrap', text: bootstrapPersona }, { name: READ_SECTION_NAME, text: bootstrapReadHint }], contexts: [] }
|
|
1353
|
+
} else if (anchoredFirst && !hasTools) {
|
|
1354
|
+
narrowed = { sections: [{ name: 'extra-plan-bootstrap', text: bootstrapPersona }], contexts: [] }
|
|
1355
|
+
}
|
|
1356
|
+
// anchoredPtc 且 tools 缺失:仍按 persona 与手写 read 文案投影,tools 维持宿主原样
|
|
1357
|
+
const diagState = anchoredDiagStateOf(agent)
|
|
1358
|
+
const diagKey = phase === 'first' ? 'first' : 'later'
|
|
1359
|
+
if (diagState[diagKey] !== true) {
|
|
1360
|
+
const keypoint = phase === 'first' ? 'first-assembly' : 'first-after-tool-call'
|
|
1361
|
+
try {
|
|
1362
|
+
if (appendDiagnostic(ctx, agent, 'extra-plan-anchored.jsonl', {
|
|
1363
|
+
ts: new Date().toISOString(),
|
|
1364
|
+
sessionId: typeof agent?.session?.header?.id === 'string' ? agent.session.header.id : '',
|
|
1365
|
+
event: 'assemble-diag',
|
|
1366
|
+
keypoint,
|
|
1367
|
+
phase,
|
|
1368
|
+
phaseSync: phase,
|
|
1369
|
+
phaseLease,
|
|
1370
|
+
phaseSource: 'sync-sessionEvents',
|
|
1371
|
+
anchoredFirst,
|
|
1372
|
+
mode,
|
|
1373
|
+
bootstrapOn: bootstrapOn(agent),
|
|
1374
|
+
role,
|
|
1375
|
+
toolsIn: Array.isArray(result.tools) ? result.tools.length : null,
|
|
1376
|
+
toolsOut: Array.isArray(presented.tools) ? presented.tools.length : null,
|
|
1377
|
+
toolsPresent: hasTools,
|
|
1378
|
+
sectionsIn: Array.isArray(result.sections) ? result.sections.map((section) => (section !== null && typeof section === 'object' ? section.name : null)) : null,
|
|
1379
|
+
sectionsOut: narrowed === null ? (Array.isArray(presented.sections) ? presented.sections.map((section) => (section !== null && typeof section === 'object' ? section.name : null)) : null) : narrowed.sections.map((section) => section.name),
|
|
1380
|
+
restrictions: restrictionsSnapshotOf(agent, diagState),
|
|
1381
|
+
})) diagState[diagKey] = true
|
|
1382
|
+
} catch (error) {
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
if (!anchoredFirst) return presented
|
|
1387
|
+
if (narrowed === null) return presented
|
|
1388
|
+
return { ...presented, ...narrowed }
|
|
1389
|
+
})
|
|
1390
|
+
|
|
1391
|
+
// 4) 模型与力度继承:子代理 agent/request 解析后,把 provider/model/maxTokens
|
|
1392
|
+
// 与 reasoningEffort 注入为父会话当前配置(requestHeader().config,非创建时
|
|
1393
|
+
// 快照)。执行者/验收者等非 planner 子代理直接继承当前值;planner 的
|
|
1394
|
+
// 有效模型由 resolvePlannerEntry 现场解析并缓存(本钩子只读缓存,不再做
|
|
1395
|
+
// 模型目录查询):已创建的 planner 不随父会话改模型而变。
|
|
1396
|
+
// 真实机制(注释订正):宿主 installModelSelection 仅由主会话侧会话控制器安装
|
|
1397
|
+
// (setup: installSelection 先于 presets.mount),其 agent/request 钩子无条件
|
|
1398
|
+
// 覆写 provider/model/reasoningEffort(剥除 resolved 的 effort);子代理瀑布不安装
|
|
1399
|
+
// 该监听器 → 本插件注入在 next() 解析后执行并最终生效。
|
|
1400
|
+
// 显式选择不覆盖:resolved(next() 结果,首请求=创建时 AgentOptions、后续请求=
|
|
1401
|
+
// logged header)的 provider/model 与父会话当前值不同 → 视为显式(官方
|
|
1402
|
+
// routeChanged 口径)→ 不注入;未显式维持现状注入。父会话在子代理运行期间
|
|
1403
|
+
// 切换模型 → 子代理保持创建时值(planner 已有 entry 缓存同语义,非 planner 子代理亦冻结)。
|
|
1404
|
+
// effort:resolved 存在且 ≠ 父值 → 显式不注入;路由显式且 resolved 无 effort →
|
|
1405
|
+
// 不注入(对齐官方 routeChanged 清 effort);其余维持父 effort 继承(现状)。
|
|
1406
|
+
ctx.on('agent/request', async (payload, next) => {
|
|
1407
|
+
const resolved = await next()
|
|
1408
|
+
if (payload.agent === undefined) return resolved
|
|
1409
|
+
if (!isSubagentChild(payload.agent)) return resolved
|
|
1410
|
+
// 本钩子只用一次判定:lease 二次判定已移除(与上一行判定同源,正常时序恒等价)。
|
|
1411
|
+
// planner 模型注入(修复 v2):在父会话 header 处理之前生效——planner 使用
|
|
1412
|
+
// 设置页 plannerModel(resolvePlannerEntry 现场解析/缓存);不再依赖父 header
|
|
1413
|
+
// 非空与 WeakMap 缓存命中(断点①pcfg-null 早退 ②缓存 miss 回退父值 均已消除)。
|
|
1414
|
+
if (isPlannerChild(payload.agent)) {
|
|
1415
|
+
const entry = await resolvePlannerEntry(payload.agent, payload.signal)
|
|
1416
|
+
const nextConfig = { ...resolved }
|
|
1417
|
+
if (entry.maxTokens !== undefined) nextConfig.maxTokens = entry.maxTokens
|
|
1418
|
+
return nextConfig
|
|
1419
|
+
}
|
|
1420
|
+
let agents
|
|
1421
|
+
try { agents = ctx.get('agents') } catch (error) { agents = undefined }
|
|
1422
|
+
const sources = resolveAgentRouteSources(payload.agent, agents)
|
|
1423
|
+
if (sources.available !== true || sources.direct === null) return resolved
|
|
1424
|
+
const parentConfig = sources.direct
|
|
1425
|
+
const parentProvider = parentConfig.provider
|
|
1426
|
+
const parentModel = parentConfig.model
|
|
1427
|
+
const resolvedProvider = typeof resolved.provider === 'string' ? resolved.provider : ''
|
|
1428
|
+
const resolvedModel = typeof resolved.model === 'string' ? resolved.model : ''
|
|
1429
|
+
const routeExplicit = isExplicitRoute(resolvedProvider, resolvedModel, parentProvider, parentModel)
|
|
1430
|
+
const probe = schemasHasTool(toolSchemasOf(payload.agent), 'save_probe')
|
|
1431
|
+
const tokenSource = probe && sources.source !== null ? sources.source : parentConfig
|
|
1432
|
+
const nextConfig = { ...resolved }
|
|
1433
|
+
// 显式 agentOptions/provider/model 相对直接父路由优先:短路 resolver、目录与真实探针。
|
|
1434
|
+
if (!routeExplicit) {
|
|
1435
|
+
// 非 planner resolver 内部把 provider/model fallback 固定取顶层主会话;probe 同样不绕过该入口。
|
|
1436
|
+
// 验收者开关只在「非显式路由」这一分支生效:开启且命中验收者时改走 resolveReviewerEntry
|
|
1437
|
+
// (复用规划者的模型与跨提供方解析);力度仍由下方尾部继承主会话(不走 planner 早退分支)。
|
|
1438
|
+
let entry
|
|
1439
|
+
if (reviewerUsesPlannerModel(payload.agent) && isReviewerChild(payload.agent)) {
|
|
1440
|
+
entry = await resolveReviewerEntry(payload.agent, payload.signal)
|
|
1441
|
+
} else {
|
|
1442
|
+
entry = await resolveOtherAgentEntry(payload.agent, payload.signal, probe)
|
|
1443
|
+
}
|
|
1444
|
+
if (entry !== null && entry.maxTokens !== undefined) nextConfig.maxTokens = entry.maxTokens
|
|
1445
|
+
} else if (tokenSource.maxTokens !== undefined) {
|
|
1446
|
+
// 显式 route 仍保持原 maxTokens 继承语义;probe 沿用顶层来源。
|
|
1447
|
+
nextConfig.maxTokens = tokenSource.maxTokens
|
|
1448
|
+
}
|
|
1449
|
+
return nextConfig
|
|
1450
|
+
})
|
|
1451
|
+
|
|
1452
|
+
// 单实例子调用上限与 PTC 拒绝记录由 runtime-lifecycle.js 持有。
|
|
1453
|
+
// 5) 硬闸门(tools/pre-execute):规划子代理只读 + 探查硬上限;主会话三锚点(route、purpose、clarified)。
|
|
1454
|
+
ctx.on('tools/pre-execute', (exec, next) => {
|
|
1455
|
+
if (exec.agent === undefined) return next()
|
|
1456
|
+
const agent = exec.agent
|
|
1457
|
+
// 0.2.2-rc.1 修复(BUG-1):引导期工具面收窄在首个工具调用前释放,使下一步装配
|
|
1458
|
+
// (宿主 assemble 早于 agent/pre-step)即为 L 段完整工具面。
|
|
1459
|
+
// 释放逻辑单一来源 releaseAnchoredToolRestriction(含诊断落盘),此处不内联释放实现。
|
|
1460
|
+
releaseAnchoredToolRestriction(agent)
|
|
1461
|
+
// 单次会话事件快照(P1-4):本钩子内全部消费点(锚点扫描、tool-jobs 通知扫描、角色判定、
|
|
1462
|
+
// planner 闸门、main 闸门与状态推导)复用同一份快照引用,只取一次。宿主无参快照返回缓存全量
|
|
1463
|
+
// 视图(无新事件即同一引用),故此处只做快照来源收敛与可读性整理——本批**不减少**各消费点
|
|
1464
|
+
// 各自的 O(n) 扫描次数(6 个独立循环各自保持 O(n))。
|
|
1465
|
+
// 改造8:tools/pre-execute 是同步钩子;普通路径仍同步取一次 execEvents,只有名称解析按需返回 Promise,
|
|
1466
|
+
// 不新增 deprecated 读取,也不把监听器整体异步化。
|
|
1467
|
+
const execEvents = sessionEvents(agent.session)
|
|
1468
|
+
// job_output 计数器锚点重置:新用户消息或 send_message 续轮转达时清空该 session 的计数器
|
|
1469
|
+
{
|
|
1470
|
+
const sessId = agent.session.header.id
|
|
1471
|
+
let currentAnchor = -1
|
|
1472
|
+
for (let i = execEvents.length - 1; i >= 0; i -= 1) {
|
|
1473
|
+
const e = execEvents[i]
|
|
1474
|
+
if (e === null || typeof e !== 'object' || e.type !== 'user/message') continue
|
|
1475
|
+
const d = e.data
|
|
1476
|
+
const kind = d !== null && typeof d === 'object' && d.source !== null && typeof d.source === 'object' ? d.source.kind : ''
|
|
1477
|
+
if (kind === 'user' || kind === 'agent-message') {
|
|
1478
|
+
currentAnchor = i
|
|
1479
|
+
break
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
const lastAnchor = jobOutputLastAnchors.get(sessId)
|
|
1483
|
+
if (lastAnchor !== currentAnchor) {
|
|
1484
|
+
// 只清当前 session:job_output 查重与本 session 的 rootCall 桶。已消费 notice-id 集合
|
|
1485
|
+
// 跨用户/agent-message 锚点保留,直到 agent/disposed 的 disposeSession 按 session 回收。
|
|
1486
|
+
// subCallCounters 已按 sessionId 分桶,故删除全局 clear()——它会把其它 session
|
|
1487
|
+
// 正在执行的 run_code 子调用计数一并清掉(跨会话锚点互不干扰)。
|
|
1488
|
+
jobOutputCallCounters.delete(sessId)
|
|
1489
|
+
subCallCounters.delete(sessId)
|
|
1490
|
+
pollGuardCounters.delete(sessId)
|
|
1491
|
+
jobOutputLastAnchors.set(sessId, currentAnchor)
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
// tool-jobs 完成通知 durable fallback:仅扫描 user/message 事件;实时 claimed 主入口与此处
|
|
1495
|
+
// 复用同一个 consumeToolJobsNotice 幂等 helper,claimed 尚未进入 durable snapshot 时也能解锁。
|
|
1496
|
+
for (const se of execEvents) {
|
|
1497
|
+
if (se === null || typeof se !== 'object' || se.type !== 'user/message') continue
|
|
1498
|
+
consumeToolJobsNotice(agent, se.data)
|
|
1499
|
+
}
|
|
1500
|
+
// 控制工具硬闸必须使用原始子代理判定:不依赖 live parent,覆盖 unknown、断链与恢复 child。
|
|
1501
|
+
const subagentChild = isSubagentChild(agent, execEvents)
|
|
1502
|
+
// 1b 硬拒:闸门与用户提问只属于主会话。用原始 subagentChild 判定(含 unknown/断链 child),
|
|
1503
|
+
// 且置于全部角色闸门之前——否则 planner 会先被 plannerGateReason 以别的文案拒绝,
|
|
1504
|
+
// 执行者与断链 child 也会走进各自分支;这里统一给同一句主会话归属说明。
|
|
1505
|
+
if (subagentChild && (exec.name === 'ask_user_question' || exec.name === 'extra_plan_gate')) {
|
|
1506
|
+
const gateUserDenyReason = '子代理不得调用「' + exec.name + '」:闸门与用户提问只属于主会话,如需澄清请把问题写进最终回复由主会话转达'
|
|
1507
|
+
recordRunCodeDeny(agent, exec, gateUserDenyReason)
|
|
1508
|
+
return { kind: 'deny', reason: gateUserDenyReason }
|
|
1509
|
+
}
|
|
1510
|
+
const child = childBaseline(agent, execEvents)
|
|
1511
|
+
const planner = isPlannerChild(agent, execEvents)
|
|
1512
|
+
const controlReason = subagentChild ? childControlGateReason(exec) : null
|
|
1513
|
+
if (controlReason !== null) {
|
|
1514
|
+
recordRunCodeDeny(agent, exec, controlReason)
|
|
1515
|
+
return { kind: 'deny', reason: controlReason }
|
|
1516
|
+
}
|
|
1517
|
+
// 执行者与断链 child 的 run_code 先只做控制成员预审,再进入既有角色/root 闸门。
|
|
1518
|
+
if (subagentChild && exec.name === 'run_code') {
|
|
1519
|
+
const controlRunReason = runCodeGroupDenyReason(undefined, exec, { kind: 'child' }, { controlOnly: true, gateRuntime })
|
|
1520
|
+
if (controlRunReason !== null) {
|
|
1521
|
+
recordRunCodeDeny(agent, exec, controlRunReason)
|
|
1522
|
+
return { kind: 'deny', reason: controlRunReason }
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
// 探查者委派属只读探查能力(与 read/glob/grep 同级):主会话在任意路由状态放行,
|
|
1526
|
+
// 委派工具已无后台参数,固定后台语义上移宿主;本处只保留角色判定。
|
|
1527
|
+
// 置于 planner/child 判定之前,但闸门函数内首先按角色拒绝 planner(T5):
|
|
1528
|
+
// subagent_probe 仅主会话可委派;放行时挂「待认领计数」,由探查子会话在 agent/created 或 pre-step
|
|
1529
|
+
// 按身份优先认领,无法精确匹配时按父会话计数回退;此处只记录放行,不改变探查资格。
|
|
1530
|
+
if (exec.name === 'subagent_probe') {
|
|
1531
|
+
const reason = subagentProbeGateReason(exec, planner ? 'planner' : child ? 'child' : 'main')
|
|
1532
|
+
if (reason !== null) {
|
|
1533
|
+
recordRunCodeDeny(agent, exec, reason)
|
|
1534
|
+
return { kind: 'deny', reason }
|
|
1535
|
+
}
|
|
1536
|
+
const parentId = agent.session.header.id
|
|
1537
|
+
recordProbeClaim(parentId)
|
|
1538
|
+
return next()
|
|
1539
|
+
}
|
|
1540
|
+
if (planner) {
|
|
1541
|
+
let reason = plannerGateReason(exec, execEvents, exploreBudget(agent), jobOutputCallCounters)
|
|
1542
|
+
// 预算耗尽时 run_code 不在此直拒:plannerGateReason 对 run_code 仅可能因预算耗尽返回非 null
|
|
1543
|
+
// (run_code 非 write/edit/pwsh/bash/job_output),置 null 让预算判定进入组判定——组判定内按白名单把关:
|
|
1544
|
+
// 成员组非空且全部 ∈ FREE_TOOLS 才放行;含非白名单成员或空组/动态访问 → 拒绝(动态拼接文案)。
|
|
1545
|
+
if (exec.name === 'run_code' && reason !== null) reason = null
|
|
1546
|
+
if (reason !== null) {
|
|
1547
|
+
recordRunCodeDeny(agent, exec, reason)
|
|
1548
|
+
return { kind: 'deny', reason }
|
|
1549
|
+
}
|
|
1550
|
+
if (exec.name === 'run_code') {
|
|
1551
|
+
const runReason = runCodeGroupDenyReason(undefined, exec, { kind: 'planner' }, { events: execEvents, exploreBudget: exploreBudget(agent), jobOutputCallCounters, runcodeCatchGate: runcodeCatchGateOn(agent), gateRuntime })
|
|
1552
|
+
if (runReason !== null) {
|
|
1553
|
+
recordRunCodeDeny(agent, exec, runReason)
|
|
1554
|
+
return { kind: 'deny', reason: runReason }
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
// job_output 的 wait 禁令与同 job 查重已由上方 plannerGateReason 首次判定完成
|
|
1558
|
+
// (B3 收敛:不再二次调用 jobOutputGateReason);此处只在全部闸门放行后记录计数器。
|
|
1559
|
+
if (exec.name === 'job_output') {
|
|
1560
|
+
recordJobOutputCall(agent, exec, jobOutputCallCounters)
|
|
1561
|
+
}
|
|
1562
|
+
if (planner && isRunCodeSubCall(exec)) {
|
|
1563
|
+
const rid = typeof exec.rootCallId === 'string' ? exec.rootCallId : ''
|
|
1564
|
+
const capReason = noteRunCodeSubCall(agent, agent.session.header.id, rid)
|
|
1565
|
+
if (capReason !== null) {
|
|
1566
|
+
recordRunCodeDeny(agent, exec, capReason)
|
|
1567
|
+
return { kind: 'deny', reason: capReason }
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
return next()
|
|
1571
|
+
}
|
|
1572
|
+
if (child) {
|
|
1573
|
+
// 只读子代理(reviewer/probe,真实工具集判定命中缓存):write/edit 与 pwsh/bash 写命令
|
|
1574
|
+
// 一律拒绝;文案按 save_probe 信号区分(probe 走「探查者只读」,reviewer 文案逐字保持)。
|
|
1575
|
+
if (readOnlyChildren.has(agent)) {
|
|
1576
|
+
const probe = schemasHasTool(toolSchemasOf(agent), 'save_probe')
|
|
1577
|
+
const reason = childReadonlyGateReason(exec, probe, jobOutputCallCounters)
|
|
1578
|
+
if (reason !== null) {
|
|
1579
|
+
recordRunCodeDeny(agent, exec, reason)
|
|
1580
|
+
return { kind: 'deny', reason }
|
|
1581
|
+
}
|
|
1582
|
+
if (exec.name === 'run_code') {
|
|
1583
|
+
const runReason = runCodeGroupDenyReason(undefined, exec, { kind: 'child', readOnly: true, probe }, { jobOutputCallCounters, runcodeCatchGate: runcodeCatchGateOn(agent), gateRuntime })
|
|
1584
|
+
if (runReason !== null) {
|
|
1585
|
+
recordRunCodeDeny(agent, exec, runReason)
|
|
1586
|
+
return { kind: 'deny', reason: runReason }
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
// job_output 的 wait 禁令与同 job 查重已由上方 childReadonlyGateReason 首次判定完成
|
|
1590
|
+
// (B3 收敛:不再二次调用 jobOutputGateReason);此处只在全部闸门放行后记录计数器。
|
|
1591
|
+
if (exec.name === 'job_output') {
|
|
1592
|
+
recordJobOutputCall(agent, exec, jobOutputCallCounters)
|
|
1593
|
+
}
|
|
1594
|
+
}
|
|
1595
|
+
return next() // 执行者子代理豁免(目录含 write/edit,缓存未命中)
|
|
1596
|
+
}
|
|
1597
|
+
|
|
1598
|
+
const state = deriveFlowState(execEvents, gateRuntime)
|
|
1599
|
+
// DSH_CURRENT_RC2:本轮局部 Set/Map 仅把 send_message.agent 名称/路径引用解析为 Session ID;
|
|
1600
|
+
// 删除边界仅限最新路径 agent 与 resolveName 适配(rc.2 与 rc.3 共用),须另行授权,不含共享安全核心。
|
|
1601
|
+
// DSH_COMPAT_RC1:agent 非字符串时保留旧 agent_id 直接 Session ID 路径;
|
|
1602
|
+
// 删除边界仅限 rc.1 旧参数兼容,须另行授权,不含共享安全核心。
|
|
1603
|
+
const messageTargetRefs = new Set()
|
|
1604
|
+
const messageTargetIds = new Map()
|
|
1605
|
+
const messageTargetIdOf = (args) => {
|
|
1606
|
+
if (args !== undefined && args !== null && typeof args === 'object' && typeof args.agent === 'string') {
|
|
1607
|
+
const ref = args.agent
|
|
1608
|
+
const targetId = messageTargetIds.get(ref)
|
|
1609
|
+
if (targetId !== undefined) return targetId
|
|
1610
|
+
messageTargetRefs.add(ref)
|
|
1611
|
+
return null
|
|
1612
|
+
}
|
|
1613
|
+
return args !== undefined && args !== null && typeof args === 'object' && typeof args.agent_id === 'string' ? args.agent_id : null
|
|
1614
|
+
}
|
|
1615
|
+
const gateCtx = { events: execEvents, planToolName, jobOutputCallCounters, pollGuardCounters, runcodeCatchGate: runcodeCatchGateOn(agent), runCodeDepth: 0, gateRuntime, getAgents: () => ctx.get('agents'), messageTargetIdOf }
|
|
1616
|
+
let finished = false
|
|
1617
|
+
const finish = (reason) => {
|
|
1618
|
+
if (finished) return undefined
|
|
1619
|
+
finished = true
|
|
1620
|
+
if (reason !== null) {
|
|
1621
|
+
recordRunCodeDeny(agent, exec, reason)
|
|
1622
|
+
return { kind: 'deny', reason }
|
|
1623
|
+
}
|
|
1624
|
+
// 放行副作用:job_output 计数器记录(B3 收敛:与 planner/只读 child 共用 recordJobOutputCall;
|
|
1625
|
+
// 仅在全部闸门放行后执行,时序等价)
|
|
1626
|
+
recordJobOutputCall(agent, exec, jobOutputCallCounters)
|
|
1627
|
+
recordPollGuardCall(agent, exec, pollGuardCounters)
|
|
1628
|
+
return next()
|
|
1629
|
+
}
|
|
1630
|
+
const reason = mainGateReason(state, exec, gateCtx)
|
|
1631
|
+
if (reason !== null || messageTargetRefs.size === 0) return finish(reason)
|
|
1632
|
+
const subagents = ctx.get('subagents')
|
|
1633
|
+
if (subagents === undefined || subagents === null || typeof subagents.resolveName !== 'function') {
|
|
1634
|
+
throw new Error('extra-plan: send_message 使用 agent 名称/路径时需要宿主 subagents.resolveName(agent, ref, exec.signal) 能力')
|
|
1635
|
+
}
|
|
1636
|
+
return (async () => {
|
|
1637
|
+
for (const ref of messageTargetRefs) {
|
|
1638
|
+
const targetId = await subagents.resolveName(agent, ref, exec.signal)
|
|
1639
|
+
if (typeof targetId !== 'string' || targetId.length === 0) {
|
|
1640
|
+
throw new Error('extra-plan: subagents.resolveName(agent, ref, exec.signal) 必须返回非空字符串 Session ID')
|
|
1641
|
+
}
|
|
1642
|
+
messageTargetIds.set(ref, targetId)
|
|
1643
|
+
}
|
|
1644
|
+
return finish(mainGateReason(state, exec, gateCtx))
|
|
1645
|
+
})()
|
|
1646
|
+
})
|
|
1647
|
+
|
|
1648
|
+
// 6) 呈现兜底(tools/post-execute):run_code 失败结果的 error.message 含本插件刚记下的
|
|
1649
|
+
// 闸门拒绝 reason(精确子串 'ToolCallError: <reason>')时,把失败结果 content 改写为
|
|
1650
|
+
// 「Error: <reason>」——宿主英文包装('code run failed (exception)' + worker.cjs 堆栈)
|
|
1651
|
+
// 不再进入模型上下文。只改 content(PostToolDecision 禁止对失败结果替换 value)。
|
|
1652
|
+
// fail-open:无记录/未命中/非 run_code/非失败一律 next() 透传(不吞错);命中与未命中
|
|
1653
|
+
// 都在读取后清掉本 root 记录(消费即清);钩子内异常由宿主 catch 后按 toolErrorResult 兜底。
|
|
1654
|
+
ctx.on('tools/post-execute', (exec, result, next) => {
|
|
1655
|
+
if (exec === null || typeof exec !== 'object') return next()
|
|
1656
|
+
if (exec.agent === undefined || exec.name !== 'run_code') return next()
|
|
1657
|
+
if (result === null || typeof result !== 'object' || result.isError !== true) return next()
|
|
1658
|
+
const sessionId = exec.agent.session !== undefined && exec.agent.session !== null && exec.agent.session.header !== undefined && exec.agent.session.header !== null ? exec.agent.session.header.id : ''
|
|
1659
|
+
const rootId = typeof exec.rootCallId === 'string' && exec.rootCallId !== '' ? exec.rootCallId : (typeof exec.callId === 'string' ? exec.callId : '')
|
|
1660
|
+
const reasons = runtimeLifecycle.takeRunCodeDenyRecords(sessionId, rootId)
|
|
1661
|
+
if (reasons === undefined || reasons.size === 0) return next()
|
|
1662
|
+
const error = result.error
|
|
1663
|
+
const message = error !== null && error !== undefined && typeof error === 'object' && typeof error.message === 'string' ? error.message : ''
|
|
1664
|
+
let matched = null
|
|
1665
|
+
for (const reason of reasons) {
|
|
1666
|
+
if (reason !== '' && message.includes('ToolCallError: ' + reason)) { matched = reason; break }
|
|
1667
|
+
}
|
|
1668
|
+
if (matched === null) return next()
|
|
1669
|
+
return { kind: 'accept', content: [{ type: 'text', text: 'Error: ' + matched }] }
|
|
1670
|
+
})
|
|
1671
|
+
}
|