@chaoset/adaptive-perf 0.7.0 → 0.7.2

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/lib/index.js ADDED
@@ -0,0 +1,1574 @@
1
+ /**
2
+ * adaptive-perf — 极简性能自适应插件(@chaoset/adaptive-perf)
3
+ *
4
+ * 目标:让「标准模式(standard)」「PTC 模式(code)」与「创造模式
5
+ * (cordis)」达到与「极简模式(minimal)」相同级别的高性能。极简模式快
6
+ * 的原因(对源码的对照结论):
7
+ * 1. persona 配置了 includeRuntimeContext: false —— 每次模型请求不注入
8
+ * "Current runtime context" 快照(文件策略 / 审批策略等动态段);
9
+ * 2. 工具目录极小(只有 bash + str_replace_editor)—— 每个请求的
10
+ * tool schema 与(PTC 的)SDK 参考段都随之变小;
11
+ * 3. persona 为 complete 固定提示,无其它全局 prompt 段;
12
+ * 4. 不挂 skill 目录提醒(~9KB)与 AGENTS.md 摘要注入。
13
+ *
14
+ * 本插件在多个维度上做"动态自适应"(而不是静态裁剪),全部参照
15
+ * dsh-anchored-standard(https://github.com/xiaobright/dsh-anchored-standard)
16
+ * 的实测结论:
17
+ * A. 运行时上下文抑制:对目标 preset 的会话调用
18
+ * agent.ctx.systemPrompt.suppressRuntimeContext()(与极简模式同一机制),
19
+ * 每次请求省掉快照文本,零功能损失。
20
+ * B. 真实 Minimal 工具对(bootstrap.realPair,0.5.0 新增):首轮"轨迹"
21
+ * (模型思维链风格)由请求 #1 可见的**工具 schema** 决定,且只有与
22
+ * Minimal 逐字相同的 schema 才能锚定(issue #11:真实工具对 5/5 锚定,
23
+ * 任何 standard 系 schema——包括 sandboxed bash/read——11/11 落入
24
+ * standard-like)。仅收窄目录不够:standard/code preset 根本没有
25
+ * str_replace_editor,其 bash 也是 sandboxed schema。因此本插件把
26
+ * Minimal 的**真实工具对**(持久 PTY bash + str_replace_editor,官方
27
+ * minimal preset 同一批插件、同一份描述)挂进 agent 作用域工具层
28
+ * (scoped registration 按名阴影继承工具),首轮目录 = 真实工具对;
29
+ * PTC 的 SDK 参考段同样按可见目录渲染,同步缩小。
30
+ * C. 首轮锚定(bootstrap):请求 #1 只暴露真实工具对,剥离自动注入上下文
31
+ * (技能目录提醒 skill-catalog、AGENTS.md 摘要 agent-instructions;
32
+ * 用户主动的技能手势不过滤);首个**持久**晋升信号(首个 tool/call 或
33
+ * assistant/message,promoteOn 可选 either/tool-call/assistant-message)
34
+ * 后**完整恢复**该模式的全部工具目录与常规上下文注入(0.7.0,
35
+ * dsh-anchored-standard 语义:只锚定首轮,不减少后续功能);阶段从
36
+ * 持久会话事件推导,resume/reload 不丢状态,晋升信号持久(compaction
37
+ * 不重置);bootstrap.maxTokens(可选)给请求 #1 封顶输出预算,晋升后
38
+ * 剥离。
39
+ * D. 常驻上下文抑制(suppressInjectedContext,0.5.0 新增,0.7.0 默认
40
+ * 开启):true = 整个会话剥离技能目录提醒与 AGENTS.md 摘要注入(功能
41
+ * 可见性由常驻发现工具 dev_tool_search / skill_search / skill_load
42
+ * 承担——实测晋升后恢复注入会把轨迹拉回 standard-like);false =
43
+ * 只剥离首轮,晋升后恢复常规注入(opt-in)。
44
+ * E. 工具目录自适应精简(leanByDefault,0.7.0 默认关闭的 opt-in):开启时
45
+ * 按"工具族"隐藏高开销低频工具(子代理 / 工作流 / ralph / goal 等编排
46
+ * 类),只保留核心编码工具,随后根据两类信号在会话内"单调升级"放行
47
+ * 对应工具族(只升不降):
48
+ * - 关键词信号:用户消息命中某工具族的触发词(如"子代理")→ 放行该族;
49
+ * - 失败信号:PTC 的 run_code 程序调用被隐藏工具报 UNKNOWN_TOOL
50
+ * (tools/result 失败文本含工具名)→ 放行该族,下次程序即可调用。
51
+ *
52
+ * 实现全部使用 dsh 公开服务契约(Inspect 确认):
53
+ * - ctx.agentPresets.composedPreset(agent.ctx) 读取会话所属 preset
54
+ * - agent.ctx.systemPrompt.suppressRuntimeContext() 抑制上下文快照
55
+ * - agent.ctx.systemPrompt.section() 按名阴影 prompt 段(persona/引导段)
56
+ * - agent.ctx.tools.schemas(agent) 读取该 agent 当前可见工具(限制交集)
57
+ * - agent.ctx.tools.restrict({ deny }) 按 agent 作用域裁剪继承工具
58
+ * - agent.ctx.plugin() 挂载官方 minimal preset 同款插件(持久 bash /
59
+ * str_replace_editor / 其依赖的 terminals 与本地 fs)
60
+ * - agent/pre-step(waterfall) 首轮剥离自动注入上下文
61
+ * - agent/request(waterfall) 首轮输出预算封顶
62
+ * - session/event 增量喂入持久事件(晋升信号)
63
+ * - agent/created、agent/disposed、agent/inbox/inserted、tools/result 事件
64
+ * 监听器都注册在 host 根作用域(与 dsh-agent-presets 自身同款用法),事件按
65
+ * scope 过滤分发,子作用域派发的事件根监听器可收到;waterfall 均以 prepend
66
+ * 注册保证"最外层"(剥离是最后一道变换)。
67
+ *
68
+ * 配置:cordis.patch.yml 的 config(安装默认)与
69
+ * ~/.dsh/plugins/adaptive-perf/config.json(设置页 UI,权威)合并,
70
+ * 保存后热生效(新会话立即生效;已运行会话按新配置重算限制)。
71
+ *
72
+ * 依赖:真实工具对需要官方插件包(@deepseek-ai/dsh-terminal 等,声明为
73
+ * optionalDependencies)。它们不可用时本插件自动降级(告警 + 退回旧行为:
74
+ * 只收窄目录、不替换 schema),绝不拖垮 harness。
75
+ */
76
+ import { createConfigStore } from './config-store.js';
77
+ // remote 服务(设置页 UI 的配置读写)可选:typert-protocol 不可用时
78
+ // 动态 import 失败,核心功能(自适应)照常工作。
79
+ let PluginConfigGateway = null;
80
+ try {
81
+ ({ PluginConfigGateway } = await import('./remote.js'));
82
+ }
83
+ catch (error) {
84
+ console.warn('adaptive-perf: settings gateway unavailable: ' + (error?.message ?? String(error)));
85
+ }
86
+ // 宿主 settings 体系的 schema 库(dsh-settings 0.1.0-rc.7+ 用 schemastery)。
87
+ // DSH profile 的 hoisted node_modules 直接解析;仓库测试环境无此包时为
88
+ // null,settings namespace 注册段静默跳过(fail-safe)。
89
+ let Schema = null;
90
+ try {
91
+ ({ default: Schema } = await import('@deepseek-ai/schemastery'));
92
+ }
93
+ catch { }
94
+ export const name = 'adaptive-perf';
95
+ /**
96
+ * 默认配置。apply 时与 YAML 传入的 config 合并(cordis 不合并小写 config 导出)。
97
+ *
98
+ * families:工具族。每族可配 tools(该族工具名,需存在于目标 preset 的目录,
99
+ * 插件运行时按实际可见工具取交集,不会因改名/缺失而崩溃)与 keywords(用户消息
100
+ * 命中任一触发词即放行该族;大小写不敏感,子串匹配)。
101
+ *
102
+ * bootstrap:首轮锚定(参照 dsh-anchored-standard 的实测结论)。请求 #1 只暴露
103
+ * bootstrap.tools(真实 Minimal 工具对),剥离 suppressedContextSources 列出的
104
+ * 自动注入上下文;首个持久晋升信号(promoteOn)后完整恢复全部工具与常规注入
105
+ * (晋升是持久信号,compaction/end 不重置);maxTokens>0 时给请求 #1 封顶输出
106
+ * 预算(晋升后剥离)。
107
+ */
108
+ export const DEFAULT_CONFIG = {
109
+ /** 总开关:关闭后插件对会话不产生任何影响。 */
110
+ enabled: true,
111
+ /** 应用自适应的 agent preset 列表(composedPreset 返回值)。 */
112
+ presets: ['standard', 'code', 'cordis'],
113
+ /**
114
+ * 默认策略(0.7.0):首轮锚定、晋升后 resident 目录(dsh-anchored-standard
115
+ * 语义)。非极简 preset 的会话:请求 #1 按极简条件组装(真实 Minimal 工具
116
+ * 对 + 极简 persona + 屏蔽全局引导段 + 剥离自动注入 + 抑制运行时快照)以
117
+ * 锚定极简轨迹;首个持久晋升信号后进入 resident 阶段——保留 bootstrap 工具
118
+ * 对 + 常驻发现工具(dev_tool_search / skill_search / skill_load),完整
119
+ * 目录经 dev_tool_search 按需解锁(避免晋升时一次性倒出完整目录把轨迹拉回
120
+ * standard-like,anchored-standard 实测的"晋升后回退"问题),常规上下文
121
+ * 注入恢复可见——功能不减少。工具目录默认零裁剪(leanByDefault 关闭,
122
+ * 编排类工具族始终可用);需要时可在设置页按需开启。
123
+ */
124
+ /** 抑制运行时上下文快照(等同极简模式的 includeRuntimeContext: false)。 */
125
+ suppressRuntimeContext: true,
126
+ /** 会话启动时默认隐藏编排类工具族(核心编码工具始终保留)。 */
127
+ leanByDefault: false,
128
+ /** 用户消息命中工具族触发词时自动放行该族(会话内单调)。 */
129
+ escalateOnKeyword: true,
130
+ /** 工具调用失败(UNKNOWN_TOOL 文本含隐藏工具名)时自动放行该族。 */
131
+ escalateOnUnknownTool: true,
132
+ /**
133
+ * 常驻上下文抑制(0.5.0):true = 整个会话剥离自动注入上下文
134
+ * (skill-catalog 技能目录提醒、agent-instructions AGENTS.md 摘要);
135
+ * false = 只在 bootstrap 未晋升阶段剥离,晋升后恢复注入(0.7.0 默认,
136
+ * 与 dsh-anchored-standard 一致:只锚定首轮、不减少后续功能)。
137
+ */
138
+ suppressInjectedContext: true,
139
+ /** 核心编码工具(不进入任何限制族;此处仅作文档展示)。 */
140
+ coreTools: [
141
+ 'bash', 'read', 'write', 'edit', 'glob', 'grep', 'read_image',
142
+ 'job_output', 'job_list', 'job_kill',
143
+ 'todo_write', 'ask_user_question', 'web_search', 'skill', 'exit_plan_mode',
144
+ ],
145
+ /** 默认隐藏、按需放行的工具族。 */
146
+ families: {
147
+ delegation: {
148
+ enabled: true,
149
+ tools: ['subagent', 'subagent_fork', 'send_message', 'list_agents', 'interrupt_agent'],
150
+ keywords: ['子代理', '子agent', '委托', '分派', '派给', '子任务', 'subagent', 'delegate', 'fork'],
151
+ },
152
+ workflow: {
153
+ enabled: true,
154
+ tools: ['workflow'],
155
+ keywords: ['工作流', 'workflow', '编排', '多阶段'],
156
+ },
157
+ ralph: {
158
+ enabled: true,
159
+ tools: ['ralph'],
160
+ keywords: ['ralph', '全新agent', 'fresh agent'],
161
+ },
162
+ goal: {
163
+ enabled: true,
164
+ tools: ['create_goal', 'get_goal', 'update_goal'],
165
+ keywords: ['长期目标', '跨轮次', '目标追踪', 'goal'],
166
+ },
167
+ },
168
+ /** 首轮锚定(参照 dsh-anchored-standard)。 */
169
+ bootstrap: {
170
+ /** 是否启用首轮锚定。 */
171
+ enabled: true,
172
+ /**
173
+ * 是否挂载真实 Minimal 工具对(0.5.0):把官方 minimal preset 的持久
174
+ * PTY bash + str_replace_editor 挂进 agent 作用域(按名阴影 standard 的
175
+ * sandboxed bash),使请求 #1 的 schema 与 Minimal 逐字相同。依赖
176
+ * @deepseek-ai 官方插件包,不可用时自动降级为旧行为(仅收窄目录)。
177
+ */
178
+ realPair: true,
179
+ /** 请求 #1 可见的工具(真实 Minimal 工具对)。 */
180
+ tools: ['bash', 'str_replace_editor'],
181
+ /** 晋升触发:either(默认)/ tool-call / assistant-message。 */
182
+ promoteOn: 'either',
183
+ /** 请求 #1 剥离的自动注入上下文 source.kind;[] 关闭剥离。 */
184
+ suppressedContextSources: ['skill-catalog', 'agent-instructions'],
185
+ /** 晋升后 resident 目录的常驻发现工具(按需解锁完整目录)。 */
186
+ discoveryTools: ['dev_tool_search', 'skill_search', 'skill_load'],
187
+ /** 请求 #1 的输出预算封顶(token);0 = 不封顶(opt-in)。 */
188
+ maxTokens: 0,
189
+ },
190
+ /**
191
+ * 极简提示词层(语域锚定,参照 dsh-anchored-standard 的完整条件)。
192
+ *
193
+ * 参考实现指出:首轮"轨迹"(思维链风格)锚定需要 **Minimal 的完整 system
194
+ * prompt**——只收窄工具 schema 不够。本层对目标 preset 的会话:
195
+ * - suppressSections:按名阴影屏蔽全局引导段(harness:identity、
196
+ * harness:source、app:web-surface),空段在装配时被丢弃,等同极简
197
+ * complete persona 的效果(plan-mode 段、PTC 的 SDK 段不受影响);
198
+ * - persona:按名阴影替换 deployment:persona 为极简语域的短 persona
199
+ * (默认与极简模式逐字相同;留空则不替换)。
200
+ * 两处都是 agent 作用域的 prompt 段阴影,仅影响目标会话,随会话销毁自动
201
+ * 释放;对已恢复/已晋升的旧会话同样生效(不依赖 bootstrap 阶段)。
202
+ */
203
+ minimalPrompt: {
204
+ /** 是否启用极简提示词层。 */
205
+ enabled: true,
206
+ /** 替换后的 persona 文本;与极简模式相同可完全对齐语域。留空不替换。 */
207
+ persona: 'You are a helpful software engineer assistant.',
208
+ /** 屏蔽全局引导段(identity / source / web-surface)。 */
209
+ suppressSections: true,
210
+ },
211
+ };
212
+ /** 轻量配置校验/归一化:非法字段回退默认值,避免 config.json 或 remote.set
213
+ * 写入错误类型后在事件路径上抛 TypeError。 */
214
+ function boolValue(value, fallback) {
215
+ return typeof value === 'boolean' ? value : fallback;
216
+ }
217
+ function stringList(value, fallback) {
218
+ if (Array.isArray(value)) {
219
+ const out = value.filter((v) => typeof v === 'string' && v.trim().length > 0).map((v) => v.trim());
220
+ return out.length > 0 ? out : fallback;
221
+ }
222
+ if (typeof value === 'string') {
223
+ const out = value.split(/[,,\s]+/).filter((v) => v.length > 0);
224
+ return out.length > 0 ? out : fallback;
225
+ }
226
+ return fallback;
227
+ }
228
+ /** 与 stringList 相同,但显式空数组保持为空(语义是有意义的配置值)。 */
229
+ function stringListOrEmpty(value, fallback) {
230
+ if (value === undefined)
231
+ return fallback;
232
+ return stringList(value, []);
233
+ }
234
+ export function normalizeConfig(source, defaults = DEFAULT_CONFIG) {
235
+ const raw = source !== null && typeof source === 'object' && !Array.isArray(source) ? source : {};
236
+ const merged = { ...defaults, ...raw };
237
+ const families = {};
238
+ const rawFamilies = raw.families !== null && typeof raw.families === 'object' && !Array.isArray(raw.families)
239
+ ? raw.families
240
+ : defaults.families;
241
+ for (const [id, fam] of Object.entries(defaults.families)) {
242
+ const candidate = rawFamilies[id] !== null && typeof rawFamilies[id] === 'object' && !Array.isArray(rawFamilies[id])
243
+ ? rawFamilies[id]
244
+ : fam;
245
+ families[id] = {
246
+ enabled: boolValue(candidate.enabled, fam.enabled),
247
+ tools: stringList(candidate.tools, fam.tools),
248
+ keywords: stringList(candidate.keywords, fam.keywords),
249
+ };
250
+ }
251
+ const rawBootstrap = raw.bootstrap !== null && typeof raw.bootstrap === 'object' && !Array.isArray(raw.bootstrap)
252
+ ? raw.bootstrap
253
+ : defaults.bootstrap;
254
+ const db = defaults.bootstrap;
255
+ const promoteOn = rawBootstrap.promoteOn === 'tool-call' || rawBootstrap.promoteOn === 'assistant-message'
256
+ ? rawBootstrap.promoteOn
257
+ : rawBootstrap.promoteOn === 'either' ? 'either' : db.promoteOn;
258
+ const maxTokensRaw = rawBootstrap.maxTokens;
259
+ const maxTokens = Number.isSafeInteger(maxTokensRaw) && maxTokensRaw > 0 ? maxTokensRaw : 0;
260
+ const bootstrap = {
261
+ enabled: boolValue(rawBootstrap.enabled, db.enabled),
262
+ realPair: boolValue(rawBootstrap.realPair, db.realPair),
263
+ tools: stringList(rawBootstrap.tools, db.tools),
264
+ promoteOn,
265
+ suppressedContextSources: stringListOrEmpty(rawBootstrap.suppressedContextSources, db.suppressedContextSources),
266
+ discoveryTools: stringList(rawBootstrap.discoveryTools, db.discoveryTools),
267
+ maxTokens,
268
+ };
269
+ const rawMP = raw.minimalPrompt !== null && typeof raw.minimalPrompt === 'object' && !Array.isArray(raw.minimalPrompt)
270
+ ? raw.minimalPrompt
271
+ : defaults.minimalPrompt;
272
+ const dm = defaults.minimalPrompt;
273
+ const minimalPrompt = {
274
+ enabled: boolValue(rawMP.enabled, dm.enabled),
275
+ persona: typeof rawMP.persona === 'string' ? rawMP.persona.trim() : dm.persona,
276
+ suppressSections: boolValue(rawMP.suppressSections, dm.suppressSections),
277
+ };
278
+ return {
279
+ enabled: boolValue(merged.enabled, defaults.enabled),
280
+ presets: stringList(merged.presets, defaults.presets),
281
+ suppressRuntimeContext: boolValue(merged.suppressRuntimeContext, defaults.suppressRuntimeContext),
282
+ leanByDefault: boolValue(merged.leanByDefault, defaults.leanByDefault),
283
+ escalateOnKeyword: boolValue(merged.escalateOnKeyword, defaults.escalateOnKeyword),
284
+ escalateOnUnknownTool: boolValue(merged.escalateOnUnknownTool, defaults.escalateOnUnknownTool),
285
+ suppressInjectedContext: boolValue(merged.suppressInjectedContext, defaults.suppressInjectedContext),
286
+ coreTools: stringList(merged.coreTools, defaults.coreTools),
287
+ families,
288
+ bootstrap,
289
+ minimalPrompt,
290
+ };
291
+ }
292
+ /** remote.set 的严格校验:非法值直接拒绝并返回错误,而不是静默写坏文件。 */
293
+ export function validateConfig(partial) {
294
+ if (partial === null || typeof partial !== 'object' || Array.isArray(partial)) {
295
+ throw new TypeError('adaptive-perf config must be a plain object');
296
+ }
297
+ const boolFields = ['enabled', 'suppressRuntimeContext', 'leanByDefault', 'escalateOnKeyword', 'escalateOnUnknownTool',
298
+ 'suppressInjectedContext'];
299
+ for (const key of boolFields) {
300
+ if (partial[key] !== void 0 && typeof partial[key] !== 'boolean') {
301
+ throw new TypeError(`adaptive-perf config field "${key}" must be a boolean`);
302
+ }
303
+ }
304
+ for (const key of ['presets', 'coreTools']) {
305
+ if (partial[key] !== void 0 && !(Array.isArray(partial[key]) && partial[key].every((v) => typeof v === 'string'))) {
306
+ throw new TypeError(`adaptive-perf config field "${key}" must be an array of strings`);
307
+ }
308
+ }
309
+ if (partial.families !== void 0) {
310
+ if (partial.families === null || typeof partial.families !== 'object' || Array.isArray(partial.families)) {
311
+ throw new TypeError('adaptive-perf config field "families" must be an object');
312
+ }
313
+ for (const [id, fam] of Object.entries(partial.families)) {
314
+ if (fam === null || typeof fam !== 'object' || Array.isArray(fam)) {
315
+ throw new TypeError(`adaptive-perf config family "${id}" must be an object { enabled, tools, keywords }`);
316
+ }
317
+ if (fam.enabled !== void 0 && typeof fam.enabled !== 'boolean') {
318
+ throw new TypeError(`adaptive-perf config family "${id}".enabled must be a boolean`);
319
+ }
320
+ for (const key of ['tools', 'keywords']) {
321
+ if (fam[key] !== void 0 && !(Array.isArray(fam[key]) && fam[key].every((v) => typeof v === 'string'))) {
322
+ throw new TypeError(`adaptive-perf config family "${id}".${key} must be an array of strings`);
323
+ }
324
+ }
325
+ }
326
+ }
327
+ if (partial.bootstrap !== void 0) {
328
+ const b = partial.bootstrap;
329
+ if (b === null || typeof b !== 'object' || Array.isArray(b)) {
330
+ throw new TypeError('adaptive-perf config field "bootstrap" must be an object');
331
+ }
332
+ if (b.enabled !== void 0 && typeof b.enabled !== 'boolean') {
333
+ throw new TypeError('adaptive-perf config field "bootstrap.enabled" must be a boolean');
334
+ }
335
+ if (b.realPair !== void 0 && typeof b.realPair !== 'boolean') {
336
+ throw new TypeError('adaptive-perf config field "bootstrap.realPair" must be a boolean');
337
+ }
338
+ if (b.promoteOn !== void 0 && !['either', 'tool-call', 'assistant-message'].includes(b.promoteOn)) {
339
+ throw new TypeError('adaptive-perf config field "bootstrap.promoteOn" must be "either" | "tool-call" | "assistant-message"');
340
+ }
341
+ if (b.maxTokens !== void 0 && !(Number.isSafeInteger(b.maxTokens) && b.maxTokens >= 0)) {
342
+ throw new TypeError('adaptive-perf config field "bootstrap.maxTokens" must be a non-negative safe integer');
343
+ }
344
+ for (const key of ['tools', 'suppressedContextSources', 'discoveryTools']) {
345
+ if (b[key] !== void 0 && !(Array.isArray(b[key]) && b[key].every((v) => typeof v === 'string'))) {
346
+ throw new TypeError(`adaptive-perf config field "bootstrap.${key}" must be an array of strings`);
347
+ }
348
+ }
349
+ }
350
+ if (partial.minimalPrompt !== void 0) {
351
+ const m = partial.minimalPrompt;
352
+ if (m === null || typeof m !== 'object' || Array.isArray(m)) {
353
+ throw new TypeError('adaptive-perf config field "minimalPrompt" must be an object');
354
+ }
355
+ if (m.enabled !== void 0 && typeof m.enabled !== 'boolean') {
356
+ throw new TypeError('adaptive-perf config field "minimalPrompt.enabled" must be a boolean');
357
+ }
358
+ if (m.suppressSections !== void 0 && typeof m.suppressSections !== 'boolean') {
359
+ throw new TypeError('adaptive-perf config field "minimalPrompt.suppressSections" must be a boolean');
360
+ }
361
+ if (m.persona !== void 0 && typeof m.persona !== 'string') {
362
+ throw new TypeError('adaptive-perf config field "minimalPrompt.persona" must be a string');
363
+ }
364
+ }
365
+ }
366
+ // ── 纯函数(导出便于回归测试)────────────────────────────────────────────
367
+ /** 被极简提示词层屏蔽的全局引导段(name, order,与 dsh-app-boot /
368
+ * dsh-web-app / dsh-system-prompt 的注册一致)。 */
369
+ export const SECTION_SHADOWS = [
370
+ ['harness:identity', -100],
371
+ ['harness:source', -99],
372
+ ['app:web-surface', -98],
373
+ ];
374
+ /** persona 段的注册名与顺序(dsh-system-prompt 的 PERSONA_SECTION/PERSONA_ORDER)。 */
375
+ export const PERSONA_SECTION_NAME = 'deployment:persona';
376
+ export const PERSONA_SECTION_ORDER = 0;
377
+ /** 提取一条用户消息的顶层文本(text 块拼接)。 */
378
+ export function extractUserText(message) {
379
+ if (message === null || typeof message !== 'object' || !Array.isArray(message.content))
380
+ return '';
381
+ let text = '';
382
+ for (const block of message.content) {
383
+ if (block !== null && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string') {
384
+ text += block.text;
385
+ }
386
+ }
387
+ return text;
388
+ }
389
+ /** 大小写不敏感的子串匹配:任一关键词命中即返回 true。 */
390
+ export function matchKeywords(text, keywords) {
391
+ if (!Array.isArray(keywords) || keywords.length === 0)
392
+ return false;
393
+ const haystack = String(text ?? '').toLowerCase();
394
+ return keywords.some((k) => typeof k === 'string' && k.length > 0 && haystack.includes(k.toLowerCase()));
395
+ }
396
+ /** 收集一次工具调用失败的模型可见文本(error 字段 + content 文本块)。 */
397
+ export function collectFailureText(result) {
398
+ if (result === null || typeof result !== 'object')
399
+ return '';
400
+ const parts = [];
401
+ const error = result.error;
402
+ if (error !== null && typeof error === 'object') {
403
+ if (typeof error.code === 'string')
404
+ parts.push(error.code);
405
+ if (typeof error.message === 'string')
406
+ parts.push(error.message);
407
+ if (typeof error.text === 'string')
408
+ parts.push(error.text);
409
+ }
410
+ if (Array.isArray(result.content)) {
411
+ for (const block of result.content) {
412
+ if (block !== null && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string') {
413
+ parts.push(block.text);
414
+ }
415
+ }
416
+ }
417
+ return parts.join('\n');
418
+ }
419
+ // ── 真实 Minimal 工具对(0.5.0,参照 dsh-anchored-standard issue #11)──────
420
+ /**
421
+ * 官方 minimal preset 的持久 bash 工具描述,逐字一致。schema(参数)由
422
+ * @deepseek-ai/dsh-tool-bash-persistent 提供,与 minimal preset 挂的是同一
423
+ * 个包;描述在这里显式传入,保证与 minimal 的 agent.cordis.yml 完全一致。
424
+ */
425
+ export const MINIMAL_BASH_DESCRIPTION = [
426
+ 'Run commands in a bash shell',
427
+ '* When invoking this tool, the contents of the "command" parameter does NOT need to be XML-escaped.',
428
+ "* You don't have access to the internet via this tool.",
429
+ '* You do have access to a mirror of common linux and python packages via apt and pip.',
430
+ '* State is persistent across command calls and discussions with the user.',
431
+ "* To inspect a particular line range of a file, e.g. lines 10-25, try 'sed -n 10,25p /path/to/the/file'.",
432
+ '* Please avoid commands that may produce a very large amount of output.',
433
+ "* Please run long lived commands in the background, e.g. 'sleep 10 &' or start a server in the background.",
434
+ ].join('\n');
435
+ /**
436
+ * 被真实工具对按名阴影的工具引导段:standard 的 sandboxed bash 注册了
437
+ * `tool:bash`(order 105)引导段,挂载真实工具对后该文本已与可见工具不符,
438
+ * 按名阴影为空段(装配时丢弃)。
439
+ */
440
+ export const TOOL_GUIDANCE_SHADOWS = [
441
+ ['tool:bash', 105],
442
+ ];
443
+ /** 真实工具对挂载所需的官方插件包说明符(声明在 optionalDependencies)。 */
444
+ export const REAL_PAIR_SPECS = {
445
+ terminal: '@deepseek-ai/dsh-terminal',
446
+ terminalBash: '@deepseek-ai/dsh-terminal-bash',
447
+ bashPersistent: '@deepseek-ai/dsh-tool-bash-persistent',
448
+ fsLocal: '@deepseek-ai/dsh-fs-local',
449
+ strReplaceEditor: '@deepseek-ai/dsh-tool-str-replace-editor',
450
+ };
451
+ /**
452
+ * 加载真实 Minimal 工具对所需模块。任一包不可用即整体返回 null(调用方
453
+ * 降级为旧行为),绝不抛出。
454
+ * @param importFn - 测试可注入的 import 实现(默认动态 import)。
455
+ */
456
+ export async function loadRealPairModules(importFn) {
457
+ const dynamicImport = importFn ?? ((spec) => import(spec));
458
+ const modules = {};
459
+ for (const [key, spec] of Object.entries(REAL_PAIR_SPECS)) {
460
+ try {
461
+ const mod = await dynamicImport(spec);
462
+ modules[key] = mod?.default ?? mod;
463
+ }
464
+ catch {
465
+ modules[key] = null;
466
+ }
467
+ }
468
+ if (Object.keys(REAL_PAIR_SPECS).some((key) => modules[key] === null))
469
+ return null;
470
+ return modules;
471
+ }
472
+ /**
473
+ * 计算真实工具对的挂载清单(纯函数,便于测试):
474
+ * 顺序 = 依赖在前(terminals → backend → bash;fs → editor)。
475
+ * @param modules - loadRealPairModules 的结果。
476
+ * @param cwd - str_replace_editor 本地 fs 的工作目录(会话 cwd)。
477
+ */
478
+ export function realPairMounts(modules, cwd) {
479
+ if (modules === null || modules === void 0)
480
+ return [];
481
+ const resolvedCwd = typeof cwd === 'string' && cwd.length > 0
482
+ ? cwd
483
+ : (process.env.DSH_CWD && process.env.DSH_CWD.trim().length > 0 ? process.env.DSH_CWD : process.cwd());
484
+ return [
485
+ { module: modules.terminal, config: {} },
486
+ { module: modules.terminalBash, config: { timeoutMs: 300000 } },
487
+ { module: modules.bashPersistent, config: { timeoutMs: 300000, description: MINIMAL_BASH_DESCRIPTION } },
488
+ { module: modules.fsLocal, config: { cwd: resolvedCwd } },
489
+ { module: modules.strReplaceEditor, config: { maxOutputChars: 16000 } },
490
+ ];
491
+ }
492
+ /**
493
+ * 在 agent 作用域挂载真实工具对(scoped registration 按名阴影继承工具)。
494
+ * 每个挂载是一个独立 fiber,dispose 时全部副作用(工具/schema/服务)撤销。
495
+ * @param agent - 目标 agent(其 ctx 必须带 scope 标签)。
496
+ * @param mounts - realPairMounts 的结果。
497
+ * @param warn - 日志回调。
498
+ * @returns 可释放的 disposer 列表。
499
+ */
500
+ export function mountRealPair(agent, mounts, warn) {
501
+ const disposers = [];
502
+ if (agent === null || typeof agent !== 'object' || typeof agent.ctx?.plugin !== 'function')
503
+ return disposers;
504
+ for (const mount of mounts) {
505
+ if (mount?.module === null || mount?.module === void 0)
506
+ continue;
507
+ try {
508
+ const fiber = agent.ctx.plugin(mount.module, mount.config ?? {});
509
+ disposers.push(() => {
510
+ try {
511
+ fiber.dispose();
512
+ }
513
+ catch { }
514
+ });
515
+ }
516
+ catch (error) {
517
+ warn?.(`mountRealPair failed for ${String(mount.module?.name ?? 'module')}: ${String(error?.message ?? String(error))}`);
518
+ }
519
+ }
520
+ return disposers;
521
+ }
522
+ /**
523
+ * 从 agent/pre-step 的 decision.messages 剥离指定 source.kind 的消息。
524
+ * 保留原数组引用(未变化时)便于调用方判断。
525
+ */
526
+ export function stripSuppressedMessages(messages, suppressedSources) {
527
+ if (!Array.isArray(messages) || suppressedSources.size === 0)
528
+ return messages;
529
+ const kept = messages.filter((message) => {
530
+ const kind = message?.source?.kind;
531
+ return typeof kind !== 'string' || !suppressedSources.has(kind);
532
+ });
533
+ return kept.length === messages.length ? messages : kept;
534
+ }
535
+ // ── bootstrap 锚定(参照 dsh-anchored-standard 的实测结论)──────────────
536
+ /** promoteOn 配置 → 晋升的持久事件类型集合。 */
537
+ export const PROMOTE_EVENTS = {
538
+ 'tool-call': ['tool/call'],
539
+ 'assistant-message': ['assistant/message'],
540
+ either: ['tool/call', 'assistant/message'],
541
+ };
542
+ /**
543
+ /**
544
+ * dev_tool_search:搜索完整可见目录并按名解锁工具(解锁结果下一请求生效,
545
+ * 经 syncBootstrap 重算 deny 集;解锁记录写入 a.unlocked,resume-safe 由
546
+ * loadUnlockedFromEvents 从持久事件恢复)。
547
+ */
548
+ export function createDevToolSearch({ schemasOf, onUnlock, catalogHint }) {
549
+ const hint = catalogHint ?? [
550
+ 'This session starts with a minimal resident set: bash, str_replace_editor.',
551
+ 'Everything else is unlocked on demand through this tool.',
552
+ ].join('\n');
553
+ return {
554
+ name: 'dev_tool_search',
555
+ description: [
556
+ 'Discover and unlock tools that are NOT currently available.',
557
+ '',
558
+ hint,
559
+ '',
560
+ 'If the current task needs internet, delegation, workflows, goals, images, background jobs, or multi-agent coordination, call dev_tool_search FIRST — do not try to work around them with bash.',
561
+ '',
562
+ 'Usage: pass `query` to search the catalog (returns matching tool names + descriptions), then pass `toolNames` with exact names to unlock them. Unlocked tools appear from the next request on and stay unlocked for the session.',
563
+ ].join('\n'),
564
+ parameters: {
565
+ type: 'object',
566
+ properties: {
567
+ query: { type: 'string', description: 'search keywords (e.g. "web", "subagent")' },
568
+ toolNames: { type: 'array', description: 'exact tool names to unlock', items: { type: 'string' } },
569
+ },
570
+ required: [],
571
+ additionalProperties: false,
572
+ },
573
+ output: {
574
+ schema: { type: 'object', additionalProperties: false, properties: { text: { type: 'string' } }, required: ['text'] },
575
+ render: (_a, value) => [{ type: 'text', text: value.text }],
576
+ },
577
+ async execute(args, exec) {
578
+ const query = args !== null && typeof args === 'object' && typeof args.query === 'string' ? args.query.trim() : '';
579
+ const unlock = args !== null && typeof args === 'object' && Array.isArray(args.toolNames)
580
+ ? args.toolNames.filter((name) => typeof name === 'string' && name.length > 0)
581
+ : [];
582
+ const lines = [];
583
+ if (unlock.length > 0) {
584
+ let available = new Set();
585
+ try {
586
+ const schemas = typeof schemasOf === 'function' ? (schemasOf(exec) ?? []) : [];
587
+ for (const schema of schemas) {
588
+ if (schema !== null && typeof schema === 'object' && typeof schema.name === 'string')
589
+ available.add(schema.name);
590
+ }
591
+ }
592
+ catch { }
593
+ const ok = unlock.filter((name) => available.has(name));
594
+ if (ok.length > 0 && typeof onUnlock === 'function') {
595
+ try {
596
+ await onUnlock(ok, exec);
597
+ }
598
+ catch { }
599
+ }
600
+ if (ok.length > 0)
601
+ lines.push(`Unlocked for the next request: ${ok.join(', ')}`);
602
+ const missing = unlock.filter((name) => !available.has(name));
603
+ if (missing.length > 0)
604
+ lines.push(`Not found in catalog: ${missing.join(', ')}`);
605
+ }
606
+ if (query.length === 0 && unlock.length === 0) {
607
+ lines.push('Provide `query` to search the catalog, or `toolNames` to unlock tools.');
608
+ return { text: lines.join('\n') };
609
+ }
610
+ if (query.length === 0) {
611
+ return { text: lines.join('\n') || 'Nothing to do.' };
612
+ }
613
+ try {
614
+ const schemas = typeof schemasOf === 'function' ? (schemasOf(exec) ?? []) : [];
615
+ const wanted = query.toLowerCase().split(/[^a-z0-9_]+/).filter(Boolean);
616
+ const matches = schemas
617
+ .filter((schema) => {
618
+ if (schema === null || typeof schema !== 'object')
619
+ return false;
620
+ const haystack = `${schema.name || ''} ${schema.description || ''}`.toLowerCase();
621
+ return wanted.every((token) => haystack.includes(token));
622
+ })
623
+ .slice(0, 25);
624
+ if (matches.length === 0) {
625
+ lines.push(`No tools match "${query}".`);
626
+ }
627
+ else {
628
+ lines.push(`Matching tools (${matches.length}):`);
629
+ for (const schema of matches) {
630
+ const desc = String(schema.description || '').split('\n')[0] ?? ''.slice(0, 90);
631
+ lines.push(`- ${schema.name}: ${desc}`);
632
+ }
633
+ lines.push('Unlock with dev_tool_search({"toolNames": ["<exact name>"]}).');
634
+ }
635
+ }
636
+ catch (error) {
637
+ lines.push(`catalog search unavailable: ${String(error?.message ?? String(error))}`);
638
+ }
639
+ return { text: lines.join('\n') };
640
+ },
641
+ };
642
+ }
643
+ /**
644
+ * skill_search:按关键词搜索可用技能(仅摘要,替代 ~9KB 目录注入)。
645
+ * skillsOf 返回宿主 skills 服务(调用期解析)。
646
+ */
647
+ export function createSkillSearch({ skillsOf }) {
648
+ const tokens = (text) => (text || '').toLowerCase().split(/[^a-z0-9_-]+/).filter(Boolean);
649
+ return {
650
+ name: 'skill_search',
651
+ description: 'Search the available skills by keyword and return matching skill names with short descriptions. This session keeps NO skill catalog in the prompt — if a task looks like it matches a skill (document conversion, image processing, game reviews, markdown, PDF, spreadsheets, …), call skill_search FIRST to find it, then skill_load to activate it. Do NOT assume skill names from memory.',
652
+ parameters: {
653
+ type: 'object',
654
+ properties: { query: { type: 'string', description: 'search keywords (e.g. "pdf", "obsidian", "game review")' } },
655
+ required: ['query'],
656
+ additionalProperties: false,
657
+ },
658
+ output: {
659
+ schema: { type: 'object', additionalProperties: false, properties: { text: { type: 'string' } }, required: ['text'] },
660
+ render: (_a, value) => [{ type: 'text', text: value.text }],
661
+ },
662
+ async execute(args, exec) {
663
+ const wanted = tokens(args?.query);
664
+ try {
665
+ const skills = skillsOf();
666
+ if (skills === void 0 || typeof skills.list !== 'function') {
667
+ return { text: 'skill_search unavailable: skills service is not mounted.' };
668
+ }
669
+ const agent = exec?.agent;
670
+ const lookup = {
671
+ scope: agent,
672
+ cwd: agent?.session?.header?.cwd,
673
+ signal: exec?.signal,
674
+ };
675
+ const all = await skills.list(lookup);
676
+ const matches = (Array.isArray(all) ? all : []).filter((skill) => {
677
+ if (wanted.length === 0)
678
+ return true;
679
+ const haystack = tokens(`${skill?.name ?? ''} ${skill?.description ?? ''} ${skill?.whenToUse ?? ''}`).join(' ');
680
+ return wanted.every((token) => haystack.includes(token));
681
+ });
682
+ const head = matches.slice(0, 20);
683
+ const lines = head.map((skill) => {
684
+ const desc = String(skill?.description || '').split('\n')[0] ?? '';
685
+ return `- ${skill?.name}: ${desc}`;
686
+ });
687
+ if (lines.length === 0)
688
+ return { text: `No skills match "${args?.query}". Use skill_search with other keywords.` };
689
+ const extra = matches.length > 20 ? `\n…(${matches.length - 20} more)` : '';
690
+ return { text: `Matching skills (${matches.length}):\n${lines.join('\n')}${extra}\n\nLoad one with skill_load (exact name).` };
691
+ }
692
+ catch (error) {
693
+ return { text: `skill_search unavailable: ${String(error?.message ?? String(error))}` };
694
+ }
695
+ },
696
+ };
697
+ }
698
+ /**
699
+ * skill_load:按精确名加载单个技能的完整说明,经 agent.inject 作为
700
+ * source.kind='skill-invocation' 的下一条上下文消息注入(用户主动技能手势
701
+ * 同款来源,绝不被默认抑制集剥离)。
702
+ */
703
+ export function createSkillLoad({ skillsOf }) {
704
+ return {
705
+ name: 'skill_load',
706
+ description: 'Load the full instructions of ONE skill by its exact name (from skill_search results) and inject them for the next request. Call this before acting on a task that matches the skill.',
707
+ parameters: {
708
+ type: 'object',
709
+ properties: { name: { type: 'string', description: 'exact skill name (kebab-case, from skill_search)' } },
710
+ required: ['name'],
711
+ additionalProperties: false,
712
+ },
713
+ output: {
714
+ schema: { type: 'object', additionalProperties: false, properties: { text: { type: 'string' } }, required: ['text'] },
715
+ render: (_a, value) => [{ type: 'text', text: value.text }],
716
+ },
717
+ async execute(args, exec) {
718
+ try {
719
+ const agent = exec?.agent;
720
+ if (agent === void 0)
721
+ return { text: 'skill_load requires an agent context.' };
722
+ const skills = skillsOf();
723
+ if (skills === void 0 || typeof skills.get !== 'function') {
724
+ return { text: 'skill_load unavailable: skills service is not mounted.' };
725
+ }
726
+ const name = typeof args?.name === 'string' ? args.name.trim() : '';
727
+ if (name.length === 0)
728
+ return { text: 'skill_load requires a skill name.' };
729
+ const skill = await skills.get(name, {
730
+ scope: agent,
731
+ cwd: agent.session?.header?.cwd,
732
+ signal: exec?.signal,
733
+ });
734
+ if (skill === void 0) {
735
+ return { text: `No skill named "${name}". Run skill_search to list available skills.` };
736
+ }
737
+ const body = extractSkillBody(skill);
738
+ if (body.length === 0) {
739
+ return { text: `Skill "${name}" has no loadable body.` };
740
+ }
741
+ if (typeof agent.inject !== 'function') {
742
+ return { text: `Skill "${name}" found, but injection is unavailable in this agent.` };
743
+ }
744
+ agent.inject({
745
+ id: `skill-load-${name}-${Date.now()}`,
746
+ role: 'user',
747
+ content: [{ type: 'text', text: body }],
748
+ source: { kind: 'skill-invocation', name, form: 'instructions' },
749
+ });
750
+ return { text: `Skill "${name}" loaded; its instructions will be injected for the next request.` };
751
+ }
752
+ catch (error) {
753
+ return { text: `skill_load failed: ${String(error?.message ?? String(error))}` };
754
+ }
755
+ },
756
+ };
757
+ }
758
+ /** 提取已加载技能定义的模型可见正文(与参考实现一致)。 */
759
+ export function extractSkillBody(skill) {
760
+ const content = skill?.content ?? skill?.instructions ?? skill?.body;
761
+ if (typeof content === 'string')
762
+ return content;
763
+ if (Array.isArray(content)) {
764
+ return content.map((part) => (typeof part === 'string' ? part : JSON.stringify(part))).join('\n');
765
+ }
766
+ return '';
767
+ }
768
+ /**
769
+ * 扫描一段持久会话日志,推导 { promoted } 阶段。
770
+ * 晋升是持久信号(与 dsh-anchored-standard 一致):首次 promoteOn 事件后
771
+ * 恒为已晋升,resume/reload 不丢状态,compaction 不重置。
772
+ */
773
+ export function scanPhase(events, promoteEvents) {
774
+ let promoted = false;
775
+ if (Array.isArray(events)) {
776
+ for (const event of events) {
777
+ if (promoteEvents.includes(event?.type)) {
778
+ promoted = true;
779
+ break;
780
+ }
781
+ }
782
+ }
783
+ return { promoted };
784
+ }
785
+ /** 增量喂入一个持久事件(仅更新已存在条目;冷会话由 scanPhase 全量推导)。 */
786
+ export function observePhase(state, sessionId, event) {
787
+ const entry = state.get(sessionId);
788
+ if (entry === void 0)
789
+ return;
790
+ if (entry.promoted)
791
+ return;
792
+ const promoteEvents = Array.isArray(entry.promoteEvents)
793
+ ? entry.promoteEvents
794
+ : PROMOTE_EVENTS[entry.promoteOn] ?? [];
795
+ if (promoteEvents.includes(event?.type)) {
796
+ state.set(sessionId, { ...entry, promoted: true });
797
+ }
798
+ }
799
+ /**
800
+ * 按 keep 集合收窄装配后的工具目录。
801
+ * @returns { tools, missing } —— missing 非空表示 keep 中的工具在目录里缺失,
802
+ * 调用方决定是否降级(全目录放行)。
803
+ */
804
+ export function filterBootstrapTools(assembly, keep) {
805
+ const keepSet = keep instanceof Set ? keep : new Set(keep);
806
+ const tools = Array.isArray(assembly?.tools) ? assembly.tools : [];
807
+ const available = new Set(tools.map((tool) => tool?.name).filter((n) => typeof n === 'string'));
808
+ const missing = [...keepSet].filter((n) => !available.has(n));
809
+ return {
810
+ tools: tools.filter((tool) => keepSet.has(tool.name)),
811
+ missing,
812
+ };
813
+ }
814
+ /** 按 source.kind 剥离自动注入的上下文消息(保留主动的用户消息)。 */
815
+ export function filterBootstrapMessages(messages, suppressedSources) {
816
+ if (!Array.isArray(messages) || suppressedSources.size === 0)
817
+ return messages;
818
+ const kept = messages.filter((message) => {
819
+ const kind = message?.source?.kind;
820
+ return typeof kind !== 'string' || !suppressedSources.has(kind);
821
+ });
822
+ return kept.length === messages.length ? messages : kept;
823
+ }
824
+ /** 首轮输出预算:未晋升 → 封顶;已晋升 → 若仍带着封顶值则剥离。 */
825
+ export function applyBootstrapBudget(config, promoted, maxTokens) {
826
+ if (!promoted)
827
+ return { ...config, maxTokens };
828
+ if (config?.maxTokens === maxTokens) {
829
+ const { maxTokens: _drop, ...rest } = config;
830
+ return rest;
831
+ }
832
+ return config;
833
+ }
834
+ // ── host 插件 ────────────────────────────────────────────────────────────
835
+ /** 把配置 namespace 注册进宿主 settings 体系(dsh-settings 0.1.0-rc.7+)。
836
+ * 设置页 describe() 只枚举 settings.register 注册过的 namespace;本插件
837
+ * 的卡片读写不经过宿主 settings 文档,注册只为让卡片出现在设置页。
838
+ * options.base 必传当前生效配置快照:宿主 resolve = schema(mergeLayers(base,
839
+ * section)),schema 无默认值时 base 缺失会让 describe() 的 value 为
840
+ * undefined,而设置页 wire 校验要求 value 非空(invalid_type: nonoptional),
841
+ * 一项失败会拖垮整个设置页。本插件的 any() schema 完全依赖 base。
842
+ * fail-safe(schema 库/服务缺失静默跳过)+ 幂等(重复注册忽略)。
843
+ * 导出以便测试注入 Schema stub。 */
844
+ export function registerSettingsNamespace(ctx, ns, schemaLib, buildSchema, options) {
845
+ if (schemaLib === null || schemaLib === undefined)
846
+ return false;
847
+ if (ctx === null || typeof ctx !== 'object' || typeof ctx.inject !== 'function')
848
+ return false;
849
+ try {
850
+ ctx.inject(['settings'], (settingsCtx) => {
851
+ try {
852
+ settingsCtx.settings.register(ns, buildSchema(schemaLib), options);
853
+ }
854
+ catch (error) {
855
+ const message = String(error?.message ?? String(error));
856
+ if (!message.includes('already registered'))
857
+ throw error;
858
+ }
859
+ });
860
+ return true;
861
+ }
862
+ catch (error) {
863
+ try {
864
+ ctx.logger?.warn?.(`adaptive-perf: settings namespace registration skipped: ${error?.message ?? String(error)}`);
865
+ }
866
+ catch { }
867
+ return false;
868
+ }
869
+ }
870
+ export async function apply(ctx, config, options = {}) {
871
+ // fail-safe:初始化失败只记录,绝不让本插件拖垮 harness(host 层挂载时
872
+ // entry 异常会导致进程启动失败)。
873
+ try {
874
+ const systemPrompt = ctx.get('systemPrompt');
875
+ const tools = ctx.get('tools');
876
+ if (systemPrompt === void 0 || tools === void 0) {
877
+ ctx.logger?.warn?.('adaptive-perf: systemPrompt/tools service unavailable; plugin inactive');
878
+ return;
879
+ }
880
+ const agentPresets = ctx.get('agentPresets');
881
+ if (agentPresets === void 0) {
882
+ ctx.logger?.warn?.('adaptive-perf: agentPresets service unavailable (no agent presets composed); plugin inactive');
883
+ return;
884
+ }
885
+ const agentsService = ctx.get('agents');
886
+ const patchConfig = config !== null && typeof config === 'object' && !Array.isArray(config) ? config : {};
887
+ /** 当前生效配置(热更新;后续 store 创建后以 config.json 权威合并结果覆盖)。 */
888
+ let cfg = normalizeConfig(patchConfig);
889
+ /** 真实 Minimal 工具对模块(0.5.0)。加载失败 = null = 降级旧行为。
890
+ * options.realPairModules 仅供测试注入。 */
891
+ let realPairModules = options.realPairModules === void 0
892
+ ? (cfg.bootstrap.enabled && cfg.bootstrap.realPair ? await loadRealPairModules() : null)
893
+ : options.realPairModules;
894
+ /** 是否已尝试加载过真实工具对模块(避免配置热更新时反复重试)。 */
895
+ let realPairModulesTried = options.realPairModules !== void 0 || (cfg.bootstrap.enabled && cfg.bootstrap.realPair);
896
+ if (cfg.bootstrap.enabled && cfg.bootstrap.realPair && realPairModules === null) {
897
+ try {
898
+ ctx.logger?.warn?.('adaptive-perf: real Minimal tool pair modules unavailable (optional @deepseek-ai deps missing?); falling back to catalog-only bootstrap');
899
+ }
900
+ catch { }
901
+ }
902
+ /**
903
+ * 配置热更新把 realPair 从关闭切到开启时补加载官方模块(初始未启用时
904
+ * 不加载)。加载成功后对已接管会话补挂。
905
+ */
906
+ function ensureRealPairModules() {
907
+ if (realPairModulesTried || cfg.bootstrap.enabled === false || cfg.bootstrap.realPair === false)
908
+ return;
909
+ realPairModulesTried = true;
910
+ loadRealPairModules().then((mods) => {
911
+ if (mods === null)
912
+ return;
913
+ realPairModules = mods;
914
+ info('real Minimal tool pair modules loaded; mounting for live agents');
915
+ for (const a of agents.values()) {
916
+ syncRealPair(a);
917
+ applyMinimalPrompt(a);
918
+ syncBootstrap(a);
919
+ }
920
+ }).catch(() => { });
921
+ }
922
+ /** agentId -> 会话自适应状态。 */
923
+ const agents = new Map();
924
+ const warn = (message) => { try {
925
+ ctx.logger?.warn?.(`adaptive-perf: ${message}`);
926
+ }
927
+ catch { } };
928
+ const info = (message) => { try {
929
+ ctx.logger?.info?.(`adaptive-perf: ${message}`);
930
+ }
931
+ catch { } };
932
+ /** 该会话是否为目标 preset。 */
933
+ function isTarget(agent) {
934
+ if (!cfg.enabled)
935
+ return false;
936
+ try {
937
+ const presetId = agentPresets.composedPreset(agent.ctx);
938
+ return presetId !== void 0 && cfg.presets.includes(presetId);
939
+ }
940
+ catch (error) {
941
+ warn(`preset lookup failed for agent ${agent.id}: ${error?.message ?? String(error)}`);
942
+ return false;
943
+ }
944
+ }
945
+ /** 计算某族当前应隐藏的工具名(与该 agent 实际可见目录取交集)。 */
946
+ function familyDeny(a, family) {
947
+ if (!Array.isArray(family.tools))
948
+ return [];
949
+ return family.tools.filter((n) => typeof n === 'string' && a.visibleNames.has(n));
950
+ }
951
+ /** 应用/更新运行时上下文抑制。总开关关闭时一并释放。 */
952
+ function applySuppression(a) {
953
+ const want = cfg.enabled && cfg.suppressRuntimeContext;
954
+ if (want && a.suppressDisposer === null) {
955
+ try {
956
+ a.suppressDisposer = a.agent.ctx.systemPrompt.suppressRuntimeContext();
957
+ info(`agent ${a.agent.id}: runtime context suppressed`);
958
+ }
959
+ catch (error) {
960
+ warn(`suppressRuntimeContext failed for agent ${a.agent.id}: ${error?.message ?? String(error)}`);
961
+ }
962
+ }
963
+ else if (!want && a.suppressDisposer !== null) {
964
+ try {
965
+ a.suppressDisposer();
966
+ }
967
+ catch { }
968
+ a.suppressDisposer = null;
969
+ }
970
+ }
971
+ /** 应用/更新极简提示词层(persona 阴影 + 全局引导段屏蔽 +
972
+ * 真实工具对替换后的 tool 引导段阴影)。 */
973
+ function applyMinimalPrompt(a) {
974
+ for (const disposer of a.promptDisposers) {
975
+ try {
976
+ disposer();
977
+ }
978
+ catch { }
979
+ }
980
+ a.promptDisposers = [];
981
+ if (!cfg.enabled || !cfg.minimalPrompt.enabled)
982
+ return;
983
+ const sp = a.agent.ctx.systemPrompt;
984
+ try {
985
+ if (cfg.minimalPrompt.suppressSections) {
986
+ for (const [name, order] of SECTION_SHADOWS) {
987
+ a.promptDisposers.push(sp.section({ name, order, text: '' }));
988
+ }
989
+ }
990
+ if (a.realPairActive) {
991
+ for (const [name, order] of TOOL_GUIDANCE_SHADOWS) {
992
+ a.promptDisposers.push(sp.section({ name, order, text: '' }));
993
+ }
994
+ }
995
+ const persona = cfg.minimalPrompt.persona.trim();
996
+ if (persona.length > 0) {
997
+ a.promptDisposers.push(sp.section({ name: PERSONA_SECTION_NAME, order: PERSONA_SECTION_ORDER, text: persona }));
998
+ }
999
+ info(`agent ${a.agent.id}: minimal prompt layer active`);
1000
+ }
1001
+ catch (error) {
1002
+ warn(`minimalPrompt failed for agent ${a.agent.id}: ${error?.message ?? String(error)}`);
1003
+ }
1004
+ }
1005
+ /** 应用/更新工具族限制(lean 模式)。总开关关闭、族被禁用、已升级、
1006
+ * 已从配置删除的族一律放行。 */ function applyFamilies(a) {
1007
+ if (!cfg.enabled || !cfg.leanByDefault) {
1008
+ for (const [id, disposer] of a.familyDisposers) {
1009
+ try {
1010
+ disposer();
1011
+ }
1012
+ catch { }
1013
+ a.familyDisposers.delete(id);
1014
+ }
1015
+ return;
1016
+ }
1017
+ // 1) 清理不再需要的限制(族被禁用 / 已升级 / 配置里已不存在)。
1018
+ for (const [id, disposer] of a.familyDisposers) {
1019
+ const family = cfg.families[id];
1020
+ if (family === void 0 || family.enabled === false || a.escalated.has(id)) {
1021
+ try {
1022
+ disposer();
1023
+ }
1024
+ catch { }
1025
+ a.familyDisposers.delete(id);
1026
+ }
1027
+ }
1028
+ // 2) 补齐需要的新限制。
1029
+ for (const [id, family] of Object.entries(cfg.families)) {
1030
+ if (a.familyDisposers.has(id))
1031
+ continue;
1032
+ if (family.enabled === false || a.escalated.has(id))
1033
+ continue;
1034
+ const deny = familyDeny(a, family);
1035
+ if (deny.length === 0)
1036
+ continue;
1037
+ try {
1038
+ const disposer = a.agent.ctx.tools.restrict({ deny });
1039
+ a.familyDisposers.set(id, disposer);
1040
+ }
1041
+ catch (error) {
1042
+ warn(`restrict failed for agent ${a.agent.id} family "${id}": ${error?.message ?? String(error)}`);
1043
+ }
1044
+ }
1045
+ }
1046
+ /** 当前隐藏的工具名(活跃限制族的 deny 并集,供失败信号匹配)。 */
1047
+ function hiddenNames(a) {
1048
+ const out = new Set();
1049
+ for (const [id, family] of Object.entries(cfg.families)) {
1050
+ if (!a.familyDisposers.has(id))
1051
+ continue;
1052
+ for (const n of familyDeny(a, family))
1053
+ out.add(n);
1054
+ }
1055
+ return out;
1056
+ }
1057
+ /** 放行一个工具族(会话内单调:只升不降)。 */
1058
+ function escalate(a, familyId, trigger) {
1059
+ if (a.escalated.has(familyId))
1060
+ return;
1061
+ a.escalated.add(familyId);
1062
+ const disposer = a.familyDisposers.get(familyId);
1063
+ if (disposer !== void 0) {
1064
+ try {
1065
+ disposer();
1066
+ }
1067
+ catch { }
1068
+ a.familyDisposers.delete(familyId);
1069
+ }
1070
+ info(`agent ${a.agent.id}: escalated family "${familyId}" (${trigger})`);
1071
+ }
1072
+ /** 从持久事件恢复 dev_tool_search 已解锁的工具(resume-safe)。 */
1073
+ function loadUnlockedFromEvents(a) {
1074
+ const events = a.agent.session && Array.isArray(a.agent.session.events) ? a.agent.session.events : [];
1075
+ for (const event of events) {
1076
+ if (event === null || typeof event !== 'object' || event.type !== 'tool/call')
1077
+ continue;
1078
+ if (event.data === null || typeof event.data !== 'object' || event.data.name !== 'dev_tool_search')
1079
+ continue;
1080
+ let args = event.data.arguments;
1081
+ if (typeof args === 'string') {
1082
+ try {
1083
+ args = JSON.parse(args);
1084
+ }
1085
+ catch {
1086
+ continue;
1087
+ }
1088
+ }
1089
+ if (args === null || typeof args !== 'object' || Array.isArray(args))
1090
+ continue;
1091
+ if (Array.isArray(args.toolNames)) {
1092
+ for (const name of args.toolNames) {
1093
+ if (typeof name === 'string' && name.length > 0)
1094
+ a.unlocked.add(name);
1095
+ }
1096
+ }
1097
+ }
1098
+ }
1099
+ /**
1100
+ * 挂载/卸载真实 Minimal 工具对(0.5.0):把官方 minimal preset 同款插件
1101
+ * (持久 PTY bash + str_replace_editor 及其依赖的 terminals/本地 fs)
1102
+ * 挂进 agent 作用域。scoped registration 按名阴影 standard 的 sandboxed
1103
+ * bash,且自身层注册不受 restrict 影响(view() 对 own layer 豁免)——
1104
+ * 首轮目录因此是"真实工具对 + 被 deny 的其他继承工具"。
1105
+ * 依赖模块缺失(realPairModules === null)或 Windows(PTY 仅 linux/darwin)
1106
+ * 时静默降级:不挂载,退回旧行为(仅收窄目录)。
1107
+ */
1108
+ function syncRealPair(a) {
1109
+ for (const dispose of a.realPairDisposers) {
1110
+ try {
1111
+ dispose();
1112
+ }
1113
+ catch { }
1114
+ }
1115
+ a.realPairDisposers = [];
1116
+ const active = cfg.enabled && cfg.bootstrap.enabled && cfg.bootstrap.realPair
1117
+ && realPairModules !== null && process.platform !== 'win32';
1118
+ if (active) {
1119
+ const mounts = realPairMounts(realPairModules, a.agent.session?.header?.cwd);
1120
+ a.realPairDisposers = mountRealPair(a.agent, mounts, warn);
1121
+ if (a.realPairDisposers.length > 0) {
1122
+ info(`agent ${a.agent.id}: real Minimal tool pair mounted (${mounts.length} plugins)`);
1123
+ }
1124
+ }
1125
+ a.realPairActive = a.realPairDisposers.length > 0;
1126
+ }
1127
+ /**
1128
+ * 给目标 agent 注册 on-demand 发现工具(dsh-anchored-standard 的 resident
1129
+ * discovery pattern):晋升后常驻 bootstrap.discoveryTools 列出的工具——
1130
+ * dev_tool_search(搜索完整目录并按名解锁,解锁结果下一请求生效,写入
1131
+ * a.unlocked 后 syncBootstrap 重算 deny 集)+ skill_search / skill_load
1132
+ * (常驻上下文抑制的替代品:按需发现/加载技能)。
1133
+ * 已存在的同名工具(preset 自带)不重复注册。
1134
+ */
1135
+ function syncDiscoveryTools(a, enabled) {
1136
+ const want = enabled ? cfg.bootstrap.discoveryTools : [];
1137
+ for (const [name, disposer] of a.toolDisposers) {
1138
+ if (!want.includes(name)) {
1139
+ try {
1140
+ disposer();
1141
+ }
1142
+ catch { }
1143
+ a.toolDisposers.delete(name);
1144
+ }
1145
+ }
1146
+ if (!enabled)
1147
+ return;
1148
+ const scopedTools = a.agent.ctx && a.agent.ctx.tools;
1149
+ if (scopedTools === void 0 || typeof scopedTools.register !== 'function')
1150
+ return;
1151
+ for (const name of want) {
1152
+ if (a.toolDisposers.has(name))
1153
+ continue;
1154
+ if (a.visibleNames.has(name))
1155
+ continue; // preset/宿主已提供同名工具
1156
+ const def = discoveryToolDef(a, name);
1157
+ if (def === null)
1158
+ continue;
1159
+ try {
1160
+ const disposer = scopedTools.register(def);
1161
+ if (typeof disposer === 'function')
1162
+ a.toolDisposers.set(name, disposer);
1163
+ }
1164
+ catch (error) {
1165
+ warn(`register ${name} failed for agent ${a.agent.id}: ${error?.message ?? String(error)}`);
1166
+ }
1167
+ }
1168
+ }
1169
+ /** 构造一个发现工具定义;未知名称返回 null。 */
1170
+ function discoveryToolDef(a, name) {
1171
+ if (name === 'dev_tool_search') {
1172
+ return createDevToolSearch({
1173
+ schemasOf: (exec) => {
1174
+ const agent = exec !== null && typeof exec === 'object' ? exec.agent : void 0;
1175
+ return agent === void 0 ? [] : tools.schemas(agent);
1176
+ },
1177
+ onUnlock: async (names, exec) => {
1178
+ const agent = exec !== null && typeof exec === 'object' ? exec.agent : void 0;
1179
+ const state = agent === void 0 ? void 0 : agents.get(agent.id);
1180
+ if (state === void 0)
1181
+ return;
1182
+ for (const name of names)
1183
+ state.unlocked.add(name);
1184
+ syncBootstrap(state);
1185
+ },
1186
+ catalogHint: 'This session starts with a minimal resident set: bash, str_replace_editor, skill_search, skill_load. Everything else is unlocked on demand through this tool.',
1187
+ });
1188
+ }
1189
+ if (name === 'skill_search') {
1190
+ return createSkillSearch({ skillsOf: () => ctx.get('skills') });
1191
+ }
1192
+ if (name === 'skill_load') {
1193
+ return createSkillLoad({ skillsOf: () => ctx.get('skills') });
1194
+ }
1195
+ return null;
1196
+ }
1197
+ /** 完整接管一个 agent(幂等)。 */
1198
+ function handleAgent(agent) {
1199
+ if (agents.has(agent.id))
1200
+ return;
1201
+ if (!isTarget(agent))
1202
+ return;
1203
+ const a = {
1204
+ agent,
1205
+ suppressDisposer: null,
1206
+ promptDisposers: [],
1207
+ familyDisposers: new Map(),
1208
+ bootstrapDisposer: null,
1209
+ bootstrapKey: null,
1210
+ escalated: new Set(),
1211
+ visibleNames: new Set(),
1212
+ unlocked: new Set(),
1213
+ toolDisposers: new Map(),
1214
+ realPairDisposers: [],
1215
+ realPairActive: false,
1216
+ };
1217
+ // 记录当前可见目录(限制前);仅记录真实存在的工具,后续 restrict 与
1218
+ // 实际目录取交集,preset 升级改名/删除工具不会让本插件崩溃。
1219
+ try {
1220
+ for (const schema of tools.schemas(agent)) {
1221
+ if (schema !== null && typeof schema === 'object' && typeof schema.name === 'string') {
1222
+ a.visibleNames.add(schema.name);
1223
+ }
1224
+ }
1225
+ }
1226
+ catch (error) {
1227
+ warn(`schemas lookup failed for agent ${agent.id}: ${error?.message ?? String(error)}`);
1228
+ }
1229
+ loadUnlockedFromEvents(a);
1230
+ agents.set(agent.id, a);
1231
+ applySuppression(a);
1232
+ syncRealPair(a);
1233
+ applyMinimalPrompt(a);
1234
+ applyFamilies(a);
1235
+ syncBootstrap(a);
1236
+ info(`agent ${agent.id}: adaptive-perf active (preset ${String(agentPresets.composedPreset(agent.ctx))})`);
1237
+ }
1238
+ /** 释放一个 agent 的全部副作用。 */
1239
+ function releaseAgent(agentId) {
1240
+ const a = agents.get(agentId);
1241
+ agents.delete(agentId);
1242
+ bootstrapState.delete(agentId);
1243
+ if (a === void 0)
1244
+ return;
1245
+ if (a.suppressDisposer !== null) {
1246
+ try {
1247
+ a.suppressDisposer();
1248
+ }
1249
+ catch { }
1250
+ }
1251
+ for (const disposer of a.promptDisposers) {
1252
+ try {
1253
+ disposer();
1254
+ }
1255
+ catch { }
1256
+ }
1257
+ a.promptDisposers = [];
1258
+ for (const dispose of a.realPairDisposers) {
1259
+ try {
1260
+ dispose();
1261
+ }
1262
+ catch { }
1263
+ }
1264
+ a.realPairDisposers = [];
1265
+ if (a.bootstrapDisposer !== null) {
1266
+ try {
1267
+ a.bootstrapDisposer();
1268
+ }
1269
+ catch { }
1270
+ }
1271
+ for (const disposer of a.toolDisposers.values()) {
1272
+ try {
1273
+ disposer();
1274
+ }
1275
+ catch { }
1276
+ }
1277
+ a.toolDisposers.clear();
1278
+ for (const disposer of a.familyDisposers.values()) {
1279
+ try {
1280
+ disposer();
1281
+ }
1282
+ catch { }
1283
+ }
1284
+ }
1285
+ // ── 事件监听(注册在 host 根作用域,与 dsh-agent-presets 同款用法)──
1286
+ ctx.on('agent/created', ({ agent }) => {
1287
+ handleAgent(agent);
1288
+ });
1289
+ ctx.on('agent/disposed', ({ agent }) => {
1290
+ releaseAgent(agent.id);
1291
+ });
1292
+ // 关键词信号:用户消息进入收件箱(早于回合处理与请求装配)。
1293
+ // 监听器无条件注册,事件时按实时 cfg 判断,热更新开关即时生效。
1294
+ ctx.on('agent/inbox/inserted', ({ agent, message }) => {
1295
+ if (!cfg.enabled || !cfg.escalateOnKeyword)
1296
+ return;
1297
+ const a = agents.get(agent.id);
1298
+ if (a === void 0)
1299
+ return;
1300
+ const text = extractUserText(message);
1301
+ if (text.length === 0)
1302
+ return;
1303
+ for (const [id, family] of Object.entries(cfg.families)) {
1304
+ if (a.escalated.has(id) || family.enabled === false)
1305
+ continue;
1306
+ if (matchKeywords(text, family.keywords))
1307
+ escalate(a, id, 'keyword');
1308
+ }
1309
+ });
1310
+ // 失败信号:PTC 程序调用隐藏工具报错(文本含工具名)时放行对应族。
1311
+ ctx.on('tools/result', (exec, result) => {
1312
+ if (!cfg.enabled || !cfg.escalateOnUnknownTool)
1313
+ return;
1314
+ const agent = exec !== null && typeof exec === 'object' ? exec.agent : void 0;
1315
+ if (agent === void 0)
1316
+ return;
1317
+ const a = agents.get(agent.id);
1318
+ if (a === void 0)
1319
+ return;
1320
+ if (result === null || typeof result !== 'object' || result.isError !== true)
1321
+ return;
1322
+ const text = collectFailureText(result);
1323
+ if (text.length === 0)
1324
+ return;
1325
+ const hidden = hiddenNames(a);
1326
+ if (hidden.size === 0)
1327
+ return;
1328
+ for (const [id, family] of Object.entries(cfg.families)) {
1329
+ if (a.escalated.has(id) || family.enabled === false)
1330
+ continue;
1331
+ for (const n of family.tools) {
1332
+ if (hidden.has(n) && text.includes(n)) {
1333
+ escalate(a, id, 'unknown-tool');
1334
+ break;
1335
+ }
1336
+ }
1337
+ }
1338
+ });
1339
+ // ── 首轮锚定(bootstrap,参照 dsh-anchored-standard 的实测结论)─────
1340
+ // 阶段状态:sessionId -> { promoted, promoteEvents }。冷会话在
1341
+ // handleAgent 时全量扫描持久日志(resume 安全),此后 session/event 增量
1342
+ // 更新。晋升是持久信号(compaction 不重置)。子代理(delegationDepth > 0)
1343
+ // 恒为已晋升。所有 waterfall 用 prepend 注册,保证本插件是"最外层"
1344
+ // 变换(剥离是最后一道)。
1345
+ const bootstrapState = new Map();
1346
+ let bootstrapWarned = false;
1347
+ const warnBootstrapOnce = (message) => {
1348
+ if (bootstrapWarned)
1349
+ return;
1350
+ bootstrapWarned = true;
1351
+ warn(message);
1352
+ };
1353
+ function bootstrapPhaseOf(agent) {
1354
+ const session = agent !== null && typeof agent === 'object' ? agent.session : void 0;
1355
+ if (session === void 0 || typeof session.id !== 'string')
1356
+ return { promoted: true };
1357
+ // 子代理首轮即可用工具(与参考实现一致)。
1358
+ if ((session.header?.delegationDepth ?? 0) > 0)
1359
+ return { promoted: true };
1360
+ let entry = bootstrapState.get(session.id);
1361
+ if (entry === void 0) {
1362
+ entry = {
1363
+ ...scanPhase(session.events, PROMOTE_EVENTS[cfg.bootstrap.promoteOn]),
1364
+ promoteOn: cfg.bootstrap.promoteOn,
1365
+ };
1366
+ bootstrapState.set(session.id, entry);
1367
+ }
1368
+ return entry;
1369
+ }
1370
+ /** bootstrap 是否对该会话生效(总开关 + 目标 preset + 无会话时放行)。 */
1371
+ function bootstrapActiveFor(agent) {
1372
+ if (!cfg.enabled || !cfg.bootstrap.enabled)
1373
+ return false;
1374
+ if (agent === void 0)
1375
+ return true;
1376
+ return isTarget(agent);
1377
+ }
1378
+ /**
1379
+ * bootstrap 阶段的保留工具集(0.7.0:首轮锚定、晋升后 resident 目录):
1380
+ * - 未晋升:bootstrap 工具对 + PTC 的直接调用工具(run_code);
1381
+ * - 已晋升:bootstrap 工具对 + 常驻发现工具(dev_tool_search /
1382
+ * skill_search / skill_load)+ dev_tool_search 已解锁工具
1383
+ * (dsh-anchored-standard 的 resident catalog:晋升时一次性倒出
1384
+ * 完整 Standard 目录会把轨迹拉回 standard-like——晋升后回退问题,
1385
+ * 因此重型工具保持一次 dev_tool_search 即可取用)。
1386
+ *
1387
+ * 注意:不能靠过滤 system-prompt/assemble 的 assembly.tools 来实现——
1388
+ * PTC 模式下 assembly.tools 只有 [run_code],Minimal 工具对不在其中,
1389
+ * 过滤会触发降级(实测首轮模型仍看到 15 个工具)。正确做法是
1390
+ * tools.restrict(与族限制同一机制):它同时驱动 API 目录和 PTC 的
1391
+ * SDK 参考段,且天然保留 run_code(不在 deny 里)。
1392
+ */
1393
+ function bootstrapKeepSet(a) {
1394
+ if (!cfg.enabled || !cfg.bootstrap.enabled)
1395
+ return null;
1396
+ const session = a.agent.session;
1397
+ if (session === void 0)
1398
+ return null; // 无会话信息时保持既有行为(测试/未知场景)
1399
+ const phase = bootstrapPhaseOf(a.agent);
1400
+ const keep = new Set(cfg.bootstrap.tools);
1401
+ if (a.visibleNames.has('run_code'))
1402
+ keep.add('run_code');
1403
+ if (phase.promoted) {
1404
+ for (const name of cfg.bootstrap.discoveryTools)
1405
+ keep.add(name);
1406
+ for (const name of a.unlocked)
1407
+ keep.add(name);
1408
+ }
1409
+ return keep;
1410
+ }
1411
+ /** 按当前阶段同步 bootstrap 的临时 restrict(幂等;仅阶段/配置变化时重挂)。 */
1412
+ function syncBootstrap(a) {
1413
+ const phase = bootstrapPhaseOf(a.agent);
1414
+ const keep = bootstrapKeepSet(a);
1415
+ // discovery 工具只在晋升后的 resident 阶段注册;bootstrap 阶段隐藏。
1416
+ syncDiscoveryTools(a, keep !== null && phase.promoted);
1417
+ const key = keep === null ? null : [...keep].sort().join(',');
1418
+ if (key === a.bootstrapKey)
1419
+ return;
1420
+ if (a.bootstrapDisposer !== null) {
1421
+ try {
1422
+ a.bootstrapDisposer();
1423
+ }
1424
+ catch { }
1425
+ a.bootstrapDisposer = null;
1426
+ a.bootstrapKey = null;
1427
+ }
1428
+ if (keep === null)
1429
+ return;
1430
+ const deny = [...a.visibleNames].filter((name) => !keep.has(name));
1431
+ if (deny.length === 0)
1432
+ return;
1433
+ try {
1434
+ a.bootstrapDisposer = a.agent.ctx.tools.restrict({ deny });
1435
+ a.bootstrapKey = key;
1436
+ info(`agent ${a.agent.id}: bootstrap restrict deny=${deny.length} keep=[${[...keep].join(',')}]`);
1437
+ }
1438
+ catch (error) {
1439
+ warn(`bootstrap restrict failed for agent ${a.agent.id}: ${String(error?.message ?? String(error))}`);
1440
+ }
1441
+ }
1442
+ // 持久事件增量喂入:晋升信号 / compaction 纪元;阶段变化时同步 bootstrap 限制。
1443
+ ctx.on('session/event', (session, event) => {
1444
+ if (session === null || typeof session !== 'object' || typeof session.id !== 'string')
1445
+ return;
1446
+ const before = bootstrapState.get(session.id);
1447
+ observePhase(bootstrapState, session.id, event);
1448
+ const a = agents.get(session.id);
1449
+ if (a !== void 0) {
1450
+ const after = bootstrapState.get(session.id);
1451
+ if (before === void 0 || after === void 0 || before.promoted !== after.promoted) {
1452
+ syncBootstrap(a);
1453
+ }
1454
+ }
1455
+ });
1456
+ // 上下文剥离(首轮锚定的注入部分)。prepend + 根作用域注册保证是
1457
+ // 最后一道变换(后注册的注入者无法再补回)。
1458
+ // 剥离条件:bootstrap 未晋升(首轮剥离)或常驻抑制开启
1459
+ // (suppressInjectedContext,0.7.0 默认开启:晋升后注入保持剥离,
1460
+ // 由常驻发现工具承担功能可见性)。
1461
+ ctx.on('agent/pre-step', async ({ agent }, next) => {
1462
+ const decision = await next();
1463
+ if (decision === null || typeof decision !== 'object' || decision.kind === 'reject')
1464
+ return decision;
1465
+ try {
1466
+ if (!cfg.enabled || !isTarget(agent))
1467
+ return decision;
1468
+ const phase = bootstrapPhaseOf(agent);
1469
+ const suppressed = new Set(cfg.bootstrap.suppressedContextSources);
1470
+ if (suppressed.size === 0)
1471
+ return decision;
1472
+ const stripActive = (cfg.bootstrap.enabled && !phase.promoted) || cfg.suppressInjectedContext;
1473
+ if (!stripActive || !Array.isArray(decision.messages))
1474
+ return decision;
1475
+ const kept = stripSuppressedMessages(decision.messages, suppressed);
1476
+ return kept === decision.messages ? decision : { ...decision, messages: kept };
1477
+ }
1478
+ catch (error) {
1479
+ // 过滤失败绝不吞掉用户的上下文:原样放行。
1480
+ warnBootstrapOnce(`bootstrap context filter failed, keeping injected context: ${String(error?.message ?? String(error))}`);
1481
+ return decision;
1482
+ }
1483
+ }, { prepend: true });
1484
+ // 可选:请求 #1 输出预算封顶(晋升后剥离,避免封顶沿 header 种子延续)。
1485
+ if (cfg.bootstrap.maxTokens > 0) {
1486
+ ctx.on('agent/request', async ({ agent }, next) => {
1487
+ const resolved = await next();
1488
+ try {
1489
+ if (!bootstrapActiveFor(agent))
1490
+ return resolved;
1491
+ const phase = bootstrapPhaseOf(agent);
1492
+ return applyBootstrapBudget(resolved, phase.promoted, cfg.bootstrap.maxTokens);
1493
+ }
1494
+ catch (error) {
1495
+ warnBootstrapOnce(`bootstrap budget filter failed: ${String(error?.message ?? String(error))}`);
1496
+ return resolved;
1497
+ }
1498
+ }, { prepend: true });
1499
+ }
1500
+ // 已运行会话补挂(插件热重载/重装时)。
1501
+ if (agentsService !== void 0 && typeof agentsService.list === 'function') {
1502
+ try {
1503
+ for (const agent of agentsService.list())
1504
+ handleAgent(agent);
1505
+ }
1506
+ catch (error) {
1507
+ warn(`existing agent sweep failed: ${error?.message ?? String(error)}`);
1508
+ }
1509
+ }
1510
+ // 配置存储:patch config 为低优先级,config.json(设置页 UI)权威。
1511
+ // onUpdate 把 UI 保存的改动热更新进 cfg,并对所有已接管会话重算。
1512
+ const store = createConfigStore({
1513
+ name: 'adaptive-perf',
1514
+ defaults: DEFAULT_CONFIG,
1515
+ patchConfig,
1516
+ validate: validateConfig,
1517
+ warn,
1518
+ onUpdate: (merged) => {
1519
+ cfg = normalizeConfig({ ...patchConfig, ...merged });
1520
+ info('config hot-updated; recomputing restrictions for live agents');
1521
+ // realPair 从关闭切到开启:补加载官方模块(首次尝试失败不反复重试)。
1522
+ ensureRealPairModules();
1523
+ // 补挂此前创建的会话(例如插件从 disabled 切换为 enabled,或新增了
1524
+ // 目标 preset):新符合条件的 agent 立即接管(handleAgent 已应用全部
1525
+ // 层,下面的重算只针对此前已接管的 agent,避免同一 onUpdate 内重复)。
1526
+ const existing = new Set(agents.keys());
1527
+ if (agentsService !== void 0 && typeof agentsService.list === 'function') {
1528
+ try {
1529
+ for (const agent of agentsService.list())
1530
+ handleAgent(agent);
1531
+ }
1532
+ catch (error) {
1533
+ warn(`config-update agent sweep failed: ${error?.message ?? String(error)}`);
1534
+ }
1535
+ }
1536
+ for (const agentId of existing) {
1537
+ const a = agents.get(agentId);
1538
+ if (a === void 0)
1539
+ continue;
1540
+ applySuppression(a);
1541
+ syncRealPair(a);
1542
+ applyMinimalPrompt(a);
1543
+ applyFamilies(a);
1544
+ syncBootstrap(a);
1545
+ }
1546
+ },
1547
+ });
1548
+ cfg = normalizeConfig(store.effective());
1549
+ // 远程配置服务(设置页 UI 读写;typert 不可用时跳过)
1550
+ if (PluginConfigGateway !== null) {
1551
+ ctx.plugin(PluginConfigGateway, { store, serviceKey: 'adaptivePerfConfig' });
1552
+ }
1553
+ // 注册进宿主 settings 体系(可见性):设置页用 settings.describe() 枚举
1554
+ // registrations,未注册的 namespace 即使卡片带正确的 key 也不渲染。
1555
+ // 卡片的实际读写仍走上面的 config gateway(config.json 权威、热更新)。
1556
+ // 配置为多层嵌套结构(families/bootstrap/minimalPrompt…),schema 用 any
1557
+ // 透传——describe 元数据只服务于可见性,卡片不读取它。any() 无默认值,
1558
+ // 必须传 base(当前生效配置快照),否则 describe() 的 value 为 undefined,
1559
+ // 设置页 wire 校验(nonoptional)会整体失败。
1560
+ registerSettingsNamespace(ctx, 'adaptivePerfConfig', Schema, (z) => z.any(), { base: cfg });
1561
+ // 卸载清理:释放全部会话副作用与监听。
1562
+ ctx.effect(() => () => {
1563
+ for (const agentId of [...agents.keys()])
1564
+ releaseAgent(agentId);
1565
+ });
1566
+ }
1567
+ catch (error) {
1568
+ try {
1569
+ ctx.logger?.error?.(`adaptive-perf: init failed (harness continues without adaptive performance): ${error?.message ?? String(error)}`);
1570
+ }
1571
+ catch { }
1572
+ }
1573
+ }
1574
+ //# sourceMappingURL=index.js.map