dsh-lean-router 2.1.0 → 2.2.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.
@@ -6,14 +6,16 @@
6
6
  // - D:\Agent Workspace\.scratch\upstream\flash-presets\presets\flash-lean-ptc-v3-balance.patch.yml
7
7
  // L13-18:balance 3 条规则全文
8
8
  // 本包增补(批准计划 .scratch/dsh-lean-router/plan.md L45/L107,62 问定案):
9
- // - 3 软门:澄清 → 计划 → 交付自检(三晋级条件,轻量、每段只停一次)
10
- // - 自检题钩子:勤勉自检(每 ~10 轮,运行时钩子由票 05 实现,此处为文本钩子)
11
- // 与「合上 AI 也能做」合卷自检(可配关,config 由票 05/master 接)
9
+ // - 软门:澄清 → 计划(交付门由规则 4 覆盖,不再单列)
10
+ // - 自检题钩子:只保留「合上 AI 也能做」合卷自检;勤勉自检并入规则 1
12
11
  // - 两个 suffix 末行各留一行拼接占位:路由分类指令由票 05 拼接(t5 交付 ROUTER_PROMPT
13
12
  // 常量,master 集成时替换占位行;本文件不写任何路由内容)
14
- // 适配说明(与上游的唯一实质差异):
13
+ // 适配说明(与上游的实质差异):
15
14
  // - 规则 7 删去 "run_code is the only tool this surface exposes"(flash 的 PTC-only 工具面
16
15
  // 口径);本包工具面为票 04 的 native+code_run,折叠逻辑原样保留。
16
+ // - no-op 审查(2026-11-29):删去宿主已注入的 "Answer in the user's language"、
17
+ // 与规则 4 重复的 DELIVER 软门、与规则 1 重叠的 Diligence 钩子,并压缩各条措辞;
18
+ // 每条约束的判据保留,4581 → 约 3.4k 字符。
17
19
  // 零依赖数据模块:纯 node / 任何宿主环境均可直接动态 import,不崩溃。
18
20
 
19
21
  /** persona 前缀(照抄上游两档共用的 prefix,flash-lean-ptc-v3.patch.yml L60)。 */
@@ -23,58 +25,53 @@ export const PERSONA_PREFIX = 'You are a coding agent powered by the {{model}} m
23
25
  export const ROUTER_SLOT_COMMENT =
24
26
  '# [ticket-05] 路由分类指令由票 05 拼接(本行为占位:集成时替换为票 05 的 ROUTER_PROMPT 常量)';
25
27
 
26
- /** lean 档 3 软门(澄清/计划/交付三晋级条件;plan.md L107 的术语口径)。 */
28
+ /** lean 档 2 软门(澄清/计划两晋级条件;交付门已由规则 4 覆盖,不再重复)。 */
27
29
  export const LEAN_SOFT_GATES = [
28
30
  'CLARIFY: if goal, scope, or acceptance is ambiguous in a way that changes the result, ask one consolidated question round before acting; when a cheap read/probe settles it, probe instead of asking.',
29
- 'PLAN: work touching more than one file or more than ~8 steps starts from a numbered plan with a check per step; single-file small changes skip this gate.',
30
- 'DELIVER: run ONE consolidated acceptance pass over every stated criterion, quote measured numbers, name what was not verified, then stop (rule 4 is this gate\'s detail).',
31
+ 'PLAN: work touching more than one file or more than ~8 steps starts with a numbered plan with a check per step; single-file small changes skip this gate.',
31
32
  ];
32
33
 
33
- /** lean 档自检题钩子(勤勉自检 + 合卷自检;只自查,失败才出声)。 */
34
+ /** lean 档自检题钩子(合卷自检;勤勉自检并入规则 1 的停止重规划)。 */
34
35
  export const LEAN_SELF_CHECK_HOOKS = [
35
- 'Diligence (~every 10 turns): what changed since the last check, and is this still the shortest path to done? If not, re-plan; do not repeat the loop.',
36
36
  'Close-the-book: could I redo the last step with the AI closed - do I actually know this fact, command, or path, or would I have to look it up again? If look-up, fetch it from the source of truth now instead of trusting recall.',
37
37
  ];
38
38
 
