dsh-lean-router 0.2.3 → 0.2.4

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.
@@ -1,6 +1,19 @@
1
1
  # Changelog
2
2
 
3
- > English version of [changelog.md](./changelog.md). Versions follow package.json (currently 0.2.3).
3
+ > English version of [changelog.md](./changelog.md). Versions follow package.json (currently 0.2.4).
4
+
5
+ ## 0.2.4 (2026-11-30)
6
+
7
+ ### Changed
8
+
9
+ - **Tool-definition payload drops from 21,123 to about 12,122 characters (−42.6%)**, via two measures used together:
10
+ - **Description slimming** (`lib/toolface/desc-slim.js`): `pwsh` 3495→1265, `subagent` 1972→949, `ask_user_question` 1419→663, `edit` 1151→565, plus `present`/`list_agents`/`subagent_fork`/`update_goal` — eight tools in all, with the six main ones shrinking 55.7% combined. Every constraint that could cause misuse is preserved: the PowerShell-vs-cmd `;`/`&&` difference, `.NET` static calls and `Add-Type` being unavailable in the Windows read-only sandbox, `run_in_background` usage, and `ask_user_question`'s "questions must go through this tool" and "an empty `selected` means skipped — do not ask again" semantics.
11
+ - **Masking low-frequency core tools**: `update_goal`, `list_agents`, `present` and `subagent_fork` no longer appear in the request's tool list but remain discoverable and callable through `code_run`'s `search`/`describe`. `subagent`, `ask_user_question`, `pwsh`, `edit`, `write`, `read`, `grep` and `glob` are unaffected.
12
+ - Environment switches: `DSH_LEAN_ROUTER_DESC_SLIM=0` disables description slimming and `DSH_LEAN_ROUTER_MASK_CORE=0` restores the four masked tools. Both are read at call time, so they take effect immediately.
13
+
14
+ ### Tests
15
+
16
+ - 10 new cases (post-slim sizes and preserved keywords, fail-safe pass-through, both switches, the masked-name list, and `describe` genuinely handing the slimmed text downstream); the full suite is 279 tests, 278 passing, 0 failing, 1 skipped.
4
17
 
5
18
  ## 0.2.3 (2026-11-30)
6
19
 
package/docs/changelog.md CHANGED
@@ -1,6 +1,19 @@
1
1
  # 变更记录(changelog)
2
2
 
3
- > 中文为主,英文版:[changelog.en.md](./changelog.en.md)。版本号遵循 package.json(当前 0.2.3)。
3
+ > 中文为主,英文版:[changelog.en.md](./changelog.en.md)。版本号遵循 package.json(当前 0.2.4)。
4
+
5
+ ## 0.2.4 (2026-11-30)
6
+
7
+ ### 变更
8
+
9
+ - **工具定义体积从 21,123 字符降到约 12,122(−42.6%)**,两个手段并用:
10
+ - **压缩描述**(`lib/toolface/desc-slim.js`):`pwsh` 3495→1265、`subagent` 1972→949、`ask_user_question` 1419→663、`edit` 1151→565,另含 `present`/`list_agents`/`subagent_fork`/`update_goal` 共 8 个,六个主要工具合计降 55.7%。压缩时保留全部会导致误用的硬约束:PowerShell 与 cmd 的 `;`/`&&` 差异、Windows 沙箱只读模式下 `.NET` 静态调用与 `Add-Type` 不可用、`run_in_background` 用法,以及 `ask_user_question` 的「必须走工具提问」和「空 selected 即跳过、不得再问」语义。
11
+ - **遮蔽低频核心工具**:`update_goal`、`list_agents`、`present`、`subagent_fork` 不再出现在请求的工具列表里,但仍可经 `code_run` 的 `search` / `describe` 发现与调用。`subagent`、`ask_user_question`、`pwsh`、`edit`、`write`、`read`、`grep`、`glob` 不受影响。
12
+ - 环境开关:`DSH_LEAN_ROUTER_DESC_SLIM=0` 关闭描述压缩,`DSH_LEAN_ROUTER_MASK_CORE=0` 放行被遮蔽的四个工具。两者都在调用时读取,可即时生效。
13
+
14
+ ### 测试
15
+
16
+ - 新增 10 项(压缩后的体积与关键词保留、fail-safe 原样返回、两个开关、遮蔽名单、以及 `describe` 确实把精简文本交给下游);全量 279 项、278 通过、0 失败、1 skip。
4
17
 
5
18
  ## 0.2.3 (2026-11-30)
6
19
 
