@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/LICENSE +165 -165
- package/README.md +151 -111
- package/docs/DETAIL.md +1 -1
- package/docs/preview.svg +25 -25
- package/icon.svg +7 -7
- package/lib/catalog.d.ts +11 -0
- package/lib/catalog.js +21 -0
- package/lib/disclose.d.ts +9 -6
- package/lib/disclose.js +51 -16
- package/lib/disclosure.d.ts +34 -0
- package/lib/disclosure.js +50 -3
- package/lib/executor.d.ts +53 -3
- package/lib/executor.js +87 -13
- package/lib/fold.d.ts +2 -2
- package/lib/fold.js +32 -21
- package/lib/index.d.ts +6 -0
- package/lib/index.js +26 -2
- package/lib/install.js +1 -0
- package/lib/render.d.ts +10 -2
- package/lib/render.js +20 -7
- package/lib/strategy.d.ts +52 -0
- package/lib/strategy.js +63 -0
- package/lib/tool-load.d.ts +16 -5
- package/lib/tool-load.js +29 -14
- package/locale/en.json +7 -7
- package/locale/zh.json +7 -7
- package/package.json +75 -75
- package/src/catalog.ts +112 -88
- package/src/disclose.ts +199 -151
- package/src/disclosure.ts +212 -147
- package/src/executor.ts +234 -145
- package/src/fold.ts +114 -104
- package/src/index.ts +209 -178
- package/src/install.ts +92 -91
- package/src/render.ts +129 -115
- package/src/source.ts +20 -20
- package/src/strategy.ts +79 -0
- package/src/tool-load.ts +126 -105
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
|
-
*
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
/** Definitions the current step admits,
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
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.
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
const
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
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
|
+
}
|