@dsh-plugin/dsh-dynamic-tools 0.0.0-stage → 0.0.1

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.
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Per-Agent installation of the frozen-catalog executor.
3
+ *
4
+ * Every installation is one plugin-owned effect, so unload releases exactly the
5
+ * registrations this plugin made, and an agent's disposal releases its executor
6
+ * immediately instead of retaining it until the plugin unloads. A scope that
7
+ * already selected another executor keeps it: this plugin then stays out of the
8
+ * declaration path instead of replacing that selection.
9
+ *
10
+ * @module dsh-dynamic-tools/install
11
+ */
12
+ import type { Context } from '@deepseek-ai/cordis';
13
+ import type { Agent } from '@deepseek-ai/dsh-agent';
14
+ import type { ClassificationRules } from './catalog.ts';
15
+ import { StableCatalogExecutor, type ExecutorOptions } from './executor.ts';
16
+ import type { SourceKind } from './source.ts';
17
+ /** Settings shared by every installed agent. */
18
+ export interface InstallOptions {
19
+ /** Message source kind owned by this plugin. */
20
+ readonly sourceKind: SourceKind;
21
+ /** Classification rules for the frozen head. */
22
+ readonly rules: ClassificationRules;
23
+ /** Execution settings. */
24
+ readonly executor: ExecutorOptions;
25
+ /** Preset ids this plugin leaves alone. */
26
+ readonly skipPresets: readonly string[];
27
+ /** Executors by agent, shared with the disclosure listener. */
28
+ readonly executors: WeakMap<Agent, StableCatalogExecutor>;
29
+ /** Agents already reported, so each diagnostic appears once. */
30
+ readonly reported: WeakSet<Agent>;
31
+ }
32
+ /**
33
+ * Install the frozen-catalog executor for one agent.
34
+ * @param ctx - plugin context that owns the registration.
35
+ * @param agent - agent whose scope receives the executor.
36
+ * @param options - installation settings.
37
+ * @param release - disposer registry, so agent disposal can release the executor.
38
+ */
39
+ export declare function installAgent(ctx: Context, agent: Agent, options: InstallOptions, release: WeakMap<Agent, () => void>): void;
package/lib/install.js ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Per-Agent installation of the frozen-catalog executor.
3
+ *
4
+ * Every installation is one plugin-owned effect, so unload releases exactly the
5
+ * registrations this plugin made, and an agent's disposal releases its executor
6
+ * immediately instead of retaining it until the plugin unloads. A scope that
7
+ * already selected another executor keeps it: this plugin then stays out of the
8
+ * declaration path instead of replacing that selection.
9
+ *
10
+ * @module dsh-dynamic-tools/install
11
+ */
12
+ import { StableCatalogExecutor } from "./executor.js";
13
+ import { currentState } from "./disclose.js";
14
+ /** Read the preset id an agent runs under, when a registry is composed. */
15
+ function presetOf(ctx, agent) {
16
+ const registry = ctx.get('agentPresets');
17
+ if (registry === undefined)
18
+ return undefined;
19
+ return registry.presetForSession(agent.session) ?? undefined;
20
+ }
21
+ /**
22
+ * Install the frozen-catalog executor for one agent.
23
+ * @param ctx - plugin context that owns the registration.
24
+ * @param agent - agent whose scope receives the executor.
25
+ * @param options - installation settings.
26
+ * @param release - disposer registry, so agent disposal can release the executor.
27
+ */
28
+ export function installAgent(ctx, agent, options, release) {
29
+ if (options.executors.has(agent))
30
+ return;
31
+ const preset = presetOf(ctx, agent);
32
+ if (preset !== undefined && options.skipPresets.includes(preset)) {
33
+ if (!options.reported.has(agent)) {
34
+ options.reported.add(agent);
35
+ ctx.logger.info('dsh-dynamic-tools: leaving preset "%s" alone; tool declarations stay as composed', preset);
36
+ }
37
+ return;
38
+ }
39
+ const holder = {
40
+ disclosed: () => currentState(agent, options.sourceKind).disclosed,
41
+ loaded: () => currentState(agent, options.sourceKind).loaded,
42
+ };
43
+ const executor = new StableCatalogExecutor(ctx, agent, options.rules, options.executor, holder);
44
+ try {
45
+ const dispose = ctx.effect(() => {
46
+ const uninstall = agent.ctx.tools.setExecutor(executor);
47
+ options.executors.set(agent, executor);
48
+ return () => {
49
+ options.executors.delete(agent);
50
+ uninstall();
51
+ };
52
+ }, 'dsh-dynamic-tools: install frozen-catalog executor');
53
+ let released = false;
54
+ release.set(agent, () => {
55
+ if (released)
56
+ return;
57
+ released = true;
58
+ release.delete(agent);
59
+ dispose();
60
+ });
61
+ }
62
+ catch (error) {
63
+ if (options.reported.has(agent))
64
+ return;
65
+ options.reported.add(agent);
66
+ ctx.logger.warn('dsh-dynamic-tools: cannot install for agent "%s": %o', agent.id, error);
67
+ }
68
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Model-visible text for disclosure messages and the tool-load notice.
3
+ * The tags are the fold's input, so both sides change together.
4
+ *
5
+ * @module dsh-dynamic-tools/render
6
+ */
7
+ import type { ToolSchemaLike } from './catalog.ts';
8
+ import type { DisclosureBatch } from './disclosure.ts';
9
+ /**
10
+ * Keep tool prose from closing a wrapper or block early. JSON accepts the
11
+ * resulting backslash-slash escape, so a definition body stays parseable.
12
+ * @param text - arbitrary tool-authored text.
13
+ * @returns the text with every closing tag escape neutralized.
14
+ */
15
+ export declare function escapeReminderText(text: string): string;
16
+ /**
17
+ * Collapse text to one announcement line, keeping the name list parseable.
18
+ * @param text - arbitrary tool-authored text.
19
+ * @returns the text with line breaks and repeated whitespace collapsed.
20
+ */
21
+ export declare function oneLine(text: string): string;
22
+ /**
23
+ * Render one disclosure batch.
24
+ * @param batch - definitions, name-only entries, and removals.
25
+ * @returns the complete user-message text.
26
+ */
27
+ export declare function renderDisclosure(batch: DisclosureBatch): string;
28
+ /**
29
+ * Render the definitions `tool_load` returns for one tool.
30
+ * @param schema - the definition to deliver.
31
+ * @returns the complete user-message text.
32
+ */
33
+ export declare function renderLoadedDefinition(schema: ToolSchemaLike): string;
34
+ /**
35
+ * Render the model-facing result of one `tool_load` call.
36
+ * @param loaded - names whose definitions were delivered.
37
+ * @param alreadyAvailable - names that are declared in the tool list already.
38
+ * @param unavailable - names no longer registered or not admitted.
39
+ * @param tooLarge - names too large to deliver.
40
+ * @returns plain-text result content.
41
+ */
42
+ export declare function renderLoadResult(loaded: readonly string[], alreadyAvailable: readonly string[], unavailable: readonly string[], tooLarge: readonly string[]): string;
43
+ /**
44
+ * The reason reported when a catalog tool is not admitted for this step.
45
+ * @param name - tool name the model called.
46
+ * @param configured - configured reason for this name, when any.
47
+ * @returns the model-facing denial reason.
48
+ */
49
+ export declare function unavailableReason(name: string, configured: string | undefined): string;
50
+ /**
51
+ * The reason reported when a loaded-on-demand tool has not been loaded.
52
+ * @param name - tool name the model called.
53
+ * @returns the model-facing denial reason.
54
+ */
55
+ export declare function loadFirstReason(name: string): string;
package/lib/render.js ADDED
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Model-visible text for disclosure messages and the tool-load notice.
3
+ * The tags are the fold's input, so both sides change together.
4
+ *
5
+ * @module dsh-dynamic-tools/render
6
+ */
7
+ const CLOSING_TAG = /<\//g;
8
+ /**
9
+ * Keep tool prose from closing a wrapper or block early. JSON accepts the
10
+ * resulting backslash-slash escape, so a definition body stays parseable.
11
+ * @param text - arbitrary tool-authored text.
12
+ * @returns the text with every closing tag escape neutralized.
13
+ */
14
+ export function escapeReminderText(text) {
15
+ return text.replace(CLOSING_TAG, '<\\/');
16
+ }
17
+ /**
18
+ * Collapse text to one announcement line, keeping the name list parseable.
19
+ * @param text - arbitrary tool-authored text.
20
+ * @returns the text with line breaks and repeated whitespace collapsed.
21
+ */
22
+ export function oneLine(text) {
23
+ return text.replace(/\s+/g, ' ').trim();
24
+ }
25
+ /**
26
+ * Render one disclosure batch.
27
+ * @param batch - definitions, name-only entries, and removals.
28
+ * @returns the complete user-message text.
29
+ */
30
+ export function renderDisclosure(batch) {
31
+ const sections = [];
32
+ const announced = [];
33
+ for (const schema of batch.added)
34
+ announced.push(`- ${schema.name}: ${oneLine(escapeReminderText(schema.description))}`);
35
+ for (const name of batch.names)
36
+ announced.push(`- ${name}`);
37
+ if (announced.length > 0)
38
+ sections.push(`<tools_added>\n${announced.join('\n')}\n</tools_added>`);
39
+ for (const schema of batch.added) {
40
+ sections.push(`<tool_definition name="${schema.name}">\n${escapeReminderText(JSON.stringify(schema))}\n</tool_definition>`);
41
+ }
42
+ if (batch.names.length > 0) {
43
+ sections.push(`<tools_load_required>\n${batch.names.map(name => `- ${name}`).join('\n')}\n</tools_load_required>`);
44
+ }
45
+ if (batch.removed.length > 0) {
46
+ sections.push(`<tools_removed>\n${batch.removed.map(name => `- ${name}`).join('\n')}\n</tools_removed>`);
47
+ }
48
+ const trailers = [];
49
+ if (batch.added.length > 0) {
50
+ trailers.push('These tools are callable directly by name even though they are not in your tool list; match the definitions above.');
51
+ }
52
+ if (batch.names.length > 0) {
53
+ trailers.push('Call tool_load with the names under tools_load_required before calling those tools.');
54
+ }
55
+ if (batch.removed.length > 0) {
56
+ trailers.push('Removed tools are unavailable; they fail if called.');
57
+ }
58
+ sections.push(...trailers);
59
+ return `<system-reminder>\n${sections.join('\n\n')}\n</system-reminder>`;
60
+ }
61
+ /**
62
+ * Render the definitions `tool_load` returns for one tool.
63
+ * @param schema - the definition to deliver.
64
+ * @returns the complete user-message text.
65
+ */
66
+ export function renderLoadedDefinition(schema) {
67
+ return `<system-reminder>\n<tool_definition name="${schema.name}">\n${escapeReminderText(JSON.stringify(schema))}\n</tool_definition>\nThese tools are callable directly by name even though they are not in your tool list; match the definitions above.\n</system-reminder>`;
68
+ }
69
+ /**
70
+ * Render the model-facing result of one `tool_load` call.
71
+ * @param loaded - names whose definitions were delivered.
72
+ * @param alreadyAvailable - names that are declared in the tool list already.
73
+ * @param unavailable - names no longer registered or not admitted.
74
+ * @param tooLarge - names too large to deliver.
75
+ * @returns plain-text result content.
76
+ */
77
+ export function renderLoadResult(loaded, alreadyAvailable, unavailable, tooLarge) {
78
+ const lines = [];
79
+ if (loaded.length > 0)
80
+ lines.push(`Loaded: ${loaded.join(', ')}`);
81
+ if (alreadyAvailable.length > 0)
82
+ lines.push(`Already available: ${alreadyAvailable.join(', ')}`);
83
+ if (unavailable.length > 0)
84
+ lines.push(`Unavailable: ${unavailable.join(', ')}`);
85
+ if (tooLarge.length > 0)
86
+ lines.push(`Definition too large to load: ${tooLarge.join(', ')}`);
87
+ if (lines.length === 0)
88
+ return 'No tool names were supplied.';
89
+ return lines.join('\n');
90
+ }
91
+ /**
92
+ * The reason reported when a catalog tool is not admitted for this step.
93
+ * @param name - tool name the model called.
94
+ * @param configured - configured reason for this name, when any.
95
+ * @returns the model-facing denial reason.
96
+ */
97
+ export function unavailableReason(name, configured) {
98
+ return configured ?? `Tool "${name}" is registered but not available in the current session state; ask the user to enable it, then retry.`;
99
+ }
100
+ /**
101
+ * The reason reported when a loaded-on-demand tool has not been loaded.
102
+ * @param name - tool name the model called.
103
+ * @returns the model-facing denial reason.
104
+ */
105
+ export function loadFirstReason(name) {
106
+ return `Tool "${name}" is available but its definition is not loaded. Call tool_load with {"names":["${name}"]} first, then call it again.`;
107
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The message source this plugin records, declared once so every module and the
3
+ * fold agree on it.
4
+ *
5
+ * @module dsh-dynamic-tools/source
6
+ */
7
+ import type { ContextFormed } from '@deepseek-ai/dsh-llm';
8
+ declare module '@deepseek-ai/dsh-llm' {
9
+ interface MessageSourceMap {
10
+ 'dynamic-tools': {
11
+ kind: 'dynamic-tools';
12
+ } & ContextFormed;
13
+ }
14
+ }
15
+ /** Message source kind used for every disclosure and loaded definition. */
16
+ export declare const SOURCE_KIND: "dynamic-tools";
17
+ /** Type of {@link SOURCE_KIND}. */
18
+ export type SourceKind = typeof SOURCE_KIND;
package/lib/source.js ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The message source this plugin records, declared once so every module and the
3
+ * fold agree on it.
4
+ *
5
+ * @module dsh-dynamic-tools/source
6
+ */
7
+ /** Message source kind used for every disclosure and loaded definition. */
8
+ export const SOURCE_KIND = 'dynamic-tools';
@@ -0,0 +1,29 @@
1
+ /**
2
+ * `tool_load`: deliver the definition of a tool the model was told about but
3
+ * whose schema it cannot see in the declaration head.
4
+ *
5
+ * The definition rides `exec.deferContext()`, so the loop logs it after this
6
+ * tool's result and the next request carries it at the tail.
7
+ *
8
+ * @module dsh-dynamic-tools/tool-load
9
+ */
10
+ import type { Context } from '@deepseek-ai/cordis';
11
+ import type { ToolDefinition } from '@deepseek-ai/dsh-tools';
12
+ import type { DisclosureLimits } from './disclosure.ts';
13
+ import type { SourceKind } from './source.ts';
14
+ /** Names this plugin owns; a deployment cannot shadow them. */
15
+ export declare const TOOL_LOAD_NAME = "tool_load";
16
+ /** Settings the load tool needs at call time. */
17
+ export interface ToolLoadOptions {
18
+ /** Message source kind owned by this plugin. */
19
+ readonly sourceKind: SourceKind;
20
+ /** Validated disclosure limits; `maxSchemaBytes` caps a loaded definition. */
21
+ readonly limits: DisclosureLimits;
22
+ }
23
+ /**
24
+ * Create the `tool_load` definition.
25
+ * @param ctx - plugin context, used to read the agent's visible tools.
26
+ * @param options - source kind and limits.
27
+ * @returns the unregistered definition.
28
+ */
29
+ export declare function createToolLoad(ctx: Context, options: ToolLoadOptions): ToolDefinition;
@@ -0,0 +1,91 @@
1
+ /**
2
+ * `tool_load`: deliver the definition of a tool the model was told about but
3
+ * whose schema it cannot see in the declaration head.
4
+ *
5
+ * The definition rides `exec.deferContext()`, so the loop logs it after this
6
+ * tool's result and the next request carries it at the tail.
7
+ *
8
+ * @module dsh-dynamic-tools/tool-load
9
+ */
10
+ import { createUserMessage } from '@deepseek-ai/dsh-llm';
11
+ import { defineTool, projectToolSchema, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools';
12
+ import { schemaBytes } from "./catalog.js";
13
+ import { renderLoadedDefinition, renderLoadResult } from "./render.js";
14
+ import { currentState, storeState } from "./disclose.js";
15
+ /** Names this plugin owns; a deployment cannot shadow them. */
16
+ export const TOOL_LOAD_NAME = 'tool_load';
17
+ /**
18
+ * Create the `tool_load` definition.
19
+ * @param ctx - plugin context, used to read the agent's visible tools.
20
+ * @param options - source kind and limits.
21
+ * @returns the unregistered definition.
22
+ */
23
+ export function createToolLoad(ctx, options) {
24
+ return defineTool({
25
+ name: TOOL_LOAD_NAME,
26
+ description: 'Read the full definition of tools that are announced in this conversation but absent from your tool list. Pass their exact names. Definitions arrive as a user message after this result; call the tool in a later step.',
27
+ parameters: {
28
+ names: {
29
+ type: 'array',
30
+ items: { type: 'string' },
31
+ required: true,
32
+ description: 'Exact tool names taken from the latest <tools_added> or <tools_load_required> announcement.',
33
+ },
34
+ },
35
+ output: {
36
+ schema: {
37
+ type: 'object',
38
+ additionalProperties: false,
39
+ properties: {
40
+ loaded: { type: 'array', items: { type: 'string' }, required: true },
41
+ alreadyAvailable: { type: 'array', items: { type: 'string' }, required: true },
42
+ unavailable: { type: 'array', items: { type: 'string' }, required: true },
43
+ tooLarge: { type: 'array', items: { type: 'string' }, required: true },
44
+ },
45
+ },
46
+ render: (_args, value) => [{
47
+ type: 'text',
48
+ text: renderLoadResult(value.loaded, value.alreadyAvailable, value.unavailable, value.tooLarge),
49
+ }],
50
+ },
51
+ async execute(args, exec) {
52
+ exec.signal.throwIfAborted();
53
+ const agent = exec.agent;
54
+ if (agent === undefined) {
55
+ throw new ToolContextUnavailableError(`${TOOL_LOAD_NAME} requires a calling Agent`);
56
+ }
57
+ const loaded = [];
58
+ const alreadyAvailable = [];
59
+ const unavailable = [];
60
+ const tooLarge = [];
61
+ const definitions = new Map(ctx.tools.definitions(agent).map(definition => [definition.name, definition]));
62
+ const state = currentState(agent, options.sourceKind);
63
+ const nextLoaded = new Set(state.loaded);
64
+ const wanted = [...new Set(args.names.map(name => name.trim()).filter(name => name.length > 0))];
65
+ for (const name of wanted) {
66
+ const definition = definitions.get(name);
67
+ if (definition === undefined) {
68
+ unavailable.push(name);
69
+ continue;
70
+ }
71
+ const schema = projectToolSchema(definition, true);
72
+ if (schemaBytes(schema) > options.limits.maxSchemaBytes) {
73
+ tooLarge.push(name);
74
+ continue;
75
+ }
76
+ if (!state.disclosed.has(name))
77
+ alreadyAvailable.push(name);
78
+ else
79
+ loaded.push(name);
80
+ nextLoaded.add(name);
81
+ exec.deferContext(createUserMessage({
82
+ content: [{ type: 'text', text: renderLoadedDefinition(schema) }],
83
+ source: { kind: options.sourceKind, form: 'catalog' },
84
+ }));
85
+ }
86
+ storeState(agent, { disclosed: state.disclosed, loaded: nextLoaded });
87
+ return { loaded, alreadyAvailable, unavailable, tooLarge };
88
+ },
89
+ isConcurrencySafe: () => false,
90
+ });
91
+ }
package/locale/en.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "Dynamic tools",
4
+ "description": "Freezes the request tool list after a session's first step and delivers later tools as trailing context, so a mid-conversation tool change no longer rewrites the cached prompt prefix. Applies to the native tool executor; tools are classified by name, and a tool that the step does not admit fails with an actionable error instead of running.",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "动态工具加载",
4
+ "description": "会话首步之后冻结请求中的工具列表,之后出现的工具以对话尾部消息下发,中途的工具变化不再重写已缓存的前缀。仅作用于原生工具执行器;按工具名分类,未在本步准入的工具会得到可执行的错误而不是被执行。",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/package.json CHANGED
@@ -1,6 +1,75 @@
1
- {
2
- "name": "@dsh-plugin/dsh-dynamic-tools",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@dsh-plugin/dsh-dynamic-tools",
3
+ "version": "0.0.1",
4
+ "type": "module",
5
+ "description": "Keeps the tool declaration head of a request frozen and discloses tools registered later as trailing context, so mid-conversation tool changes stop invalidating the cached prompt prefix.",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./lib/index.d.ts",
9
+ "default": "./lib/index.js"
10
+ },
11
+ "./locale/*.json": "./locale/*.json",
12
+ "./icon": "./icon.svg"
13
+ },
14
+ "files": [
15
+ "lib/**/*.js",
16
+ "lib/**/*.d.ts",
17
+ "src/**/*.ts",
18
+ "cordis.patch.yml",
19
+ "locale/*.json",
20
+ "docs",
21
+ "icon.svg",
22
+ "README.md",
23
+ "LICENSE"
24
+ ],
25
+ "scripts": {
26
+ "build": "tsc -p tsconfig.json",
27
+ "typecheck": "tsc -p tsconfig.json --noEmit",
28
+ "test": "node --test \"tests/*.test.ts\"",
29
+ "prepack": "npm run build"
30
+ },
31
+ "license": "LGPL-3.0-only",
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/dsh-plugins/dsh-dynamic-tools.git"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "keywords": [
40
+ "deepseek-harness",
41
+ "dsh",
42
+ "plugin",
43
+ "tools",
44
+ "prompt-cache"
45
+ ],
46
+ "peerDependencies": {
47
+ "@deepseek-ai/cordis": "~4.1.0",
48
+ "@deepseek-ai/dsh-agent": "^0.2.2-rc.2",
49
+ "@deepseek-ai/dsh-llm": "^0.2.2-rc.2",
50
+ "@deepseek-ai/dsh-scope": "^0.2.2-rc.2",
51
+ "@deepseek-ai/dsh-session": "^0.2.2-rc.2",
52
+ "@deepseek-ai/dsh-system-prompt": "^0.2.2-rc.2",
53
+ "@deepseek-ai/dsh-tools": "^0.2.2-rc.2",
54
+ "@deepseek-ai/schemastery": "~3.19.0"
55
+ },
56
+ "devDependencies": {
57
+ "@deepseek-ai/cordis": "4.1.0",
58
+ "@deepseek-ai/dsh-agent": "0.2.2-rc.2",
59
+ "@deepseek-ai/dsh-llm": "0.2.2-rc.2",
60
+ "@deepseek-ai/dsh-scope": "0.2.2-rc.2",
61
+ "@deepseek-ai/dsh-session": "0.2.2-rc.2",
62
+ "@deepseek-ai/dsh-system-prompt": "0.2.2-rc.2",
63
+ "@deepseek-ai/dsh-tools": "0.2.2-rc.2",
64
+ "@deepseek-ai/schemastery": "3.19.0",
65
+ "typescript": "5.9.3"
66
+ },
67
+ "engines": {
68
+ "dsh": ">=0.2.2-rc.2 <0.3.0"
69
+ },
70
+ "dsh": {
71
+ "bundle": {
72
+ "patch": "./cordis.patch.yml"
73
+ }
74
+ }
75
+ }
package/src/catalog.ts ADDED
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Pure classification and signature helpers for the frozen tool catalog.
3
+ * No Harness imports: these run under the Node type-stripping loader in tests.
4
+ *
5
+ * @module dsh-dynamic-tools/catalog
6
+ */
7
+
8
+ /** Model-facing tool schema fields this plugin reads without Harness types. */
9
+ export interface ToolSchemaLike {
10
+ readonly name: string
11
+ readonly description: string
12
+ readonly parameters: Record<string, unknown>
13
+ }
14
+
15
+ /** How one registered tool name is disclosed. */
16
+ export type ToolClass = 'inline' | 'dynamic'
17
+
18
+ /** Rules that decide which tools belong in the frozen declaration head. */
19
+ export interface ClassificationRules {
20
+ /** Exact names that never enter the frozen catalog. */
21
+ readonly dynamicNames: readonly string[]
22
+ /** Name prefixes that never enter the frozen catalog. */
23
+ readonly dynamicPrefixes: readonly string[]
24
+ /** Exact names forced into the catalog, overriding the rules above. */
25
+ readonly inlineNames: readonly string[]
26
+ }
27
+
28
+ /**
29
+ * Decide how one tool name is disclosed.
30
+ * @param name - registered tool name.
31
+ * @param rules - configured classification rules.
32
+ * @returns `inline` for the frozen catalog, `dynamic` for tail disclosure.
33
+ */
34
+ export function classifyTool(name: string, rules: ClassificationRules): ToolClass {
35
+ if (rules.inlineNames.includes(name)) return 'inline'
36
+ if (rules.dynamicNames.includes(name)) return 'dynamic'
37
+ if (rules.dynamicPrefixes.some(prefix => name.startsWith(prefix))) return 'dynamic'
38
+ return 'inline'
39
+ }
40
+
41
+ /** Deterministic JSON text with object keys sorted, so equal schemas compare equal. */
42
+ function stableJson(value: unknown): string {
43
+ if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null'
44
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`
45
+ const entries = Object.keys(value as Record<string, unknown>).sort()
46
+ .map(key => `${JSON.stringify(key)}:${stableJson((value as Record<string, unknown>)[key])}`)
47
+ return `{${entries.join(',')}}`
48
+ }
49
+
50
+ /**
51
+ * Identity of one tool definition for change detection.
52
+ * Same-name registrations that differ only in key order share a signature.
53
+ * @param schema - model-facing schema of the definition.
54
+ * @returns a comparable signature string.
55
+ */
56
+ export function toolSignature(schema: ToolSchemaLike): string {
57
+ return `${schema.name}\u0000${schema.description}\u0000${stableJson(schema.parameters)}`
58
+ }
59
+
60
+ /**
61
+ * Split the registered definitions into the frozen catalog and tail disclosures.
62
+ * @param definitions - every definition visible to the agent at capture time.
63
+ * @param rules - configured classification rules.
64
+ * @returns inline schemas for the head and configured dynamic schemas.
65
+ */
66
+ export function splitCatalog(
67
+ definitions: readonly ToolSchemaLike[],
68
+ rules: ClassificationRules,
69
+ ): { inline: ToolSchemaLike[], dynamic: ToolSchemaLike[] } {
70
+ const inline: ToolSchemaLike[] = []
71
+ const dynamic: ToolSchemaLike[] = []
72
+ for (const definition of definitions) {
73
+ if (classifyTool(definition.name, rules) === 'inline') inline.push(definition)
74
+ else dynamic.push(definition)
75
+ }
76
+ return { inline, dynamic }
77
+ }
78
+
79
+ const encoder = new TextEncoder()
80
+
81
+ /**
82
+ * JSON size of one definition as it would be disclosed.
83
+ * @param schema - model-facing schema of the definition.
84
+ * @returns UTF-8 byte length of its JSON encoding.
85
+ */
86
+ export function schemaBytes(schema: ToolSchemaLike): number {
87
+ return encoder.encode(JSON.stringify(schema)).length
88
+ }