@@ -0,0 +1,140 @@
1
+ /**
2
+ * [dsh-lean-router ticket tool-description-slimming] Compact model-facing
3
+ * descriptions for the host's biggest tool definitions.
4
+ *
5
+ * WHY: the request carries a serialized catalog, and ten of the host's core
6
+ * tools account for two thirds of it. Their prose is duplicated from DSH docs
7
+ * that the model already receives elsewhere (the pwsh text restates the sandbox
8
+ * policy three ways), so the catalog pays for paragraphs the turn does not
9
+ * need. This table is a *presentation* transform only: it swaps the
10
+ * `description` a definition is described with, never the definition the
11
+ * registry stores, and never a parameter schema, name or behaviour.
12
+ *
13
+ * WHAT STAYS: every constraint whose loss would cause a wrong action rather
14
+ * than a slightly worse sentence — the PowerShell-vs-cmd syntax rules, the
15
+ * read-only/ConstrainedLanguage restriction on .NET static calls in the
16
+ * Windows sandbox, `run_in_background` for long commands, the
17
+ * "ask through the tool" rule for `ask_user_question`. Those are the points a
18
+ * model gets burned by, so the compression is deliberately allowed to run
19
+ * longer to keep them.
20
+ *
21
+ * NOT COMPRESSED: `code_run`, `read`, `grep`, `glob`, `write` and the other
22
+ * definitions this repo already tuned. A name absent from the table means
23
+ * "leave untouched", which is also why `slimDefinition` returns the *same
24
+ * reference* for it.
25
+ *
26
+ * FAIL-SAFE: a missing/blanked description, a non-object definition or a
27
+ * malformed table entry all fall back to the input. This layer must never be
28
+ * the reason a session cannot be created or a tool cannot be described.
29
+ *
30
+ * @module dsh-lean-router/toolface/desc-slim
31
+ */
32
+
33
+ /** Environment switch: `0` disables every rewrite in this module. */
34
+ export const DESC_SLIM_ENV = 'DSH_LEAN_ROUTER_DESC_SLIM';
35
+
36
+ /**
37
+ * Whether description slimming is enabled for this process.
38
+ *
39
+ * Read per call, not at module load, so a test (or a host that flips the
40
+ * variable) sees the change without re-importing.
41
+ */
42
+ export function isDescSlimEnabled() {
43
+ return process.env?.[DESC_SLIM_ENV] !== '0';
44
+ }
45
+
46
+ /**
47
+ * Slim descriptions, keyed by exact tool name.
48
+ *
49
+ * Each value is the model-facing description only. Nothing else about the
50
+ * definition changes.
51
+ */
52
+ export const SLIM_DESCRIPTIONS = {
53
+ pwsh: [
54
+ 'Execute a PowerShell command (`pwsh -Command`) and return stdout/stderr; each call is a fresh pwsh process. Pass `description` before `command`.',
55
+ 'Windows: native paths (`C:\\...`); env vars as `$env:NAME` (`$env:DSH_*` = harness facts). This is PowerShell, not cmd: no `&&`/`||`, join with `;`. Before a delete or move, verify the resolved absolute target is intended; never a path you have not checked.',
56
+ 'A blocked file op reports `[sandbox: file access denied under <mode> mode]`: do not retry another way. In the Windows sandbox read-only pwsh is ConstrainedLanguage while workspace-write is FullLanguage: read-only must stick to cmdlets and core types (`[string]`, `[regex]`), because .NET static calls (`[System.IO.*]::`, `[math]::`), `Add-Type`, COM and reflection fail with "only core types". Both confined modes lack named pipes: Node `child_process` with default `stdio:\'pipe\'` fails EPERM, so escalate once or restructure; `stdio:\'inherit\'`/`\'ignore\'` work.',
57
+ 'Args: `command`; `description` (5-10 words, shown in the UI); `workdir` (default: session workspace); `timeoutMs` (on expiry it moves to the background); `run_in_background: true` returns a job id with no timeout — collect with `job_output`, stop with `job_kill`. Use it up front for long commands.',
58
+ ].join('\n\n'),
59
+
60
+ subagent: [
61
+ 'Delegate a self-contained task to a subagent — a separate agent with its own context — to offload focused, independent work so it does not consume this conversation\'s context. You receive its result, not its intermediate steps.',
62
+ 'It is independently managed: the call returns its name immediately, and if you are still online a completion notice carrying the final answer arrives when it finishes (unless the child messaged you first). `send_message` steers it while running or continues it afterwards.',
63
+ 'Args: `description` (3-5 words, for display, in the language of the request); `name` (optional, unique among the subagents you create: lower-case letters, digits and hyphens, starting with a letter, at most 32 chars, `lead` reserved; defaults to `agent-1`, `agent-2`, ...); `prompt` (the complete, self-contained task — it does not share this conversation, so include everything it needs); `provider`/`model` only if the task needs another model.',
64
+ ].join('\n\n'),
65
+
66
+ subagent_fork: [
67
+ 'Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn). Use it when the subtask builds on this conversation\'s context and should not re-derive it in this context.',
68
+ 'Same contract as `subagent`: you receive its result, not its steps; it starts independently managed and returns its name immediately; `send_message` steers it while running or continues it after it finishes.',
69
+ 'Args: `description` (3-5 words); `name` (optional, same naming rules as `subagent`); `prompt` — build freely on the inherited turns and state only what is new.',
70
+ ].join('\n\n'),
71
+
72
+ ask_user_question: [
73
+ 'Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. Questions to the user go through this tool; do not ask in prose and stop. An answer item with empty `selected` and no `custom` means the user skipped it: continue without it, do not ask again, and do not treat the skip as permission.',
74
+ 'Args: `questions` — array of `{ id, question, header?, options?, multi_select? }`. `header` is a short heading such as "Confirm"; `options` are optional choices to show, and if you recommend one, put it first and append " (Recommended)" to its label; `multi_select` allows more than one option and defaults to false.',
75
+ ].join('\n\n'),
76
+
77
+ edit: [
78
+ 'Edit an existing UTF-8 text file by replacing literal text. Provide `file_path` before `old_string` and `new_string`.',
79
+ '`new_string` is the literal replacement; an empty string deletes the match. `replace_all` defaults to false, and when false `old_string` must appear exactly once.',
80
+ '`sandbox_permissions` names the narrowest wider mode for a one-shot retry of the exact operation the sandbox just denied; that retry asks the user for approval, and `justification` is required with it — one sentence, in the user\'s language, on why this operation needs wider access.',
81
+ ].join('\n\n'),
82
+
83
+ present: [
84
+ 'Declare existing files as final deliverables. Hosts may show them only after your turn ends, so call it once the files are final; if the user must review them earlier, link them in your message instead. Use it when a separate file helps (especially Office documents, spreadsheets and slide decks); prefer your final response otherwise.',
85
+ '`files`: usually the 1-2 most important deliverables, at most 4 per call, each `{ path, description }`; `path` resolves against the session working directory.',
86
+ ].join('\n\n'),
87
+
88
+ update_goal: [
89
+ 'Update the current goal. `get_goal` returns the goal, including the `id` and `revision` this call requires.',
90
+ '`edit`, `pause` and `resume` need a direct top-level human request. `complete` and `blocked` are also allowed during an automatic continuation; `blocked` is rejected before the minimum round count.',
91
+ 'Args: `action`; `objective` (replacement goal, `edit` only); `max_goal_rounds` (replacement cap, `edit` only); `blocked_reason` (required with `blocked`: the concrete condition that persisted across rounds).',
92
+ ].join('\n\n'),
93
+
94
+ list_agents: [
95
+ 'List your subagent tree: root and all reachable continuable descendants, including yourself. Shared capacity reports running/limit; do not spawn more when capacity is limited.',
96
+ 'A descendant\'s name is its path from the root (`reviewer/checker`). `running` = working, `inactive` = no turn executing (neither proves done/success/failure); `corrupt`/`unsupported`/`unavailable` = its own descendants unreadable, row still messageable. Use `send_message` to continue it.',
97
+ ].join('\n\n'),
98
+ };
99
+
100
+ /**
101
+ * Replace one definition's description with its slim counterpart.
102
+ *
103
+ * @param definition - a visible tool definition.
104
+ * @returns a shallow copy carrying the slim description, or the *same*
105
+ * reference when the name is absent, the entry is unusable, the definition is
106
+ * not an object, or slimming is switched off.
107
+ *
108
+ * The registry's own definition object is never mutated: `code_tools_describe`
109
+ * and the discovery tools keep reporting the full text, and the model-facing
110
+ * catalog is the only surface that changes.
111
+ */
112
+ export function slimDefinition(definition) {
113
+ try {
114
+ if (!isDescSlimEnabled()) return definition;
115
+ if (definition === null || typeof definition !== 'object') return definition;
116
+ const slim = SLIM_DESCRIPTIONS[definition.name];
117
+ if (typeof slim !== 'string' || slim.length === 0) return definition;
118
+ if (typeof definition.description !== 'string' || definition.description.length === 0) return definition;
119
+ return { ...definition, description: slim };
120
+ } catch {
121
+ /* a hostile definition must never break request assembly */
122
+ return definition;
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Apply {@link slimDefinition} across one model-facing definition list.
128
+ *
129
+ * Non-array input is returned untouched, so a caller that passes nothing gets
130
+ * nothing rather than an exception.
131
+ */
132
+ export function slimDefinitions(definitions) {
133
+ try {
134
+ if (!isDescSlimEnabled()) return definitions;
135
+ if (!Array.isArray(definitions)) return definitions;
136
+ return definitions.map((definition) => slimDefinition(definition));
137
+ } catch {
138
+ return definitions;
139
+ }
140
+ }
@@ -41,6 +41,7 @@
41
41
  */
42
42
 
43
43
  import { isMaskedName } from './rules.js';
44
+ import { slimDefinitions } from './desc-slim.js';
44
45
  import { slimContentBlocks } from '../lean/output-slim.js';
45
46
  import { budgetContentBlocks } from '../lean/history-budget.js';
46
47
 
@@ -242,7 +243,16 @@ export function createCodemodeExecutor(ctx, options, hooks = {}) {
242
243
  // execution pipeline snapshots `finalizeContent` from), and it touches
243
244
  // `content` only — never `value`, so nested sub-calls settle unchanged.
244
245
  for (const definition of visible) wrapFinalizeContent(definition);
245
- return native.describe(visible);
246
+ // [dsh-lean-router ticket tool-description-slimming] `describe()` is the
247
+ // request surface, so this is where a compact description has to land.
248
+ // `slimDefinitions` returns shallow copies for the names in its table and
249
+ // the *same* reference for everything else, so the registry's own
250
+ // definitions (and `code_tools_describe`, which reads them) keep their
251
+ // full text; only the model-facing catalog is shortened. Wrapping above
252
+ // happens on the originals first, so a copy still carries the
253
+ // `finalizeContent` wrapper it was made from. `visible` is left untouched,
254
+ // which also keeps `onDescribe` and the execution path unchanged.
255
+ return native.describe(slimDefinitions(visible));
246
256
  },
247
257
 
248
258
  /** Execute one batch, denying model-direct calls to masked names. */
@@ -235,6 +235,14 @@ export {
235
235
  normalizeConfig,
236
236
  summarizeHidden,
237
237
  } from './rules.js';
238
+ export { CORE_MASK_ENV, DEFAULT_HIDDEN_CORE_TOOLS, isCoreMaskEnabled } from './rules.js';
239
+ export {
240
+ DESC_SLIM_ENV,
241
+ SLIM_DESCRIPTIONS,
242
+ isDescSlimEnabled,
243
+ slimDefinition,
244
+ slimDefinitions,
245
+ } from './desc-slim.js';
238
246
  export { createDiscoveryTools, visibleDefinitions } from './discovery.js';
239
247
  export { disabledView, findScopeKey, isForeignAtCall, resolveCatalogView, resolveScopeView } from './scope.js';
240
248
  export { createTransportTool, parameterSchema, ProgramFailedError } from './transport.js';
@@ -15,6 +15,36 @@
15
15
  /** Tool-name prefixes hidden from the model's request surface. */
16
16
  export const DEFAULT_HIDDEN_PREFIXES = ['mcp__'];
17
17
 
18
+ /**
19
+ * [dsh-lean-router ticket core-tool-masking] Low-frequency host core tools
20
+ * hidden from the request surface.
21
+ *
22
+ * These four are not part of any task loop: `update_goal` only moves a goal
23
+ * around, `list_agents` only inspects the subagent tree, `present` only
24
+ * declares files once work is done, and `subagent_fork` is a variant of
25
+ * `subagent`. Each one still costs its full schema in every request, so they
26
+ * are masked by default and stay reachable from inside `code_run` through
27
+ * `code_tools_search` / `code_tools_describe` — the same path every other
28
+ * masked tool uses. Nothing about their behaviour changes.
29
+ *
30
+ * Deliberately NOT listed: `subagent`, `ask_user_question`, `pwsh`, `edit`,
31
+ * `write`, `read`, `grep`, `glob` — these are the loop itself.
32
+ */
33
+ export const DEFAULT_HIDDEN_CORE_TOOLS = ['update_goal', 'list_agents', 'present', 'subagent_fork'];
34
+
35
+ /** Environment switch: `0` keeps the core tools visible. */
36
+ export const CORE_MASK_ENV = 'DSH_LEAN_ROUTER_MASK_CORE';
37
+
38
+ /**
39
+ * Whether core-tool masking is enabled for this process.
40
+ *
41
+ * Read per `normalizeConfig` call rather than at module load, so a host or a
42
+ * test that flips the variable takes effect without re-importing.
43
+ */
44
+ export function isCoreMaskEnabled() {
45
+ return process.env?.[CORE_MASK_ENV] !== '0';
46
+ }
47
+
18
48
  /** Discovery tools this plugin registers; hidden like everything else it hides. */
19
49
  export const DEFAULT_META_TOOLS = ['code_tools_list', 'code_tools_search', 'code_tools_describe', 'code_debug'];
20
50
 
@@ -107,6 +137,16 @@ export function normalizeConfig(config = {}) {
107
137
  const maxParallelSubCalls = Number.isFinite(config.maxParallelSubCalls) && config.maxParallelSubCalls >= 1
108
138
  ? Math.floor(config.maxParallelSubCalls)
109
139
  : DEFAULTS.maxParallelSubCalls;
140
+ // [dsh-lean-router ticket core-tool-masking] The four core tools ride the
141
+ // existing `hiddenTools` rule rather than a second masking mechanism: merging
142
+ // them here means `isHiddenName`, `isMaskedName`, `filterAssemblyTools`,
143
+ // `summarizeHidden` and the executor's denial all pick them up with no
144
+ // further change. `nativeTools` still wins over `hiddenTools` (see
145
+ // `isAlwaysNativeName`), so a deployment can opt one back in explicitly.
146
+ const hiddenTools = stringList([
147
+ ...stringList(config.hiddenTools),
148
+ ...(isCoreMaskEnabled() ? DEFAULT_HIDDEN_CORE_TOOLS : []),
149
+ ]);
110
150
  return {
111
151
  hiddenPrefixes,
112
152
  metaTools,
@@ -120,7 +160,7 @@ export function normalizeConfig(config = {}) {
120
160
  maxParallelSubCalls,
121
161
  nativeScope: config.nativeScope !== false,
122
162
  nativeTools: stringList(config.nativeTools),
123
- hiddenTools: stringList(config.hiddenTools),
163
+ hiddenTools,
124
164
  };
125
165
  }
126
166
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-lean-router",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "lean 省 token × 思考链路由 × code_run 工具遮蔽的 DSH cordis 插件(单 bundle:预设)",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -107,12 +107,13 @@ run('git', ['commit', '-m', 'chore(release): ' + version]);
107
107
  console.log('[release] 已提交版本号变更');
108
108
 
109
109
  console.log('[release] 发布到官方 registry');
110
- // npm 拒绝把 latest 隐式指回更低版本;显式声明 tag 才能切换版本线。
111
- // 平时不需要 --tag,保持 npm 的默认行为(latest)。
110
+ // 始终显式声明 tag。npm 在「新版本低于历史最高版本」时会拒绝隐式 latest
111
+ // (例如 2.2.x 之后切回 0.2.x 线,即使 latest 已经指向 0.2.3 也照样报错),
112
+ // 显式传 --tag latest 才能让版本线正常推进。
112
113
  const tagIndex = argv.indexOf('--tag');
113
- const publishTag = tagIndex >= 0 ? argv[tagIndex + 1] : argv.includes('--allow-downgrade') ? 'latest' : undefined;
114
- if (tagIndex >= 0 && !publishTag) fail('--tag 后面必须跟 tag 名称');
115
- npm(publishTag ? ['publish', '--registry', REGISTRY, '--tag', publishTag] : ['publish', '--registry', REGISTRY]);
114
+ const publishTag = tagIndex >= 0 ? argv[tagIndex + 1] : 'latest';
115
+ if (!publishTag) fail('--tag 后面必须跟 tag 名称');
116
+ npm(['publish', '--registry', REGISTRY, '--tag', publishTag]);
116
117
 
117
118
  console.log('[release] 等待 registry 可见(最长 5 分钟)');
118
119
  const deadline = Date.now() + VISIBILITY_TIMEOUT_MS;
@@ -0,0 +1,255 @@
1
+ /**
2
+ * Tests for the two ticket deliverables that share the toolface surface:
3
+ * description slimming (lib/toolface/desc-slim.js, applied in executor.js) and
4
+ * low-frequency core-tool masking (rules.js `DEFAULT_HIDDEN_CORE_TOOLS`).
5
+ *
6
+ * The original description lengths below are *pinned measurements* of the host
7
+ * catalog this repo targets (26 tools, 21,123 chars serialized). They are
8
+ * constants rather than re-read from the host so this suite stays hermetic: a
9
+ * test run must not depend on which DSH build happens to be installed.
10
+ */
11
+
12
+ import test from 'node:test';
13
+ import assert from 'node:assert/strict';
14
+
15
+ import {
16
+ DESC_SLIM_ENV,
17
+ SLIM_DESCRIPTIONS,
18
+ isDescSlimEnabled,
19
+ slimDefinition,
20
+ slimDefinitions,
21
+ } from '../lib/toolface/desc-slim.js';
22
+ import {
23
+ CORE_MASK_ENV,
24
+ DEFAULT_HIDDEN_CORE_TOOLS,
25
+ isMaskedName,
26
+ normalizeConfig,
27
+ } from '../lib/toolface/rules.js';
28
+ import {
29
+ createCodemodeExecutor,
30
+ markNested,
31
+ } from '../lib/toolface/executor.js';
32
+
33
+ /** Measured lengths of the definitions in the host catalog this repo targets. */
34
+ const ORIGINAL_CHARS = {
35
+ pwsh: 3495,
36
+ subagent: 1972,
37
+ subagent_fork: 1527,
38
+ ask_user_question: 1419,
39
+ edit: 1151,
40
+ present: 1006,
41
+ update_goal: 984,
42
+ list_agents: 889,
43
+ };
44
+
45
+ /** The six tools the ticket requires to be compressed. */
46
+ const REQUIRED = ['pwsh', 'subagent', 'ask_user_question', 'edit', 'present', 'list_agents'];
47
+
48
+ /** The already-tuned definitions this module must not touch. */
49
+ const UNTOUCHED = ['code_run', 'read', 'grep', 'glob', 'write'];
50
+
51
+ /** Run `fn` with an environment variable set, restoring the prior value. */
52
+ function withEnv(name, value, fn) {
53
+ const prior = process.env[name];
54
+ if (value === undefined) delete process.env[name];
55
+ else process.env[name] = value;
56
+ try {
57
+ return fn();
58
+ } finally {
59
+ if (prior === undefined) delete process.env[name];
60
+ else process.env[name] = prior;
61
+ }
62
+ }
63
+
64
+ /** A definition carrying a realistic (long) description, as the host sends it. */
65
+ function definition(name, description = 'x'.repeat(ORIGINAL_CHARS[name] ?? 500)) {
66
+ return { name, description, parameters: { type: 'object', properties: {} } };
67
+ }
68
+
69
+ test('slimDefinition swaps in a shorter description without mutating the input', () => {
70
+ for (const name of REQUIRED) {
71
+ const original = definition(name);
72
+ const slim = slimDefinition(original);
73
+ assert.notEqual(slim, original, `${name}: a slimmed definition is a new object`);
74
+ assert.equal(slim.description, SLIM_DESCRIPTIONS[name], `${name}: the table value is used verbatim`);
75
+ assert.ok(slim.description.length < original.description.length, `${name}: it is shorter`);
76
+ assert.equal(original.description.length, ORIGINAL_CHARS[name], `${name}: the caller's definition is untouched`);
77
+ assert.equal(slim.name, name, `${name}: name is preserved`);
78
+ assert.deepEqual(slim.parameters, original.parameters, `${name}: parameters are preserved`);
79
+ }
80
+ });
81
+
82
+ test('slimDefinition returns the same reference for names outside the table', () => {
83
+ for (const name of UNTOUCHED) {
84
+ const original = definition(name);
85
+ assert.equal(slimDefinition(original), original, `${name} is left alone`);
86
+ }
87
+ // A whole list keeps references for untuned names and copies for tuned ones.
88
+ const list = [definition('code_run'), definition('pwsh')];
89
+ const slimmed = slimDefinitions(list);
90
+ assert.equal(slimmed[0], list[0], 'untouched names keep their reference');
91
+ assert.notEqual(slimmed[1], list[1], 'tuned names are copied');
92
+ assert.deepEqual(slimDefinitions([]), [], 'an empty list is fine');
93
+ });
94
+
95
+ test('slimDefinition is fail-safe: malformed input comes back unchanged, never throws', () => {
96
+ for (const bad of [null, undefined, 'pwsh', 42, [], {}]) {
97
+ assert.doesNotThrow(() => slimDefinition(bad));
98
+ assert.equal(slimDefinition(bad), bad, `${String(bad)} is returned as-is`);
99
+ }
100
+ // A definition with no usable description is not rewritten either.
101
+ const withoutDescription = { name: 'pwsh', parameters: {} };
102
+ assert.equal(slimDefinition(withoutDescription), withoutDescription, 'no description -> untouched');
103
+ const blank = { name: 'pwsh', description: '' };
104
+ assert.equal(slimDefinition(blank), blank, 'empty description -> untouched');
105
+ // Non-array input to the list helper is passed through.
106
+ assert.equal(slimDefinitions(undefined), undefined);
107
+ });
108
+
109
+ test('the slim descriptions keep the constraints whose loss causes misuse', () => {
110
+ const pwsh = SLIM_DESCRIPTIONS.pwsh;
111
+ for (const keyword of ['PowerShell', 'cmd', 'run_in_background', '.NET', 'ConstrainedLanguage', 'sandbox: file access denied']) {
112
+ assert.ok(pwsh.includes(keyword), `pwsh must still say ${keyword}`);
113
+ }
114
+ assert.ok(pwsh.includes('`&&`') || pwsh.includes('&&'), 'pwsh must warn about cmd chaining');
115
+ assert.ok(pwsh.includes('job_output') && pwsh.includes('job_kill'), 'pwsh must say how to collect a background job');
116
+
117
+ // The "questions go through this tool" rule and the option shape are both load-bearing.
118
+ const ask = SLIM_DESCRIPTIONS.ask_user_question;
119
+ for (const keyword of ['this tool', 'prose', 'questions', 'options', 'Recommended', 'multi_select', 'selected']) {
120
+ assert.ok(ask.includes(keyword), `ask_user_question must still say ${keyword}`);
121
+ }
122
+
123
+ const edit = SLIM_DESCRIPTIONS.edit;
124
+ for (const keyword of ['file_path', 'old_string', 'new_string', 'replace_all', 'sandbox_permissions', 'justification']) {
125
+ assert.ok(edit.includes(keyword), `edit must still document ${keyword}`);
126
+ }
127
+
128
+ assert.ok(SLIM_DESCRIPTIONS.present.includes('files'), 'present keeps its argument');
129
+ assert.ok(SLIM_DESCRIPTIONS.list_agents.includes('send_message'), 'list_agents keeps the follow-up path');
130
+ assert.ok(SLIM_DESCRIPTIONS.subagent.includes('prompt'), 'subagent keeps its required argument');
131
+ assert.ok(SLIM_DESCRIPTIONS.update_goal.includes('revision'), 'update_goal keeps the revision rule');
132
+ });
133
+
134
+ test('the slimmed catalog is at least 55% smaller, and pwsh fits its 1300-char cap', () => {
135
+ const before = REQUIRED.reduce((sum, name) => sum + ORIGINAL_CHARS[name], 0);
136
+ const after = REQUIRED.reduce((sum, name) => sum + SLIM_DESCRIPTIONS[name].length, 0);
137
+ assert.equal(before, 9932, 'the pinned baseline is the one the ticket measured');
138
+
139
+ for (const name of REQUIRED) {
140
+ const limit = Math.floor(ORIGINAL_CHARS[name] * 0.55);
141
+ assert.ok(
142
+ SLIM_DESCRIPTIONS[name].length <= limit,
143
+ `${name}: ${SLIM_DESCRIPTIONS[name].length} chars must be <= ${limit} (55% of ${ORIGINAL_CHARS[name]})`,
144
+ );
145
+ }
146
+ assert.ok(SLIM_DESCRIPTIONS.pwsh.length <= 1300, `pwsh: ${SLIM_DESCRIPTIONS.pwsh.length} must be <= 1300`);
147
+
148
+ const saved = (before - after) / before;
149
+ assert.ok(saved >= 0.55, `saved ${(saved * 100).toFixed(2)}% must be >= 55%`);
150
+
151
+ // Every entry must be a real string, or the module would silently do nothing.
152
+ for (const name of Object.keys(SLIM_DESCRIPTIONS)) {
153
+ assert.equal(typeof SLIM_DESCRIPTIONS[name], 'string', name);
154
+ assert.ok(SLIM_DESCRIPTIONS[name].trim().length > 0, name);
155
+ }
156
+ });
157
+
158
+ test('DSH_LEAN_ROUTER_DESC_SLIM=0 disables every rewrite', () => {
159
+ const original = definition('pwsh');
160
+ withEnv(DESC_SLIM_ENV, '0', () => {
161
+ assert.equal(isDescSlimEnabled(), false);
162
+ assert.equal(slimDefinition(original), original, 'no copy when switched off');
163
+ const list = [definition('pwsh'), definition('subagent')];
164
+ assert.equal(slimDefinitions(list), list, 'the list itself is returned unchanged');
165
+ });
166
+ assert.equal(isDescSlimEnabled(), true, 'the default is enabled');
167
+ assert.notEqual(slimDefinition(original), original, 'and rewrites again once restored');
168
+ });
169
+
170
+ test('the four low-frequency core tools are masked by default; the loop tools are not', () => {
171
+ const options = normalizeConfig({});
172
+ for (const name of ['update_goal', 'list_agents', 'present', 'subagent_fork']) {
173
+ assert.equal(isMaskedName(name, options), true, `${name} must be masked`);
174
+ }
175
+ for (const name of ['subagent', 'ask_user_question', 'pwsh', 'edit', 'write', 'read', 'grep', 'glob', 'code_run']) {
176
+ assert.equal(isMaskedName(name, options), false, `${name} must stay visible`);
177
+ }
178
+ assert.deepEqual([...DEFAULT_HIDDEN_CORE_TOOLS].sort(), ['list_agents', 'present', 'subagent_fork', 'update_goal']);
179
+ // Merging must not disturb explicitly configured names.
180
+ const configured = normalizeConfig({ hiddenTools: ['custom_tool'] });
181
+ assert.equal(isMaskedName('custom_tool', configured), true, 'configured names still hide');
182
+ assert.equal(isMaskedName('present', configured), true, 'core names still hide alongside them');
183
+ });
184
+
185
+ test('DSH_LEAN_ROUTER_MASK_CORE=0 keeps the four core tools visible', () => {
186
+ withEnv(CORE_MASK_ENV, '0', () => {
187
+ const options = normalizeConfig({});
188
+ for (const name of DEFAULT_HIDDEN_CORE_TOOLS) {
189
+ assert.equal(isMaskedName(name, options), false, `${name} must be visible when the switch is off`);
190
+ }
191
+ // An explicit hiddenTools entry still wins: the switch only drops the default list.
192
+ const configured = normalizeConfig({ hiddenTools: ['present'] });
193
+ assert.equal(isMaskedName('present', configured), true, 'explicit configuration is unaffected');
194
+ });
195
+ assert.equal(isMaskedName('present', normalizeConfig({})), true, 'and masking is back once restored');
196
+ });
197
+
198
+ test('describe() hands the delegate the slim description and leaves the registry definition intact', () => {
199
+ const seen = [];
200
+ const delegate = {
201
+ describe: (tools) => {
202
+ seen.push(...tools);
203
+ return { schemas: tools.map(t => ({ name: t.name, description: t.description, parameters: t.parameters })) };
204
+ },
205
+ execute: async () => ({ results: [], additionalContexts: [], concluded: false }),
206
+ };
207
+ const executor = createCodemodeExecutor({ get: () => undefined }, normalizeConfig({}), {
208
+ createDelegate: () => delegate,
209
+ });
210
+ const registryDefinition = definition('pwsh');
211
+ const out = executor.describe([registryDefinition]);
212
+
213
+ assert.deepEqual(out.schemas.map(schema => schema.name), ['pwsh'], 'the request surface is unchanged in shape');
214
+ assert.equal(seen[0].description, SLIM_DESCRIPTIONS.pwsh, 'the model receives the slim text');
215
+ assert.ok(seen[0].description.length <= 1300);
216
+ assert.equal(seen[0].finalizeContent, registryDefinition.finalizeContent, 'the copy keeps the output wrapper');
217
+ assert.equal(typeof seen[0].finalizeContent, 'function', 'and it is still callable');
218
+ assert.equal(registryDefinition.description.length, ORIGINAL_CHARS.pwsh, 'the registry keeps the full text');
219
+ assert.notEqual(seen[0], registryDefinition, 'the delegate gets a copy, not the registry object');
220
+ });
221
+
222
+ test('masked core tools are denied model-direct but still reachable from inside code_run', async () => {
223
+ const forwarded = [];
224
+ const delegate = {
225
+ describe: () => ({ schemas: [] }),
226
+ execute: async (input) => {
227
+ forwarded.push(...(input.calls ?? []).map(call => call.name));
228
+ return {
229
+ results: (input.calls ?? []).map(call => ({ callId: call.id, result: { isError: false, value: { ok: call.name }, content: [] } })),
230
+ additionalContexts: [],
231
+ concluded: false,
232
+ };
233
+ },
234
+ };
235
+ const executor = createCodemodeExecutor({ get: () => undefined }, normalizeConfig({}), {
236
+ createDelegate: () => delegate,
237
+ });
238
+
239
+ const denied = await executor.execute({
240
+ calls: [{ id: 'c1', name: 'present', arguments: '{}' }],
241
+ agent: {},
242
+ signal: new AbortController().signal,
243
+ });
244
+ assert.equal(denied.results[0].result.isError, true, 'a model-direct call is refused');
245
+ assert.match(denied.results[0].result.error.message, /code_tools_search/, 'with the discovery hint');
246
+ assert.deepEqual(forwarded, [], 'nothing is dispatched');
247
+
248
+ const nested = await executor.execute({
249
+ calls: [{ id: 'c2', name: 'present', arguments: '{}' }],
250
+ agent: {},
251
+ signal: markNested(new AbortController().signal),
252
+ });
253
+ assert.equal(nested.results[0].result.isError, false, 'a program-nested call is allowed');
254
+ assert.deepEqual(forwarded, ['present'], 'masking does not remove the capability');
255
+ });