@logictan/dsh-tool-toolsets 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,114 @@
1
- # Temporary Holding Version
1
+ # dsh-tool-toolsets
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ On-demand toolset loading for DeepSeek Harness: a plugin hands its tools over as
4
+ a named *toolset*, only a catalog (`get_tools`) joins the global tool list, and a
5
+ toolset's schemas cost nothing until an agent asks for them.
6
+
7
+ ## Why
8
+
9
+ Every registered tool's schema is paid on every request, whether or not the model
10
+ ever calls it. Measured on one profile: 100 tools / 126,498 characters of schema
11
+ per request, of which the 52 MCP tools are 83,495 characters (66%). A plugin with
12
+ dozens of rarely-used tools spends most of its context budget on definitions the
13
+ model reads once.
14
+
15
+ This plugin defers that cost: a toolset's schemas are registered into the
16
+ *calling agent's own scope layer* only when that agent calls `get_tools` for it,
17
+ and the next request assembly picks them up.
18
+
19
+ ## How it works
20
+
21
+ - A plugin calls `ctx.toolsets.register({ name, description, tools })`. `name`
22
+ matches `^[a-z][a-z0-9_-]*$`; `description` is the model-facing "when to use
23
+ this" line; `tools` are complete `defineTool` definitions.
24
+ - The plugin registers one global `get_tools` tool whose description is the
25
+ catalog: one line per toolset (name, when-to-use, tool count). Registering or
26
+ removing a toolset rebuilds the catalog.
27
+ - `get_tools({ toolset: "<name>" })` registers that group's tools into
28
+ `exec.agent.ctx` — the calling agent's scope. They are callable from the next
29
+ turn, are visible only to that agent, and unwind with the agent's fiber.
30
+ - Loading a toolset twice in one agent is a no-op returning the current list.
31
+ - Reviewing registration fails loud: bad name, empty tool list, a tool without
32
+ `execute`, a name collision across toolsets, or the reserved name `get_tools`.
33
+
34
+ ## Consuming (other plugins in this repo)
35
+
36
+ ```js
37
+ import { defineTool } from '@deepseek-ai/dsh-tools';
38
+
39
+ export const name = 'my-plugin';
40
+ export const inject = ['tools', 'toolsets'];
41
+
42
+ export function apply(ctx) {
43
+ ctx.toolsets.register({
44
+ name: 'android',
45
+ description: 'Operate a real Android phone over ADB — tap, swipe, screenshot.',
46
+ tools: [defineTool({ /* … */ })],
47
+ });
48
+ }
49
+ ```
50
+
51
+ `inject: ['toolsets']` is required: without it the service is not visible and the
52
+ plugin silently does nothing.
53
+
54
+ ## The host's own tools: `adopt`
55
+
56
+ A plugin's tools are handed to `register`. The HOST's tools cannot be: they are
57
+ registered before any plugin row mounts, so no plugin owns them and re-registering
58
+ one throws on the duplicate name.
59
+
60
+ `adopt({ name, description, tools })` claims such a group by NAME instead. The
61
+ definitions stay exactly where the host put them — so they keep their real
62
+ schemas — and the service's assembly hook hides them from each agent until that
63
+ agent loads the group. `activate` then does not register anything for an adopted
64
+ group; it only flips that agent's visibility.
65
+
66
+ `host-toolsets.mjs` is the policy on top of it: the host tools that are not
67
+ high-frequency are grouped by job (ssh, schedule, MCP resources, agent control,
68
+ goals, desktop/web, workflow, config sync, images) and claimed in full the tick
69
+ after mount. A group whose every tool is not yet registered is not claimed at
70
+ all — a catalog line promising tools that are absent would be the silent failure
71
+ class again.
72
+
73
+ This replaced `dsh-tool-surface`, deleted 2026-11-17. That plugin also withdrew
74
+ tools, but it described their arguments in prose; a tool known only by a one-line
75
+ summary is not usable, and an adopted group restores the full schema on load.
76
+
77
+ ## A name-based filter elsewhere in the host
78
+
79
+ `ctx.toolsets.protectedNames()` returns every tool name a registered toolset owns
80
+ plus `get_tools`. Nothing in this repository consumes it now that
81
+ `dsh-tool-surface` is gone; it exists because a third-party filter that withdrew
82
+ tools by name would otherwise remove a tool an agent had just loaded, and the
83
+ symptom — a load that appears to work and then vanishes — has no error anywhere.
84
+
85
+ ## Known trade-offs
86
+
87
+ - **Next-turn effect**: a load returns before the group is callable; it appears in
88
+ the following request. This is inherent to any deferred-schema design — the
89
+ tool list is fixed per request.
90
+ - **Per agent**: a sub-agent must load what it needs; it does not inherit its
91
+ parent's loads.
92
+ - **Prefix cache**: activation changes the tool list and so invalidates the
93
+ provider's tool prefix cache once, in exchange for a permanently smaller list.
94
+ - **In-memory activation**: a restarted session reloads what it needs (a no-op if
95
+ already loaded).
96
+ - **Not `deferLoading`**: this is a registry-layer mechanism and works regardless
97
+ of provider. `dsh-llm`'s built-in `deferLoading` is a different, provider-level
98
+ mechanism; it can coexist but does not replace this.
99
+
100
+ ## Tests
101
+
102
+ ```sh
103
+ pnpm test # registry unit tests + real-host composition tests
104
+ ```
105
+
106
+ The composition tests stand up a real cordis `Context`, the real `dsh-tools`
107
+ `ToolRuntime`, and the real `dsh-system-prompt` registry, then assert a toolset's
108
+ schemas are absent from the assembled request before activation and present
109
+ after — the one claim unit tests on pure functions cannot make. Host packages
110
+ resolve as devDependencies (pnpm links them), as peers for consumers.
111
+
112
+ ## License
113
+
114
+ MIT
@@ -0,0 +1,8 @@
1
+ # Patch row of @logictan/dsh-tool-toolsets.
2
+ #
3
+ # `id` equals the host half's `export const name` ('tool-toolsets' in index.mjs).
4
+ # `aggregate.mjs --check` does not validate row-id uniqueness; `check:host` does,
5
+ # and a duplicate hard-crashes the host with `duplicate loader entry id`.
6
+ - insert:
7
+ - id: tool-toolsets
8
+ name: '@logictan/dsh-tool-toolsets'
@@ -0,0 +1,116 @@
1
+ /**
2
+ * host-toolsets.mjs — the host's own tools, handed over as on-demand groups.
3
+ *
4
+ * This is the policy half of the retirement of `dsh-tool-surface`. That plugin
5
+ * filtered the assembled list down to a whitelist and moved the withdrawn
6
+ * arguments into prose; the prose was the weak part, because a tool described
7
+ * in one line is not a tool with a schema. An adopted group does strictly
8
+ * better: the tools keep their real definitions in the registry, the model
9
+ * loads the group, and the NEXT request carries those definitions in full.
10
+ *
11
+ * Only the host's own tools live here. A plugin's tools belong to that plugin's
12
+ * `register` call; these are registered by the host before any plugin runs, so
13
+ * nobody can own them — `ctx.toolsets.adopt` claims them instead.
14
+ *
15
+ * The groups are also the policy: a tool named in one of them is withdrawn from
16
+ * every request until an agent loads that group, and a tool named in none stays
17
+ * announced. There is deliberately no separate keep list — with two lists the
18
+ * second one drifts, which is exactly how the announced-but-unusable class of
19
+ * failure happened before.
20
+ *
21
+ * @module @logictan/dsh-tool-toolsets/host-toolsets
22
+ */
23
+
24
+ /**
25
+ * The host tools grouped by the job they do, in the order the catalog shows.
26
+ *
27
+ * Each `description` is the when-to-use line the model reads in the `get_tools`
28
+ * catalog, so it names the JOB and never a parameter: the parameters arrive with
29
+ * the schemas when the group is loaded, and restating them here would be the
30
+ * prose-instead-of-schema trade this whole arrangement exists to avoid.
31
+ */
32
+ export const HOST_TOOLSETS = [
33
+ {
34
+ name: 'ssh_remote',
35
+ description:
36
+ 'Work on a machine the user configured in the dsh-ssh plugin: list hosts, run one shell command on a host, '
37
+ + 'read a text file there, upload a local file to it, or download one from it. Use when the task names a remote host.',
38
+ tools: ['ssh_list', 'ssh_read', 'ssh_upload', 'ssh_download'],
39
+ },
40
+ {
41
+ name: 'schedule',
42
+ description:
43
+ 'Schedule work to run later without the user present: create a task with exactly one time form '
44
+ + '(after N seconds, at a timestamp, every N seconds, daily, weekly, or a cron expression), '
45
+ + 'list pending tasks, change one, or delete one.',
46
+ tools: ['schedule_create', 'schedule_list', 'schedule_update', 'schedule_delete'],
47
+ },
48
+ {
49
+ name: 'mcp_resources',
50
+ description:
51
+ 'Read MCP resources rather than MCP tools: list the resource servers, list the URI templates a server '
52
+ + 'exposes, and read one resource by URI. Use when a server publishes data as resources.',
53
+ tools: ['list_mcp_resources', 'list_mcp_resource_templates', 'read_mcp_resource'],
54
+ },
55
+ {
56
+ name: 'agent_control',
57
+ description:
58
+ 'Manage the agents this session started: fork one that inherits this conversation, list the models a '
59
+ + 'sub-agent may run on, or interrupt one that is no longer needed.',
60
+ tools: ['subagent_fork', 'list_subagent_models', 'interrupt_agent'],
61
+ },
62
+ {
63
+ name: 'goals',
64
+ description:
65
+ 'Set and steer the session goal (the objective an autonomous run works toward), leave plan mode by '
66
+ + 'presenting the plan, or change the working directory.',
67
+ tools: ['create_goal', 'exit_plan_mode', 'working_directory'],
68
+ },
69
+ {
70
+ name: 'desktop_web',
71
+ description:
72
+ 'Drive a real user interface instead of reasoning about it: operate a browser to a URL with a goal, '
73
+ + 'or operate a native desktop app or window. Use when verification needs the actual screen.',
74
+ tools: ['browser_agent', 'desktop_agent'],
75
+ },
76
+ {
77
+ name: 'workflow',
78
+ description:
79
+ 'Run one JavaScript script that fans work out across many subagents in phases and returns structured '
80
+ + 'results. Use only when the user asks for a workflow or the work is a large multi-agent fan-out.',
81
+ tools: ['workflow'],
82
+ },
83
+ {
84
+ name: 'config_sync',
85
+ description:
86
+ 'Pull or push the configuration snapshot of this DSH installation to its sync channel.',
87
+ tools: ['config_sync_pull', 'config_sync_push'],
88
+ },
89
+ {
90
+ name: 'images',
91
+ description:
92
+ 'Generate or edit an image from a prompt, and collect or cancel a generation that was still running, '
93
+ + 'by the task id it returned.',
94
+ tools: ['generate_image', 'edit_image', 'get_image_generation_task', 'cancel_image_generation_task'],
95
+ },
96
+ ];
97
+
98
+ /**
99
+ * The groups whose every tool is registered right now.
100
+ *
101
+ * A group is adopted WHOLE or not at all. A partial group would list a toolset
102
+ * whose catalog line promises tools that are not there, and the model would load
103
+ * it and receive fewer tools than the line said — the failure mode is silence
104
+ * again, which is what this arrangement is trying to leave behind.
105
+ *
106
+ * The answer depends on WHEN it is asked: plugins register during their own
107
+ * `apply`, in an order this module does not control, so the caller asks at the
108
+ * first assembly rather than at mount time.
109
+ *
110
+ * @param available - every tool name the registry currently knows.
111
+ * @returns the groups that can be adopted in full.
112
+ */
113
+ export function adoptableGroups(available) {
114
+ const names = available instanceof Set ? available : new Set(available);
115
+ return HOST_TOOLSETS.filter((group) => group.tools.every((tool) => names.has(tool)));
116
+ }
package/index.mjs ADDED
@@ -0,0 +1,465 @@
1
+ /**
2
+ * index.mjs — the `ctx.toolsets` service and the `get_tools` catalog tool.
3
+ *
4
+ * The problem this solves: every tool a plugin registers enters the global tool
5
+ * list, and its schema is paid on every request — whether or not the model ever
6
+ * calls it. A plugin with forty tools spends most of its context on definitions
7
+ * the model reads once and never uses.
8
+ *
9
+ * This plugin lets a plugin hand its tools over as a named *toolset* instead.
10
+ * Only a catalog (`get_tools`) joins the global list; a toolset's schemas are
11
+ * registered into the *calling agent's own scope layer* at the moment that
12
+ * agent asks for them, and the request assembly picks them up on the next turn.
13
+ *
14
+ * Why the agent's scope rather than the global registry: the tool list is
15
+ * assembled per request from the agent's view (`dsh-tools` resolves `schemas`
16
+ * through `view(exec.agent)`), activation is per-agent by construction, and the
17
+ * registrations unwind with the agent's fiber — a finished sub-agent leaves no
18
+ * tools behind and needs no cleanup.
19
+ *
20
+ * @module @logictan/dsh-tool-toolsets
21
+ */
22
+
23
+ import { defineTool } from '@deepseek-ai/dsh-tools';
24
+ import { HOST_TOOLSETS } from './host-toolsets.mjs';
25
+ import {
26
+ CATALOG_TOOL_NAME,
27
+ renderCatalogDescription,
28
+ validateToolset,
29
+ } from './registry.mjs';
30
+
31
+ export const name = 'tool-toolsets';
32
+
33
+ /** Registers tools (`ctx.tools`), so it must wait for that service. */
34
+ export const inject = ['tools'];
35
+
36
+ /**
37
+ * The `ctx.toolsets` service: a registry of tool groups plus per-agent
38
+ * activation.
39
+ *
40
+ * Registrations are owned by the fiber of the plugin that called `register`,
41
+ * so unloading or HMR-swapping that plugin removes its toolset — and the
42
+ * catalog line with it — without this service tracking anything.
43
+ */
44
+ export class ToolsetsService {
45
+ /**
46
+ * @param {import('@deepseek-ai/cordis').Context} ctx - the service's own context.
47
+ */
48
+ constructor(ctx) {
49
+ // `this.ctx` is rebound to whichever caller reaches the service, so it
50
+ // cannot reach `ctx.tools` — that needs the inject this plugin declared,
51
+ // which only the plugin's OWN context carries. `ownCtx` is that context.
52
+ this.ownCtx = ctx;
53
+ this.ctx = ctx;
54
+ /** @type {Map<string, {name: string, description: string, tools: readonly object[]}>} */
55
+ this.registered = new Map();
56
+ /**
57
+ * Activation state, keyed by the agent object. A WeakMap because the key
58
+ * is the agent itself: when the agent is collected, its record goes too.
59
+ * In-memory only — a restarted session simply re-loads what it needs, and
60
+ * loading twice is a no-op.
61
+ * @type {WeakMap<object, Set<string>>}
62
+ */
63
+ this.activated = new WeakMap();
64
+ /** @type {Set<string>} toolsets whose tools this service gates but does not own. */
65
+ this.adopted = new Set();
66
+ /** @type {(() => void) | undefined} */
67
+ this.catalogDispose = undefined;
68
+ }
69
+
70
+ /**
71
+ * Register one toolset. The registration (and its removal) is owned by the
72
+ * calling plugin's fiber.
73
+ *
74
+ * @param {{name: string, description: string, tools: readonly object[]}} toolset
75
+ * @returns {() => void} disposer that removes this toolset.
76
+ */
77
+ register(toolset) {
78
+ validateToolset(toolset, this.registered.values());
79
+ return this.ctx.effect(() => {
80
+ this.registered.set(toolset.name, toolset);
81
+ this.#refreshCatalog();
82
+ return () => {
83
+ this.registered.delete(toolset.name);
84
+ this.#refreshCatalog();
85
+ };
86
+ }, `toolsets.register(${toolset.name})`);
87
+ }
88
+
89
+ /**
90
+ * Registered toolsets, in registration order.
91
+ * @returns {readonly {name: string, description: string, tools: readonly object[]}[]}
92
+ */
93
+ list() {
94
+ return [...this.registered.values()];
95
+ }
96
+
97
+ /**
98
+ * Every tool name a registered toolset owns, plus the catalog tool's own name.
99
+ *
100
+ * Kept as public surface because a name-based filter elsewhere in the host
101
+ * would otherwise remove a tool an agent had just loaded — the silent-no-op
102
+ * class of failure that this repo saw twice. `dsh-tool-surface`, the plugin
103
+ * that consumed it, was deleted on 2026-11-17 (this plugin's own assembly hook
104
+ * now does that job for adopted groups), so nothing in this repository calls
105
+ * it today; a third-party filter can.
106
+ *
107
+ * @returns {Set<string>} names that a name-based filter must not withdraw.
108
+ */
109
+ protectedNames() {
110
+ const names = new Set([CATALOG_TOOL_NAME]);
111
+ for (const toolset of this.registered.values()) {
112
+ for (const tool of toolset.tools) names.add(tool.name);
113
+ }
114
+ return names;
115
+ }
116
+
117
+ /**
118
+ * Adopt already-registered tools into a toolset that this service only gates.
119
+ *
120
+ * `register` owns its tools: nothing else registered them, and activation
121
+ * registers them into the agent. Some groups cannot work that way — the host's
122
+ * own tools are registered by the host before any plugin runs, so a plugin can
123
+ * neither re-register them (the registry rejects a duplicate name) nor take
124
+ * over their execution. What it *can* do is decide when the model is told
125
+ * about them, because the assembly is a separate surface from the registry.
126
+ *
127
+ * So an adopted toolset is a claim, not an owner: the names are checked for
128
+ * existence and left exactly where they are; activation only records that this
129
+ * agent may see them. `#adopted` is what the assembly hook subtracts from an
130
+ * agent's announced list until that agent loads the toolset — loading then
131
+ * restores each schema in full, which the prose-carrying approach it replaces
132
+ * could never do.
133
+ *
134
+ * @param {{name: string, description: string, tools: readonly {name: string, execute?: unknown}[]}} toolset
135
+ * @returns {() => void} disposer that releases the claim.
136
+ */
137
+ adopt(toolset) {
138
+ validateToolset(toolset, this.registered.values(), 'adopt');
139
+ return this.ctx.effect(() => {
140
+ this.registered.set(toolset.name, toolset);
141
+ this.adopted.add(toolset.name);
142
+ this.#refreshCatalog();
143
+ return () => {
144
+ this.registered.delete(toolset.name);
145
+ this.adopted.delete(toolset.name);
146
+ this.#refreshCatalog();
147
+ };
148
+ }, `toolsets.adopt(${toolset.name})`);
149
+ }
150
+
151
+ /**
152
+ * Drop adopted groups whose tools this host does not have, and drop individual
153
+ * phantom names from the groups it keeps.
154
+ *
155
+ * The mount-time claim is deliberately blind: this plugin's own `ctx` view
156
+ * cannot see the host's tools, so it records the static list and lets the
157
+ * assembly settle which of them exist. Without this step the catalog
158
+ * advertises groups from a configuration this installation never had, and the
159
+ * failure is the worst shape available — `get_tools` happily reports the
160
+ * phantom tools as "now available", the model calls one, and the host answers
161
+ * `unknown tool "list_mcp_resources"` (measured on the isolated profile,
162
+ * 2026-11-18, which has no MCP-resource plugin installed at all).
163
+ *
164
+ * A group with no tool present is dropped whole: a catalog line for it is a
165
+ * promise this host cannot keep. A group with some tools present keeps only
166
+ * those, so a partially-installed set still works.
167
+ *
168
+ * @param present - every tool name the current assembly carries.
169
+ */
170
+ pruneToExisting(present) {
171
+ for (const [name, toolset] of [...this.registered]) {
172
+ if (!this.adopted.has(name)) continue;
173
+ const kept = toolset.tools.filter((tool) => present.has(tool.name));
174
+ if (kept.length === toolset.tools.length) continue;
175
+ this.registered.delete(name);
176
+ this.adopted.delete(name);
177
+ if (kept.length > 0) {
178
+ this.registered.set(name, { ...toolset, tools: kept });
179
+ this.adopted.add(name);
180
+ }
181
+ this.#refreshCatalog();
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Whether one toolset's tools are adopted rather than owned.
187
+ *
188
+ * @param toolsetName - the toolset to test.
189
+ * @returns true when the tools are already registered by someone else.
190
+ */
191
+ isAdopted(toolsetName) {
192
+ return this.adopted.has(toolsetName);
193
+ }
194
+
195
+ /**
196
+ * Names to subtract from one agent's announced list: every tool of every
197
+ * adopted toolset that the agent has not loaded.
198
+ *
199
+ * The assembly hook calls this per request, so the answer depends on the
200
+ * requesting agent — an adopted group is hidden from an agent that never asked
201
+ * for it and visible to one that did, without the two seeing each other's
202
+ * choice.
203
+ *
204
+ * @param agent - the scope key of the request being assembled, or undefined.
205
+ * @returns {Set<string>} names absent from that agent's tool list.
206
+ */
207
+ withheldNames(agent) {
208
+ const names = new Set();
209
+ if (this.adopted.size === 0) return names;
210
+ const loaded = agent === undefined ? undefined : this.activated.get(agent);
211
+ for (const toolsetName of this.adopted) {
212
+ if (loaded?.has(toolsetName) === true) continue;
213
+ for (const tool of this.registered.get(toolsetName).tools) names.add(tool.name);
214
+ }
215
+ return names;
216
+ }
217
+
218
+ /**
219
+ * Load one toolset into one agent's scope. Idempotent per (agent, toolset).
220
+ *
221
+ * Refuses to shadow a tool the agent already sees: a collision is almost
222
+ * always a misconfiguration (the same tool registered twice, or a toolset
223
+ * loaded after its own tools), and silently letting one definition win would
224
+ * make the effective schema depend on load order.
225
+ *
226
+ * @param {{ctx: {tools: {register: (tool: object) => () => void}}}} agent
227
+ * @param {string} toolsetName
228
+ * @returns {{toolset: string, description: string, alreadyActive: boolean, tools: {name: string, description: string}[]}}
229
+ */
230
+ activate(agent, toolsetName) {
231
+ const toolset = this.registered.get(toolsetName);
232
+ if (toolset === undefined) {
233
+ throw new Error(`toolsets.activate: unknown toolset ${JSON.stringify(toolsetName)}`);
234
+ }
235
+
236
+ let names = this.activated.get(agent);
237
+ if (names === undefined) {
238
+ names = new Set();
239
+ this.activated.set(agent, names);
240
+ }
241
+
242
+ const alreadyActive = names.has(toolsetName);
243
+ if (!alreadyActive) {
244
+ // An adopted toolset's tools are ALREADY registered (by the host), so
245
+ // registering them here would throw on the duplicate name and, worse,
246
+ // shadow the host's definition if it did not. Loading it only flips this
247
+ // agent's visibility.
248
+ if (!this.adopted.has(toolsetName)) {
249
+ const visible = new Set(this.ownCtx.tools.schemas(agent).map((schema) => schema.name));
250
+ const collisions = toolset.tools.filter((tool) => visible.has(tool.name)).map((tool) => tool.name);
251
+ if (collisions.length > 0) {
252
+ throw new Error(
253
+ `toolsets: toolset "${toolsetName}" exposes tool(s) ${collisions.map((n) => JSON.stringify(n)).join(', ')} already visible to this agent; refusing to shadow`,
254
+ );
255
+ }
256
+ for (const tool of toolset.tools) {
257
+ agent.ctx.tools.register(tool);
258
+ }
259
+ }
260
+ names.add(toolsetName);
261
+ }
262
+
263
+ return {
264
+ toolset: toolset.name,
265
+ description: toolset.description,
266
+ alreadyActive,
267
+ tools: toolset.tools.map((tool) => ({
268
+ name: tool.name,
269
+ // `?? ''` rather than a bare pass-through: an adopted tool's descriptor
270
+ // has no description here, and `undefined` in the result is what failed
271
+ // the lossless-JSON check. An empty string says the same thing legally.
272
+ description: tool.description ?? '',
273
+ })),
274
+ };
275
+ }
276
+
277
+ /**
278
+ * Replace the catalog tool with one built from the current registry.
279
+ *
280
+ * The catalog text is embedded in the tool's description, so any change to
281
+ * the set of toolsets means a new tool definition.
282
+ *
283
+ * Registered even when NO toolset exists yet. That is deliberate and it is the
284
+ * difference between saving the first request and saving nothing: the host
285
+ * reads its provider list before the assembly waterfall runs, so a catalog
286
+ * registered from inside that hook only reaches the SECOND request — and a
287
+ * first request that withholds tools without a loader is unreachable-by-design
288
+ * (measured 2026-11-17). Registering at mount time means every request,
289
+ * including the first, names the loader.
290
+ */
291
+ #refreshCatalog() {
292
+ this.catalogDispose?.();
293
+ this.catalogDispose = undefined;
294
+ this.catalogDispose = this.ownCtx.tools.register(
295
+ buildGetToolsTool({
296
+ catalog: () => this.list(),
297
+ activate: (agent, toolsetName) => this.activate(agent, toolsetName),
298
+ }),
299
+ );
300
+ }
301
+ }
302
+
303
+ /**
304
+ * Build the `get_tools` catalog tool against the current registry.
305
+ *
306
+ * @param {{catalog: () => readonly object[], activate: (agent: object, name: string) => object}} deps
307
+ * @returns {object} a `defineTool` definition ready for `ctx.tools.register`.
308
+ */
309
+ export function buildGetToolsTool(deps) {
310
+ return defineTool({
311
+ name: CATALOG_TOOL_NAME,
312
+ description: renderCatalogDescription(deps.catalog()),
313
+ parameters: {
314
+ toolset: {
315
+ type: 'string',
316
+ required: true,
317
+ description: 'Name of the toolset to load. See the toolsets listed in this tool\'s description.',
318
+ },
319
+ },
320
+ output: {
321
+ schema: {
322
+ type: 'object',
323
+ additionalProperties: false,
324
+ properties: {
325
+ toolset: { type: 'string', required: true, description: 'Loaded toolset name.' },
326
+ description: { type: 'string', required: true, description: "The toolset's when-to-use statement." },
327
+ alreadyActive: {
328
+ type: 'boolean',
329
+ required: true,
330
+ description: 'True when the toolset was already loaded for this agent.',
331
+ },
332
+ tools: {
333
+ type: 'array',
334
+ required: true,
335
+ description: 'Tools now available in the calling agent\'s tool list.',
336
+ items: {
337
+ type: 'object',
338
+ additionalProperties: false,
339
+ properties: {
340
+ name: { type: 'string', required: true },
341
+ // NOT required: an ADOPTED group records names only — its
342
+ // definitions live in the registry, which this service does not
343
+ // own. Requiring it forced `undefined` into the output, and a
344
+ // required-but-absent field is not lossless JSON, so the whole
345
+ // call failed validation (measured 2026-11-18, `mcp_resources`).
346
+ description: { type: 'string' },
347
+ },
348
+ },
349
+ },
350
+ },
351
+ },
352
+ render: (_args, value) => [
353
+ {
354
+ type: 'text',
355
+ text: value.alreadyActive
356
+ ? `Toolset "${value.toolset}" was already loaded; its tools remain available. Tools (${value.tools.length}): ${value.tools.map((tool) => tool.name).join(', ')}`
357
+ : `Loaded toolset "${value.toolset}". Tools now in your list (${value.tools.length}): ${value.tools.map((tool) => tool.name).join(', ')}`,
358
+ },
359
+ ],
360
+ },
361
+ async execute(args, exec) {
362
+ const requested = args.toolset;
363
+ const known = deps.catalog();
364
+ if (!known.some((toolset) => toolset.name === requested)) {
365
+ const { ToolArgsError } = await import('@deepseek-ai/dsh-tools');
366
+ throw new ToolArgsError([
367
+ `toolset: unknown toolset ${JSON.stringify(requested)}; known toolsets: ${known.map((t) => t.name).join(', ') || '(none)'}`,
368
+ ]);
369
+ }
370
+ const agent = exec.agent;
371
+ if (agent === undefined) {
372
+ throw new Error('get_tools: this execution carries no agent; toolsets activate per agent');
373
+ }
374
+ const activated = deps.activate(agent, requested);
375
+ return { ...activated, tools: [...activated.tools] };
376
+ },
377
+ });
378
+ }
379
+
380
+ /**
381
+ * Mount the service. Cordis class-plugin entry point.
382
+ * @param {import('@deepseek-ai/cordis').Context} ctx
383
+ */
384
+ export function apply(ctx) {
385
+ const service = new ToolsetsService(ctx);
386
+ ctx.provide('toolsets', service);
387
+
388
+ // The assembly hook is the ONLY place adoption happens, and it acts on the
389
+ // list the providers just produced.
390
+ //
391
+ // Why not claim earlier from `ctx.tools.schemas()`: this plugin's own context
392
+ // resolves `tools` to its own layer, and on a real host that view holds only
393
+ // what this plugin registered — measured in the isolated profile, where the
394
+ // post-mount claim saw 0 tools while the request carried 23. The assembly is
395
+ // the one view that is correct by construction: it IS what the model is about
396
+ // to be told, whichever layer each definition came from.
397
+ //
398
+ // Claim the host groups NOW, from the static list, without first checking that
399
+ // their tools are registered.
400
+ //
401
+ // The check is what made the first request expensive: this plugin's own
402
+ // `ctx.tools` view resolves to its own layer, and the host's tools are not in
403
+ // it — measured on an isolated profile, `schemas()` returned 0 at mount and 1
404
+ // (`get_tools` itself) a tick later, while the assembly carried 31. Waiting
405
+ // for a view that never fills meant no catalog on the first request, and the
406
+ // gate below then (correctly) refused to hide anything, so nothing was saved.
407
+ //
408
+ // Claiming blind is safe because `adopt` brings nothing with it: it records
409
+ // names and hides what the assembly actually carries. A group whose tools are
410
+ // absent from this host simply hides nothing.
411
+ for (const group of HOST_TOOLSETS) {
412
+ service.adopt({
413
+ name: group.name,
414
+ description: group.description,
415
+ tools: group.tools.map((toolName) => ({ name: toolName })),
416
+ });
417
+ }
418
+
419
+ ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
420
+ const nextAssembly = await next();
421
+ const present = new Set(nextAssembly.tools.map((tool) => tool.name));
422
+
423
+ // First settle which adopted groups this host actually has — the catalog
424
+ // must never promise a group whose tools are not here.
425
+ service.pruneToExisting(present);
426
+
427
+ // Safety gate, kept as an invariant rather than as a timing repair.
428
+ //
429
+ // The catalog is registered at MOUNT time, so on a normal boot it is already
430
+ // in this list and this line does nothing. It exists for the case where it
431
+ // is not: a request that withholds tools without naming a loader leaves the
432
+ // model with a hidden tool set and no way to ask for it. That exact shape
433
+ // was measured on an isolated profile on 2026-11-17 — 23 tools, host tools
434
+ // removed, `get_tools` absent — and it is the same silent failure as the
435
+ // `write` incident, arrived at from the other side.
436
+ //
437
+ // Costing one visible request when the loader is genuinely missing is the
438
+ // cheap side of that trade: the tools stay reachable, and the next request
439
+ // carries the catalog.
440
+ if (!present.has(CATALOG_TOOL_NAME)) return nextAssembly;
441
+
442
+ const withheld = service.withheldNames(context?.scope);
443
+ if (withheld.size === 0) return nextAssembly;
444
+ const kept = nextAssembly.tools.filter((tool) => !withheld.has(tool.name));
445
+ // Returning the original array when nothing changed keeps the cached prefix
446
+ // intact; a fresh array every step would defeat the caching this saves.
447
+ return kept.length === nextAssembly.tools.length ? nextAssembly : { ...nextAssembly, tools: kept };
448
+ });
449
+
450
+ ctx.effect(() => () => {
451
+ service.catalogDispose?.();
452
+ service.catalogDispose = undefined;
453
+ }, 'tool-toolsets: dispose catalog tool');
454
+ }
455
+
456
+ /**
457
+ * The plugin object. `inject` must live HERE rather than only as a module
458
+ * export: cordis reads `plugin.inject` off the plugin value it is handed, and a
459
+ * bare function carries no properties. A module-level `export const inject`
460
+ * satisfies the loader (which builds a plugin object from the namespace) but is
461
+ * invisible when a test — or any caller — passes the function itself, and the
462
+ * symptom is an "cannot get property tools without inject" at the first
463
+ * `ctx.tools` touch.
464
+ */
465
+ export default { name, inject, apply };
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@logictan/dsh-tool-toolsets",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "On-demand toolset loading for DeepSeek Harness: plugins register named tool groups, the model loads one through a get_tools catalog tool, and its schemas cost nothing until then.",
5
+ "type": "module",
6
+ "main": "index.mjs",
7
+ "exports": {
8
+ ".": "./index.mjs",
9
+ "./package.json": "./package.json"
10
+ },
11
+ "files": [
12
+ "index.mjs",
13
+ "registry.mjs",
14
+ "host-toolsets.mjs",
15
+ "cordis.patch.yml",
16
+ "README.md"
17
+ ],
18
+ "dsh": {
19
+ "bundle": {
20
+ "patch": "./cordis.patch.yml"
21
+ }
22
+ },
23
+ "scripts": {
24
+ "test": "node --test"
25
+ },
26
+ "peerDependencies": {
27
+ "@deepseek-ai/cordis": "^4.0.2",
28
+ "@deepseek-ai/dsh-tools": "^0.2.1-rc.2"
29
+ },
30
+ "license": "MIT",
31
+ "devDependencies": {
32
+ "@deepseek-ai/cordis": "^4.0.5",
33
+ "@deepseek-ai/dsh-tools": "^0.2.1-rc.2",
34
+ "@deepseek-ai/dsh-system-prompt": "^0.2.1-rc.2",
35
+ "@deepseek-ai/dsh-scope": "^0.2.1-rc.2"
36
+ }
6
37
  }
