@dsh-plugin/dsh-dynamic-tools 0.1.0-dev.43450988228 → 0.1.0-dev.43582542989

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/executor.js CHANGED
@@ -7,12 +7,19 @@
7
7
  * through tail disclosure, but only while the step admits them: an unadmitted
8
8
  * call is reported as an executable denial before policy and approval run.
9
9
  *
10
+ * Routes that call only declared tools need the second half: a definition the
11
+ * model loaded through `tool_load` is appended to the declaration head, so the
12
+ * model can invoke it natively. The addition is monotone — a loaded tool keeps
13
+ * its declaration for the rest of the session — so the head changes once per
14
+ * loaded tool instead of once per admission change.
15
+ *
10
16
  * @module dsh-dynamic-tools/executor
11
17
  */
12
18
  import { executeToolBatch, ToolExecutionPipeline } from '@deepseek-ai/dsh-tools/pipeline';
13
19
  import { projectToolSchema } from '@deepseek-ai/dsh-tools';
14
- import { classifyTool } from "./catalog.js";
20
+ import { classifyTool, extendCatalog, } from "./catalog.js";
15
21
  import { loadFirstReason, unavailableReason } from "./render.js";
22
+ import { selectStrategy } from "./strategy.js";
16
23
  /**
17
24
  * Executes the frozen declaration head plus admitted dynamic tools.
18
25
  */
