@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/executor.ts CHANGED
@@ -1,145 +1,234 @@
1
- /**
2
- * Frozen-catalog tool executor.
3
- *
4
- * The declaration head is captured once, when this executor is installed, and
5
- * returned unchanged for every later step, so a mid-conversation tool change
6
- * never rewrites the request prefix. Tools outside that head stay callable
7
- * through tail disclosure, but only while the step admits them: an unadmitted
8
- * call is reported as an executable denial before policy and approval run.
9
- *
10
- * @module dsh-dynamic-tools/executor
11
- */
12
-
13
- import type { Context } from '@deepseek-ai/cordis'
14
- import type { Agent } from '@deepseek-ai/dsh-agent'
15
- import { executeToolBatch, ToolExecutionPipeline } from '@deepseek-ai/dsh-tools/pipeline'
16
- import { projectToolSchema } from '@deepseek-ai/dsh-tools'
17
- import type {
18
- ResolvedToolSet,
19
- ToolBatchInput,
20
- ToolBatchResult,
21
- ToolDefinition,
22
- ToolExecutor,
23
- ToolModelInput,
24
- } from '@deepseek-ai/dsh-tools'
25
- import type { ScopeKey } from '@deepseek-ai/dsh-scope'
26
- import { classifyTool, type ClassificationRules, type ToolSchemaLike } from './catalog.ts'
27
- import type { DisclosedEntry } from './disclosure.ts'
28
- import { loadFirstReason, unavailableReason } from './render.ts'
29
-
30
- /** Delivered disclosure state shared with the pre-step listener. */
31
- export interface DisclosureStateHandle {
32
- /** Definitions the model has been told about. */
33
- disclosed(): ReadonlyMap<string, DisclosedEntry>
34
- /** Names whose definition was delivered through `tool_load`. */
35
- loaded(): ReadonlySet<string>
36
- }
37
-
38
- /** Runtime settings the executor reads on every step. */
39
- export interface ExecutorOptions {
40
- /** Whether a dynamic tool must be loaded before it may run. */
41
- readonly requireLoad: boolean
42
- /** Configured denial reasons by tool name. */
43
- readonly unavailableReasons: Readonly<Record<string, string>>
44
- /** Concurrency used when the loop supplies none. */
45
- readonly maxParallelCalls: number
46
- }
47
-
48
- /**
49
- * Executes the frozen declaration head plus admitted dynamic tools.
50
- */
51
- export class StableCatalogExecutor implements ToolExecutor {
52
- /** Declaration head, captured by the first assembly and never replaced. */
53
- private catalog: readonly ToolSchemaLike[] | undefined
54
- /** Names the head declares. */
55
- private readonly catalogNames = new Set<string>()
56
- /** Definitions the current step admits, recorded by the last assembly. */
57
- private lastAdmitted: readonly ToolDefinition[] = []
58
- /** Names the current batch's step admits. */
59
- private admittedNames: ReadonlySet<string> = new Set()
60
-
61
- constructor(
62
- private readonly ctx: Context,
63
- private readonly agent: Agent,
64
- private readonly rules: ClassificationRules,
65
- private readonly options: ExecutorOptions,
66
- private readonly state: DisclosureStateHandle,
67
- ) {}
68
-
69
- /** Names the frozen head declares; empty before the first assembly. */
70
- declaredNames(): ReadonlySet<string> {
71
- return this.catalogNames
72
- }
73
-
74
- /** Definitions the current step admits, captured by the last assembly. */
75
- admittedDefinitions(): readonly ToolDefinition[] {
76
- return this.lastAdmitted
77
- }
78
-
79
- /**
80
- * Capture the head from the first assembly, then return it unchanged.
81
- * The first assembly's admission is exactly the declaration set the session
82
- * starts with, so the head matches what every later request would have
83
- * declared while the tool set is unchanged.
84
- * @param tools - definitions this step admits, in registry order.
85
- * @returns the frozen model-facing catalog.
86
- */
87
- describe(tools: readonly ToolDefinition[]): ToolModelInput {
88
- 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] }
96
- }
97
-
98
- /**
99
- * Execute one batch against the frozen head and the admitted dynamic set.
100
- * @param input - original calls, admission, agent, and logging step.
101
- * @returns settled results in model order.
102
- */
103
- execute(input: ToolBatchInput): Promise<ToolBatchResult> {
104
- this.admittedNames = new Set((input.toolSet?.view(this.agent) ?? new Map<string, ToolDefinition>()).keys())
105
- const pipeline = new ToolExecutionPipeline(this.ctx, {
106
- get: (name: string, scope: ScopeKey | undefined, toolSet: ResolvedToolSet | undefined) => this.resolve(name, scope, toolSet),
107
- reject: (name: string) => this.reject(name),
108
- })
109
- return executeToolBatch(input, pipeline, () => input.maxParallelToolCalls ?? this.options.maxParallelCalls)
110
- }
111
-
112
- /**
113
- * Resolve one call name: the step's admission first, then the registered
114
- * definition for a name the head declares or the model was told about.
115
- * @param name - tool name the model called.
116
- * @param scope - calling agent scope.
117
- * @param toolSet - step admission, when one exists.
118
- * @returns the definition to run, or undefined for an unknown tool.
119
- */
120
- private resolve(
121
- name: string,
122
- scope: ScopeKey | undefined,
123
- toolSet: ResolvedToolSet | undefined,
124
- ): ToolDefinition | undefined {
125
- const admitted = toolSet?.view(scope).get(name)
126
- if (admitted !== undefined) return admitted
127
- if (!this.catalogNames.has(name) && !this.state.disclosed().has(name)) return undefined
128
- return this.ctx.tools.definitions(this.agent).find(definition => definition.name === name)
129
- }
130
-
131
- /**
132
- * Decide the model-facing denial for a declared but unadmitted name, and for a
133
- * dynamic tool that must be loaded first. Runs before policy and approval.
134
- * @param name - tool name the model called.
135
- * @returns the denial, or undefined to let dispatch proceed.
136
- */
137
- private reject(name: string): Error | undefined {
138
- if (this.admittedNames.has(name)) {
139
- if (this.catalogNames.has(name) || !this.options.requireLoad) return undefined
140
- return this.state.loaded().has(name) ? undefined : new Error(loadFirstReason(name))
141
- }
142
- if (!this.catalogNames.has(name) && !this.state.disclosed().has(name)) return undefined
143
- return new Error(unavailableReason(name, this.options.unavailableReasons[name]))
144
- }
145
- }
1
+ /**
2
+ * Frozen-catalog tool executor.
3
+ *
4
+ * The declaration head is captured once, when this executor is installed, and
5
+ * returned unchanged for every later step, so a mid-conversation tool change
6
+ * never rewrites the request prefix. Tools outside that head stay callable
7
+ * through tail disclosure, but only while the step admits them: an unadmitted
8
+ * call is reported as an executable denial before policy and approval run.
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
+ *
16
+ * @module dsh-dynamic-tools/executor
17
+ */
18
+
19
+ import type { Context } from '@deepseek-ai/cordis'
20
+ import type { Agent } from '@deepseek-ai/dsh-agent'
21
+ import { executeToolBatch, ToolExecutionPipeline } from '@deepseek-ai/dsh-tools/pipeline'
22
+ import { projectToolSchema } from '@deepseek-ai/dsh-tools'
23
+ import type {
24
+ ResolvedToolSet,
25
+ ToolBatchInput,
26
+ ToolBatchResult,
27
+ ToolDefinition,
28
+ ToolExecutor,
29
+ ToolModelInput,
30
+ } from '@deepseek-ai/dsh-tools'
31
+ import type { ScopeKey } from '@deepseek-ai/dsh-scope'
32
+ import {
33
+ classifyTool,
34
+ extendCatalog,
35
+ type ClassificationRules,
36
+ type ToolSchemaLike,
37
+ } from './catalog.ts'
38
+ import type { DisclosedEntry } from './disclosure.ts'
39
+ import { loadFirstReason, unavailableReason } from './render.ts'
40
+ import { selectStrategy, type StrategyRules, type ToolStrategy } from './strategy.ts'
41
+
42
+ /** Delivered disclosure state shared with the pre-step listener. */
43
+ export interface DisclosureStateHandle {
44
+ /** Definitions the model has been told about. */
45
+ disclosed(): ReadonlyMap<string, DisclosedEntry>
46
+ /** Names whose definition was delivered through `tool_load`. */
47
+ loaded(): ReadonlySet<string>
48
+ /** Definitions the model has read, in delivery order. */
49
+ definitions(): ReadonlyMap<string, ToolSchemaLike>
50
+ }
51
+
52
+ /** Runtime settings the executor reads on every step. */
53
+ export interface ExecutorOptions {
54
+ /** Whether a dynamic tool must be loaded before it may run. */
55
+ readonly requireLoad: boolean
56
+ /** Configured denial reasons by tool name. */
57
+ readonly unavailableReasons: Readonly<Record<string, string>>
58
+ /** Concurrency used when the loop supplies none. */
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
64
+ }
65
+
66
+ /**
67
+ * Executes the frozen declaration head plus admitted dynamic tools.
68
+ */
69
+ export class StableCatalogExecutor implements ToolExecutor {
70
+ /** Declaration head, captured by the first assembly and never replaced. */
71
+ private catalog: readonly ToolSchemaLike[] | undefined
72
+ /** Names the head declares. */
73
+ private readonly catalogNames = new Set<string>()
74
+ /** Definitions the current step admits, recorded by the last assembly. */
75
+ private lastAdmitted: readonly ToolDefinition[] = []
76
+ /** Names the current batch's step admits. */
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
82
+
83
+ constructor(
84
+ private readonly ctx: Context,
85
+ private readonly agent: Agent,
86
+ private readonly rules: ClassificationRules,
87
+ private readonly options: ExecutorOptions,
88
+ private readonly state: DisclosureStateHandle,
89
+ ) {}
90
+
91
+ /** Names the frozen head declares, plus every loaded tool on a declare route. */
92
+ declaredNames(): ReadonlySet<string> {
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
97
+ }
98
+
99
+ /** Definitions the current step admits, captured by the last assembly. */
100
+ admittedDefinitions(): readonly ToolDefinition[] {
101
+ return this.lastAdmitted
102
+ }
103
+
104
+ /**
105
+ * Capture the head from the first assembly, then return it unchanged, plus
106
+ * every loaded definition on a declare route.
107
+ * The first assembly's admission is exactly the declaration set the session
108
+ * starts with, so the head matches what every later request would have
109
+ * declared while the tool set is unchanged.
110
+ * @param tools - definitions this step admits, in registry order.
111
+ * @returns the frozen model-facing catalog.
112
+ */
113
+ describe(tools: readonly ToolDefinition[]): ToolModelInput {
114
+ this.lastAdmitted = tools
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) }
120
+ }
121
+
122
+ /**
123
+ * Execute one batch against the frozen head and the admitted dynamic set.
124
+ * @param input - original calls, admission, agent, and logging step.
125
+ * @returns settled results in model order.
126
+ */
127
+ execute(input: ToolBatchInput): Promise<ToolBatchResult> {
128
+ this.admittedNames = new Set((input.toolSet?.view(this.agent) ?? new Map<string, ToolDefinition>()).keys())
129
+ const pipeline = new ToolExecutionPipeline(this.ctx, {
130
+ get: (name: string, scope: ScopeKey | undefined, toolSet: ResolvedToolSet | undefined) => this.resolve(name, scope, toolSet),
131
+ reject: (name: string) => this.reject(name),
132
+ })
133
+ return executeToolBatch(input, pipeline, () => input.maxParallelToolCalls ?? this.options.maxParallelCalls)
134
+ }
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
+
196
+ /**
197
+ * Resolve one call name: the step's admission first, then the registered
198
+ * definition for a name the head declares or the model was told about.
199
+ * @param name - tool name the model called.
200
+ * @param scope - calling agent scope.
201
+ * @param toolSet - step admission, when one exists.
202
+ * @returns the definition to run, or undefined for an unknown tool.
203
+ */
204
+ private resolve(
205
+ name: string,
206
+ scope: ScopeKey | undefined,
207
+ toolSet: ResolvedToolSet | undefined,
208
+ ): ToolDefinition | undefined {
209
+ const admitted = toolSet?.view(scope).get(name)
210
+ if (admitted !== undefined) return admitted
211
+ if (!this.catalogNames.has(name) && !this.state.disclosed().has(name)) return undefined
212
+ return this.ctx.tools.definitions(this.agent).find(definition => definition.name === name)
213
+ }
214
+
215
+ /**
216
+ * Decide the model-facing denial for a declared but unadmitted name, and for a
217
+ * dynamic tool that must be loaded first. Runs before policy and approval.
218
+ * @param name - tool name the model called.
219
+ * @returns the denial, or undefined to let dispatch proceed.
220
+ */
221
+ private reject(name: string): Error | undefined {
222
+ if (this.admittedNames.has(name)) {
223
+ if (this.catalogNames.has(name) || !this.requiresLoad()) return undefined
224
+ return this.state.loaded().has(name) ? undefined : new Error(loadFirstReason(name))
225
+ }
226
+ if (!this.catalogNames.has(name) && !this.state.disclosed().has(name)) return undefined
227
+ return new Error(unavailableReason(name, this.options.unavailableReasons[name]))
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
+ }
234
+ }
package/src/fold.ts CHANGED
@@ -1,104 +1,114 @@
1
- /**
2
- * Fold durable disclosure messages back into delivery state, so compaction,
3
- * resume, and fork rebuild the comparison instead of trusting process memory.
4
- *
5
- * @module dsh-dynamic-tools/fold
6
- */
7
-
8
- import { toolSignature, type ToolSchemaLike } from './catalog.ts'
9
- import type { DisclosedEntry, DisclosedState } from './disclosure.ts'
10
-
11
- /** The subset of a model message this fold reads. */
12
- export interface FoldableMessage {
13
- readonly role: string
14
- readonly content: readonly { readonly type: string, readonly text?: string }[]
15
- readonly source?: { readonly kind?: string }
16
- }
17
-
18
- const ADDED = /<tools_added>\n?([\s\S]*?)\n?<\/tools_added>/g
19
- const REMOVED = /<tools_removed>\n?([\s\S]*?)\n?<\/tools_removed>/g
20
- const DEFINITION = /<tool_definition name="([^"\n]+)">\n?([\s\S]*?)\n?<\/tool_definition>/g
21
-
22
- function textOf(message: FoldableMessage): string {
23
- return message.content.map(block => block.type === 'text' ? block.text ?? '' : '').join('')
24
- }
25
-
26
- function namesOf(body: string): string[] {
27
- const names: string[] = []
28
- for (const line of body.split('\n')) {
29
- const trimmed = line.trim()
30
- if (!trimmed.startsWith('- ')) continue
31
- const rest = trimmed.slice(2)
32
- const colon = rest.indexOf(': ')
33
- names.push(colon < 0 ? rest : rest.slice(0, colon))
34
- }
35
- return names.filter(name => name.length > 0)
36
- }
37
-
38
- function matches(text: string, pattern: RegExp): string[] {
39
- const bodies: string[] = []
40
- pattern.lastIndex = 0
41
- for (const match of text.matchAll(pattern)) bodies.push(match[1] ?? '')
42
- return bodies.flatMap(namesOf)
43
- }
44
-
45
- /**
46
- * Read one definition block, if it is a valid schema.
47
- * @param json - the block body.
48
- * @returns the parsed schema, or undefined when the text is not a schema object.
49
- */
50
- function parseDefinition(json: string): ToolSchemaLike | undefined {
51
- try {
52
- const value: unknown = JSON.parse(json)
53
- if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined
54
- const candidate = value as Partial<ToolSchemaLike>
55
- if (typeof candidate.name !== 'string' || typeof candidate.description !== 'string') return undefined
56
- if (typeof candidate.parameters !== 'object' || candidate.parameters === null) return undefined
57
- return candidate as ToolSchemaLike
58
- } catch (error: unknown) {
59
- void error
60
- return undefined
61
- }
62
- }
63
-
64
- /**
65
- * Fold every dynamic-tools message in delivery order.
66
- * Damaged blocks are ignored: an unreadable disclosure only costs one
67
- * re-announcement, never a wrong refusal.
68
- *
69
- * @param messages - derived session messages in model order.
70
- * @param kind - message source kind owned by this plugin.
71
- * @returns the delivered state at the end of the history.
72
- */
73
- export function foldDisclosed(messages: readonly FoldableMessage[], kind: string): DisclosedState {
74
- const disclosed = new Map<string, DisclosedEntry>()
75
- const loaded = new Set<string>()
76
- for (const message of messages) {
77
- if (message.source?.kind !== kind) continue
78
- const text = textOf(message)
79
- for (const name of matches(text, REMOVED)) {
80
- disclosed.delete(name)
81
- loaded.delete(name)
82
- }
83
- const definitions = new Map<string, ToolSchemaLike>()
84
- DEFINITION.lastIndex = 0
85
- for (const match of text.matchAll(DEFINITION)) {
86
- const schema = parseDefinition(match[2] ?? '')
87
- if (schema !== undefined) definitions.set(schema.name, schema)
88
- }
89
- for (const name of matches(text, ADDED)) {
90
- const schema = definitions.get(name)
91
- if (schema === undefined) {
92
- disclosed.set(name, { signature: null, schema: false })
93
- continue
94
- }
95
- disclosed.set(name, { signature: toolSignature(schema), schema: true })
96
- loaded.add(name)
97
- }
98
- for (const schema of definitions.values()) {
99
- disclosed.set(schema.name, { signature: toolSignature(schema), schema: true })
100
- loaded.add(schema.name)
101
- }
102
- }
103
- return { disclosed, loaded }
104
- }
1
+ /**
2
+ * Fold durable disclosure messages back into delivery state, so compaction,
3
+ * resume, and fork rebuild the comparison instead of trusting process memory.
4
+ *
5
+ * @module dsh-dynamic-tools/fold
6
+ */
7
+
8
+ import { toolSignature, type ToolSchemaLike } from './catalog.ts'
9
+ import type { DisclosedEntry, DisclosedState } from './disclosure.ts'
10
+
11
+ /** The subset of a model message this fold reads. */
12
+ export interface FoldableMessage {
13
+ readonly role: string
14
+ readonly content: readonly { readonly type: string, readonly text?: string }[]
15
+ readonly source?: { readonly kind?: string }
16
+ }
17
+
18
+ const ADDED = /<tools_added>\n?([\s\S]*?)\n?<\/tools_added>/g
19
+ const REMOVED = /<tools_removed>\n?([\s\S]*?)\n?<\/tools_removed>/g
20
+ const DEFINITION = /<tool_definition name="([^"\n]+)">\n?([\s\S]*?)\n?<\/tool_definition>/g
21
+
22
+ function textOf(message: FoldableMessage): string {
23
+ return message.content.map(block => block.type === 'text' ? block.text ?? '' : '').join('')
24
+ }
25
+
26
+ function namesOf(body: string): string[] {
27
+ const names: string[] = []
28
+ for (const line of body.split('\n')) {
29
+ const trimmed = line.trim()
30
+ if (!trimmed.startsWith('- ')) continue
31
+ const rest = trimmed.slice(2)
32
+ const colon = rest.indexOf(': ')
33
+ names.push(colon < 0 ? rest : rest.slice(0, colon))
34
+ }
35
+ return names.filter(name => name.length > 0)
36
+ }
37
+
38
+ function matches(text: string, pattern: RegExp): string[] {
39
+ const bodies: string[] = []
40
+ for (const match of text.matchAll(pattern)) bodies.push(match[1] ?? '')
41
+ return bodies.flatMap(namesOf)
42
+ }
43
+
44
+ /**
45
+ * Read one definition block, if it is a valid schema.
46
+ *
47
+ * A malformed block is not an error here: the fold reports it as damage, so the
48
+ * next step re-announces the tool instead of trusting a wrong record.
49
+ *
50
+ * @param json - the block body.
51
+ * @returns the parsed schema, or undefined when the text is not a schema object.
52
+ */
53
+ function parseDefinition(json: string): ToolSchemaLike | undefined {
54
+ let value: unknown
55
+ try {
56
+ value = JSON.parse(json)
57
+ } catch {
58
+ return undefined
59
+ }
60
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined
61
+ const candidate = value as Partial<ToolSchemaLike>
62
+ if (typeof candidate.name !== 'string' || typeof candidate.description !== 'string') return undefined
63
+ if (typeof candidate.parameters !== 'object' || candidate.parameters === null) return undefined
64
+ return candidate as ToolSchemaLike
65
+ }
66
+
67
+ /**
68
+ * Fold every dynamic-tools message in delivery order.
69
+ * A damaged block still marks its name as announced, so the model keeps seeing
70
+ * the name; the definition is re-disclosed because it was never recorded.
71
+ *
72
+ * @param messages - derived session messages in model order.
73
+ * @param kind - message source kind owned by this plugin.
74
+ * @returns the delivered state at the end of the history.
75
+ */
76
+ export function foldDisclosed(messages: readonly FoldableMessage[], kind: string): DisclosedState {
77
+ const disclosed = new Map<string, DisclosedEntry>()
78
+ const loaded = new Set<string>()
79
+ const definitions = new Map<string, ToolSchemaLike>()
80
+ const damaged = new Set<string>()
81
+ for (const message of messages) {
82
+ if (message.source?.kind !== kind) continue
83
+ const text = textOf(message)
84
+ for (const name of matches(text, REMOVED)) {
85
+ disclosed.delete(name)
86
+ loaded.delete(name)
87
+ definitions.delete(name)
88
+ damaged.delete(name)
89
+ }
90
+ const parsed = new Map<string, ToolSchemaLike>()
91
+ for (const match of text.matchAll(DEFINITION)) {
92
+ const schema = parseDefinition(match[2] ?? '')
93
+ if (schema === undefined) damaged.add(match[1] ?? '')
94
+ else parsed.set(schema.name, schema)
95
+ }
96
+ for (const name of matches(text, ADDED)) {
97
+ const schema = parsed.get(name)
98
+ if (schema === undefined) {
99
+ disclosed.set(name, { signature: null, schema: false })
100
+ continue
101
+ }
102
+ disclosed.set(name, { signature: toolSignature(schema), schema: true })
103
+ loaded.add(name)
104
+ definitions.set(name, schema)
105
+ damaged.delete(name)
106
+ }
107
+ for (const schema of parsed.values()) {
108
+ disclosed.set(schema.name, { signature: toolSignature(schema), schema: true })
109
+ loaded.add(schema.name)
110
+ definitions.set(schema.name, schema)
111
+ }
112
+ }
113
+ return { disclosed, loaded, definitions, damaged: [...damaged] }
114
+ }