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

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/tool-load.js CHANGED
@@ -1,15 +1,21 @@
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 { createUserMessage } from '@deepseek-ai/dsh-llm';
11
16
  import { defineTool, projectToolSchema, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools';
12
17
  import { schemaBytes } from "./catalog.js";
18
+ import { withDefinition } from "./disclosure.js";
13
19
  import { renderLoadedDefinition, renderLoadResult } from "./render.js";
14
20
  import { currentState, storeState } from "./disclose.js";
15
21
  /** Names this plugin owns; a deployment cannot shadow them. */
@@ -17,13 +23,13 @@ export const TOOL_LOAD_NAME = 'tool_load';
17
23
  /**
18
24
  * Create the `tool_load` definition.
19
25
  * @param ctx - plugin context, used to read the agent's visible tools.
20
- * @param options - source kind and limits.
26
+ * @param options - source kind, limits, and the agent's declaration facts.
21
27
  * @returns the unregistered definition.
22
28
  */
23
29
  export function createToolLoad(ctx, options) {
24
30
  return defineTool({
25
31
  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.',
32
+ 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; on a route that loads tools on demand the tool is declared in your tool list from the next step on.',
27
33
  parameters: {
28
34
  names: {
29
35
  type: 'array',
@@ -54,13 +60,14 @@ export function createToolLoad(ctx, options) {
54
60
  if (agent === undefined) {
55
61
  throw new ToolContextUnavailableError(`${TOOL_LOAD_NAME} requires a calling Agent`);
56
62
  }
63
+ const strategy = options.strategy(agent) ?? 'tail';
64
+ const declared = options.declaredNames(agent);
57
65
  const loaded = [];
58
66
  const alreadyAvailable = [];
59
67
  const unavailable = [];
60
68
  const tooLarge = [];
61
69
  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);
70
+ let state = currentState(agent, options.sourceKind);
64
71
  const wanted = [...new Set(args.names.map(name => name.trim()).filter(name => name.length > 0))];
65
72
  for (const name of wanted) {
66
73
  const definition = definitions.get(name);
@@ -68,22 +75,30 @@ export function createToolLoad(ctx, options) {
68
75
  unavailable.push(name);
69
76
  continue;
70
77
  }
78
+ if (declared.has(name)) {
79
+ // The definition is already in the tool list; repeating it adds nothing.
80
+ alreadyAvailable.push(name);
81
+ continue;
82
+ }
83
+ if (!state.disclosed.has(name)) {
84
+ // A registered name nobody announced: bringing it in would declare a
85
+ // tool the model was never told about.
86
+ unavailable.push(name);
87
+ continue;
88
+ }
71
89
  const schema = projectToolSchema(definition, true);
72
90
  if (schemaBytes(schema) > options.limits.maxSchemaBytes) {
73
91
  tooLarge.push(name);
74
92
  continue;
75
93
  }
76
- if (!state.disclosed.has(name))
77
- alreadyAvailable.push(name);
78
- else
79
- loaded.push(name);
80
- nextLoaded.add(name);
94
+ loaded.push(name);
95
+ state = withDefinition(state, schema);
81
96
  exec.deferContext(createUserMessage({
82
- content: [{ type: 'text', text: renderLoadedDefinition(schema) }],
97
+ content: [{ type: 'text', text: renderLoadedDefinition(schema, strategy) }],
83
98
  source: { kind: options.sourceKind, form: 'catalog' },
84
99
  }));
85
100
  }
86
- storeState(agent, { disclosed: state.disclosed, loaded: nextLoaded });
101
+ storeState(agent, state);
87
102
  return { loaded, alreadyAvailable, unavailable, tooLarge };
88
103
  },
89
104
  isConcurrencySafe: () => false,
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@dsh-plugin/dsh-dynamic-tools",
3
- "version": "0.1.0-dev.43450988228",
3
+ "version": "0.1.0-dev.43611140243",
4
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.",
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; routes that call only declared tools load those definitions on demand and get them declared instead.",
6
6
  "exports": {
7
7
  ".": {
8
8
  "types": "./lib/index.d.ts",
package/src/catalog.ts CHANGED
@@ -76,6 +76,30 @@ export function splitCatalog(
76
76
  return { inline, dynamic }
77
77
  }
78
78
 
79
+ /**
80
+ * Append declared definitions to the frozen catalog, keeping both orders.
81
+ *
82
+ * A name the catalog already declares keeps its catalog position and
83
+ * definition: the head must not move because a tool became loadable.
84
+ *
85
+ * @param catalog - frozen declaration head.
86
+ * @param declared - definitions loaded on demand, in load order.
87
+ * @returns the head followed by every declared name it does not declare.
88
+ */
89
+ export function extendCatalog(
90
+ catalog: readonly ToolSchemaLike[],
91
+ declared: readonly ToolSchemaLike[],
92
+ ): ToolSchemaLike[] {
93
+ const names = new Set(catalog.map(schema => schema.name))
94
+ const extended = [...catalog]
95
+ for (const schema of declared) {
96
+ if (names.has(schema.name)) continue
97
+ names.add(schema.name)
98
+ extended.push(schema)
99
+ }
100
+ return extended
101
+ }
102
+
79
103
  const encoder = new TextEncoder()
80
104
 
81
105
  /**
package/src/disclose.ts CHANGED
@@ -6,6 +6,10 @@
6
6
  * registry, not the step's admission: a tool the model may not call right now
7
7
  * is still worth naming, because the call itself reports why it is unavailable.
8
8
  *
9
+ * A route that reads only declared tool lists gets names instead of schemas:
10
+ * its definition can only take effect once `tool_load` added it to the head, so
11
+ * attaching it here would claim a callability the route does not have.
12
+ *
9
13
  * @module dsh-dynamic-tools/disclose
10
14
  */
11
15
 
@@ -16,10 +20,17 @@ import type { UserMessage } from '@deepseek-ai/dsh-llm'
16
20
  import { projectToolSchema } from '@deepseek-ai/dsh-tools'
17
21
  import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
18
22
  import type { ToolSchemaLike } from './catalog.ts'
19
- import { applyDisclosure, planDisclosure, type DisclosedState, type DisclosureLimits } from './disclosure.ts'
23
+ import {
24
+ applyDisclosure,
25
+ oversizedNames,
26
+ planDisclosure,
27
+ type DisclosedState,
28
+ type DisclosureLimits,
29
+ } from './disclosure.ts'
20
30
  import { foldDisclosed } from './fold.ts'
21
31
  import { renderDisclosure } from './render.ts'
22
32
  import type { SourceKind } from './source.ts'
33
+ import type { ToolStrategy } from './strategy.ts'
23
34
 
24
35
  /** Everything the pre-step listener needs to plan one step's disclosure. */
25
36
  export interface DiscloseOptions {
@@ -29,19 +40,19 @@ export interface DiscloseOptions {
29
40
  readonly limits: DisclosureLimits
30
41
  /** Whether names that disappear from the registry are announced. */
31
42
  readonly announceRemovals: boolean
43
+ /** Strategy this step's executor settled, per installed agent. */
44
+ readonly strategy: (agent: Agent) => ToolStrategy | undefined
32
45
  /** Names the frozen head declares, per installed agent. */
33
46
  readonly catalogNames: (agent: Agent) => ReadonlySet<string>
34
47
  /** Definitions this step admits, recorded by the executor's last assembly. */
35
48
  readonly admitted: (agent: Agent) => readonly ToolDefinition[] | undefined
36
49
  }
37
50
 
38
- /** Process-local delivery state, kept as a fast path beside the durable fold. */
39
- interface HeldState {
40
- state: DisclosedState
41
- }
42
-
43
51
  /** Per-Agent delivery state without retaining agents. */
44
- const stateByAgent = new WeakMap<Agent, HeldState>()
52
+ const stateByAgent = new WeakMap<Agent, DisclosedState>()
53
+
54
+ /** Per-Agent diagnostics already reported, so each one appears once. */
55
+ const reportedByAgent = new WeakMap<Agent, Set<string>>()
45
56
 
46
57
  /**
47
58
  * Read the session's delivered state, rebuilding it from durable messages when
@@ -51,10 +62,10 @@ const stateByAgent = new WeakMap<Agent, HeldState>()
51
62
  * @returns the folded state.
52
63
  */
53
64
  export function currentState(agent: Agent, kind: SourceKind): DisclosedState {
54
- const holder = stateByAgent.get(agent)
55
- if (holder !== undefined) return holder.state
65
+ const held = stateByAgent.get(agent)
66
+ if (held !== undefined) return held
56
67
  const folded = foldDisclosed(agent.session.deriveMessages(), kind)
57
- stateByAgent.set(agent, { state: folded })
68
+ stateByAgent.set(agent, folded)
58
69
  return folded
59
70
  }
60
71
 
@@ -64,15 +75,22 @@ export function currentState(agent: Agent, kind: SourceKind): DisclosedState {
64
75
  * @param state - new state.
65
76
  */
66
77
  export function storeState(agent: Agent, state: DisclosedState): void {
67
- stateByAgent.set(agent, { state })
78
+ stateByAgent.set(agent, state)
68
79
  }
69
80
 
70
81
  /**
71
- * Drop process-local state so the next read folds the durable messages again.
72
- * @param agent - agent whose session was compacted or replaced.
82
+ * Report a per-agent diagnostic once, so a repeated condition does not repeat
83
+ * its log line on every step.
84
+ * @param agent - agent the condition belongs to.
85
+ * @param key - stable key for this condition.
86
+ * @param report - emitter, called only for a key not reported before.
73
87
  */
74
- export function invalidateState(agent: Agent): void {
75
- stateByAgent.delete(agent)
88
+ function reportOnce(agent: Agent, key: string, report: () => void): void {
89
+ const reported = reportedByAgent.get(agent) ?? new Set<string>()
90
+ if (reported.has(key)) return
91
+ reported.add(key)
92
+ reportedByAgent.set(agent, reported)
93
+ report()
76
94
  }
77
95
 
78
96
  function schemasOutsideCatalog(
@@ -96,6 +114,7 @@ function schemasOutsideCatalog(
96
114
  * @param admitted - definitions this step admits.
97
115
  * @param executorCatalog - names the frozen head declares.
98
116
  * @param options - disclosure settings.
117
+ * @param strategy - how this step's route receives dynamic tools.
99
118
  * @returns the messages to append, in order.
100
119
  */
101
120
  export function disclosureMessages(
@@ -104,14 +123,32 @@ export function disclosureMessages(
104
123
  admitted: readonly ToolDefinition[],
105
124
  executorCatalog: ReadonlySet<string>,
106
125
  options: DiscloseOptions,
126
+ strategy: ToolStrategy,
107
127
  ): readonly UserMessage[] {
108
128
  const candidates = schemasOutsideCatalog(admitted, executorCatalog)
109
129
  const current = currentState(agent, options.sourceKind)
130
+ for (const name of current.damaged) {
131
+ reportOnce(agent, `damaged:${name}`, () => {
132
+ ctx.logger.warn('dsh-dynamic-tools: recorded definition for "%s" could not be parsed; disclosing it again', name)
133
+ })
134
+ }
135
+ const limits: DisclosureLimits = strategy === 'declare' ? { ...options.limits, mode: 'names' } : options.limits
136
+ if (limits.mode === 'names') {
137
+ for (const name of oversizedNames(candidates, limits)) {
138
+ reportOnce(agent, `oversized:${name}`, () => {
139
+ ctx.logger.warn(
140
+ 'dsh-dynamic-tools: "%s" exceeds maxSchemaBytes (%d) and cannot be loaded on this route; it is not announced',
141
+ name,
142
+ limits.maxSchemaBytes,
143
+ )
144
+ })
145
+ }
146
+ }
110
147
  const available = new Set(candidates.map(schema => schema.name))
111
148
  const removed = options.announceRemovals
112
149
  ? [...current.disclosed.keys()].filter(name => !available.has(name) && !executorCatalog.has(name))
113
150
  : []
114
- const batches = planDisclosure(candidates, removed, current, options.limits)
151
+ const batches = planDisclosure(candidates, removed, current, limits)
115
152
  if (batches.length === 0) {
116
153
  // A pruned history still needs its records re-linked for later comparisons.
117
154
  const folded = foldDisclosed(agent.session.deriveMessages(), options.sourceKind)
@@ -119,7 +156,7 @@ export function disclosureMessages(
119
156
  return []
120
157
  }
121
158
  const messages = batches.map(batch => createUserMessage({
122
- content: [{ type: 'text', text: renderDisclosure(batch) }],
159
+ content: [{ type: 'text', text: renderDisclosure(batch, strategy) }],
123
160
  source: { kind: options.sourceKind, form: 'catalog' },
124
161
  }))
125
162
  storeState(agent, applyDisclosure(current, batches))
@@ -133,14 +170,25 @@ export function disclosureMessages(
133
170
  * @param options - disclosure settings.
134
171
  */
135
172
  export function registerDisclosure(ctx: Context, options: DiscloseOptions): void {
136
- ctx.on('agent/pre-step', async ({ agent, signal }, next): Promise<PreStepDecision> => {
173
+ ctx.on('agent/pre-step', async ({ agent, signal, modelSelection }, next): Promise<PreStepDecision> => {
137
174
  const decision = await next()
138
175
  if (decision.kind === 'reject' || signal.aborted) return decision
139
176
  try {
140
- // The executor recorded this step's admission when assembly described the head.
177
+ // The executor recorded this step's admission and strategy when assembly
178
+ // described the head, which happens before this listener runs.
141
179
  const admitted = options.admitted(agent)
142
180
  if (admitted === undefined) return decision
143
- const messages = disclosureMessages(ctx, agent, admitted, options.catalogNames(agent), options)
181
+ const strategy = options.strategy(agent) ?? 'tail'
182
+ if (strategy === 'declare') {
183
+ reportOnce(agent, 'declare', () => {
184
+ ctx.logger.info(
185
+ 'dsh-dynamic-tools: announcing definitions by name only on %s/%s; a loaded tool is declared in the next request',
186
+ modelSelection.provider,
187
+ modelSelection.model,
188
+ )
189
+ })
190
+ }
191
+ const messages = disclosureMessages(ctx, agent, admitted, options.catalogNames(agent), options, strategy)
144
192
  if (messages.length === 0) return decision
145
193
  return { ...decision, messages: [...decision.messages, ...messages] }
146
194
  } catch (error: unknown) {
package/src/disclosure.ts CHANGED
@@ -43,10 +43,48 @@ export interface DisclosedState {
43
43
  readonly disclosed: ReadonlyMap<string, DisclosedEntry>
44
44
  /** Names whose full definition the model has read, attached or loaded on demand. */
45
45
  readonly loaded: ReadonlySet<string>
46
+ /**
47
+ * Definitions the model has read, in delivery order.
48
+ *
49
+ * The declare-on-load strategy turns these into tool-list declarations, so
50
+ * they outlive the announcement: a loaded tool stays declared even after the
51
+ * registry stops admitting it.
52
+ */
53
+ readonly definitions: ReadonlyMap<string, ToolSchemaLike>
54
+ /**
55
+ * Names whose recorded definition block could not be parsed, in delivery
56
+ * order. The caller reports them: the definition is disclosed again, and the
57
+ * damage must not stay silent.
58
+ */
59
+ readonly damaged: readonly string[]
46
60
  }
47
61
 
48
62
  /** The empty state of a session that has disclosed nothing yet. */
49
- export const EMPTY_DISCLOSED: DisclosedState = { disclosed: new Map(), loaded: new Set() }
63
+ export const EMPTY_DISCLOSED: DisclosedState = {
64
+ disclosed: new Map(),
65
+ loaded: new Set(),
66
+ definitions: new Map(),
67
+ damaged: [],
68
+ }
69
+
70
+ /**
71
+ * Definitions that no route can deliver because they exceed the schema cap.
72
+ *
73
+ * A `tail` route can still announce such a tool by name — the model calls it
74
+ * without reading the schema, and `tool_load` reports the cap. A `names` route
75
+ * has no such fallback: the tool can only run after its definition was loaded,
76
+ * so announcing it would promise a load that must fail.
77
+ *
78
+ * @param schemas - dynamic definitions admitted for this step.
79
+ * @param limits - validated disclosure limits.
80
+ * @returns names whose definition exceeds `maxSchemaBytes`.
81
+ */
82
+ export function oversizedNames(
83
+ schemas: readonly ToolSchemaLike[],
84
+ limits: DisclosureLimits,
85
+ ): string[] {
86
+ return schemas.filter(schema => schemaBytes(schema) > limits.maxSchemaBytes).map(schema => schema.name)
87
+ }
50
88
 
51
89
  /**
52
90
  * Plan the disclosures one step needs.
@@ -75,7 +113,11 @@ export function planDisclosure(
75
113
  if (!entry.schema) continue
76
114
  if (entry.signature === toolSignature(schema)) continue
77
115
  }
78
- if (limits.mode === 'schema' && schemaBytes(schema) <= limits.maxSchemaBytes) attached.push(schema)
116
+ if (schemaBytes(schema) > limits.maxSchemaBytes) {
117
+ if (limits.mode === 'schema') namesOnly.push(schema.name)
118
+ continue
119
+ }
120
+ if (limits.mode === 'schema') attached.push(schema)
79
121
  else namesOnly.push(schema.name)
80
122
  }
81
123
 
@@ -118,6 +160,23 @@ export function planDisclosure(
118
160
  return batches
119
161
  }
120
162
 
163
+ /**
164
+ * Record one delivered definition, clearing any earlier damage for that name.
165
+ * @param state - state before this delivery.
166
+ * @param schema - definition the model has now read.
167
+ * @returns the updated state.
168
+ */
169
+ export function withDefinition(state: DisclosedState, schema: ToolSchemaLike): DisclosedState {
170
+ const loaded = new Set(state.loaded).add(schema.name)
171
+ const definitions = new Map(state.definitions).set(schema.name, schema)
172
+ return {
173
+ disclosed: state.disclosed,
174
+ loaded,
175
+ definitions,
176
+ damaged: state.damaged.filter(name => name !== schema.name),
177
+ }
178
+ }
179
+
121
180
  /**
122
181
  * Fold delivered batches into the delivered state.
123
182
  * @param previous - state before these batches.
@@ -130,10 +189,14 @@ export function applyDisclosure(
130
189
  ): DisclosedState {
131
190
  const disclosed = new Map(previous.disclosed)
132
191
  const loaded = new Set(previous.loaded)
192
+ const definitions = new Map(previous.definitions)
193
+ const damaged = new Set(previous.damaged)
133
194
  for (const batch of batches) {
134
195
  for (const schema of batch.added) {
135
196
  disclosed.set(schema.name, { signature: toolSignature(schema), schema: true })
136
197
  loaded.add(schema.name)
198
+ definitions.set(schema.name, schema)
199
+ damaged.delete(schema.name)
137
200
  }
138
201
  for (const name of batch.names) {
139
202
  disclosed.set(name, { signature: null, schema: false })
@@ -141,7 +204,9 @@ export function applyDisclosure(
141
204
  for (const name of batch.removed) {
142
205
  disclosed.delete(name)
143
206
  loaded.delete(name)
207
+ definitions.delete(name)
208
+ damaged.delete(name)
144
209
  }
145
210
  }
146
- return { disclosed, loaded }
211
+ return { disclosed, loaded, definitions, damaged: [...damaged] }
147
212
  }
package/src/executor.ts CHANGED
@@ -7,6 +7,12 @@
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
 
@@ -23,9 +29,15 @@ import type {
23
29
  ToolModelInput,
24
30
  } from '@deepseek-ai/dsh-tools'
25
31
  import type { ScopeKey } from '@deepseek-ai/dsh-scope'
26
- import { classifyTool, type ClassificationRules, type ToolSchemaLike } from './catalog.ts'
32
+ import {
33
+ classifyTool,
34
+ extendCatalog,
35
+ type ClassificationRules,
36
+ type ToolSchemaLike,
37
+ } from './catalog.ts'
27
38
  import type { DisclosedEntry } from './disclosure.ts'
28
39
  import { loadFirstReason, unavailableReason } from './render.ts'
40
+ import { selectStrategy, type StrategyRules, type ToolStrategy } from './strategy.ts'
29
41
 
30
42
  /** Delivered disclosure state shared with the pre-step listener. */
31
43
  export interface DisclosureStateHandle {
@@ -33,6 +45,8 @@ export interface DisclosureStateHandle {
33
45
  disclosed(): ReadonlyMap<string, DisclosedEntry>
34
46
  /** Names whose definition was delivered through `tool_load`. */
35
47
  loaded(): ReadonlySet<string>
48
+ /** Definitions the model has read, in delivery order. */
49
+ definitions(): ReadonlyMap<string, ToolSchemaLike>
36
50
  }
37
51
 
38
52
  /** Runtime settings the executor reads on every step. */
@@ -43,6 +57,10 @@ export interface ExecutorOptions {
43
57
  readonly unavailableReasons: Readonly<Record<string, string>>
44
58
  /** Concurrency used when the loop supplies none. */
45
59
  readonly maxParallelCalls: number
60
+ /** Route matching rules for the declare-on-load strategy. */
61
+ readonly strategyRules: StrategyRules
62
+ /** Name of the tool that delivers a definition on demand. */
63
+ readonly loadToolName: string
46
64
  }
47
65
 
48
66
  /**
@@ -57,6 +75,10 @@ export class StableCatalogExecutor implements ToolExecutor {
57
75
  private lastAdmitted: readonly ToolDefinition[] = []
58
76
  /** Names the current batch's step admits. */
59
77
  private admittedNames: ReadonlySet<string> = new Set()
78
+ /** Strategy settled by the current step's assembly, so every reader agrees. */
79
+ private stepStrategy: ToolStrategy | undefined
80
+ /** Whether the missing-load-tool diagnostic was already reported. */
81
+ private loadWarningReported = false
60
82
 
61
83
  constructor(
62
84
  private readonly ctx: Context,
@@ -66,9 +88,12 @@ export class StableCatalogExecutor implements ToolExecutor {
66
88
  private readonly state: DisclosureStateHandle,
67
89
  ) {}
68
90
 
69
- /** Names the frozen head declares; empty before the first assembly. */
91
+ /** Names the frozen head declares, plus every loaded tool on a declare route. */
70
92
  declaredNames(): ReadonlySet<string> {
71
- return this.catalogNames
93
+ if (this.planStrategy() !== 'declare') return this.catalogNames
94
+ const names = new Set(this.catalogNames)
95
+ for (const name of this.state.definitions().keys()) names.add(name)
96
+ return names
72
97
  }
73
98
 
74
99
  /** Definitions the current step admits, captured by the last assembly. */
@@ -77,7 +102,8 @@ export class StableCatalogExecutor implements ToolExecutor {
77
102
  }
78
103
 
79
104
  /**
80
- * Capture the head from the first assembly, then return it unchanged.
105
+ * Capture the head from the first assembly, then return it unchanged, plus
106
+ * every loaded definition on a declare route.
81
107
  * The first assembly's admission is exactly the declaration set the session
82
108
  * starts with, so the head matches what every later request would have
83
109
  * declared while the tool set is unchanged.
@@ -86,13 +112,11 @@ export class StableCatalogExecutor implements ToolExecutor {
86
112
  */
87
113
  describe(tools: readonly ToolDefinition[]): ToolModelInput {
88
114
  this.lastAdmitted = tools
89
- if (this.catalog === undefined) {
90
- this.catalog = Object.freeze(tools
91
- .filter(definition => classifyTool(definition.name, this.rules) === 'inline')
92
- .map(definition => Object.freeze(projectToolSchema(definition, true))))
93
- for (const schema of this.catalog) this.catalogNames.add(schema.name)
94
- }
95
- return { schemas: [...this.catalog] }
115
+ this.stepStrategy = selectStrategy(this.agent.model.current(), this.options.strategyRules)
116
+ const catalog = this.catalog ?? this.capture(tools)
117
+ if (this.stepStrategy !== 'declare') return { schemas: [...catalog] }
118
+ this.reportMissingLoadTool()
119
+ return { schemas: this.withDeclared(catalog) }
96
120
  }
97
121
 
98
122
  /**
@@ -109,6 +133,66 @@ export class StableCatalogExecutor implements ToolExecutor {
109
133
  return executeToolBatch(input, pipeline, () => input.maxParallelToolCalls ?? this.options.maxParallelCalls)
110
134
  }
111
135
 
136
+ /**
137
+ * How this step's route receives dynamic tools.
138
+ *
139
+ * The assembly that described this step's head fixes it once. Every later
140
+ * reader in the same step — declaration names, the load requirement, the
141
+ * disclosure listener — sees that one decision, so a model switch cannot make
142
+ * the head and the announcement disagree.
143
+ * @returns the recorded strategy, or the current route's before any assembly.
144
+ */
145
+ planStrategy(): ToolStrategy {
146
+ return this.stepStrategy ?? selectStrategy(this.agent.model.current(), this.options.strategyRules)
147
+ }
148
+
149
+ /**
150
+ * Capture the declaration head from the first assembly.
151
+ * @param tools - definitions the first assembly admits.
152
+ * @returns the frozen model-facing catalog.
153
+ */
154
+ private capture(tools: readonly ToolDefinition[]): readonly ToolSchemaLike[] {
155
+ const catalog = Object.freeze(tools
156
+ .filter(definition => classifyTool(definition.name, this.rules) === 'inline')
157
+ .map(definition => Object.freeze(projectToolSchema(definition, true))))
158
+ this.catalog = catalog
159
+ for (const schema of catalog) this.catalogNames.add(schema.name)
160
+ return catalog
161
+ }
162
+
163
+ /**
164
+ * Append every loaded definition to the frozen head.
165
+ * A loaded tool the step still admits uses its live definition, so argument
166
+ * validation matches the call it will run; a tool that no longer admits keeps
167
+ * the definition the model read, because the head must not shrink.
168
+ * @param catalog - frozen declaration head.
169
+ * @returns the head followed by the loaded definitions, in load order.
170
+ */
171
+ private withDeclared(catalog: readonly ToolSchemaLike[]): ToolSchemaLike[] {
172
+ const live = new Map(this.lastAdmitted.map(definition => [definition.name, definition]))
173
+ const declared: ToolSchemaLike[] = []
174
+ for (const [name, recorded] of this.state.definitions()) {
175
+ if (this.catalogNames.has(name)) continue
176
+ const current = live.get(name)
177
+ declared.push(Object.freeze(current === undefined ? recorded : projectToolSchema(current, true)))
178
+ }
179
+ return extendCatalog(catalog, declared)
180
+ }
181
+
182
+ /**
183
+ * Report once that a declare route cannot load anything because the frozen
184
+ * head does not declare the load tool.
185
+ */
186
+ private reportMissingLoadTool(): void {
187
+ if (this.loadWarningReported || this.catalogNames.has(this.options.loadToolName)) return
188
+ this.loadWarningReported = true
189
+ this.ctx.logger.warn(
190
+ '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',
191
+ this.agent.id,
192
+ this.options.loadToolName,
193
+ )
194
+ }
195
+
112
196
  /**
113
197
  * Resolve one call name: the step's admission first, then the registered
114
198
  * definition for a name the head declares or the model was told about.
@@ -136,10 +220,15 @@ export class StableCatalogExecutor implements ToolExecutor {
136
220
  */
137
221
  private reject(name: string): Error | undefined {
138
222
  if (this.admittedNames.has(name)) {
139
- if (this.catalogNames.has(name) || !this.options.requireLoad) return undefined
223
+ if (this.catalogNames.has(name) || !this.requiresLoad()) return undefined
140
224
  return this.state.loaded().has(name) ? undefined : new Error(loadFirstReason(name))
141
225
  }
142
226
  if (!this.catalogNames.has(name) && !this.state.disclosed().has(name)) return undefined
143
227
  return new Error(unavailableReason(name, this.options.unavailableReasons[name]))
144
228
  }
229
+
230
+ /** Whether a dynamic tool must be loaded before it may run on this route. */
231
+ private requiresLoad(): boolean {
232
+ return this.options.requireLoad || this.planStrategy() === 'declare'
233
+ }
145
234
  }