@@ -30,6 +37,10 @@ export class StableCatalogExecutor {
30
37
  lastAdmitted = [];
31
38
  /** Names the current batch's step admits. */
32
39
  admittedNames = new Set();
40
+ /** Strategy settled by the current step's assembly, so every reader agrees. */
41
+ stepStrategy;
42
+ /** Whether the missing-load-tool diagnostic was already reported. */
43
+ loadWarningReported = false;
33
44
  constructor(ctx, agent, rules, options, state) {
34
45
  this.ctx = ctx;
35
46
  this.agent = agent;
@@ -37,16 +48,22 @@ export class StableCatalogExecutor {
37
48
  this.options = options;
38
49
  this.state = state;
39
50
  }
40
- /** Names the frozen head declares; empty before the first assembly. */
51
+ /** Names the frozen head declares, plus every loaded tool on a declare route. */
41
52
  declaredNames() {
42
- return this.catalogNames;
53
+ if (this.planStrategy() !== 'declare')
54
+ return this.catalogNames;
55
+ const names = new Set(this.catalogNames);
56
+ for (const name of this.state.definitions().keys())
57
+ names.add(name);
58
+ return names;
43
59
  }
44
60
  /** Definitions the current step admits, captured by the last assembly. */
45
61
  admittedDefinitions() {
46
62
  return this.lastAdmitted;
47
63
  }
48
64
  /**
49
- * Capture the head from the first assembly, then return it unchanged.
65
+ * Capture the head from the first assembly, then return it unchanged, plus
66
+ * every loaded definition on a declare route.
50
67
  * The first assembly's admission is exactly the declaration set the session
51
68
  * starts with, so the head matches what every later request would have
52
69
  * declared while the tool set is unchanged.
@@ -55,14 +72,12 @@ export class StableCatalogExecutor {
55
72
  */
56
73
  describe(tools) {
57
74
  this.lastAdmitted = tools;
58
- if (this.catalog === undefined) {
59
- this.catalog = Object.freeze(tools
60
- .filter(definition => classifyTool(definition.name, this.rules) === 'inline')
61
- .map(definition => Object.freeze(projectToolSchema(definition, true))));
62
- for (const schema of this.catalog)
63
- this.catalogNames.add(schema.name);
64
- }
65
- return { schemas: [...this.catalog] };
75
+ this.stepStrategy = selectStrategy(this.agent.model.current(), this.options.strategyRules);
76
+ const catalog = this.catalog ?? this.capture(tools);
77
+ if (this.stepStrategy !== 'declare')
78
+ return { schemas: [...catalog] };
79
+ this.reportMissingLoadTool();
80
+ return { schemas: this.withDeclared(catalog) };
66
81
  }
67
82
  /**
68
83
  * Execute one batch against the frozen head and the admitted dynamic set.
@@ -77,6 +92,61 @@ export class StableCatalogExecutor {
77
92
  });
78
93
  return executeToolBatch(input, pipeline, () => input.maxParallelToolCalls ?? this.options.maxParallelCalls);
79
94
  }
95
+ /**
96
+ * How this step's route receives dynamic tools.
97
+ *
98
+ * The assembly that described this step's head fixes it once. Every later
99
+ * reader in the same step — declaration names, the load requirement, the
100
+ * disclosure listener — sees that one decision, so a model switch cannot make
101
+ * the head and the announcement disagree.
102
+ * @returns the recorded strategy, or the current route's before any assembly.
103
+ */
104
+ planStrategy() {
105
+ return this.stepStrategy ?? selectStrategy(this.agent.model.current(), this.options.strategyRules);
106
+ }
107
+ /**
108
+ * Capture the declaration head from the first assembly.
109
+ * @param tools - definitions the first assembly admits.
110
+ * @returns the frozen model-facing catalog.
111
+ */
112
+ capture(tools) {
113
+ const catalog = Object.freeze(tools
114
+ .filter(definition => classifyTool(definition.name, this.rules) === 'inline')
115
+ .map(definition => Object.freeze(projectToolSchema(definition, true))));
116
+ this.catalog = catalog;
117
+ for (const schema of catalog)
118
+ this.catalogNames.add(schema.name);
119
+ return catalog;
120
+ }
121
+ /**
122
+ * Append every loaded definition to the frozen head.
123
+ * A loaded tool the step still admits uses its live definition, so argument
124
+ * validation matches the call it will run; a tool that no longer admits keeps
125
+ * the definition the model read, because the head must not shrink.
126
+ * @param catalog - frozen declaration head.
127
+ * @returns the head followed by the loaded definitions, in load order.
128
+ */
129
+ withDeclared(catalog) {
130
+ const live = new Map(this.lastAdmitted.map(definition => [definition.name, definition]));
131
+ const declared = [];
132
+ for (const [name, recorded] of this.state.definitions()) {
133
+ if (this.catalogNames.has(name))
134
+ continue;
135
+ const current = live.get(name);
136
+ declared.push(Object.freeze(current === undefined ? recorded : projectToolSchema(current, true)));
137
+ }
138
+ return extendCatalog(catalog, declared);
139
+ }
140
+ /**
141
+ * Report once that a declare route cannot load anything because the frozen
142
+ * head does not declare the load tool.
143
+ */
144
+ reportMissingLoadTool() {
145
+ if (this.loadWarningReported || this.catalogNames.has(this.options.loadToolName))
146
+ return;
147
+ this.loadWarningReported = true;
148
+ this.ctx.logger.warn('dsh-dynamic-tools: agent "%s" declares loaded tools in its tool list, but "%s" is absent from its frozen head; dynamic tools cannot be loaded in this session', this.agent.id, this.options.loadToolName);
149
+ }
80
150
  /**
81
151
  * Resolve one call name: the step's admission first, then the registered
82
152
  * definition for a name the head declares or the model was told about.
@@ -101,7 +171,7 @@ export class StableCatalogExecutor {
101
171
  */
102
172
  reject(name) {
103
173
  if (this.admittedNames.has(name)) {
104
- if (this.catalogNames.has(name) || !this.options.requireLoad)
174
+ if (this.catalogNames.has(name) || !this.requiresLoad())
105
175
  return undefined;
106
176
  return this.state.loaded().has(name) ? undefined : new Error(loadFirstReason(name));
107
177
  }
@@ -109,4 +179,8 @@ export class StableCatalogExecutor {
109
179
  return undefined;
110
180
  return new Error(unavailableReason(name, this.options.unavailableReasons[name]));
111
181
  }
182
+ /** Whether a dynamic tool must be loaded before it may run on this route. */
183
+ requiresLoad() {
184
+ return this.options.requireLoad || this.planStrategy() === 'declare';
185
+ }
112
186
  }
package/lib/fold.d.ts CHANGED
@@ -18,8 +18,8 @@ export interface FoldableMessage {
18
18
  }
19
19
  /**
20
20
  * Fold every dynamic-tools message in delivery order.
21
- * Damaged blocks are ignored: an unreadable disclosure only costs one
22
- * re-announcement, never a wrong refusal.
21
+ * A damaged block still marks its name as announced, so the model keeps seeing
22
+ * the name; the definition is re-disclosed because it was never recorded.
23
23
  *
24
24
  * @param messages - derived session messages in model order.
25
25
  * @param kind - message source kind owned by this plugin.
package/lib/fold.js CHANGED
@@ -25,37 +25,40 @@ function namesOf(body) {
25
25
  }
26
26
  function matches(text, pattern) {
27
27
  const bodies = [];
28
- pattern.lastIndex = 0;
29
28
  for (const match of text.matchAll(pattern))
30
29
  bodies.push(match[1] ?? '');
31
30
  return bodies.flatMap(namesOf);
32
31
  }
33
32
  /**
34
33
  * Read one definition block, if it is a valid schema.
34
+ *
35
+ * A malformed block is not an error here: the fold reports it as damage, so the
36
+ * next step re-announces the tool instead of trusting a wrong record.
37
+ *
35
38
  * @param json - the block body.
36
39
  * @returns the parsed schema, or undefined when the text is not a schema object.
37
40
  */
38
41
  function parseDefinition(json) {
42
+ let value;
39
43
  try {
40
- const value = JSON.parse(json);
41
- if (typeof value !== 'object' || value === null || Array.isArray(value))
42
- return undefined;
43
- const candidate = value;
44
- if (typeof candidate.name !== 'string' || typeof candidate.description !== 'string')
45
- return undefined;
46
- if (typeof candidate.parameters !== 'object' || candidate.parameters === null)
47
- return undefined;
48
- return candidate;
44
+ value = JSON.parse(json);
49
45
  }
50
- catch (error) {
51
- void error;
46
+ catch {
52
47
  return undefined;
53
48
  }
49
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
50
+ return undefined;
51
+ const candidate = value;
52
+ if (typeof candidate.name !== 'string' || typeof candidate.description !== 'string')
53
+ return undefined;
54
+ if (typeof candidate.parameters !== 'object' || candidate.parameters === null)
55
+ return undefined;
56
+ return candidate;
54
57
  }
55
58
  /**
56
59
  * Fold every dynamic-tools message in delivery order.
57
- * Damaged blocks are ignored: an unreadable disclosure only costs one
58
- * re-announcement, never a wrong refusal.
60
+ * A damaged block still marks its name as announced, so the model keeps seeing
61
+ * the name; the definition is re-disclosed because it was never recorded.
59
62
  *
60
63
  * @param messages - derived session messages in model order.
61
64
  * @param kind - message source kind owned by this plugin.
@@ -64,6 +67,8 @@ function parseDefinition(json) {
64
67
  export function foldDisclosed(messages, kind) {
65
68
  const disclosed = new Map();
66
69
  const loaded = new Set();
70
+ const definitions = new Map();
71
+ const damaged = new Set();
67
72
  for (const message of messages) {
68
73
  if (message.source?.kind !== kind)
69
74
  continue;
@@ -71,27 +76,33 @@ export function foldDisclosed(messages, kind) {
71
76
  for (const name of matches(text, REMOVED)) {
72
77
  disclosed.delete(name);
73
78
  loaded.delete(name);
79
+ definitions.delete(name);
80
+ damaged.delete(name);
74
81
  }
75
- const definitions = new Map();
76
- DEFINITION.lastIndex = 0;
82
+ const parsed = new Map();
77
83
  for (const match of text.matchAll(DEFINITION)) {
78
84
  const schema = parseDefinition(match[2] ?? '');
79
- if (schema !== undefined)
80
- definitions.set(schema.name, schema);
85
+ if (schema === undefined)
86
+ damaged.add(match[1] ?? '');
87
+ else
88
+ parsed.set(schema.name, schema);
81
89
  }
82
90
  for (const name of matches(text, ADDED)) {
83
- const schema = definitions.get(name);
91
+ const schema = parsed.get(name);
84
92
  if (schema === undefined) {
85
93
  disclosed.set(name, { signature: null, schema: false });
86
94
  continue;
87
95
  }
88
96
  disclosed.set(name, { signature: toolSignature(schema), schema: true });
89
97
  loaded.add(name);
98
+ definitions.set(name, schema);
99
+ damaged.delete(name);
90
100
  }
91
- for (const schema of definitions.values()) {
101
+ for (const schema of parsed.values()) {
92
102
  disclosed.set(schema.name, { signature: toolSignature(schema), schema: true });
93
103
  loaded.add(schema.name);
104
+ definitions.set(schema.name, schema);
94
105
  }
95
106
  }
96
- return { disclosed, loaded };
107
+ return { disclosed, loaded, definitions, damaged: [...damaged] };
97
108
  }
package/lib/index.d.ts CHANGED
@@ -45,6 +45,12 @@ export interface Config {
45
45
  /** Announce tools that stop being available. */
46
46
  announceRemovals: boolean;
47
47
  };
48
+ declareOnLoad: {
49
+ /** Model-id patterns whose routes declare loaded tools instead of reading the tail. */
50
+ models: string[];
51
+ /** Provider-route patterns restricted to that handling; empty matches every provider. */
52
+ providers: string[];
53
+ };
48
54
  /** Model-facing reason reported when a declared tool is not admitted. */
49
55
  unavailableReasons: Record<string, string>;
50
56
  /** Concurrency used when the loop supplies no limit. */
package/lib/index.js CHANGED
@@ -15,6 +15,7 @@ import z from '@deepseek-ai/schemastery';
15
15
  import { registerDisclosure } from "./disclose.js";
16
16
  import { installAgent } from "./install.js";
17
17
  import { SOURCE_KIND } from "./source.js";
18
+ import { DEFAULT_DECLARE_MODELS } from "./strategy.js";
18
19
  import { createToolLoad, TOOL_LOAD_NAME } from "./tool-load.js";
19
20
  /** Cordis plugin name. */
20
21
  export const name = '@dsh-plugin/dsh-dynamic-tools';
@@ -48,6 +49,12 @@ export const Config = z.object({
48
49
  announceRemovals: z.boolean().default(true)
49
50
  .description('Announce tools that stop being available.'),
50
51
  }).default({}),
52
+ declareOnLoad: z.object({
53
+ models: z.array(z.string()).default([...DEFAULT_DECLARE_MODELS])
54
+ .description('Model-id patterns whose routes call only declared tools; dynamic tools are loaded on demand there.'),
55
+ providers: z.array(z.string()).default([])
56
+ .description('Provider-route patterns restricted to that handling; empty matches every provider.'),
57
+ }).default({}),
51
58
  unavailableReasons: z.dict(z.string()).default({
52
59
  exit_plan_mode: 'Plan mode is not active in this session. Ask the user to switch to plan mode, then call it again.',
53
60
  }).description('Model-facing reason reported when a declared tool is not admitted.'),
@@ -60,13 +67,23 @@ export const Config = z.object({
60
67
  * @returns classification, execution, and disclosure settings.
61
68
  */
62
69
  function resolveSettings(config) {
70
+ const strategyRules = {
71
+ models: config.declareOnLoad.models,
72
+ providers: config.declareOnLoad.providers,
73
+ };
74
+ // A route that declares loaded tools needs the loader in its head, so a
75
+ // deployment cannot classify it onto the tail and lose the only path in.
76
+ const inlineNames = config.dynamic.inlineNames.includes(TOOL_LOAD_NAME)
77
+ ? config.dynamic.inlineNames
78
+ : [...config.dynamic.inlineNames, TOOL_LOAD_NAME];
63
79
  const rules = {
64
80
  dynamicNames: config.dynamic.names,
65
81
  dynamicPrefixes: config.dynamic.prefixes,
66
- inlineNames: config.dynamic.inlineNames,
82
+ inlineNames,
67
83
  };
68
84
  return {
69
85
  rules,
86
+ strategyRules,
70
87
  install: {
71
88
  sourceKind: SOURCE_KIND,
72
89
  rules,
@@ -74,6 +91,8 @@ function resolveSettings(config) {
74
91
  requireLoad: config.disclosure.requireLoad,
75
92
  unavailableReasons: config.unavailableReasons,
76
93
  maxParallelCalls: config.maxParallelCalls,
94
+ strategyRules,
95
+ loadToolName: TOOL_LOAD_NAME,
77
96
  },
78
97
  skipPresets: config.skipPresets,
79
98
  },
@@ -100,9 +119,13 @@ export function apply(ctx, config) {
100
119
  const release = new WeakMap();
101
120
  const reported = new WeakSet();
102
121
  const installOptions = { ...settings.install, executors, reported };
122
+ const strategyOf = (agent) => executors.get(agent)?.planStrategy();
123
+ const declaredNamesOf = (agent) => executors.get(agent)?.declaredNames() ?? new Set();
103
124
  ctx.effect(() => ctx.tools.register(createToolLoad(ctx, {
104
125
  sourceKind: SOURCE_KIND,
105
126
  limits: settings.disclose.limits,
127
+ strategy: strategyOf,
128
+ declaredNames: declaredNamesOf,
106
129
  })), `dsh-dynamic-tools: register ${TOOL_LOAD_NAME}`);
107
130
  ctx.on('agent/created', ({ agent }) => {
108
131
  installAgent(ctx, agent, installOptions, release);
@@ -120,7 +143,8 @@ export function apply(ctx, config) {
120
143
  }
121
144
  registerDisclosure(ctx, {
122
145
  ...settings.disclose,
123
- catalogNames: agent => executors.get(agent)?.declaredNames() ?? new Set(),
146
+ strategy: strategyOf,
147
+ catalogNames: declaredNamesOf,
124
148
  admitted: agent => executors.get(agent)?.admittedDefinitions(),
125
149
  });
126
150
  }
package/lib/install.js CHANGED
@@ -39,6 +39,7 @@ export function installAgent(ctx, agent, options, release) {
39
39
  const holder = {
40
40
  disclosed: () => currentState(agent, options.sourceKind).disclosed,
41
41
  loaded: () => currentState(agent, options.sourceKind).loaded,
42
+ definitions: () => currentState(agent, options.sourceKind).definitions,
42
43
  };
43
44
  const executor = new StableCatalogExecutor(ctx, agent, options.rules, options.executor, holder);
44
45
  try {
package/lib/render.d.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import type { ToolSchemaLike } from './catalog.ts';
8
8
  import type { DisclosureBatch } from './disclosure.ts';
9
+ import type { ToolStrategy } from './strategy.ts';
9
10
  /**
10
11
  * Keep tool prose from closing a wrapper or block early. JSON accepts the
11
12
  * resulting backslash-slash escape, so a definition body stays parseable.
@@ -21,16 +22,23 @@ export declare function escapeReminderText(text: string): string;
21
22
  export declare function oneLine(text: string): string;
22
23
  /**
23
24
  * Render one disclosure batch.
25
+ *
26
+ * An attached definition is only ever planned in `schema` mode, which the
27
+ * declare-on-load strategy never uses, so it always carries the direct-call
28
+ * instruction.
29
+ *
24
30
  * @param batch - definitions, name-only entries, and removals.
31
+ * @param strategy - how this route receives dynamic tools.
25
32
  * @returns the complete user-message text.
26
33
  */
27
- export declare function renderDisclosure(batch: DisclosureBatch): string;
34
+ export declare function renderDisclosure(batch: DisclosureBatch, strategy: ToolStrategy): string;
28
35
  /**
29
36
  * Render the definitions `tool_load` returns for one tool.
30
37
  * @param schema - the definition to deliver.
38
+ * @param strategy - how this route receives dynamic tools.
31
39
  * @returns the complete user-message text.
32
40
  */
33
- export declare function renderLoadedDefinition(schema: ToolSchemaLike): string;
41
+ export declare function renderLoadedDefinition(schema: ToolSchemaLike, strategy: ToolStrategy): string;
34
42
  /**
35
43
  * Render the model-facing result of one `tool_load` call.
36
44
  * @param loaded - names whose definitions were delivered.
package/lib/render.js CHANGED
@@ -5,6 +5,8 @@
5
5
  * @module dsh-dynamic-tools/render
6
6
  */
7
7
  const CLOSING_TAG = /<\//g;
8
+ /** What the model must do with a definition attached to the disclosure. */
9
+ const DIRECT_CALL_TRAILER = 'These tools are callable directly by name even though they are not in your tool list; match the definitions above.';
8
10
  /**
9
11
  * Keep tool prose from closing a wrapper or block early. JSON accepts the
10
12
  * resulting backslash-slash escape, so a definition body stays parseable.
@@ -24,10 +26,16 @@ export function oneLine(text) {
24
26
  }
25
27
  /**
26
28
  * Render one disclosure batch.
29
+ *
30
+ * An attached definition is only ever planned in `schema` mode, which the
31
+ * declare-on-load strategy never uses, so it always carries the direct-call
32
+ * instruction.
33
+ *
27
34
  * @param batch - definitions, name-only entries, and removals.
35
+ * @param strategy - how this route receives dynamic tools.
28
36
  * @returns the complete user-message text.
29
37
  */
30
- export function renderDisclosure(batch) {
38
+ export function renderDisclosure(batch, strategy) {
31
39
  const sections = [];
32
40
  const announced = [];
33
41
  for (const schema of batch.added)
@@ -46,11 +54,12 @@ export function renderDisclosure(batch) {
46
54
  sections.push(`<tools_removed>\n${batch.removed.map(name => `- ${name}`).join('\n')}\n</tools_removed>`);
47
55
  }
48
56
  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
- }
57
+ if (batch.added.length > 0)
58
+ trailers.push(DIRECT_CALL_TRAILER);
52
59
  if (batch.names.length > 0) {
53
- trailers.push('Call tool_load with the names under tools_load_required before calling those tools.');
60
+ trailers.push(strategy === 'declare'
61
+ ? 'Call tool_load with the names under tools_load_required — also when you need to read what a tool does. A loaded tool is added to your tool list for later steps.'
62
+ : 'Call tool_load with the names under tools_load_required before calling those tools.');
54
63
  }
55
64
  if (batch.removed.length > 0) {
56
65
  trailers.push('Removed tools are unavailable; they fail if called.');
@@ -61,10 +70,14 @@ export function renderDisclosure(batch) {
61
70
  /**
62
71
  * Render the definitions `tool_load` returns for one tool.
63
72
  * @param schema - the definition to deliver.
73
+ * @param strategy - how this route receives dynamic tools.
64
74
  * @returns the complete user-message text.
65
75
  */
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>`;
76
+ export function renderLoadedDefinition(schema, strategy) {
77
+ const trailer = strategy === 'declare'
78
+ ? 'This tool is declared in your tool list from the next step on; call it directly by name.'
79
+ : DIRECT_CALL_TRAILER;
80
+ return `<system-reminder>\n<tool_definition name="${schema.name}">\n${escapeReminderText(JSON.stringify(schema))}\n</tool_definition>\n${trailer}\n</system-reminder>`;
68
81
  }
69
82
  /**
70
83
  * Render the model-facing result of one `tool_load` call.
@@ -0,0 +1,52 @@
1
+ /**
2
+ * How one route receives dynamic tools: at the conversation tail, or declared
3
+ * in the tool list after an explicit load.
4
+ *
5
+ * OpenAI Responses routes call only the functions present in the request's
6
+ * `tools` array, so a definition delivered as conversation text is never
7
+ * invoked. Those routes need the definition loaded through `tool_load` and
8
+ * declared on the following request. Every other route reads the tail
9
+ * disclosure and calls the tool directly, which needs no declaration change.
10
+ *
11
+ * Pure module: no Harness imports, so it runs under the Node type-stripping
12
+ * loader in tests.
13
+ *
14
+ * @module dsh-dynamic-tools/strategy
15
+ */
16
+ /** How one Agent's dynamic tools reach the model. */
17
+ export type ToolStrategy = 'tail' | 'declare';
18
+ /** Route matching rules for the declare-on-load strategy. */
19
+ export interface StrategyRules {
20
+ /** Model-id patterns; an empty list matches every model. */
21
+ readonly models: readonly string[];
22
+ /** Provider-route patterns; an empty list matches every provider. */
23
+ readonly providers: readonly string[];
24
+ }
25
+ /** Model families whose routes call only tools declared in the request. */
26
+ export declare const DEFAULT_DECLARE_MODELS: readonly string[];
27
+ /**
28
+ * Match one identifier against a `*` wildcard pattern, ignoring case.
29
+ *
30
+ * The `*` is the only metacharacter; every other character is literal, so a
31
+ * model id containing `.` or `-` matches only itself. The pattern is anchored,
32
+ * so `gpt*` does not match `x-gpt-6`.
33
+ *
34
+ * @param pattern - glob-like pattern from configuration.
35
+ * @param value - model id or provider route to test.
36
+ * @returns whether the whole value matches the whole pattern.
37
+ */
38
+ export declare function patternMatches(pattern: string, value: string): boolean;
39
+ /**
40
+ * Decide how one step's route receives dynamic tools.
41
+ *
42
+ * A missing selection cannot be classified, so it keeps the tail strategy: the
43
+ * declaration head must never be guessed into a different shape.
44
+ *
45
+ * @param selection - route the step fixed for its request, when one is recorded.
46
+ * @param rules - configured declare-on-load matching rules.
47
+ * @returns `declare` only when both the model and the provider match.
48
+ */
49
+ export declare function selectStrategy(selection: {
50
+ readonly provider: string;
51
+ readonly model: string;
52
+ } | undefined, rules: StrategyRules): ToolStrategy;
@@ -0,0 +1,63 @@
1
+ /**
2
+ * How one route receives dynamic tools: at the conversation tail, or declared
3
+ * in the tool list after an explicit load.
4
+ *
5
+ * OpenAI Responses routes call only the functions present in the request's
6
+ * `tools` array, so a definition delivered as conversation text is never
7
+ * invoked. Those routes need the definition loaded through `tool_load` and
8
+ * declared on the following request. Every other route reads the tail
9
+ * disclosure and calls the tool directly, which needs no declaration change.
10
+ *
11
+ * Pure module: no Harness imports, so it runs under the Node type-stripping
12
+ * loader in tests.
13
+ *
14
+ * @module dsh-dynamic-tools/strategy
15
+ */
16
+ /** Model families whose routes call only tools declared in the request. */
17
+ export const DEFAULT_DECLARE_MODELS = Object.freeze([
18
+ 'gpt*',
19
+ 'o1*',
20
+ 'o3*',
21
+ 'o4*',
22
+ 'chatgpt*',
23
+ 'codex*',
24
+ ]);
25
+ /** Everything a pattern-match treats literally, apart from `*`. */
26
+ const REGEX_SPECIALS = /[.+?^${}()|[\]\\]/g;
27
+ /**
28
+ * Match one identifier against a `*` wildcard pattern, ignoring case.
29
+ *
30
+ * The `*` is the only metacharacter; every other character is literal, so a
31
+ * model id containing `.` or `-` matches only itself. The pattern is anchored,
32
+ * so `gpt*` does not match `x-gpt-6`.
33
+ *
34
+ * @param pattern - glob-like pattern from configuration.
35
+ * @param value - model id or provider route to test.
36
+ * @returns whether the whole value matches the whole pattern.
37
+ */
38
+ export function patternMatches(pattern, value) {
39
+ const source = pattern.replace(REGEX_SPECIALS, '\\$&').split('*').join('.*');
40
+ return new RegExp(`^${source}$`, 'i').test(value);
41
+ }
42
+ function matchesAny(patterns, value) {
43
+ return patterns.length === 0 || patterns.some(pattern => patternMatches(pattern, value));
44
+ }
45
+ /**
46
+ * Decide how one step's route receives dynamic tools.
47
+ *
48
+ * A missing selection cannot be classified, so it keeps the tail strategy: the
49
+ * declaration head must never be guessed into a different shape.
50
+ *
51
+ * @param selection - route the step fixed for its request, when one is recorded.
52
+ * @param rules - configured declare-on-load matching rules.
53
+ * @returns `declare` only when both the model and the provider match.
54
+ */
55
+ export function selectStrategy(selection, rules) {
56
+ if (selection === undefined)
57
+ return 'tail';
58
+ if (!matchesAny(rules.models, selection.model))
59
+ return 'tail';
60
+ if (!matchesAny(rules.providers, selection.provider))
61
+ return 'tail';
62
+ return 'declare';
63
+ }
@@ -1,16 +1,23 @@
1
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.
2
+ * `tool_load`: deliver the definition of a tool the conversation announced but
3
+ * the declaration head does not contain.
4
4
  *
5
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.
6
+ * tool's result and the next request carries it at the tail. On a route that
7
+ * reads only declared tool lists, the next request also declares it.
8
+ *
9
+ * Only a name the model was actually told about is served: announcing is what
10
+ * makes a definition fair game. Serving any registered name would let a guessed
11
+ * name pull an unannounced definition into the head and keep it there.
7
12
  *
8
13
  * @module dsh-dynamic-tools/tool-load
9
14
  */
10
15
  import type { Context } from '@deepseek-ai/cordis';
16
+ import type { Agent } from '@deepseek-ai/dsh-agent';
11
17
  import type { ToolDefinition } from '@deepseek-ai/dsh-tools';
12
- import type { DisclosureLimits } from './disclosure.ts';
18
+ import { type DisclosureLimits } from './disclosure.ts';
13
19
  import type { SourceKind } from './source.ts';
20
+ import type { ToolStrategy } from './strategy.ts';
14
21
  /** Names this plugin owns; a deployment cannot shadow them. */
15
22
  export declare const TOOL_LOAD_NAME = "tool_load";
16
23
  /** Settings the load tool needs at call time. */
@@ -19,11 +26,15 @@ export interface ToolLoadOptions {
19
26
  readonly sourceKind: SourceKind;
20
27
  /** Validated disclosure limits; `maxSchemaBytes` caps a loaded definition. */
21
28
  readonly limits: DisclosureLimits;
29
+ /** Strategy this step's executor settled, per installed agent. */
30
+ readonly strategy: (agent: Agent) => ToolStrategy | undefined;
31
+ /** Names the frozen head declares, per installed agent. */
32
+ readonly declaredNames: (agent: Agent) => ReadonlySet<string>;
22
33
  }
23
34
  /**
24
35
  * Create the `tool_load` definition.
25
36
  * @param ctx - plugin context, used to read the agent's visible tools.
26
- * @param options - source kind and limits.
37
+ * @param options - source kind, limits, and the agent's declaration facts.
27
38
  * @returns the unregistered definition.
28
39
  */
29
40
  export declare function createToolLoad(ctx: Context, options: ToolLoadOptions): ToolDefinition;