@dsh-plugin/dsh-dynamic-tools 0.1.0-dev.43582542989 → 0.1.0-dev.43800186861

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/install.ts CHANGED
@@ -14,11 +14,14 @@ import type { Context } from '@deepseek-ai/cordis'
14
14
  import type { Agent } from '@deepseek-ai/dsh-agent'
15
15
  import type { ClassificationRules } from './catalog.ts'
16
16
  import { StableCatalogExecutor, type ExecutorOptions } from './executor.ts'
17
- import { currentState } from './disclose.ts'
17
+ import type { DisclosureHistory } from './history.ts'
18
+ import type { HostBindings } from './host.ts'
18
19
  import type { SourceKind } from './source.ts'
19
20
 
20
21
  /** Settings shared by every installed agent. */
21
22
  export interface InstallOptions {
23
+ readonly host: HostBindings
24
+ readonly history: DisclosureHistory
22
25
  /** Message source kind owned by this plugin. */
23
26
  readonly sourceKind: SourceKind
24
27
  /** Classification rules for the frozen head. */
@@ -36,7 +39,7 @@ export interface InstallOptions {
36
39
  /** Read the preset id an agent runs under, when a registry is composed. */
37
40
  function presetOf(ctx: Context, agent: Agent): string | undefined {
38
41
  const registry = ctx.get('agentPresets')
39
- if (registry === undefined) return undefined
42
+ if (registry === undefined) { return undefined }
40
43
  return registry.presetForSession(agent.session) ?? undefined
41
44
  }
42
45
 
@@ -53,7 +56,7 @@ export function installAgent(
53
56
  options: InstallOptions,
54
57
  release: WeakMap<Agent, () => void>,
55
58
  ): void {
56
- if (options.executors.has(agent)) return
59
+ if (options.executors.has(agent)) { return }
57
60
  const preset = presetOf(ctx, agent)
58
61
  if (preset !== undefined && options.skipPresets.includes(preset)) {
59
62
  if (!options.reported.has(agent)) {
@@ -63,11 +66,11 @@ export function installAgent(
63
66
  return
64
67
  }
65
68
  const holder = {
66
- disclosed: () => currentState(agent, options.sourceKind).disclosed,
67
- loaded: () => currentState(agent, options.sourceKind).loaded,
68
- definitions: () => currentState(agent, options.sourceKind).definitions,
69
+ disclosed: () => options.history.read(agent, executor.planStrategy()).disclosed,
70
+ loaded: () => options.history.read(agent, executor.planStrategy()).loaded,
71
+ definitions: () => options.history.read(agent, executor.planStrategy()).definitions,
69
72
  }
70
- const executor = new StableCatalogExecutor(ctx, agent, options.rules, options.executor, holder)
73
+ const executor: StableCatalogExecutor = new StableCatalogExecutor(ctx, agent, options.rules, options.executor, holder, options.host)
71
74
  try {
72
75
  const dispose = ctx.effect(() => {
73
76
  const uninstall = agent.ctx.tools.setExecutor(executor)
@@ -79,13 +82,14 @@ export function installAgent(
79
82
  }, 'dsh-dynamic-tools: install frozen-catalog executor')
80
83
  let released = false
81
84
  release.set(agent, () => {
82
- if (released) return
85
+ if (released) { return }
83
86
  released = true
84
87
  release.delete(agent)
85
88
  dispose()
86
89
  })
87
90
  } catch (error: unknown) {
88
- if (options.reported.has(agent)) return
91
+ if (executor.planStrategy() === 'responses') { throw error }
92
+ if (options.reported.has(agent)) { return }
89
93
  options.reported.add(agent)
90
94
  ctx.logger.warn('dsh-dynamic-tools: cannot install for agent "%s": %o', agent.id, error)
91
95
  }
@@ -0,0 +1,154 @@
1
+ import type { ResponsesToolAddition, ResponsesToolAdditionRecord } from '@dsh-plugin/dsh-loader'
2
+ import type { UserMessage } from '@deepseek-ai/dsh-llm'
3
+ import { schemaBytes, toolSignature, type ToolSchemaLike } from './catalog.ts'
4
+ import type { DisclosedState, DisclosureLimits, DisclosureBatch } from './disclosure.ts'
5
+ import { renderDisclosure } from './render.ts'
6
+ import type { FoldableMessage } from './fold.ts'
7
+ import type { HostBindings } from './host.ts'
8
+ import { SOURCE_KIND, TOOL_LOAD_NAME, type ResponsesToolNotice } from './source.ts'
9
+
10
+ /** 有效历史中带原生声明或公告元数据的消息投影。 */
11
+ export interface ResponsesMessage extends FoldableMessage {
12
+ readonly id?: string
13
+ readonly source?: {
14
+ readonly kind?: string
15
+ readonly responsesToolAddition?: ResponsesToolAddition
16
+ readonly responsesToolNotice?: ResponsesToolNotice
17
+ }
18
+ }
19
+
20
+ /** 固定正文编码供持久化与发送时双向核验,不依赖可变注册表。 */
21
+ export function renderAddition(addition: ResponsesToolAddition): string {
22
+ return `[dsh-responses-tools:${addition.id}]\n${JSON.stringify(addition.tools)}`
23
+ }
24
+
25
+ function makeAddition(schemas: readonly ToolSchemaLike[], id: string): ResponsesToolAddition {
26
+ return {
27
+ version: 1, id,
28
+ tools: schemas.map(schema => ({ type: 'function', name: schema.name, description: schema.description, parameters: schema.parameters, strict: false })),
29
+ }
30
+ }
31
+
32
+ /** 声明先保存到宿主消息,随后才可计入已加载状态。 */
33
+ export function additionMessage(host: HostBindings, schemas: readonly ToolSchemaLike[]): UserMessage {
34
+ const addition = makeAddition(schemas, crypto.randomUUID())
35
+ return host.createUserMessage({
36
+ content: [{ type: 'text', text: renderAddition(addition) }],
37
+ source: { kind: SOURCE_KIND, form: 'catalog', responsesToolAddition: addition },
38
+ })
39
+ }
40
+
41
+ /** UUID 固定长度,预算包含标识与原生函数包装。 */
42
+ export function additionBytes(schemas: readonly ToolSchemaLike[]): number {
43
+ return new TextEncoder().encode(renderAddition(makeAddition(schemas, '00000000-0000-0000-0000-000000000000'))).length
44
+ }
45
+
46
+ /** 单个定义必须同时适合 schema 预算和持久化消息预算。 */
47
+ export function canLoadNative(schema: ToolSchemaLike, limits: DisclosureLimits): boolean {
48
+ return schemaBytes(schema) <= limits.maxSchemaBytes && additionBytes([schema]) <= limits.maxMessageBytes
49
+ }
50
+
51
+ /** 按最终 UTF-8 文本大小分批,定义、名字与移除通知分别记录。 */
52
+ export function planResponsesDisclosure(candidates: readonly ToolSchemaLike[], state: DisclosedState, limits: DisclosureLimits, requireLoad: boolean) {
53
+ const additions: ToolSchemaLike[][] = []
54
+ const notices: { batch: DisclosureBatch, notice: ResponsesToolNotice, text: string }[] = []
55
+ const names: ToolSchemaLike[] = []
56
+ let pending: ToolSchemaLike[] = []
57
+ for (const schema of candidates) {
58
+ const known = state.disclosed.get(schema.name)
59
+ const bootstrap = schema.name === TOOL_LOAD_NAME
60
+ if (known?.signature === toolSignature(schema)
61
+ && (known.schema || (!bootstrap && (requireLoad || limits.mode === 'names' || !canLoadNative(schema, limits))))) { continue }
62
+ if (bootstrap && !canLoadNative(schema, limits)) { throw new Error('dsh-dynamic-tools: tool_load 超过声明大小限制,无法建立原生加载入口') }
63
+ if (!bootstrap && (requireLoad || limits.mode === 'names' || !canLoadNative(schema, limits))) { names.push(schema); continue }
64
+ if (pending.length && (pending.length >= limits.maxToolsPerMessage || additionBytes([...pending, schema]) > limits.maxMessageBytes)) {
65
+ additions.push(pending)
66
+ pending = []
67
+ }
68
+ pending.push(schema)
69
+ }
70
+ if (pending.length) { additions.push(pending) }
71
+ const available = new Set(candidates.map(schema => schema.name))
72
+ const entries = [
73
+ ...[...state.disclosed.keys()].filter(name => !available.has(name)).map(name => ({ name, removed: true, signature: '' })),
74
+ ...names.map(schema => ({ name: schema.name, removed: false, signature: toolSignature(schema) })),
75
+ ]
76
+ let group: typeof entries = []
77
+ const build = (entries: typeof group) => {
78
+ const batch: DisclosureBatch = { added: [], names: entries.filter(entry => !entry.removed).map(entry => entry.name), removed: entries.filter(entry => entry.removed).map(entry => entry.name) }
79
+ const notice: ResponsesToolNotice = { version: 1, added: entries.filter(entry => !entry.removed).map(({ name, signature }) => ({ name, signature })), removed: batch.removed }
80
+ return { batch, notice, text: renderDisclosure(batch, 'responses') }
81
+ }
82
+ const fits = (entries: typeof group): boolean => entries.length <= limits.maxToolsPerMessage && new TextEncoder().encode(build(entries).text).length <= limits.maxMessageBytes
83
+ for (const entry of entries) {
84
+ if (group.length && !fits([...group, entry])) { notices.push(build(group)); group = [] }
85
+ if (!fits([entry])) { throw new Error(`dsh-dynamic-tools: maxMessageBytes 无法容纳 ${entry.name} 的工具通知,请提高限制`) }
86
+ group.push(entry)
87
+ }
88
+ if (group.length) { notices.push(build(group)) }
89
+ return { additions, notices }
90
+ }
91
+
92
+ /** 只接受插件来源的版本化记录,普通文本中的 schema 从不成为声明。 */
93
+ export function projectResponsesRecords(messages: readonly ResponsesMessage[]): ResponsesToolAdditionRecord[] {
94
+ const records: ResponsesToolAdditionRecord[] = []
95
+ const ids = new Set<string>()
96
+ for (const message of messages) {
97
+ if (message.source?.kind !== SOURCE_KIND || message.source.responsesToolAddition === undefined) { continue }
98
+ const addition = message.source.responsesToolAddition
99
+ if (message.role !== 'user' || !message.id || !addition || addition.version !== 1
100
+ || typeof addition.id !== 'string' || !/^[a-zA-Z0-9_-]{1,128}$/.test(addition.id) || ids.has(addition.id)
101
+ || !Array.isArray(addition.tools) || addition.tools.length === 0) {
102
+ throw new Error('dsh-dynamic-tools: 原生声明记录损坏、标识缺失或重复')
103
+ }
104
+ const names = new Set<string>()
105
+ for (const tool of addition.tools) {
106
+ if (tool.type !== 'function' || typeof tool.name !== 'string' || !tool.name
107
+ || typeof tool.description !== 'string' || tool.strict !== false || !tool.parameters
108
+ || typeof tool.parameters !== 'object' || Array.isArray(tool.parameters) || names.has(tool.name)) {
109
+ throw new Error(`dsh-dynamic-tools: 原生工具定义无效 ${addition.id}`)
110
+ }
111
+ names.add(tool.name)
112
+ }
113
+ const text = renderAddition(addition)
114
+ if (message.content.length !== 1 || message.content[0]?.type !== 'text' || message.content[0].text !== text) {
115
+ throw new Error(`dsh-dynamic-tools: 原生声明正文不匹配 ${addition.id}`)
116
+ }
117
+ ids.add(addition.id)
118
+ records.push({ messageId: message.id, sourceKind: SOURCE_KIND, text, addition })
119
+ }
120
+ return records
121
+ }
122
+
123
+ /** 声明保留历史最新定义;移除通知只撤销可见状态,执行准入另由当步工具集决定。 */
124
+ export function foldResponses(messages: readonly ResponsesMessage[], baseline: readonly ToolSchemaLike[] = []): DisclosedState {
125
+ const records = new Map(projectResponsesRecords(messages).map(record => [record.messageId, record]))
126
+ const disclosed = new Map<string, { signature: string | null, schema: boolean }>()
127
+ const definitions = new Map<string, ToolSchemaLike>()
128
+ const loaded = new Set<string>()
129
+ for (const schema of baseline) {
130
+ definitions.set(schema.name, schema)
131
+ loaded.add(schema.name)
132
+ disclosed.set(schema.name, { signature: toolSignature(schema), schema: true })
133
+ }
134
+ for (const message of messages) {
135
+ const record = message.id ? records.get(message.id) : undefined
136
+ if (record) {
137
+ for (const tool of record.addition.tools) {
138
+ const schema = { name: tool.name, description: tool.description, parameters: tool.parameters }
139
+ definitions.set(tool.name, schema)
140
+ loaded.add(tool.name)
141
+ disclosed.set(tool.name, { signature: toolSignature(schema), schema: true })
142
+ }
143
+ }
144
+ if (message.role !== 'user' || message.source?.kind !== SOURCE_KIND) { continue }
145
+ const notice = message.source.responsesToolNotice
146
+ if (!notice) { continue }
147
+ if (notice.version !== 1 || !Array.isArray(notice.added) || !Array.isArray(notice.removed)) {
148
+ throw new Error('dsh-dynamic-tools: 原生工具通知记录无效')
149
+ }
150
+ for (const name of notice.removed) { disclosed.delete(name) }
151
+ for (const entry of notice.added) { disclosed.set(entry.name, { signature: entry.signature, schema: false }) }
152
+ }
153
+ return { disclosed, definitions, loaded, damaged: [] }
154
+ }
package/src/source.ts CHANGED
@@ -6,15 +6,30 @@
6
6
  */
7
7
 
8
8
  import type { ContextFormed } from '@deepseek-ai/dsh-llm'
9
+ import type { ResponsesToolAddition } from '@dsh-plugin/dsh-loader'
10
+
11
+ /** 公告记录保存定义签名,使未加载的同名更新仍能与已公告版本区分。 */
12
+ export interface ResponsesToolNotice {
13
+ readonly version: 1
14
+ readonly added: readonly { readonly name: string, readonly signature: string }[]
15
+ readonly removed: readonly string[]
16
+ }
9
17
 
10
18
  declare module '@deepseek-ai/dsh-llm' {
11
19
  interface MessageSourceMap {
12
- 'dynamic-tools': { kind: 'dynamic-tools' } & ContextFormed
20
+ 'dynamic-tools': {
21
+ kind: 'dynamic-tools'
22
+ responsesToolAddition?: ResponsesToolAddition
23
+ responsesToolNotice?: ResponsesToolNotice
24
+ } & ContextFormed
13
25
  }
14
26
  }
15
27
 
16
28
  /** Message source kind used for every disclosure and loaded definition. */
17
29
  export const SOURCE_KIND = 'dynamic-tools' as const
18
30
 
31
+ /** 静态加载入口名称,原生接管已有会话时可在历史中补齐。 */
32
+ export const TOOL_LOAD_NAME = 'tool_load'
33
+
19
34
  /** Type of {@link SOURCE_KIND}. */
20
35
  export type SourceKind = typeof SOURCE_KIND
package/src/strategy.ts CHANGED
@@ -1,21 +1,13 @@
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
- */
1
+ /** 按显式 Responses 路由、declareOnLoad 和 tail 的顺序选择动态工具协议。 */
16
2
 
17
3
  /** How one Agent's dynamic tools reach the model. */
18
- export type ToolStrategy = 'tail' | 'declare'
4
+ export type ToolStrategy = 'tail' | 'declare' | 'responses'
5
+
6
+ /** provider 精确匹配;models 沿用大小写不敏感的 * 通配规则。 */
7
+ export interface ResponsesRoute {
8
+ readonly provider: string
9
+ readonly models: readonly string[]
10
+ }
19
11
 
20
12
  /** Route matching rules for the declare-on-load strategy. */
21
13
  export interface StrategyRules {
@@ -23,6 +15,7 @@ export interface StrategyRules {
23
15
  readonly models: readonly string[]
24
16
  /** Provider-route patterns; an empty list matches every provider. */
25
17
  readonly providers: readonly string[]
18
+ readonly responses?: readonly ResponsesRoute[]
26
19
  }
27
20
 
28
21
  /** Model families whose routes call only tools declared in the request. */
@@ -66,14 +59,15 @@ function matchesAny(patterns: readonly string[], value: string): boolean {
66
59
  *
67
60
  * @param selection - route the step fixed for its request, when one is recorded.
68
61
  * @param rules - configured declare-on-load matching rules.
69
- * @returns `declare` only when both the model and the provider match.
62
+ * @returns 显式原生路由优先,其次按需声明,其余使用尾部文本。
70
63
  */
71
64
  export function selectStrategy(
72
65
  selection: { readonly provider: string, readonly model: string } | undefined,
73
66
  rules: StrategyRules,
74
67
  ): 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'
68
+ if (selection === undefined) { return 'tail' }
69
+ if (rules.responses?.some(route => route.provider === selection.provider && matchesAny(route.models, selection.model))) { return 'responses' }
70
+ if (!matchesAny(rules.models, selection.model)) { return 'tail' }
71
+ if (!matchesAny(rules.providers, selection.provider)) { return 'tail' }
78
72
  return 'declare'
79
73
  }
package/src/tool-load.ts CHANGED
@@ -1,35 +1,25 @@
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
- */
1
+ /** tool_load 只加载已公告且当前准入的工具;声明通过 deferContext 保存后才生效。 */
15
2
 
16
- import type { Context } from '@deepseek-ai/cordis'
17
3
  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
4
  import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
21
- import { schemaBytes } from './catalog.ts'
22
- import { withDefinition, type DisclosureLimits } from './disclosure.ts'
5
+ import { schemaBytes, toolSignature } from './catalog.ts'
6
+ import type { DisclosureLimits } from './disclosure.ts'
7
+ import type { DisclosureHistory } from './history.ts'
8
+ import type { HostBindings } from './host.ts'
9
+ import { additionMessage, canLoadNative } from './responses.ts'
23
10
  import { renderLoadedDefinition, renderLoadResult } from './render.ts'
24
- import { currentState, storeState } from './disclose.ts'
25
11
  import type { SourceKind } from './source.ts'
12
+ import { TOOL_LOAD_NAME } from './source.ts'
26
13
  import type { ToolStrategy } from './strategy.ts'
27
14
 
28
15
  /** Names this plugin owns; a deployment cannot shadow them. */
29
- export const TOOL_LOAD_NAME = 'tool_load'
16
+ export { TOOL_LOAD_NAME } from './source.ts'
30
17
 
31
18
  /** Settings the load tool needs at call time. */
32
19
  export interface ToolLoadOptions {
20
+ readonly host: HostBindings
21
+ readonly history: DisclosureHistory
22
+ readonly admitted: (agent: Agent) => readonly ToolDefinition[] | undefined
33
23
  /** Message source kind owned by this plugin. */
34
24
  readonly sourceKind: SourceKind
35
25
  /** Validated disclosure limits; `maxSchemaBytes` caps a loaded definition. */
@@ -42,14 +32,14 @@ export interface ToolLoadOptions {
42
32
 
43
33
  /**
44
34
  * Create the `tool_load` definition.
45
- * @param ctx - plugin context, used to read the agent's visible tools.
46
35
  * @param options - source kind, limits, and the agent's declaration facts.
47
36
  * @returns the unregistered definition.
48
37
  */
49
- export function createToolLoad(ctx: Context, options: ToolLoadOptions): ToolDefinition {
38
+ export function createToolLoad(options: ToolLoadOptions): ToolDefinition {
39
+ const { defineTool, projectToolSchema, ToolContextUnavailableError, createUserMessage } = options.host
50
40
  return defineTool({
51
41
  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.',
42
+ description: '加载会话中已公布的工具完整定义,传入工具原名。定义在本次调用结果之后保存;Responses 路由从该历史位置追加原生声明,后续可按原名调用。',
53
43
  parameters: {
54
44
  names: {
55
45
  type: 'array',
@@ -86,8 +76,8 @@ export function createToolLoad(ctx: Context, options: ToolLoadOptions): ToolDefi
86
76
  const alreadyAvailable: string[] = []
87
77
  const unavailable: string[] = []
88
78
  const tooLarge: string[] = []
89
- const definitions = new Map(ctx.tools.definitions(agent).map(definition => [definition.name, definition]))
90
- let state = currentState(agent, options.sourceKind)
79
+ const definitions = new Map((options.admitted(agent) ?? []).map(definition => [definition.name, definition]))
80
+ const state = options.history.read(agent, strategy)
91
81
  const wanted = [...new Set(args.names.map(name => name.trim()).filter(name => name.length > 0))]
92
82
  for (const name of wanted) {
93
83
  const definition = definitions.get(name)
@@ -95,8 +85,9 @@ export function createToolLoad(ctx: Context, options: ToolLoadOptions): ToolDefi
95
85
  unavailable.push(name)
96
86
  continue
97
87
  }
98
- if (declared.has(name)) {
99
- // The definition is already in the tool list; repeating it adds nothing.
88
+ const schema = projectToolSchema(definition, true)
89
+ const known = state.definitions.get(name)
90
+ if ((strategy !== 'responses' && declared.has(name)) || (known && toolSignature(known) === toolSignature(schema))) {
100
91
  alreadyAvailable.push(name)
101
92
  continue
102
93
  }
@@ -106,19 +97,16 @@ export function createToolLoad(ctx: Context, options: ToolLoadOptions): ToolDefi
106
97
  unavailable.push(name)
107
98
  continue
108
99
  }
109
- const schema = projectToolSchema(definition, true)
110
- if (schemaBytes(schema) > options.limits.maxSchemaBytes) {
100
+ if (schemaBytes(schema) > options.limits.maxSchemaBytes || (strategy === 'responses' && !canLoadNative(schema, options.limits))) {
111
101
  tooLarge.push(name)
112
102
  continue
113
103
  }
114
104
  loaded.push(name)
115
- state = withDefinition(state, schema)
116
- exec.deferContext(createUserMessage({
105
+ exec.deferContext(strategy === 'responses' ? additionMessage(options.host, [schema]) : createUserMessage({
117
106
  content: [{ type: 'text', text: renderLoadedDefinition(schema, strategy) }],
118
107
  source: { kind: options.sourceKind, form: 'catalog' },
119
108
  }))
120
109
  }
121
- storeState(agent, state)
122
110
  return { loaded, alreadyAvailable, unavailable, tooLarge }
123
111
  },
124
112
  isConcurrencySafe: () => false,