@dsh-plugin/dsh-dynamic-tools 0.0.1 → 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/src/disclose.ts CHANGED
@@ -1,151 +1,199 @@
1
- /**
2
- * Trailing disclosure of dynamic tool definitions.
3
- *
4
- * Runs after the step's own pre-step listeners settle and appends recorded user
5
- * messages, so the request head never changes. The disclosed set follows the
6
- * registry, not the step's admission: a tool the model may not call right now
7
- * is still worth naming, because the call itself reports why it is unavailable.
8
- *
9
- * @module dsh-dynamic-tools/disclose
10
- */
11
-
12
- import type { Context } from '@deepseek-ai/cordis'
13
- import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent'
14
- import { createUserMessage } from '@deepseek-ai/dsh-llm'
15
- import type { UserMessage } from '@deepseek-ai/dsh-llm'
16
- import { projectToolSchema } from '@deepseek-ai/dsh-tools'
17
- import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
18
- import type { ToolSchemaLike } from './catalog.ts'
19
- import { applyDisclosure, planDisclosure, type DisclosedState, type DisclosureLimits } from './disclosure.ts'
20
- import { foldDisclosed } from './fold.ts'
21
- import { renderDisclosure } from './render.ts'
22
- import type { SourceKind } from './source.ts'
23
-
24
- /** Everything the pre-step listener needs to plan one step's disclosure. */
25
- export interface DiscloseOptions {
26
- /** Message source kind owned by this plugin. */
27
- readonly sourceKind: SourceKind
28
- /** Validated disclosure limits. */
29
- readonly limits: DisclosureLimits
30
- /** Whether names that disappear from the registry are announced. */
31
- readonly announceRemovals: boolean
32
- /** Names the frozen head declares, per installed agent. */
33
- readonly catalogNames: (agent: Agent) => ReadonlySet<string>
34
- /** Definitions this step admits, recorded by the executor's last assembly. */
35
- readonly admitted: (agent: Agent) => readonly ToolDefinition[] | undefined
36
- }
37
-
38
- /** Process-local delivery state, kept as a fast path beside the durable fold. */
39
- interface HeldState {
40
- state: DisclosedState
41
- }
42
-
43
- /** Per-Agent delivery state without retaining agents. */
44
- const stateByAgent = new WeakMap<Agent, HeldState>()
45
-
46
- /**
47
- * Read the session's delivered state, rebuilding it from durable messages when
48
- * the process-local holder is missing (resume, fork, compaction).
49
- * @param agent - agent whose session is read.
50
- * @param kind - message source kind owned by this plugin.
51
- * @returns the folded state.
52
- */
53
- export function currentState(agent: Agent, kind: SourceKind): DisclosedState {
54
- const holder = stateByAgent.get(agent)
55
- if (holder !== undefined) return holder.state
56
- const folded = foldDisclosed(agent.session.deriveMessages(), kind)
57
- stateByAgent.set(agent, { state: folded })
58
- return folded
59
- }
60
-
61
- /**
62
- * Replace the process-local state after a disclosure or a load.
63
- * @param agent - agent whose session was updated.
64
- * @param state - new state.
65
- */
66
- export function storeState(agent: Agent, state: DisclosedState): void {
67
- stateByAgent.set(agent, { state })
68
- }
69
-
70
- /**
71
- * Drop process-local state so the next read folds the durable messages again.
72
- * @param agent - agent whose session was compacted or replaced.
73
- */
74
- export function invalidateState(agent: Agent): void {
75
- stateByAgent.delete(agent)
76
- }
77
-
78
- function schemasOutsideCatalog(
79
- definitions: readonly ToolDefinition[],
80
- catalogNames: ReadonlySet<string>,
81
- ): ToolSchemaLike[] {
82
- return definitions
83
- .filter(definition => !catalogNames.has(definition.name))
84
- .map(definition => projectToolSchema(definition, true))
85
- }
86
-
87
- /**
88
- * Append this step's disclosure messages.
89
- *
90
- * Only definitions the step actually admits are candidates. A registered tool
91
- * whose `when` condition is false is unavailable right now: announcing it would
92
- * invite a call that can only be denied, so it is not disclosed at all.
93
- *
94
- * @param ctx - plugin context for diagnostics.
95
- * @param agent - agent entering the step.
96
- * @param admitted - definitions this step admits.
97
- * @param executorCatalog - names the frozen head declares.
98
- * @param options - disclosure settings.
99
- * @returns the messages to append, in order.
100
- */
101
- export function disclosureMessages(
102
- ctx: Context,
103
- agent: Agent,
104
- admitted: readonly ToolDefinition[],
105
- executorCatalog: ReadonlySet<string>,
106
- options: DiscloseOptions,
107
- ): readonly UserMessage[] {
108
- const candidates = schemasOutsideCatalog(admitted, executorCatalog)
109
- const current = currentState(agent, options.sourceKind)
110
- const available = new Set(candidates.map(schema => schema.name))
111
- const removed = options.announceRemovals
112
- ? [...current.disclosed.keys()].filter(name => !available.has(name) && !executorCatalog.has(name))
113
- : []
114
- const batches = planDisclosure(candidates, removed, current, options.limits)
115
- if (batches.length === 0) {
116
- // A pruned history still needs its records re-linked for later comparisons.
117
- const folded = foldDisclosed(agent.session.deriveMessages(), options.sourceKind)
118
- if (folded.disclosed.size !== current.disclosed.size) storeState(agent, folded)
119
- return []
120
- }
121
- const messages = batches.map(batch => createUserMessage({
122
- content: [{ type: 'text', text: renderDisclosure(batch) }],
123
- source: { kind: options.sourceKind, form: 'catalog' },
124
- }))
125
- storeState(agent, applyDisclosure(current, batches))
126
- ctx.logger.debug('dsh-dynamic-tools: disclosed %d batch(es) at step start', batches.length)
127
- return messages
128
- }
129
-
130
- /**
131
- * Register the pre-step listener that appends disclosures.
132
- * @param ctx - plugin context owning the listener.
133
- * @param options - disclosure settings.
134
- */
135
- export function registerDisclosure(ctx: Context, options: DiscloseOptions): void {
136
- ctx.on('agent/pre-step', async ({ agent, signal }, next): Promise<PreStepDecision> => {
137
- const decision = await next()
138
- if (decision.kind === 'reject' || signal.aborted) return decision
139
- try {
140
- // The executor recorded this step's admission when assembly described the head.
141
- const admitted = options.admitted(agent)
142
- if (admitted === undefined) return decision
143
- const messages = disclosureMessages(ctx, agent, admitted, options.catalogNames(agent), options)
144
- if (messages.length === 0) return decision
145
- return { ...decision, messages: [...decision.messages, ...messages] }
146
- } catch (error: unknown) {
147
- ctx.logger.warn('dsh-dynamic-tools: failed to disclose tool definitions at step start: %o', error)
148
- return decision
149
- }
150
- })
151
- }
1
+ /**
2
+ * Trailing disclosure of dynamic tool definitions.
3
+ *
4
+ * Runs after the step's own pre-step listeners settle and appends recorded user
5
+ * messages, so the request head never changes. The disclosed set follows the
6
+ * registry, not the step's admission: a tool the model may not call right now
7
+ * is still worth naming, because the call itself reports why it is unavailable.
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
+ *
13
+ * @module dsh-dynamic-tools/disclose
14
+ */
15
+
16
+ import type { Context } from '@deepseek-ai/cordis'
17
+ import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent'
18
+ import { createUserMessage } from '@deepseek-ai/dsh-llm'
19
+ import type { UserMessage } from '@deepseek-ai/dsh-llm'
20
+ import { projectToolSchema } from '@deepseek-ai/dsh-tools'
21
+ import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
22
+ import type { ToolSchemaLike } from './catalog.ts'
23
+ import {
24
+ applyDisclosure,
25
+ oversizedNames,
26
+ planDisclosure,
27
+ type DisclosedState,
28
+ type DisclosureLimits,
29
+ } from './disclosure.ts'
30
+ import { foldDisclosed } from './fold.ts'
31
+ import { renderDisclosure } from './render.ts'
32
+ import type { SourceKind } from './source.ts'
33
+ import type { ToolStrategy } from './strategy.ts'
34
+
35
+ /** Everything the pre-step listener needs to plan one step's disclosure. */
36
+ export interface DiscloseOptions {
37
+ /** Message source kind owned by this plugin. */
38
+ readonly sourceKind: SourceKind
39
+ /** Validated disclosure limits. */
40
+ readonly limits: DisclosureLimits
41
+ /** Whether names that disappear from the registry are announced. */
42
+ readonly announceRemovals: boolean
43
+ /** Strategy this step's executor settled, per installed agent. */
44
+ readonly strategy: (agent: Agent) => ToolStrategy | undefined
45
+ /** Names the frozen head declares, per installed agent. */
46
+ readonly catalogNames: (agent: Agent) => ReadonlySet<string>
47
+ /** Definitions this step admits, recorded by the executor's last assembly. */
48
+ readonly admitted: (agent: Agent) => readonly ToolDefinition[] | undefined
49
+ }
50
+
51
+ /** Per-Agent delivery state without retaining agents. */
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>>()
56
+
57
+ /**
58
+ * Read the session's delivered state, rebuilding it from durable messages when
59
+ * the process-local holder is missing (resume, fork, compaction).
60
+ * @param agent - agent whose session is read.
61
+ * @param kind - message source kind owned by this plugin.
62
+ * @returns the folded state.
63
+ */
64
+ export function currentState(agent: Agent, kind: SourceKind): DisclosedState {
65
+ const held = stateByAgent.get(agent)
66
+ if (held !== undefined) return held
67
+ const folded = foldDisclosed(agent.session.deriveMessages(), kind)
68
+ stateByAgent.set(agent, folded)
69
+ return folded
70
+ }
71
+
72
+ /**
73
+ * Replace the process-local state after a disclosure or a load.
74
+ * @param agent - agent whose session was updated.
75
+ * @param state - new state.
76
+ */
77
+ export function storeState(agent: Agent, state: DisclosedState): void {
78
+ stateByAgent.set(agent, state)
79
+ }
80
+
81
+ /**
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.
87
+ */
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()
94
+ }
95
+
96
+ function schemasOutsideCatalog(
97
+ definitions: readonly ToolDefinition[],
98
+ catalogNames: ReadonlySet<string>,
99
+ ): ToolSchemaLike[] {
100
+ return definitions
101
+ .filter(definition => !catalogNames.has(definition.name))
102
+ .map(definition => projectToolSchema(definition, true))
103
+ }
104
+
105
+ /**
106
+ * Append this step's disclosure messages.
107
+ *
108
+ * Only definitions the step actually admits are candidates. A registered tool
109
+ * whose `when` condition is false is unavailable right now: announcing it would
110
+ * invite a call that can only be denied, so it is not disclosed at all.
111
+ *
112
+ * @param ctx - plugin context for diagnostics.
113
+ * @param agent - agent entering the step.
114
+ * @param admitted - definitions this step admits.
115
+ * @param executorCatalog - names the frozen head declares.
116
+ * @param options - disclosure settings.
117
+ * @param strategy - how this step's route receives dynamic tools.
118
+ * @returns the messages to append, in order.
119
+ */
120
+ export function disclosureMessages(
121
+ ctx: Context,
122
+ agent: Agent,
123
+ admitted: readonly ToolDefinition[],
124
+ executorCatalog: ReadonlySet<string>,
125
+ options: DiscloseOptions,
126
+ strategy: ToolStrategy,
127
+ ): readonly UserMessage[] {
128
+ const candidates = schemasOutsideCatalog(admitted, executorCatalog)
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
+ }
147
+ const available = new Set(candidates.map(schema => schema.name))
148
+ const removed = options.announceRemovals
149
+ ? [...current.disclosed.keys()].filter(name => !available.has(name) && !executorCatalog.has(name))
150
+ : []
151
+ const batches = planDisclosure(candidates, removed, current, limits)
152
+ if (batches.length === 0) {
153
+ // A pruned history still needs its records re-linked for later comparisons.
154
+ const folded = foldDisclosed(agent.session.deriveMessages(), options.sourceKind)
155
+ if (folded.disclosed.size !== current.disclosed.size) storeState(agent, folded)
156
+ return []
157
+ }
158
+ const messages = batches.map(batch => createUserMessage({
159
+ content: [{ type: 'text', text: renderDisclosure(batch, strategy) }],
160
+ source: { kind: options.sourceKind, form: 'catalog' },
161
+ }))
162
+ storeState(agent, applyDisclosure(current, batches))
163
+ ctx.logger.debug('dsh-dynamic-tools: disclosed %d batch(es) at step start', batches.length)
164
+ return messages
165
+ }
166
+
167
+ /**
168
+ * Register the pre-step listener that appends disclosures.
169
+ * @param ctx - plugin context owning the listener.
170
+ * @param options - disclosure settings.
171
+ */
172
+ export function registerDisclosure(ctx: Context, options: DiscloseOptions): void {
173
+ ctx.on('agent/pre-step', async ({ agent, signal, modelSelection }, next): Promise<PreStepDecision> => {
174
+ const decision = await next()
175
+ if (decision.kind === 'reject' || signal.aborted) return decision
176
+ try {
177
+ // The executor recorded this step's admission and strategy when assembly
178
+ // described the head, which happens before this listener runs.
179
+ const admitted = options.admitted(agent)
180
+ if (admitted === undefined) return decision
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)
192
+ if (messages.length === 0) return decision
193
+ return { ...decision, messages: [...decision.messages, ...messages] }
194
+ } catch (error: unknown) {
195
+ ctx.logger.warn('dsh-dynamic-tools: failed to disclose tool definitions at step start: %o', error)
196
+ return decision
197
+ }
198
+ })
199
+ }