@dsh-plugin/dsh-dynamic-tools 0.0.1 → 0.1.0-dev.43450988228
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 +111 -111
- package/docs/DETAIL.md +1 -1
- package/docs/preview.svg +25 -25
- package/icon.svg +7 -7
- package/locale/en.json +7 -7
- package/locale/zh.json +7 -7
- package/package.json +75 -75
- package/src/catalog.ts +88 -88
- package/src/disclose.ts +151 -151
- package/src/disclosure.ts +147 -147
- package/src/executor.ts +145 -145
- package/src/fold.ts +104 -104
- package/src/index.ts +178 -178
- package/src/install.ts +91 -91
- package/src/render.ts +115 -115
- package/src/source.ts +20 -20
- package/src/tool-load.ts +105 -105
package/src/executor.ts
CHANGED
|
@@ -1,145 +1,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
|
-
* @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
|
+
* @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
|
+
}
|
package/src/fold.ts
CHANGED
|
@@ -1,104 +1,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
|
-
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
|
+
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
|
+
}
|