39
- /** lean 档 suffix 全文:13 条硬规则(上游原文,规则 7 微调见头部说明)+ 3 软门 + 自检题钩子 + 拼接占位。 */
39
+ /** lean 档 suffix 全文:13 条硬规则(上游原文,规则 7 微调见头部说明)+ 2 软门 + 自检钩 + 拼接占位。 */
40
40
  export const LEAN_PERSONA_SUFFIX = [
41
41
  'LEAN OPERATING RULES (hard constraints; they override habit and tool default wording):',
42
42
  '',
43
43
  'BUDGET FIRST',
44
- '1. Turn budget, not step budget. Target <=20 turns; turns are the measured cost (folding many calls',
45
- ' into one turn is cheap, thrashing across turns is expensive). If a task passes 3x the expected',
46
- ' turns (~60), stop and re-plan instead of repeating the same loop.',
47
- '2. Deliberate briefly. Do not enumerate an exhaustive design before acting: one short',
48
- ' deliberation, then run one cheap probe/command to learn the facts. Acting beats more planning.',
44
+ '1. Turn budget, not step budget. Target <=20 turns; folding calls into one turn is cheap, thrashing',
45
+ ' across turns is not. Past 3x the expected turns (~60), stop and re-plan instead of looping.',
46
+ ' Re-check roughly every 10 turns that this is still the shortest path; if it is not, re-plan.',
47
+ '2. Deliberate briefly. One short deliberation, then one cheap probe/command to learn the facts;',
48
+ ' do not enumerate an exhaustive design before acting.',
49
49
  '3. Input/answer-type tasks (submit a file or an answer): produce the SMALLEST artifact that',
50
50
  ' satisfies the stated constraints first; refine only while you are under the turn budget.',
51
- '4. Gate before delivery, not after. If the task states hidden tests, a judge, or hard limits',
52
- ' (time/memory/output), run ONE consolidated acceptance pass over every stated criterion at once (all',
53
- ' samples, edge cases, largest legal scale) and quote the measured numbers; measure hard limits with',
54
- ' the command the judge would use (/usr/bin/time -v, ulimit -v, ...), and treat over-limit as a failure',
55
- ' even when the answer is otherwise correct. Otherwise ONE consolidated check per deliverable is enough:',
56
- ' do not verify claim by claim, do not re-run a check that already passed, and name what you did not',
57
- ' verify. Once the gate passes, stop testing and deliver: do not add extra randomized or stress rounds unless the gate itself failed.',
51
+ '4. Gate before delivery, not after. Run ONE consolidated acceptance pass over every stated',
52
+ ' criterion, quote the measured numbers, and name what you did not verify. Measure hard limits',
53
+ ' with the command the judge would use (/usr/bin/time -v, ulimit -v). Over-limit is a failure even',
54
+ ' when the answer is otherwise correct. Do not verify claim by claim, do not re-run a check that',
55
+ ' already passed, and once the gate passes stop testing and deliver.',
58
56
  '',
59
57
  '5. Tool choice. Inspect files with read/glob/grep; never use the shell to browse a file',
60
- ' (no cat/head/tail/sed -n/find/ls -R); piping a command\'s own output through head is fine.',
61
- '6. Output budget. Batch independent calls into one step. Pipe or redirect long output',
62
- ' (| head -40; redirect to "$env:TEMP/out.log" in PowerShell, %TEMP%\\out.log in cmd, /tmp/out.log on POSIX).',
58
+ ' (no cat/head/tail/sed -n/find/ls -R). Piping a command\'s own output through head is fine.',
59
+ '6. Output budget. Batch independent calls into one step; pipe or redirect long output',
60
+ ' (| head -40; redirect to $env:TEMP/out.log on PowerShell, %TEMP%\\out.log in cmd, /tmp/out.log on POSIX).',
63
61
  ' Never print a dump you could grep.',
64
62
  '7. Programmatic tool mode, adaptively. Fold 3+ independent calls of one logical step into ONE',
65
- ' run_code program; a single-call step may still go through a one-line program so its noise stays',
66
- ' out of context. Measured: folding pays off on multi-file/repo work (up to 8x fewer turns, 2-8x',
67
- ' less wall clock) and is neutral on single-file algorithm tasks - there spend the budget on',
68
- ' reasoning and testing, not on batching.',
69
- '8. Context discipline (biggest measured lever). Read only what is new; rebuild derived',
70
- ' answers from files with grep/scripts instead of re-reading them into context. Keep NOTES',
71
- ' short and factual (<=60 lines).',
72
- '9. Author incrementally: create a file once (skeleton), then extend it with edit. Never',
73
- ' re-emit an unchanged file. After two failed shell patches, switch to the editor.',
63
+ ' run_code program; a single call may still go through a one-line program so its noise stays out',
64
+ ' of context. Measured: pays off on multi-file/repo work (up to 8x fewer turns) and is neutral on',
65
+ ' single-file algorithm tasks - there spend the budget on reasoning and testing, not batching.',
66
+ '8. Context discipline (biggest measured lever). Read only what is new; rebuild derived answers',
67
+ ' from files with grep/scripts instead of re-reading them into context. Keep NOTES short and',
68
+ ' factual (<=60 lines).',
69
+ '9. Author incrementally: create a file once (skeleton), then extend it with edit. Never re-emit an',
70
+ ' unchanged file. After two failed shell patches, switch to the editor.',
74
71
  '',
75
72
  'SAFETY',
76
- '10. Answer in the user\'s language. Honour scope literally (new project => do not read or',
77
- ' copy old-project files). Use subagents only when the user asks or the harness delegates; never spawn them to look busy.',
73
+ '10. Honour scope literally (a new project means do not read or copy old-project files). Use',
74
+ ' subagents only when the user asks or the harness delegates; never spawn them to look busy.',
78
75
  '11. Never put secrets, tokens or private raw material into the session; reference by path.',
79
76
  '',
80
77
  'WHEN BLOCKED',
@@ -84,7 +81,7 @@ export const LEAN_PERSONA_SUFFIX = [
84
81
  ' prefer fewer, larger turns; on a low-latency route more probing is affordable. Never trade',
85
82
  ' correctness for turn count.',
86
83
  '',
87
- 'SOFT GATES (clarify -> plan -> deliver; each is one pause, never a stall)',
84
+ 'SOFT GATES (each is one pause, never a stall)',
88
85
  ...LEAN_SOFT_GATES.map((line) => '- ' + line),
89
86
  '',
90
87
  'SELF-CHECK HOOKS (questions answered to yourself; speak up only when a check fails)',
@@ -0,0 +1,246 @@
1
+ // dsh-lean-router · lib/lean/usage-ledger.js —— 加料件 · live Usage 账本挂载点
2
+ //
3
+ // 背景:lib/token-ledger/live.js 的 createLiveUsageAdapter 已能订阅 session/event、只收
4
+ // 带 usage 的 assistant/message 并按 session/turn/step/seq 去重落账,但此前没有任何地方
5
+ // 调用它,运行时完全不采集。本模块把它挂到宿主 preset:
6
+ // 1. 创建 live adapter(订阅失败由适配器自己 warn 降级,绝不抛);
7
+ // 2. 注册斜杠命令 token-report([session|all]),读账本 + createTokenReport 生成报告;
8
+ // 3. 宿主 dispose 时卸载适配器与订阅,重复卸载幂等。
9
+ // 与 live.js 同口径:所有失败路径只 warn 不抛 —— 账本采集不得破坏宿主。
10
+ // 数据同源:报告字段 = lib/token-ledger/index.js 的 createTokenReport
11
+ // (usage.prompt = input + cacheRead + cacheWrite,五项分项由 normalizeUsage 补零)。
12
+ import { createTokenReport } from '../token-ledger/index.js';
13
+ import { createLiveUsageAdapter } from '../token-ledger/live.js';
14
+
15
+ export const name = 'lean-usage-ledger';
16
+
17
+ const TAG = '[lean-usage-ledger]';
18
+ const COMMAND_NAME = 'token-report';
19
+ const SCOPES = ['session', 'all'];
20
+ // 会话跟踪只服务于 /token-report all,上限与 delivery-gate 的 SESSION_CAP 同量级。
21
+ const SESSION_CAP = 200;
22
+ const EMPTY_HINT = '尚未采集到 usage,可能本会话还没有 assistant/message 事件';
23
+
24
+ function describeError(error) {
25
+ if (error && typeof error.message === 'string') return error.message;
26
+ return String(error);
27
+ }
28
+
29
+ function warn(ctx, message) {
30
+ const logger = ctx && typeof ctx === 'object' ? ctx.logger : undefined;
31
+ if (!logger || typeof logger.warn !== 'function') return;
32
+ try {
33
+ logger.warn(TAG + ' ' + message);
34
+ } catch {
35
+ // A logger must never break usage capture.
36
+ }
37
+ }
38
+
39
+ /**
40
+ * 归一化插件配置:只认 `{ enabled?: boolean }`,缺省开启;显式 false 才关闭。
41
+ * 非对象 / 未知键不抛,按默认值继续(配置错误不该让宿主启动失败)。
42
+ */
43
+ export function resolveConfig(config) {
44
+ const source = config && typeof config === 'object' ? config : {};
45
+ return { enabled: source.enabled !== false };
46
+ }
47
+
48
+ /** 从命令 invocation 里取当前会话 id(host 端 agent.session.id;测试可传裸对象)。 */
49
+ function sessionIdOf(invocation) {
50
+ if (invocation === undefined || invocation === null || typeof invocation !== 'object') return null;
51
+ const agent = invocation.agent;
52
+ const candidates = [
53
+ agent && agent.session && agent.session.id,
54
+ agent && agent.sessionId,
55
+ invocation.session && invocation.session.id,
56
+ invocation.sessionId,
57
+ ];
58
+ for (const candidate of candidates) {
59
+ if (typeof candidate === 'string' && candidate.length > 0) return candidate;
60
+ }
61
+ return null;
62
+ }
63
+
64
+ /**
65
+ * 把 createTokenReport 的结果排成命令文本。
66
+ * 必含:记录条数、prompt 总量(input+cacheRead+cacheWrite)、五项分项、最近一条 turn/step/seq。
67
+ * 没有任何记录时返回 success 文案(尚未采集),不返回空串。
68
+ */
69
+ function formatReport(report, { scope = 'session', sessions = [] } = {}) {
70
+ const entries = Array.isArray(report.entries) ? report.entries : [];
71
+ const usage = report.usage ?? {};
72
+ const n = (value) => (typeof value === 'number' && Number.isFinite(value) ? value : 0);
73
+ const where = scope === 'all'
74
+ ? 'all · ' + sessions.length + ' 个会话'
75
+ : 'session · ' + (sessions.length > 0 ? sessions[0] : '未知会话');
76
+ const head = 'token-report · ' + where + ' · 记录 ' + entries.length + ' 条';
77
+ if (entries.length === 0) return head + '\n' + EMPTY_HINT;
78
+ const last = entries[entries.length - 1];
79
+ return [
80
+ head,
81
+ 'prompt 总量 ' + n(usage.prompt) + '(input ' + n(usage.inputTokens) + ' + cacheRead '
82
+ + n(usage.cacheReadTokens) + ' + cacheWrite ' + n(usage.cacheWriteTokens) + ')',
83
+ '分项:input ' + n(usage.inputTokens) + ' · output ' + n(usage.outputTokens)
84
+ + ' · cacheRead ' + n(usage.cacheReadTokens) + ' · cacheWrite ' + n(usage.cacheWriteTokens)
85
+ + ' · reasoning ' + n(usage.reasoningTokens),
86
+ '最近一条:turn ' + n(last.turn) + ' · step ' + n(last.step) + ' · seq ' + n(last.seq),
87
+ ].join('\n');
88
+ }
89
+
90
+ /**
91
+ * 账本运行时:live adapter + 会话跟踪 + token-report handler + dispose。
92
+ *
93
+ * @param ctx - 插件上下文;只用 `on` 与 `logger`。缺 `on` 时适配器自身降级,本模块不抛。
94
+ * @returns `{ adapter, handler, readRecords, dispose, seenSessions }`。
95
+ */
96
+ export function createUsageLedger(ctx) {
97
+ const adapter = createLiveUsageAdapter(ctx);
98
+ const seenSessions = [];
99
+ const seen = new Set();
100
+ let trackerOff = null;
101
+ let disposed = false;
102
+
103
+ // 跟踪出现过的会话,供 `/token-report all` 汇总;与适配器各用一条订阅,互不共享内部状态。
104
+ if (ctx && typeof ctx.on === 'function') {
105
+ try {
106
+ const off = ctx.on('session/event', (session) => {
107
+ const id = session && typeof session.id === 'string' ? session.id : null;
108
+ if (id === null || id.length === 0 || seen.has(id)) return;
109
+ if (seenSessions.length >= SESSION_CAP) {
110
+ seen.delete(seenSessions.shift());
111
+ }
112
+ seen.add(id);
113
+ seenSessions.push(id);
114
+ });
115
+ if (typeof off === 'function') trackerOff = off;
116
+ } catch (error) {
117
+ warn(ctx, 'could not track sessions for ' + COMMAND_NAME + ': ' + describeError(error));
118
+ }
119
+ }
120
+
121
+ /**
122
+ * 按范围读记录:session = 当前会话(取不到会话时退回已跟踪集合);all = 已跟踪 ∪ 当前。
123
+ * 单会话读失败只 warn 跳过,不让一条坏记录毁掉整份报告。
124
+ */
125
+ function readRecords(invocation, scope) {
126
+ const current = sessionIdOf(invocation);
127
+ const sessions = [];
128
+ const push = (id) => {
129
+ if (typeof id === 'string' && id.length > 0 && !sessions.includes(id)) sessions.push(id);
130
+ };
131
+ if (scope === 'all') {
132
+ for (const id of seenSessions) push(id);
133
+ push(current);
134
+ } else if (current !== null) {
135
+ push(current);
136
+ } else {
137
+ for (const id of seenSessions) push(id);
138
+ }
139
+ const records = [];
140
+ for (const id of sessions) {
141
+ try {
142
+ records.push(...adapter.read(id, 0));
143
+ } catch (error) {
144
+ warn(ctx, 'read failed for session ' + id + ': ' + describeError(error));
145
+ }
146
+ }
147
+ return { records, sessions };
148
+ }
149
+
150
+ /** 命令 handler:返回 `{ kind: 'success'|'error', text }`(与 /band 同形态)。 */
151
+ function handler(invocation) {
152
+ if (disposed) return { kind: 'error', text: '/' + COMMAND_NAME + ' 已随插件卸载' };
153
+ const raw = invocation && typeof invocation.rawInput === 'string'
154
+ ? invocation.rawInput.trim().toLowerCase()
155
+ : '';
156
+ const scope = raw.length === 0 ? 'session' : raw;
157
+ if (!SCOPES.includes(scope)) {
158
+ warn(ctx, 'unknown scope "' + raw + '"; expected session or all');
159
+ return { kind: 'error', text: '/' + COMMAND_NAME + ' 未知范围 "' + raw + '",用法:/' + COMMAND_NAME + ' [session|all]' };
160
+ }
161
+ try {
162
+ const collected = readRecords(invocation, scope);
163
+ const report = createTokenReport({ records: collected.records });
164
+ return { kind: 'success', text: formatReport(report, { scope, sessions: collected.sessions }) };
165
+ } catch (error) {
166
+ warn(ctx, 'report failed: ' + describeError(error));
167
+ return { kind: 'error', text: '/' + COMMAND_NAME + ' 生成报告失败:' + describeError(error) };
168
+ }
169
+ }
170
+
171
+ function dispose() {
172
+ if (disposed) return;
173
+ disposed = true;
174
+ try {
175
+ adapter.dispose();
176
+ } catch (error) {
177
+ warn(ctx, 'adapter dispose failed: ' + describeError(error));
178
+ }
179
+ const off = trackerOff;
180
+ trackerOff = null;
181
+ if (typeof off !== 'function') return;
182
+ try {
183
+ off();
184
+ } catch (error) {
185
+ warn(ctx, 'listener dispose failed: ' + describeError(error));
186
+ }
187
+ }
188
+
189
+ return { adapter, handler, readRecords, dispose, seenSessions };
190
+ }
191
+
192
+ /**
193
+ * 插件入口(形态与 lib/lean/delivery-gate.js 的 apply 一致)。
194
+ *
195
+ * enabled: false 时既不订阅 session/event 也不注册命令;宿主在模块加载阶段不会被猜测性采集。
196
+ */
197
+ export function apply(ctx, config) {
198
+ const resolved = resolveConfig(config);
199
+ if (!resolved.enabled) return;
200
+ const ledger = createUsageLedger(ctx);
201
+ const context = ctx && typeof ctx === 'object' ? ctx : {};
202
+ const commands = context.commands;
203
+
204
+ if (commands && typeof commands.register === 'function') {
205
+ try {
206
+ commands.register({
207
+ name: COMMAND_NAME,
208
+ description: 'Report the live Usage ledger captured from assistant/message events',
209
+ input: { hint: '[session|all]' },
210
+ handler: (invocation) => ledger.handler(invocation),
211
+ });
212
+ } catch (error) {
213
+ warn(context, 'could not register /' + COMMAND_NAME + ': ' + describeError(error));
214
+ }
215
+ } else {
216
+ warn(context, 'ctx.commands is unavailable; /' + COMMAND_NAME + ' not registered');
217
+ }
218
+
219
+ // 宿主卸载:优先走 dispose 事件;订阅不到就靠 ctx.effect/宿主自行回收,绝不让挂载失败。
220
+ if (typeof context.on === 'function') {
221
+ try {
222
+ context.on('dispose', () => {
223
+ ledger.dispose();
224
+ });
225
+ } catch (error) {
226
+ warn(context, 'could not hook dispose: ' + describeError(error));
227
+ }
228
+ } else {
229
+ warn(context, 'ctx.on is unavailable; usage-ledger dispose hook disabled');
230
+ }
231
+ }
232
+
233
+ /** 默认导出(插件行兼容形态,与命名导出同体)。 */
234
+ export default { name, apply };
235
+
236
+ /** 测试与集成内用的内部实现出口(不进公开契约文档)。 */
237
+ export const __internals = {
238
+ resolveConfig,
239
+ sessionIdOf,
240
+ formatReport,
241
+ createUsageLedger,
242
+ COMMAND_NAME,
243
+ EMPTY_HINT,
244
+ SESSION_CAP,
245
+ TAG,
246
+ };
@@ -2,6 +2,7 @@
2
2
  * [vendored @ upstream dsh-codemode 0.3.x main f9758ec1061a9a0af4f1dfefbacc19c5987b11d1]
3
3
  * Source: upstream lib/discovery.js (dsh-codemode 0.3.0, main @ f9758ec).
4
4
  * Vendored for dsh-lean-router ticket-04, file-for-file unchanged; the four meta tools (list/search/describe/debug), their definitions and the registry-public reads are unchanged.
5
+ * Deviation from upstream: this fork returns parameter NAMES (`params`) from search and keeps the full JSON parameter schema on describe only (lazy schema fetch).
5
6
  *
6
7
  * The three discovery tools registered inside the codemode preset scope.
7
8
  *
@@ -34,6 +35,17 @@ const OUTPUT_SCHEMA = { type: 'object', additionalProperties: true };
34
35
  /** Upper bound on rows a single call materializes, so a 300-tool server cannot blow up a program. */
35
36
  const MAX_ROWS = 2000;
36
37
 
38
+ /**
39
+ * Parameter NAMES for one definition, in declaration order, or `undefined` when
40
+ * the schema declares no `properties` at all — the caller then says `noParams`
41
+ * so a free-form argument object is not mistaken for "takes no arguments".
42
+ */
43
+ function parameterNames(parameters) {
44
+ const properties = parameters?.properties;
45
+ if (properties === null || typeof properties !== 'object' || Array.isArray(properties)) return undefined;
46
+ return Object.keys(properties);
47
+ }
48
+
37
49
  /** Render a JSON value as one text block. */
38
50
  function renderJson(value) {
39
51
  const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
@@ -125,7 +137,7 @@ export function createDiscoveryTools(ctx, options, runToolName = DEFAULT_RUN_TOO
125
137
  description:
126
138
  `List every tool this session can call from inside ${runToolName}, including the ones masked out of the `
127
139
  + 'model context (MCP tools, tools contributed by plugins outside this preset). Returns name, truncated '
128
- + 'description, namespace and a hidden flag — no schemas. Use the search tool to obtain parameter schemas.',
140
+ + 'description, namespace and a hidden flag — no schemas. Use the search tool for parameter names, then describe for a full schema.',
129
141
  parameters: {
130
142
  type: 'object',
131
143
  additionalProperties: false,
@@ -158,8 +170,9 @@ export function createDiscoveryTools(ctx, options, runToolName = DEFAULT_RUN_TOO
158
170
  {
159
171
  name: searchName,
160
172
  description:
161
- 'Rank the callable tools against a query and return the best matches WITH their full JSON parameter '
162
- + `schemas. This is the intended first step before calling a tool the model cannot see from inside ${runToolName}.`,
173
+ 'Rank the callable tools against a query and return the best matches with their parameter NAMES, not their '
174
+ + `full JSON schemas; call ${describeName} with a match's name for its complete parameter schema. This is the `
175
+ + `intended first step before calling a tool the model cannot see from inside ${runToolName}.`,
163
176
  parameters: {
164
177
  type: 'object',
165
178
  additionalProperties: false,
@@ -188,14 +201,16 @@ export function createDiscoveryTools(ctx, options, runToolName = DEFAULT_RUN_TOO
188
201
  return {
189
202
  query,
190
203
  count: ranked.length,
191
- tools: ranked.map((row) => ({
192
- name: row.name,
193
- description: truncate(row.description, options.maxDescriptionChars * 2),
194
- namespace: isMaskedName(row.name, options, view) ? namespaceOf(row.name) : 'native',
195
- hidden: isMaskedName(row.name, options, view),
196
- parameters: row.definition.parameters ?? { type: 'object', additionalProperties: true },
197
- output: row.definition.output?.schema,
198
- })),
204
+ tools: ranked.map((row) => {
205
+ const names = parameterNames(row.definition.parameters);
206
+ return {
207
+ name: row.name,
208
+ description: truncate(row.description, options.maxDescriptionChars * 2),
209
+ namespace: isMaskedName(row.name, options, view) ? namespaceOf(row.name) : 'native',
210
+ hidden: isMaskedName(row.name, options, view),
211
+ ...(names === undefined ? { noParams: true } : { params: names }),
212
+ };
213
+ }),
199
214
  };
200
215
  },
201
216
  },
@@ -41,6 +41,76 @@
41
41
  */
42
42
 
43
43
  import { isMaskedName } from './rules.js';
44
+ import { slimContentBlocks } from '../lean/output-slim.js';
45
+
46
+ /**
47
+ * [dsh-lean-router ticket context_output_compactor] Proof that a definition's
48
+ * `finalizeContent` already carries this preset's wrapper.
49
+ *
50
+ * `describe()` runs once per request assembly, on the *same* definition objects
51
+ * the registry stores (`definitions()` hands out `registration.definition`), so
52
+ * the wrapper is installed in place. Without this flag the wrapper would nest
53
+ * once per assembly and compact the already-compacted text.
54
+ */
55
+ export const SLIM_FINALIZER_MARK = Symbol.for('dsh-lean-router.output-slim.finalizer');
56
+
57
+ /**
58
+ * Install the conservative output compactor on one definition's
59
+ * `finalizeContent` hook, in place.
60
+ *
61
+ * WHY THIS HOOK: `finalizeContent` is the last-mile content transform — the
62
+ * pipeline applies its return value to `result.content` only, so the canonical
63
+ * `value` (which a program's sub-call settles to) is never touched. `content` is
64
+ * what the model sees; that is the whole surface this ticket may change.
65
+ *
66
+ * Chaining rules, in order:
67
+ * 1. a tool that already has `finalizeContent` is called first, with the same
68
+ * `this` the pipeline would have given it, and its result is then compacted;
69
+ * 2. `undefined` from the original means "keep the renderer output", so the
70
+ * renderer's `result.content` is the text to compact;
71
+ * 3. when no block actually changes, the original return value is passed through
72
+ * untouched (including `undefined`), so a tool that did not compact behaves
73
+ * exactly as before;
74
+ * 4. an exception from the original is NOT caught: the pipeline already turns a
75
+ * throwing finalizer into an error result, and swallowing it here would turn
76
+ * a failing tool into a silently succeeding one.
77
+ *
78
+ * A frozen definition keeps its original finalizer: compaction must never be the
79
+ * reason a tool stops describing or running.
80
+ *
81
+ * @param definition - one visible tool definition.
82
+ * @returns the same definition, wrapped when possible.
83
+ */
84
+ export function wrapFinalizeContent(definition) {
85
+ if (definition === null || typeof definition !== 'object') return definition;
86
+ if (definition[SLIM_FINALIZER_MARK] === true) return definition;
87
+
88
+ const original = typeof definition.finalizeContent === 'function' ? definition.finalizeContent : undefined;
89
+ const wrapped = function finalizeContentWithSlimOutput(exec, result) {
90
+ const finalized = original === undefined ? undefined : original.call(this, exec, result);
91
+ const current = finalized === undefined ? result?.content : finalized;
92
+ const slimmed = slimContentBlocks(current);
93
+ if (slimmed === current) return finalized;
94
+ return slimmed;
95
+ };
96
+
97
+ try {
98
+ Object.defineProperty(definition, 'finalizeContent', {
99
+ value: wrapped,
100
+ enumerable: true,
101
+ configurable: true,
102
+ writable: true,
103
+ });
104
+ Object.defineProperty(definition, SLIM_FINALIZER_MARK, {
105
+ value: true,
106
+ enumerable: false,
107
+ configurable: true,
108
+ });
109
+ } catch {
110
+ /* frozen definition: keep the original behaviour rather than break describe() */
111
+ }
112
+ return definition;
113
+ }
44
114
 
45
115
  // [vendored dsh-lean-router 2026-11-18] The native executor module is loaded on
46
116
  // demand (a dynamic import inside loadNativeExecutorModule) instead of a
@@ -159,6 +229,12 @@ export function createCodemodeExecutor(ctx, options, hooks = {}) {
159
229
  masked: tools.map((tool) => tool?.name).filter((name) => isMaskedName(name, options, view)),
160
230
  view,
161
231
  });
232
+ // [dsh-lean-router ticket context_output_compactor] Conservative output
233
+ // compaction covers `code_run` and every preset-owned visible tool. It is
234
+ // installed on the definitions the registry stores (the same objects the
235
+ // execution pipeline snapshots `finalizeContent` from), and it touches
236
+ // `content` only — never `value`, so nested sub-calls settle unchanged.
237
+ for (const definition of visible) wrapFinalizeContent(definition);
162
238
  return native.describe(visible);
163
239
  },
164
240
 
@@ -330,33 +330,31 @@ export function buildCodemodeSectionText(input) {
330
330
 
331
331
  lines.push('## Code Mode');
332
332
  lines.push('');
333
- lines.push(`This session runs in Code Mode. Tools listed in your tool list are called directly, as usual. A second, larger set of tools — every tool this preset does not own, including every MCP tool and every tool contributed by a plugin outside the preset — is deliberately **not** in your context and is reachable only from inside \`${runToolName}\`.`);
333
+ lines.push(`Code Mode: tools in your list are called directly; everything else — MCP servers, outside plugins — is **not** in your context and is reachable only from inside \`${runToolName}\`.`);
334
334
  lines.push('');
335
- lines.push('### Calling tools from a program');
335
+ lines.push('### Calling tools');
336
336
  lines.push('');
337
337
  lines.push('```js');
338
- lines.push(`// standard tools and every masked tool alike`);
339
338
  lines.push('const files = await tools.glob({ pattern: "src/**/*.ts" })');
340
- lines.push('const rows = await Promise.all(files.map((f) => tools.read({ file_path: f })))');
341
339
  lines.push(retained
342
- ? 'rows.filter((r) => r.includes("TODO")).map((r) => r.split("\\n")[0])'
343
- : 'return rows.filter((r) => r.includes("TODO")).map((r) => r.split("\\n")[0])');
340
+ ? 'await Promise.all(files.map((f) => tools.read({ file_path: f })))'
341
+ : 'return Promise.all(files.map((f) => tools.read({ file_path: f })))');
344
342
  lines.push('```');
345
343
  lines.push('');
346
344
  if (retained) {
347
- lines.push('- A retained TypeScript REPL: top-level declarations, `await`, and a final expression. This program shares its variables, functions, and imported modules with your later programs in this session.');
348
- lines.push('- Only printed values and the final expression become program output; every intermediate result stays in the program, so filter and aggregate there instead of emitting raw payloads.');
345
+ lines.push('- A retained TypeScript REPL: later programs share its variables and imports; top-level declarations, `await` and a final expression, but no top-level `return`.');
346
+ lines.push('- Only printed values and the final expression reach the conversation; aggregate intermediate results inside the program.');
349
347
  } else {
350
348
  lines.push('- Erasable TypeScript, run as the body of an async function: top-level `await` and `return` work.');
351
- lines.push('- Only what you `return` or `console.log` reaches the conversation; every intermediate result stays in the program, so filter and aggregate there instead of returning raw payloads.');
349
+ lines.push('- Only what you return or print reaches the conversation; aggregate intermediate results inside the program.');
352
350
  }
353
351
  lines.push('- Independent read-only calls may overlap under `Promise.all`; mutating calls run alone, in submission order.');
354
- lines.push('- A failed sub-call rejects; `try/catch` or `Promise.allSettled` it to keep the calls that succeeded. Completed calls are real side effects and are not rolled back.');
352
+ lines.push('- A failed sub-call rejects; `try/catch` or `Promise.allSettled` it. Completed calls are real side effects, not rolled back.');
355
353
  lines.push('');
356
354
  if (hidden.total > 0) {
357
355
  lines.push('### Masked tools');
358
356
  lines.push('');
359
- lines.push(`${hidden.total} tool(s) are outside this preset's standard composition and are hidden from your context, by namespace:`);
357
+ lines.push(`${hidden.total} tool(s) are outside this preset's standard composition and hidden from your context, by namespace:`);
360
358
  lines.push('');
361
359
  for (const entry of hidden.namespaces) {
362
360
  lines.push(entry.kind === 'mcp'
@@ -364,34 +362,34 @@ export function buildCodemodeSectionText(input) {
364
362
  : `- \`${entry.namespace}\` (contributed by plugins outside this preset) — ${entry.count} tool(s), callable by exact name as \`tools.<name>({...})\``);
365
363
  }
366
364
  lines.push('');
367
- lines.push('Discover them from inside a program, then call them by exact name:');
365
+ lines.push('Find and call them by exact name from a program:');
368
366
  lines.push('');
369
367
  lines.push('```js');
370
368
  lines.push(`const { tools: hits } = await tools.${searchTool}({ query: "what you need", limit: ${searchLimit} })`);
371
- lines.push('// hits[0].name, hits[0].description, hits[0].parameters (full JSON Schema)');
369
+ lines.push(`const { parameters } = await tools.${describeTool}({ name: hits[0].name }); // only when the parameter names are not enough`);
372
370
  lines.push(retained
373
- ? 'await tools[hits[0].name]({ /* arguments matching hits[0].parameters */ })'
374
- : 'return await tools[hits[0].name]({ /* arguments matching hits[0].parameters */ })');
371
+ ? 'await tools[hits[0].name]({ /* args from parameters */ })'
372
+ : 'return await tools[hits[0].name]({ /* args from parameters */ })');
375
373
  lines.push('```');
376
374
  } else {
377
375
  lines.push('### Masked tools');
378
376
  lines.push('');
379
- lines.push('No masked tools are connected right now. If an MCP server or an out-of-preset plugin contributes one later, it appears here automatically and is reachable the same way.');
377
+ lines.push('No masked tools are connected right now. One that appears later shows up here automatically and is reachable the same way.');
380
378
  }
381
379
  lines.push('');
382
- lines.push('### Discovery API (all callable from inside a program)');
380
+ lines.push('### Discovery API');
383
381
  lines.push('');
384
- lines.push(`- \`tools.${listTool}({ namespace? })\` — every callable tool as \`{ name, description, namespace, hidden }\`, masked ones included.`);
385
- lines.push(`- \`tools.${searchTool}({ query, limit?, namespace? })\` — ranked matches with their full parameter schemas; this is the intended first step.`);
386
- lines.push(`- \`tools.${describeTool}({ name })\` — one tool's description and complete parameter schema.`);
382
+ lines.push(`- \`tools.${listTool}({ namespace? })\` — every callable tool, masked ones included: \`{ name, description, namespace, hidden }\`.`);
383
+ lines.push(`- \`tools.${searchTool}({ query, limit?, namespace? })\` — ranked matches with their parameter names; the intended first step, then \`${describeTool}\` for one match's full schema.`);
384
+ lines.push(`- \`tools.${describeTool}({ name })\` — one tool's description and full parameter schema.`);
387
385
  if (metaTools.length > 3) {
388
- lines.push(`- \`tools.${metaTools[3]}({ limit? })\` — what Code Mode masked out of this session's request surface, for troubleshooting.`);
386
+ lines.push(`- \`tools.${metaTools[3]}({ limit? })\` — what Code Mode masked out of this session, for troubleshooting.`);
389
387
  }
390
388
  lines.push('');
391
389
  lines.push('### Hard rules');
392
390
  lines.push('');
393
- lines.push(`- Never guess a masked tool's name or arguments. Call \`${searchTool}\` first, read \`parameters\`, then call it inside the same or a later \`${runToolName}\` program.`);
394
- lines.push('- A direct call to a masked tool — one that does not come from inside a program — is rejected by the harness.');
395
- lines.push(`- The discovery tools are themselves only callable from inside \`${runToolName}\`; they are not part of your tool list.`);
391
+ lines.push(`- Never guess a masked tool's name or arguments: call \`${searchTool}\` for the name and its parameter names, call \`${describeTool}\` when you need the full parameter schema, then call it inside a \`${runToolName}\` program.`);
392
+ lines.push('- A direct call to a masked tool from outside a program is rejected by the harness.');
393
+ lines.push(`- The discovery tools are only callable from inside \`${runToolName}\`; they are not in your tool list.`);
396
394
  return lines.join('\n');
397
395
  }