package/registry.mjs ADDED
@@ -0,0 +1,135 @@
1
+ /**
2
+ * registry.mjs — pure logic for the toolset registry: name rules, registration
3
+ * validation, and the model-facing catalog text.
4
+ *
5
+ * Nothing here touches a Context, a registry, or an agent. That is deliberate:
6
+ * these are the rules the plugin must obey, and keeping them as plain functions
7
+ * is what lets a test pin them without standing up a host.
8
+ *
9
+ * @module @logictan/dsh-tool-toolsets/registry
10
+ */
11
+
12
+ /** A toolset name is lowercase, starts with a letter, and fits a catalog line. */
13
+ export const TOOLSET_NAME_PATTERN = /^[a-z][a-z0-9_-]*$/;
14
+
15
+ /** The catalog tool's own name, reserved so a toolset can never claim it. */
16
+ export const CATALOG_TOOL_NAME = 'get_tools';
17
+
18
+ /** Longest a toolset name may be, so one catalog entry stays one line. */
19
+ export const MAX_TOOLSET_NAME = 64;
20
+
21
+ /** Longest a catalog line's when-to-use text may run before it is truncated. */
22
+ const MAX_CATALOG_LINE = 200;
23
+
24
+ /**
25
+ * Collapse multiline prose to one trimmed line, truncated at the catalog limit.
26
+ *
27
+ * A toolset description is written as prose and may wrap; the catalog is a list
28
+ * where each entry must occupy exactly one line, or the model reads a ragged
29
+ * block instead of a list.
30
+ *
31
+ * @param text - the description as written.
32
+ * @returns a single line, ellipsized past {@link MAX_CATALOG_LINE}.
33
+ */
34
+ export function collapseToOneLine(text) {
35
+ const collapsed = text.trim().replace(/\s+/g, ' ');
36
+ return collapsed.length > MAX_CATALOG_LINE ? `${collapsed.slice(0, MAX_CATALOG_LINE - 3)}…` : collapsed;
37
+ }
38
+
39
+ /**
40
+ * Validate one toolset against its own shape and the toolsets already present.
41
+ *
42
+ * Every rule is checked at registration, which is the earliest point the
43
+ * mistake is resolvable: by the time the model calls `get_tools` the bad entry
44
+ * is already in the catalog or has silently vanished from it.
45
+ *
46
+ * `mode` decides one rule only. A toolset this service OWNS registers its own
47
+ * tools, so each needs an `execute`; `'adopt'` claims tools that are already
48
+ * registered elsewhere, where demanding a local `execute` would reject the
49
+ * definition the host already supplied. Everything else — names, emptiness,
50
+ * collisions — is identical, because those are about the catalog rather than
51
+ * about who executes the call.
52
+ *
53
+ * @param toolset - candidate definition (`{ name, description, tools }`).
54
+ * @param existing - toolset definitions already registered, in order.
55
+ * @param {'own' | 'adopt'} [mode] - whether this toolset registers its tools.
56
+ * @throws TypeError or Error naming the first violation found.
57
+ */
58
+ export function validateToolset(toolset, existing, mode = 'own') {
59
+ if (typeof toolset !== 'object' || toolset === null) {
60
+ throw new TypeError('toolsets.register: toolset must be an object');
61
+ }
62
+ const { name, description, tools } = toolset;
63
+
64
+ if (typeof name !== 'string' || !TOOLSET_NAME_PATTERN.test(name) || name.length > MAX_TOOLSET_NAME) {
65
+ throw new Error(
66
+ `toolsets.register: name must match ${TOOLSET_NAME_PATTERN} and be at most ${MAX_TOOLSET_NAME} chars, got ${JSON.stringify(name)}`,
67
+ );
68
+ }
69
+ if (typeof description !== 'string' || description.trim() === '') {
70
+ throw new Error(`toolsets.register(${name}): description must be a non-empty string`);
71
+ }
72
+ if (!Array.isArray(tools) || tools.length === 0) {
73
+ throw new Error(`toolsets.register(${name}): tools must be a non-empty array`);
74
+ }
75
+
76
+ const seen = new Set();
77
+ for (const tool of tools) {
78
+ if (typeof tool !== 'object' || tool === null) {
79
+ throw new Error(`toolsets.register(${name}): every tool must be an object`);
80
+ }
81
+ if (typeof tool.name !== 'string' || tool.name === '') {
82
+ throw new Error(`toolsets.register(${name}): every tool needs a non-empty string name`);
83
+ }
84
+ if (tool.name === CATALOG_TOOL_NAME) {
85
+ throw new Error(`toolsets.register(${name}): tool name "${CATALOG_TOOL_NAME}" is reserved for the catalog tool`);
86
+ }
87
+ if (mode === 'own' && typeof tool.execute !== 'function') {
88
+ throw new Error(`toolsets.register(${name}): tool "${tool.name}" must declare an execute function`);
89
+ }
90
+ if (seen.has(tool.name)) {
91
+ throw new Error(`toolsets.register(${name}): duplicate tool name "${tool.name}" within the toolset`);
92
+ }
93
+ seen.add(tool.name);
94
+ }
95
+
96
+ for (const other of existing) {
97
+ if (other.name === name) {
98
+ throw new Error(`toolsets.register: toolset name "${name}" is already registered`);
99
+ }
100
+ for (const tool of tools) {
101
+ if (other.tools.some((registered) => registered.name === tool.name)) {
102
+ throw new Error(
103
+ `toolsets.register(${name}): tool name "${tool.name}" is already claimed by toolset "${other.name}"`,
104
+ );
105
+ }
106
+ }
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Render the model-facing catalog embedded in the `get_tools` description: one
112
+ * preamble paragraph, then one line per toolset (name, when-to-use, tool count).
113
+ *
114
+ * The preamble states the three things a model cannot infer from a list of
115
+ * names: how to load one, that loading takes effect next turn, and that loading
116
+ * again is harmless. Each is a real behaviour of this plugin, not advice.
117
+ *
118
+ * @param toolsets - registered definitions in registration order.
119
+ * @returns the catalog text.
120
+ */
121
+ export function renderCatalogDescription(toolsets) {
122
+ const lines = toolsets.map(
123
+ (toolset) =>
124
+ `- ${toolset.name}: ${collapseToOneLine(toolset.description)} (${toolset.tools.length} tool${toolset.tools.length === 1 ? '' : 's'})`,
125
+ );
126
+ return [
127
+ 'On-demand toolsets. Each entry below names one toolset and when to use it.',
128
+ 'Call this tool with {"toolset": "<name>"} to load that toolset\'s tools into your tool list:',
129
+ 'they become callable from your next turn and stay available for the rest of the session.',
130
+ 'Loading an already-loaded toolset is a harmless no-op that returns its current tool list.',
131
+ '',
132
+ 'Toolsets:',
133
+ ...lines,
134
+ ].join('\n');
135
+ }