@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/render.ts CHANGED
@@ -1,115 +1,129 @@
1
- /**
2
- * Model-visible text for disclosure messages and the tool-load notice.
3
- * The tags are the fold's input, so both sides change together.
4
- *
5
- * @module dsh-dynamic-tools/render
6
- */
7
-
8
- import type { ToolSchemaLike } from './catalog.ts'
9
- import type { DisclosureBatch } from './disclosure.ts'
10
-
11
- const CLOSING_TAG = /<\//g
12
-
13
- /**
14
- * Keep tool prose from closing a wrapper or block early. JSON accepts the
15
- * resulting backslash-slash escape, so a definition body stays parseable.
16
- * @param text - arbitrary tool-authored text.
17
- * @returns the text with every closing tag escape neutralized.
18
- */
19
- export function escapeReminderText(text: string): string {
20
- return text.replace(CLOSING_TAG, '<\\/')
21
- }
22
-
23
- /**
24
- * Collapse text to one announcement line, keeping the name list parseable.
25
- * @param text - arbitrary tool-authored text.
26
- * @returns the text with line breaks and repeated whitespace collapsed.
27
- */
28
- export function oneLine(text: string): string {
29
- return text.replace(/\s+/g, ' ').trim()
30
- }
31
-
32
- /**
33
- * Render one disclosure batch.
34
- * @param batch - definitions, name-only entries, and removals.
35
- * @returns the complete user-message text.
36
- */
37
- export function renderDisclosure(batch: DisclosureBatch): string {
38
- const sections: string[] = []
39
- const announced: string[] = []
40
- for (const schema of batch.added) announced.push(`- ${schema.name}: ${oneLine(escapeReminderText(schema.description))}`)
41
- for (const name of batch.names) announced.push(`- ${name}`)
42
- if (announced.length > 0) sections.push(`<tools_added>\n${announced.join('\n')}\n</tools_added>`)
43
- for (const schema of batch.added) {
44
- sections.push(`<tool_definition name="${schema.name}">\n${escapeReminderText(JSON.stringify(schema))}\n</tool_definition>`)
45
- }
46
- if (batch.names.length > 0) {
47
- sections.push(`<tools_load_required>\n${batch.names.map(name => `- ${name}`).join('\n')}\n</tools_load_required>`)
48
- }
49
- if (batch.removed.length > 0) {
50
- sections.push(`<tools_removed>\n${batch.removed.map(name => `- ${name}`).join('\n')}\n</tools_removed>`)
51
- }
52
- const trailers: string[] = []
53
- if (batch.added.length > 0) {
54
- trailers.push('These tools are callable directly by name even though they are not in your tool list; match the definitions above.')
55
- }
56
- if (batch.names.length > 0) {
57
- trailers.push('Call tool_load with the names under tools_load_required before calling those tools.')
58
- }
59
- if (batch.removed.length > 0) {
60
- trailers.push('Removed tools are unavailable; they fail if called.')
61
- }
62
- sections.push(...trailers)
63
- return `<system-reminder>\n${sections.join('\n\n')}\n</system-reminder>`
64
- }
65
-
66
- /**
67
- * Render the definitions `tool_load` returns for one tool.
68
- * @param schema - the definition to deliver.
69
- * @returns the complete user-message text.
70
- */
71
- export function renderLoadedDefinition(schema: ToolSchemaLike): string {
72
- return `<system-reminder>\n<tool_definition name="${schema.name}">\n${escapeReminderText(JSON.stringify(schema))}\n</tool_definition>\nThese tools are callable directly by name even though they are not in your tool list; match the definitions above.\n</system-reminder>`
73
- }
74
-
75
- /**
76
- * Render the model-facing result of one `tool_load` call.
77
- * @param loaded - names whose definitions were delivered.
78
- * @param alreadyAvailable - names that are declared in the tool list already.
79
- * @param unavailable - names no longer registered or not admitted.
80
- * @param tooLarge - names too large to deliver.
81
- * @returns plain-text result content.
82
- */
83
- export function renderLoadResult(
84
- loaded: readonly string[],
85
- alreadyAvailable: readonly string[],
86
- unavailable: readonly string[],
87
- tooLarge: readonly string[],
88
- ): string {
89
- const lines: string[] = []
90
- if (loaded.length > 0) lines.push(`Loaded: ${loaded.join(', ')}`)
91
- if (alreadyAvailable.length > 0) lines.push(`Already available: ${alreadyAvailable.join(', ')}`)
92
- if (unavailable.length > 0) lines.push(`Unavailable: ${unavailable.join(', ')}`)
93
- if (tooLarge.length > 0) lines.push(`Definition too large to load: ${tooLarge.join(', ')}`)
94
- if (lines.length === 0) return 'No tool names were supplied.'
95
- return lines.join('\n')
96
- }
97
-
98
- /**
99
- * The reason reported when a catalog tool is not admitted for this step.
100
- * @param name - tool name the model called.
101
- * @param configured - configured reason for this name, when any.
102
- * @returns the model-facing denial reason.
103
- */
104
- export function unavailableReason(name: string, configured: string | undefined): string {
105
- return configured ?? `Tool "${name}" is registered but not available in the current session state; ask the user to enable it, then retry.`
106
- }
107
-
108
- /**
109
- * The reason reported when a loaded-on-demand tool has not been loaded.
110
- * @param name - tool name the model called.
111
- * @returns the model-facing denial reason.
112
- */
113
- export function loadFirstReason(name: string): string {
114
- return `Tool "${name}" is available but its definition is not loaded. Call tool_load with {"names":["${name}"]} first, then call it again.`
115
- }
1
+ /**
2
+ * Model-visible text for disclosure messages and the tool-load notice.
3
+ * The tags are the fold's input, so both sides change together.
4
+ *
5
+ * @module dsh-dynamic-tools/render
6
+ */
7
+
8
+ import type { ToolSchemaLike } from './catalog.ts'
9
+ import type { DisclosureBatch } from './disclosure.ts'
10
+ import type { ToolStrategy } from './strategy.ts'
11
+
12
+ const CLOSING_TAG = /<\//g
13
+
14
+ /** What the model must do with a definition attached to the disclosure. */
15
+ const DIRECT_CALL_TRAILER = 'These tools are callable directly by name even though they are not in your tool list; match the definitions above.'
16
+
17
+ /**
18
+ * Keep tool prose from closing a wrapper or block early. JSON accepts the
19
+ * resulting backslash-slash escape, so a definition body stays parseable.
20
+ * @param text - arbitrary tool-authored text.
21
+ * @returns the text with every closing tag escape neutralized.
22
+ */
23
+ export function escapeReminderText(text: string): string {
24
+ return text.replace(CLOSING_TAG, '<\\/')
25
+ }
26
+
27
+ /**
28
+ * Collapse text to one announcement line, keeping the name list parseable.
29
+ * @param text - arbitrary tool-authored text.
30
+ * @returns the text with line breaks and repeated whitespace collapsed.
31
+ */
32
+ export function oneLine(text: string): string {
33
+ return text.replace(/\s+/g, ' ').trim()
34
+ }
35
+
36
+ /**
37
+ * Render one disclosure batch.
38
+ *
39
+ * An attached definition is only ever planned in `schema` mode, which the
40
+ * declare-on-load strategy never uses, so it always carries the direct-call
41
+ * instruction.
42
+ *
43
+ * @param batch - definitions, name-only entries, and removals.
44
+ * @param strategy - how this route receives dynamic tools.
45
+ * @returns the complete user-message text.
46
+ */
47
+ export function renderDisclosure(batch: DisclosureBatch, strategy: ToolStrategy): string {
48
+ const sections: string[] = []
49
+ const announced: string[] = []
50
+ for (const schema of batch.added) announced.push(`- ${schema.name}: ${oneLine(escapeReminderText(schema.description))}`)
51
+ for (const name of batch.names) announced.push(`- ${name}`)
52
+ if (announced.length > 0) sections.push(`<tools_added>\n${announced.join('\n')}\n</tools_added>`)
53
+ for (const schema of batch.added) {
54
+ sections.push(`<tool_definition name="${schema.name}">\n${escapeReminderText(JSON.stringify(schema))}\n</tool_definition>`)
55
+ }
56
+ if (batch.names.length > 0) {
57
+ sections.push(`<tools_load_required>\n${batch.names.map(name => `- ${name}`).join('\n')}\n</tools_load_required>`)
58
+ }
59
+ if (batch.removed.length > 0) {
60
+ sections.push(`<tools_removed>\n${batch.removed.map(name => `- ${name}`).join('\n')}\n</tools_removed>`)
61
+ }
62
+ const trailers: string[] = []
63
+ if (batch.added.length > 0) trailers.push(DIRECT_CALL_TRAILER)
64
+ if (batch.names.length > 0) {
65
+ trailers.push(strategy === 'declare'
66
+ ? 'Call tool_load with the names under tools_load_required — also when you need to read what a tool does. A loaded tool is added to your tool list for later steps.'
67
+ : 'Call tool_load with the names under tools_load_required before calling those tools.')
68
+ }
69
+ if (batch.removed.length > 0) {
70
+ trailers.push('Removed tools are unavailable; they fail if called.')
71
+ }
72
+ sections.push(...trailers)
73
+ return `<system-reminder>\n${sections.join('\n\n')}\n</system-reminder>`
74
+ }
75
+
76
+ /**
77
+ * Render the definitions `tool_load` returns for one tool.
78
+ * @param schema - the definition to deliver.
79
+ * @param strategy - how this route receives dynamic tools.
80
+ * @returns the complete user-message text.
81
+ */
82
+ export function renderLoadedDefinition(schema: ToolSchemaLike, strategy: ToolStrategy): string {
83
+ const trailer = strategy === 'declare'
84
+ ? 'This tool is declared in your tool list from the next step on; call it directly by name.'
85
+ : DIRECT_CALL_TRAILER
86
+ return `<system-reminder>\n<tool_definition name="${schema.name}">\n${escapeReminderText(JSON.stringify(schema))}\n</tool_definition>\n${trailer}\n</system-reminder>`
87
+ }
88
+
89
+ /**
90
+ * Render the model-facing result of one `tool_load` call.
91
+ * @param loaded - names whose definitions were delivered.
92
+ * @param alreadyAvailable - names that are declared in the tool list already.
93
+ * @param unavailable - names no longer registered or not admitted.
94
+ * @param tooLarge - names too large to deliver.
95
+ * @returns plain-text result content.
96
+ */
97
+ export function renderLoadResult(
98
+ loaded: readonly string[],
99
+ alreadyAvailable: readonly string[],
100
+ unavailable: readonly string[],
101
+ tooLarge: readonly string[],
102
+ ): string {
103
+ const lines: string[] = []
104
+ if (loaded.length > 0) lines.push(`Loaded: ${loaded.join(', ')}`)
105
+ if (alreadyAvailable.length > 0) lines.push(`Already available: ${alreadyAvailable.join(', ')}`)
106
+ if (unavailable.length > 0) lines.push(`Unavailable: ${unavailable.join(', ')}`)
107
+ if (tooLarge.length > 0) lines.push(`Definition too large to load: ${tooLarge.join(', ')}`)
108
+ if (lines.length === 0) return 'No tool names were supplied.'
109
+ return lines.join('\n')
110
+ }
111
+
112
+ /**
113
+ * The reason reported when a catalog tool is not admitted for this step.
114
+ * @param name - tool name the model called.
115
+ * @param configured - configured reason for this name, when any.
116
+ * @returns the model-facing denial reason.
117
+ */
118
+ export function unavailableReason(name: string, configured: string | undefined): string {
119
+ return configured ?? `Tool "${name}" is registered but not available in the current session state; ask the user to enable it, then retry.`
120
+ }
121
+
122
+ /**
123
+ * The reason reported when a loaded-on-demand tool has not been loaded.
124
+ * @param name - tool name the model called.
125
+ * @returns the model-facing denial reason.
126
+ */
127
+ export function loadFirstReason(name: string): string {
128
+ return `Tool "${name}" is available but its definition is not loaded. Call tool_load with {"names":["${name}"]} first, then call it again.`
129
+ }
package/src/source.ts CHANGED
@@ -1,20 +1,20 @@
1
- /**
2
- * The message source this plugin records, declared once so every module and the
3
- * fold agree on it.
4
- *
5
- * @module dsh-dynamic-tools/source
6
- */
7
-
8
- import type { ContextFormed } from '@deepseek-ai/dsh-llm'
9
-
10
- declare module '@deepseek-ai/dsh-llm' {
11
- interface MessageSourceMap {
12
- 'dynamic-tools': { kind: 'dynamic-tools' } & ContextFormed
13
- }
14
- }
15
-
16
- /** Message source kind used for every disclosure and loaded definition. */
17
- export const SOURCE_KIND = 'dynamic-tools' as const
18
-
19
- /** Type of {@link SOURCE_KIND}. */
20
- export type SourceKind = typeof SOURCE_KIND
1
+ /**
2
+ * The message source this plugin records, declared once so every module and the
3
+ * fold agree on it.
4
+ *
5
+ * @module dsh-dynamic-tools/source
6
+ */
7
+
8
+ import type { ContextFormed } from '@deepseek-ai/dsh-llm'
9
+
10
+ declare module '@deepseek-ai/dsh-llm' {
11
+ interface MessageSourceMap {
12
+ 'dynamic-tools': { kind: 'dynamic-tools' } & ContextFormed
13
+ }
14
+ }
15
+
16
+ /** Message source kind used for every disclosure and loaded definition. */
17
+ export const SOURCE_KIND = 'dynamic-tools' as const
18
+
19
+ /** Type of {@link SOURCE_KIND}. */
20
+ export type SourceKind = typeof SOURCE_KIND
@@ -0,0 +1,79 @@
1
+ /**
2
+ * How one route receives dynamic tools: at the conversation tail, or declared
3
+ * in the tool list after an explicit load.
4
+ *
5
+ * OpenAI Responses routes call only the functions present in the request's
6
+ * `tools` array, so a definition delivered as conversation text is never
7
+ * invoked. Those routes need the definition loaded through `tool_load` and
8
+ * declared on the following request. Every other route reads the tail
9
+ * disclosure and calls the tool directly, which needs no declaration change.
10
+ *
11
+ * Pure module: no Harness imports, so it runs under the Node type-stripping
12
+ * loader in tests.
13
+ *
14
+ * @module dsh-dynamic-tools/strategy
15
+ */
16
+
17
+ /** How one Agent's dynamic tools reach the model. */
18
+ export type ToolStrategy = 'tail' | 'declare'
19
+
20
+ /** Route matching rules for the declare-on-load strategy. */
21
+ export interface StrategyRules {
22
+ /** Model-id patterns; an empty list matches every model. */
23
+ readonly models: readonly string[]
24
+ /** Provider-route patterns; an empty list matches every provider. */
25
+ readonly providers: readonly string[]
26
+ }
27
+
28
+ /** Model families whose routes call only tools declared in the request. */
29
+ export const DEFAULT_DECLARE_MODELS: readonly string[] = Object.freeze([
30
+ 'gpt*',
31
+ 'o1*',
32
+ 'o3*',
33
+ 'o4*',
34
+ 'chatgpt*',
35
+ 'codex*',
36
+ ])
37
+
38
+ /** Everything a pattern-match treats literally, apart from `*`. */
39
+ const REGEX_SPECIALS = /[.+?^${}()|[\]\\]/g
40
+
41
+ /**
42
+ * Match one identifier against a `*` wildcard pattern, ignoring case.
43
+ *
44
+ * The `*` is the only metacharacter; every other character is literal, so a
45
+ * model id containing `.` or `-` matches only itself. The pattern is anchored,
46
+ * so `gpt*` does not match `x-gpt-6`.
47
+ *
48
+ * @param pattern - glob-like pattern from configuration.
49
+ * @param value - model id or provider route to test.
50
+ * @returns whether the whole value matches the whole pattern.
51
+ */
52
+ export function patternMatches(pattern: string, value: string): boolean {
53
+ const source = pattern.replace(REGEX_SPECIALS, '\\$&').split('*').join('.*')
54
+ return new RegExp(`^${source}$`, 'i').test(value)
55
+ }
56
+
57
+ function matchesAny(patterns: readonly string[], value: string): boolean {
58
+ return patterns.length === 0 || patterns.some(pattern => patternMatches(pattern, value))
59
+ }
60
+
61
+ /**
62
+ * Decide how one step's route receives dynamic tools.
63
+ *
64
+ * A missing selection cannot be classified, so it keeps the tail strategy: the
65
+ * declaration head must never be guessed into a different shape.
66
+ *
67
+ * @param selection - route the step fixed for its request, when one is recorded.
68
+ * @param rules - configured declare-on-load matching rules.
69
+ * @returns `declare` only when both the model and the provider match.
70
+ */
71
+ export function selectStrategy(
72
+ selection: { readonly provider: string, readonly model: string } | undefined,
73
+ rules: StrategyRules,
74
+ ): ToolStrategy {
75
+ if (selection === undefined) return 'tail'
76
+ if (!matchesAny(rules.models, selection.model)) return 'tail'
77
+ if (!matchesAny(rules.providers, selection.provider)) return 'tail'
78
+ return 'declare'
79
+ }
package/src/tool-load.ts CHANGED
@@ -1,105 +1,126 @@
1
- /**
2
- * `tool_load`: deliver the definition of a tool the model was told about but
3
- * whose schema it cannot see in the declaration head.
4
- *
5
- * The definition rides `exec.deferContext()`, so the loop logs it after this
6
- * tool's result and the next request carries it at the tail.
7
- *
8
- * @module dsh-dynamic-tools/tool-load
9
- */
10
-
11
- import type { Context } from '@deepseek-ai/cordis'
12
- import { createUserMessage } from '@deepseek-ai/dsh-llm'
13
- import { defineTool, projectToolSchema, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools'
14
- import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
15
- import { schemaBytes } from './catalog.ts'
16
- import type { DisclosureLimits } from './disclosure.ts'
17
- import { renderLoadedDefinition, renderLoadResult } from './render.ts'
18
- import { currentState, storeState } from './disclose.ts'
19
- import type { SourceKind } from './source.ts'
20
-
21
- /** Names this plugin owns; a deployment cannot shadow them. */
22
- export const TOOL_LOAD_NAME = 'tool_load'
23
-
24
- /** Settings the load tool needs at call time. */
25
- export interface ToolLoadOptions {
26
- /** Message source kind owned by this plugin. */
27
- readonly sourceKind: SourceKind
28
- /** Validated disclosure limits; `maxSchemaBytes` caps a loaded definition. */
29
- readonly limits: DisclosureLimits
30
- }
31
-
32
- /**
33
- * Create the `tool_load` definition.
34
- * @param ctx - plugin context, used to read the agent's visible tools.
35
- * @param options - source kind and limits.
36
- * @returns the unregistered definition.
37
- */
38
- export function createToolLoad(ctx: Context, options: ToolLoadOptions): ToolDefinition {
39
- return defineTool({
40
- name: TOOL_LOAD_NAME,
41
- description: 'Read the full definition of tools that are announced in this conversation but absent from your tool list. Pass their exact names. Definitions arrive as a user message after this result; call the tool in a later step.',
42
- parameters: {
43
- names: {
44
- type: 'array',
45
- items: { type: 'string' },
46
- required: true,
47
- description: 'Exact tool names taken from the latest <tools_added> or <tools_load_required> announcement.',
48
- },
49
- },
50
- output: {
51
- schema: {
52
- type: 'object',
53
- additionalProperties: false,
54
- properties: {
55
- loaded: { type: 'array', items: { type: 'string' }, required: true },
56
- alreadyAvailable: { type: 'array', items: { type: 'string' }, required: true },
57
- unavailable: { type: 'array', items: { type: 'string' }, required: true },
58
- tooLarge: { type: 'array', items: { type: 'string' }, required: true },
59
- },
60
- },
61
- render: (_args, value) => [{
62
- type: 'text',
63
- text: renderLoadResult(value.loaded, value.alreadyAvailable, value.unavailable, value.tooLarge),
64
- }],
65
- },
66
- async execute(args, exec) {
67
- exec.signal.throwIfAborted()
68
- const agent = exec.agent
69
- if (agent === undefined) {
70
- throw new ToolContextUnavailableError(`${TOOL_LOAD_NAME} requires a calling Agent`)
71
- }
72
- const loaded: string[] = []
73
- const alreadyAvailable: string[] = []
74
- const unavailable: string[] = []
75
- const tooLarge: string[] = []
76
- const definitions = new Map(ctx.tools.definitions(agent).map(definition => [definition.name, definition]))
77
- const state = currentState(agent, options.sourceKind)
78
- const nextLoaded = new Set(state.loaded)
79
- const wanted = [...new Set(args.names.map(name => name.trim()).filter(name => name.length > 0))]
80
- for (const name of wanted) {
81
- const definition = definitions.get(name)
82
- if (definition === undefined) {
83
- unavailable.push(name)
84
- continue
85
- }
86
- const schema = projectToolSchema(definition, true)
87
- if (schemaBytes(schema) > options.limits.maxSchemaBytes) {
88
- tooLarge.push(name)
89
- continue
90
- }
91
- if (!state.disclosed.has(name)) alreadyAvailable.push(name)
92
- else loaded.push(name)
93
- nextLoaded.add(name)
94
- exec.deferContext(createUserMessage({
95
- content: [{ type: 'text', text: renderLoadedDefinition(schema) }],
96
- source: { kind: options.sourceKind, form: 'catalog' },
97
- }))
98
- }
99
- storeState(agent, { disclosed: state.disclosed, loaded: nextLoaded })
100
- return { loaded, alreadyAvailable, unavailable, tooLarge }
101
- },
102
- isConcurrencySafe: () => false,
103
- })
104
- }
105
-
1
+ /**
2
+ * `tool_load`: deliver the definition of a tool the conversation announced but
3
+ * the declaration head does not contain.
4
+ *
5
+ * The definition rides `exec.deferContext()`, so the loop logs it after this
6
+ * tool's result and the next request carries it at the tail. On a route that
7
+ * reads only declared tool lists, the next request also declares it.
8
+ *
9
+ * Only a name the model was actually told about is served: announcing is what
10
+ * makes a definition fair game. Serving any registered name would let a guessed
11
+ * name pull an unannounced definition into the head and keep it there.
12
+ *
13
+ * @module dsh-dynamic-tools/tool-load
14
+ */
15
+
16
+ import type { Context } from '@deepseek-ai/cordis'
17
+ import type { Agent } from '@deepseek-ai/dsh-agent'
18
+ import { createUserMessage } from '@deepseek-ai/dsh-llm'
19
+ import { defineTool, projectToolSchema, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools'
20
+ import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
21
+ import { schemaBytes } from './catalog.ts'
22
+ import { withDefinition, type DisclosureLimits } from './disclosure.ts'
23
+ import { renderLoadedDefinition, renderLoadResult } from './render.ts'
24
+ import { currentState, storeState } from './disclose.ts'
25
+ import type { SourceKind } from './source.ts'
26
+ import type { ToolStrategy } from './strategy.ts'
27
+
28
+ /** Names this plugin owns; a deployment cannot shadow them. */
29
+ export const TOOL_LOAD_NAME = 'tool_load'
30
+
31
+ /** Settings the load tool needs at call time. */
32
+ export interface ToolLoadOptions {
33
+ /** Message source kind owned by this plugin. */
34
+ readonly sourceKind: SourceKind
35
+ /** Validated disclosure limits; `maxSchemaBytes` caps a loaded definition. */
36
+ readonly limits: DisclosureLimits
37
+ /** Strategy this step's executor settled, per installed agent. */
38
+ readonly strategy: (agent: Agent) => ToolStrategy | undefined
39
+ /** Names the frozen head declares, per installed agent. */
40
+ readonly declaredNames: (agent: Agent) => ReadonlySet<string>
41
+ }
42
+
43
+ /**
44
+ * Create the `tool_load` definition.
45
+ * @param ctx - plugin context, used to read the agent's visible tools.
46
+ * @param options - source kind, limits, and the agent's declaration facts.
47
+ * @returns the unregistered definition.
48
+ */
49
+ export function createToolLoad(ctx: Context, options: ToolLoadOptions): ToolDefinition {
50
+ return defineTool({
51
+ name: TOOL_LOAD_NAME,
52
+ description: 'Read the full definition of tools that are announced in this conversation but absent from your tool list. Pass their exact names. Definitions arrive as a user message after this result; on a route that loads tools on demand the tool is declared in your tool list from the next step on.',
53
+ parameters: {
54
+ names: {
55
+ type: 'array',
56
+ items: { type: 'string' },
57
+ required: true,
58
+ description: 'Exact tool names taken from the latest <tools_added> or <tools_load_required> announcement.',
59
+ },
60
+ },
61
+ output: {
62
+ schema: {
63
+ type: 'object',
64
+ additionalProperties: false,
65
+ properties: {
66
+ loaded: { type: 'array', items: { type: 'string' }, required: true },
67
+ alreadyAvailable: { type: 'array', items: { type: 'string' }, required: true },
68
+ unavailable: { type: 'array', items: { type: 'string' }, required: true },
69
+ tooLarge: { type: 'array', items: { type: 'string' }, required: true },
70
+ },
71
+ },
72
+ render: (_args, value) => [{
73
+ type: 'text',
74
+ text: renderLoadResult(value.loaded, value.alreadyAvailable, value.unavailable, value.tooLarge),
75
+ }],
76
+ },
77
+ async execute(args, exec) {
78
+ exec.signal.throwIfAborted()
79
+ const agent = exec.agent
80
+ if (agent === undefined) {
81
+ throw new ToolContextUnavailableError(`${TOOL_LOAD_NAME} requires a calling Agent`)
82
+ }
83
+ const strategy = options.strategy(agent) ?? 'tail'
84
+ const declared = options.declaredNames(agent)
85
+ const loaded: string[] = []
86
+ const alreadyAvailable: string[] = []
87
+ const unavailable: string[] = []
88
+ const tooLarge: string[] = []
89
+ const definitions = new Map(ctx.tools.definitions(agent).map(definition => [definition.name, definition]))
90
+ let state = currentState(agent, options.sourceKind)
91
+ const wanted = [...new Set(args.names.map(name => name.trim()).filter(name => name.length > 0))]
92
+ for (const name of wanted) {
93
+ const definition = definitions.get(name)
94
+ if (definition === undefined) {
95
+ unavailable.push(name)
96
+ continue
97
+ }
98
+ if (declared.has(name)) {
99
+ // The definition is already in the tool list; repeating it adds nothing.
100
+ alreadyAvailable.push(name)
101
+ continue
102
+ }
103
+ if (!state.disclosed.has(name)) {
104
+ // A registered name nobody announced: bringing it in would declare a
105
+ // tool the model was never told about.
106
+ unavailable.push(name)
107
+ continue
108
+ }
109
+ const schema = projectToolSchema(definition, true)
110
+ if (schemaBytes(schema) > options.limits.maxSchemaBytes) {
111
+ tooLarge.push(name)
112
+ continue
113
+ }
114
+ loaded.push(name)
115
+ state = withDefinition(state, schema)
116
+ exec.deferContext(createUserMessage({
117
+ content: [{ type: 'text', text: renderLoadedDefinition(schema, strategy) }],
118
+ source: { kind: options.sourceKind, form: 'catalog' },
119
+ }))
120
+ }
121
+ storeState(agent, state)
122
+ return { loaded, alreadyAvailable, unavailable, tooLarge }
123
+ },
124
+ isConcurrencySafe: () => false,
125
+ })
126
+ }