@dsh-plugin/dsh-dynamic-tools 0.1.0-dev.43450988228 → 0.1.0-dev.43611140243

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/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  冻结会话首步的工具声明头部,把之后才出现的工具以对话尾部消息下发。这样中途的工具变化不再改写请求前缀,模型提供方的缓存可以继续复用。
4
4
 
5
+ 对只调用 `tools` 数组内函数的模型(GPT 系列走 OpenAI Responses 协议),尾部文本读得到却调不了,因此另有一条「按需声明」通道:调用 `tool_load` 后再把该工具补进声明。见[GPT 系列路由](#gpt-系列路由按需声明)。
6
+
5
7
  ## 解决什么问题
6
8
 
7
9
  DSH 的 `agent-loop` 在工具集发生变化、且当前路由没有声明 `toolUpdate` 能力时,会开启新的请求序列并重发完整系统提示词与工具声明。`openai-responses` 系列路由的 `supportsAdditionalTools` 在 `dsh-llm-pi-ai` 中被固定为 `withhold`,无法在 profile 里打开,所以在这类路由上:
@@ -9,7 +11,7 @@ DSH 的 `agent-loop` 在工具集发生变化、且当前路由没有声明 `too
9
11
  - 进入计划模式时原生 `exit_plan_mode` 被准入 → 工具表变化 → 整个前缀失效;
10
12
  - MCP 服务器晚连接、插件热插拔、条件工具转为可用,都会造成同样的失效。
11
13
 
12
- 本插件把声明头部固定下来:首步的声明集合被冻结,之后出现或被准入的工具通过尾部消息交给模型,模型仍可直接按名调用。
14
+ 本插件把声明头部固定下来:首步的声明集合被冻结,之后出现或被准入的工具通过尾部消息交给模型,模型仍可直接按名调用。只认声明列表的路由则走「按需声明」,多一次 `tool_load` 换取原生可调用。
13
15
 
14
16
  ## 机制
15
17
 
@@ -18,6 +20,7 @@ DSH 的 `agent-loop` 在工具集发生变化、且当前路由没有声明 `too
18
20
  3. **声明≠准入**:头部里的工具若本步未被准入(`when` 判定为假),调用会在策略与审批之前返回一条可执行错误,绝不执行。工具被撤下时 `UNKNOWN_TOOL`。
19
21
  4. **可见即记录**:披露消息带 `source.kind = dynamic-tools`,resume、fork、compaction 后由历史折叠重建;被压缩遮蔽的内容会在下一次开始时重发。
20
22
  5. **按需加载**:`disclosure.mode: names` 时只报名字,模型调用 `tool_load` 取完整定义;`disclosure.requireLoad` 可要求动态工具必须先加载才能执行。
23
+ 6. **按需声明**:命中 [`declareOnLoad`](#gpt-系列路由按需声明) 的路由把"已加载"的定义补进头部,让只认声明列表的模型也能调用动态工具。
21
24
 
22
25
  披露消息形状:
23
26
 
@@ -35,6 +38,24 @@ These tools are callable directly by name even though they are not in your tool
35
38
  </system-reminder>
36
39
  ```
37
40
 
41
+ ## GPT 系列路由:按需声明
42
+
43
+ OpenAI Responses 系路由只调用请求 `tools` 数组里声明过的函数。把定义写进对话文本时,这类模型只把它当作对话内容:没有声明就没有可调用的名字,它也不会为了看不见的定义去 `tool_load`。本插件在这类路由上切到 `declare`:
44
+
45
+ 1. 动态工具被准入时只公告名字(`<tools_added>` 与 `<tools_load_required>`),不带完整定义。
46
+ 2. 模型调用 `tool_load`(在头部,必定可调用)拿到定义。
47
+ 3. 该工具从下一步起进入请求的 `tools` 声明,模型直接按名调用;参数校验用的正是它读到的定义。
48
+
49
+ `tool_load` 只服务本会话公告过的名字:已注册但从未公告的工具(例如 `when` 判为不可用)返回 `Unavailable`,否则猜中的名字也会被永久塞进头部。`alreadyAvailable` 只表示"已在工具列表里",不再重复下发。
50
+
51
+ 这与 codex 的 `tool_search` → `tool_search_output` → 调用是同一形态。区别只在 codex 用 BM25 检索候选,本插件的公告已经给出确切名字,因此少一次检索回合,也不需要索引。
52
+
53
+ 声明是单调的:已加载的工具此后一直留在头部,即使它失去准入或被注销。失去准入时调用返回 `unavailableReasons` 里的可执行拒绝,注销时得到 `UNKNOWN_TOOL`;头部不回撤,一次 `when` 抖动不会再把前缀打散。
54
+
55
+ 代价是「每个加载过的工具一次前缀变化」:首个动态工具加载后请求头发生变化(`request/header` 的 `reason` 为 `change`),前缀从该点重建,此后只要不再加载新工具就保持稳定。动态工具用得越多,这笔一次性的账越接近默认策略的收益。
56
+
57
+ 为什么不走原生 `tool_search`:`dsh-llm-pi-ai` 只在模型 compat 打开 `supportsToolSearch` 或 `supportsAdditionalTools` 时才把工具变化写成 `tool-addition`,而它对 `openai-responses`、`azure-openai-responses`、`openai-codex-responses` 三个协议把这两项固定标为 `withhold`,profile 打不开。所以这里由插件自己补一次声明。
58
+
38
59
  ## 安装
39
60
 
40
61
  ```powershell
@@ -67,6 +88,9 @@ npm test
67
88
  prefixes: ['mcp__']
68
89
  disclosure:
69
90
  mode: schema
91
+ declareOnLoad:
92
+ models: ['gpt*', 'o1*', 'o3*', 'o4*', 'chatgpt*', 'codex*']
93
+ providers: []
70
94
  ```
71
95
 
72
96
  | 字段 | 默认 | 说明 |
@@ -75,37 +99,53 @@ npm test
75
99
  | `skipPresets` | `['ptc']` | 这些预设自带执行器,本插件不接管(PTC 只能看到 `run_code`) |
76
100
  | `dynamic.names` | `['exit_plan_mode']` | 永不进入头部的精确工具名 |
77
101
  | `dynamic.prefixes` | `[]` | 同上,按前缀匹配(如 `mcp__`) |
78
- | `dynamic.inlineNames` | `[]` | 强制进入头部,覆盖上面两条 |
102
+ | `dynamic.inlineNames` | `[]` | 强制进入头部,覆盖上面两条;`tool_load` 恒在其中 |
79
103
  | `disclosure.mode` | `schema` | `schema` 附完整定义;`names` 只报名字,需用 `tool_load` |
80
104
  | `disclosure.requireLoad` | `false` | 动态工具必须先 `tool_load` 才能执行 |
81
105
  | `disclosure.maxToolsPerMessage` | `8` | 单条披露消息的工具数 |
82
106
  | `disclosure.maxSchemaBytes` | `6000` | 单个定义上限,超出转为名字公告 |
83
107
  | `disclosure.maxMessageBytes` | `20000` | 单条消息上限,超出拆条 |
84
108
  | `disclosure.announceRemovals` | `true` | 工具失去准入时追加 `<tools_removed>` |
109
+ | `declareOnLoad.models` | `['gpt*', 'o1*', 'o3*', 'o4*', 'chatgpt*', 'codex*']` | 命中这些模型名的路由改用按需声明 |
110
+ | `declareOnLoad.providers` | `[]` | 同上,按路由名限制;空表示不限路由 |
85
111
  | `unavailableReasons` | `{ exit_plan_mode: … }` | 头部工具未准入时的模型可见原因 |
86
112
  | `maxParallelCalls` | `10` | 循环未给出并发上限时使用 |
87
113
 
88
114
  分类只看名字,因为注册时的 `when` 条件对插件不可见;未列入 `dynamic` 的工具默认进入头部。工具一旦进入头部就保持声明,即使当前不可调用——这正是缓存稳定的代价与保证。
89
115
 
116
+ `declareOnLoad` 的两个列表都支持 `*` 通配、大小写不敏感、整串匹配(`gpt*` 不匹配 `x-gpt-6`,`gpt-6.1*` 里的 `.` 是字面点)。两个列表为空表示强制所有路由走按需声明;策略按每一步的模型选择重算,中途切模型会随之切换。
117
+
90
118
  ## 模型体验
91
119
 
92
120
  ### 模型看到什么
93
121
 
94
- 头部声明保持不变。动态工具在本步首次被准入时以一条 `<system-reminder>` 出现:名字 + 描述 + 完整 JSON 定义 + "可直接按名调用"的说明;移除时出现 `<tools_removed>`。`names` 模式下模型需先调 `tool_load`,定义在其结果之后作为用户消息到达。
122
+ `tail` 路由:头部声明保持不变。动态工具在本步首次被准入时以一条 `<system-reminder>` 出现:名字 + 描述 + 完整 JSON 定义 + "可直接按名调用"的说明;移除时出现 `<tools_removed>`。`names` 模式下模型需先调 `tool_load`,定义在其结果之后作为用户消息到达。
123
+
124
+ `declare` 路由:公告只给名字,说明改为"调用 `tool_load` 把名字加进工具列表,之后直接调用";`tool_load` 的结果除了定义还会说明"从下一步起已声明"。
95
125
 
96
126
  ### Token 影响
97
127
 
98
128
  头部每步大小固定;披露只在工具真正增减时追加一次。相比每步重发全部声明,动态工具越多、会话越长,节省越明显。定义上限保护单条消息不被超大 schema 撑大。
99
129
 
130
+ `declare` 路由上,每个被加载的工具会长期占据头部一份定义;只有确定要用的工具才值得加载一次。
131
+
100
132
  ### KV Cache 影响
101
133
 
102
- 前缀在会话内保持字节稳定:工具声明、系统提示词都不再随工具状态变化。这是本插件的全部目的——实测进入计划模式后,切换点的缓存命中读数保持在同一量级而不是归零。代价是模型必须先读到披露消息才能调用新工具,且披露本身会新增若干 token。
134
+ `tail` 路由:前缀在会话内保持字节稳定,工具声明、系统提示词都不再随工具状态变化。这是本插件的全部目的——实测进入计划模式后,切换点的缓存命中读数保持在同一量级而不是归零。
135
+
136
+ `declare` 路由:稳定区间是「两次加载之间」。每次 `tool_load` 生效后的下一步会重发一次声明与系统提示词(`request/header` 的 `reason` 为 `change`),此后不再变化。代价是模型必须先加载再调用,且披露本身会新增若干 token。
103
137
 
104
138
  ## 已知限制
105
139
 
106
140
  - **首次捕获时机**:头部在 Agent 首步组装时捕获。若插件在会话中途安装,或 resume 后注册集合与历史头部不同,会出现一次头部变化,此后稳定。
107
141
  - **PTC 预设不接管**:PTC 只能用 `run_code`,其 SDK 文本随工具集变化;冻结 `tools:sdk` 不在本版范围。命中 `skipPresets` 时插件对该 Agent 完全让位并记录一次 info 日志。
108
142
  - **分类靠配置**:`when` 条件不可见,无法自动识别"条件工具";动态名单需要按名称或前缀配置。
143
+ - **路由匹配靠配置**:`declareOnLoad` 只认模型名与路由名;换供应商、改模型别名后需要同步,否则会退回 `tail` 策略而不是猜。
144
+ - **会话中切模型会有一次头部变化**:从 `tail` 切到 `declare` 时,此前的披露已经算作"已加载",这些工具会直接进入头部;反向切换则退回初始的冻结集合。两端都是一次性变化,之后各自稳定。
145
+ - **声明单调**:`declare` 路由上加载过的工具不再回撤。工具注销后仍留在头部,调用得到 `UNKNOWN_TOOL`;这换来的是 `when` 抖动不打断缓存。
146
+ - **`declare` 下强制名字公告**:该策略要把"已加载"当作声明依据,附完整定义会被记成已加载,因此 `disclosure.mode` 在该路由上不生效,首次切换时记录一条 info 日志。
147
+ - **定义漂移**:已加载且仍准入的工具,声明用注册表里的实时定义(保证参数校验与执行一致),可能与模型当初读到的版本不同。
148
+ - **超大定义**:超过 `maxSchemaBytes` 的工具在 `tail` 路由仍按名字公告(模型可直呼其名),在 `declare` 路由则完全不公告——那里只能靠加载,公告一个注定加载失败的名字只会浪费回合;两种情况都会记录一次 warn。
109
149
  - **重放外观**:披露消息在 Chat 里显示为普通用户上下文;重放时工具卡片使用通用样式。
110
150
  - **拒绝文案**:默认只预置 `exit_plan_mode` 的原因,其它头部工具的拒绝信息是通用文案,可通过 `unavailableReasons` 覆盖。
111
151
  - **无 UI 控制**:没有开关面板,所有行为通过 profile 配置。
package/icon.svg CHANGED
@@ -1,7 +1,7 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36" role="img" aria-label="Dynamic tools">
2
- <rect x="7.5" y="6" width="3.5" height="24" rx="1.75" fill="#176b5b"/>
3
- <rect x="13" y="7" width="16" height="5" rx="2.5" fill="#176b5b" fill-opacity="0.85"/>
4
- <rect x="13" y="14" width="16" height="5" rx="2.5" fill="#176b5b" fill-opacity="0.55"/>
5
- <rect x="13" y="21" width="16" height="9" rx="2.5" fill="none" stroke="#db6b2c" stroke-width="2"/>
6
- <path d="M18.5 25.5h5M21 23v5" fill="none" stroke="#db6b2c" stroke-width="2" stroke-linecap="round"/>
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36" fill="none" role="img" aria-label="Dynamic tools">
2
+ <rect x="6.6" y="4.8" width="22.8" height="7.8" rx="3.4" fill="url(#dyn-bar)"/>
3
+ <rect x="6.6" y="14.4" width="22.8" height="7.8" rx="3.9" fill="#5269E1" fill-opacity="0.45"/>
4
+ <rect x="6.6" y="23.4" width="22.8" height="8" rx="3" stroke="#45D9E7" stroke-width="2.4"/>
5
+ <path d="M14.4 27.4h7.2M18 23.8v7.2" stroke="#45D9E7" stroke-width="2.4" stroke-linecap="round"/>
6
+ <defs><linearGradient id="dyn-bar" x1="6.6" y1="4.8" x2="29.4" y2="12.6" gradientUnits="userSpaceOnUse"><stop stop-color="#67C7FE"/><stop offset="1" stop-color="#3F77D8"/></linearGradient></defs>
7
7
  </svg>
package/lib/catalog.d.ts CHANGED
@@ -45,6 +45,17 @@ export declare function splitCatalog(definitions: readonly ToolSchemaLike[], rul
45
45
  inline: ToolSchemaLike[];
46
46
  dynamic: ToolSchemaLike[];
47
47
  };
48
+ /**
49
+ * Append declared definitions to the frozen catalog, keeping both orders.
50
+ *
51
+ * A name the catalog already declares keeps its catalog position and
52
+ * definition: the head must not move because a tool became loadable.
53
+ *
54
+ * @param catalog - frozen declaration head.
55
+ * @param declared - definitions loaded on demand, in load order.
56
+ * @returns the head followed by every declared name it does not declare.
57
+ */
58
+ export declare function extendCatalog(catalog: readonly ToolSchemaLike[], declared: readonly ToolSchemaLike[]): ToolSchemaLike[];
48
59
  /**
49
60
  * JSON size of one definition as it would be disclosed.
50
61
  * @param schema - model-facing schema of the definition.
package/lib/catalog.js CHANGED
@@ -55,6 +55,27 @@ export function splitCatalog(definitions, rules) {
55
55
  }
56
56
  return { inline, dynamic };
57
57
  }
58
+ /**
59
+ * Append declared definitions to the frozen catalog, keeping both orders.
60
+ *
61
+ * A name the catalog already declares keeps its catalog position and
62
+ * definition: the head must not move because a tool became loadable.
63
+ *
64
+ * @param catalog - frozen declaration head.
65
+ * @param declared - definitions loaded on demand, in load order.
66
+ * @returns the head followed by every declared name it does not declare.
67
+ */
68
+ export function extendCatalog(catalog, declared) {
69
+ const names = new Set(catalog.map(schema => schema.name));
70
+ const extended = [...catalog];
71
+ for (const schema of declared) {
72
+ if (names.has(schema.name))
73
+ continue;
74
+ names.add(schema.name);
75
+ extended.push(schema);
76
+ }
77
+ return extended;
78
+ }
58
79
  const encoder = new TextEncoder();
59
80
  /**
60
81
  * JSON size of one definition as it would be disclosed.
package/lib/disclose.d.ts CHANGED
@@ -6,6 +6,10 @@
6
6
  * registry, not the step's admission: a tool the model may not call right now
7
7
  * is still worth naming, because the call itself reports why it is unavailable.
8
8
  *
9
+ * A route that reads only declared tool lists gets names instead of schemas:
10
+ * its definition can only take effect once `tool_load` added it to the head, so
11
+ * attaching it here would claim a callability the route does not have.
12
+ *
9
13
  * @module dsh-dynamic-tools/disclose
10
14
  */
11
15
  import type { Context } from '@deepseek-ai/cordis';
@@ -14,6 +18,7 @@ import type { UserMessage } from '@deepseek-ai/dsh-llm';
14
18
  import type { ToolDefinition } from '@deepseek-ai/dsh-tools';
15
19
  import { type DisclosedState, type DisclosureLimits } from './disclosure.ts';
16
20
  import type { SourceKind } from './source.ts';
21
+ import type { ToolStrategy } from './strategy.ts';
17
22
  /** Everything the pre-step listener needs to plan one step's disclosure. */
18
23
  export interface DiscloseOptions {
19
24
  /** Message source kind owned by this plugin. */
@@ -22,6 +27,8 @@ export interface DiscloseOptions {
22
27
  readonly limits: DisclosureLimits;
23
28
  /** Whether names that disappear from the registry are announced. */
24
29
  readonly announceRemovals: boolean;
30
+ /** Strategy this step's executor settled, per installed agent. */
31
+ readonly strategy: (agent: Agent) => ToolStrategy | undefined;
25
32
  /** Names the frozen head declares, per installed agent. */
26
33
  readonly catalogNames: (agent: Agent) => ReadonlySet<string>;
27
34
  /** Definitions this step admits, recorded by the executor's last assembly. */
@@ -41,11 +48,6 @@ export declare function currentState(agent: Agent, kind: SourceKind): DisclosedS
41
48
  * @param state - new state.
42
49
  */
43
50
  export declare function storeState(agent: Agent, state: DisclosedState): void;
44
- /**
45
- * Drop process-local state so the next read folds the durable messages again.
46
- * @param agent - agent whose session was compacted or replaced.
47
- */
48
- export declare function invalidateState(agent: Agent): void;
49
51
  /**
50
52
  * Append this step's disclosure messages.
51
53
  *
@@ -58,9 +60,10 @@ export declare function invalidateState(agent: Agent): void;
58
60
  * @param admitted - definitions this step admits.
59
61
  * @param executorCatalog - names the frozen head declares.
60
62
  * @param options - disclosure settings.
63
+ * @param strategy - how this step's route receives dynamic tools.
61
64
  * @returns the messages to append, in order.
62
65
  */
63
- export declare function disclosureMessages(ctx: Context, agent: Agent, admitted: readonly ToolDefinition[], executorCatalog: ReadonlySet<string>, options: DiscloseOptions): readonly UserMessage[];
66
+ export declare function disclosureMessages(ctx: Context, agent: Agent, admitted: readonly ToolDefinition[], executorCatalog: ReadonlySet<string>, options: DiscloseOptions, strategy: ToolStrategy): readonly UserMessage[];
64
67
  /**
65
68
  * Register the pre-step listener that appends disclosures.
66
69
  * @param ctx - plugin context owning the listener.
package/lib/disclose.js CHANGED
@@ -6,15 +6,21 @@
6
6
  * registry, not the step's admission: a tool the model may not call right now
7
7
  * is still worth naming, because the call itself reports why it is unavailable.
8
8
  *
9
+ * A route that reads only declared tool lists gets names instead of schemas:
10
+ * its definition can only take effect once `tool_load` added it to the head, so
11
+ * attaching it here would claim a callability the route does not have.
12
+ *
9
13
  * @module dsh-dynamic-tools/disclose
10
14
  */
11
15
  import { createUserMessage } from '@deepseek-ai/dsh-llm';
12
16
  import { projectToolSchema } from '@deepseek-ai/dsh-tools';
13
- import { applyDisclosure, planDisclosure } from "./disclosure.js";
17
+ import { applyDisclosure, oversizedNames, planDisclosure, } from "./disclosure.js";
14
18
  import { foldDisclosed } from "./fold.js";
15
19
  import { renderDisclosure } from "./render.js";
16
20
  /** Per-Agent delivery state without retaining agents. */
17
21
  const stateByAgent = new WeakMap();
22
+ /** Per-Agent diagnostics already reported, so each one appears once. */
23
+ const reportedByAgent = new WeakMap();
18
24
  /**
19
25
  * Read the session's delivered state, rebuilding it from durable messages when
20
26
  * the process-local holder is missing (resume, fork, compaction).
@@ -23,11 +29,11 @@ const stateByAgent = new WeakMap();
23
29
  * @returns the folded state.
24
30
  */
25
31
  export function currentState(agent, kind) {
26
- const holder = stateByAgent.get(agent);
27
- if (holder !== undefined)
28
- return holder.state;
32
+ const held = stateByAgent.get(agent);
33
+ if (held !== undefined)
34
+ return held;
29
35
  const folded = foldDisclosed(agent.session.deriveMessages(), kind);
30
- stateByAgent.set(agent, { state: folded });
36
+ stateByAgent.set(agent, folded);
31
37
  return folded;
32
38
  }
33
39
  /**
@@ -36,14 +42,22 @@ export function currentState(agent, kind) {
36
42
  * @param state - new state.
37
43
  */
38
44
  export function storeState(agent, state) {
39
- stateByAgent.set(agent, { state });
45
+ stateByAgent.set(agent, state);
40
46
  }
41
47
  /**
42
- * Drop process-local state so the next read folds the durable messages again.
43
- * @param agent - agent whose session was compacted or replaced.
48
+ * Report a per-agent diagnostic once, so a repeated condition does not repeat
49
+ * its log line on every step.
50
+ * @param agent - agent the condition belongs to.
51
+ * @param key - stable key for this condition.
52
+ * @param report - emitter, called only for a key not reported before.
44
53
  */
45
- export function invalidateState(agent) {
46
- stateByAgent.delete(agent);
54
+ function reportOnce(agent, key, report) {
55
+ const reported = reportedByAgent.get(agent) ?? new Set();
56
+ if (reported.has(key))
57
+ return;
58
+ reported.add(key);
59
+ reportedByAgent.set(agent, reported);
60
+ report();
47
61
  }
48
62
  function schemasOutsideCatalog(definitions, catalogNames) {
49
63
  return definitions
@@ -62,16 +76,30 @@ function schemasOutsideCatalog(definitions, catalogNames) {
62
76
  * @param admitted - definitions this step admits.
63
77
  * @param executorCatalog - names the frozen head declares.
64
78
  * @param options - disclosure settings.
79
+ * @param strategy - how this step's route receives dynamic tools.
65
80
  * @returns the messages to append, in order.
66
81
  */
67
- export function disclosureMessages(ctx, agent, admitted, executorCatalog, options) {
82
+ export function disclosureMessages(ctx, agent, admitted, executorCatalog, options, strategy) {
68
83
  const candidates = schemasOutsideCatalog(admitted, executorCatalog);
69
84
  const current = currentState(agent, options.sourceKind);
85
+ for (const name of current.damaged) {
86
+ reportOnce(agent, `damaged:${name}`, () => {
87
+ ctx.logger.warn('dsh-dynamic-tools: recorded definition for "%s" could not be parsed; disclosing it again', name);
88
+ });
89
+ }
90
+ const limits = strategy === 'declare' ? { ...options.limits, mode: 'names' } : options.limits;
91
+ if (limits.mode === 'names') {
92
+ for (const name of oversizedNames(candidates, limits)) {
93
+ reportOnce(agent, `oversized:${name}`, () => {
94
+ ctx.logger.warn('dsh-dynamic-tools: "%s" exceeds maxSchemaBytes (%d) and cannot be loaded on this route; it is not announced', name, limits.maxSchemaBytes);
95
+ });
96
+ }
97
+ }
70
98
  const available = new Set(candidates.map(schema => schema.name));
71
99
  const removed = options.announceRemovals
72
100
  ? [...current.disclosed.keys()].filter(name => !available.has(name) && !executorCatalog.has(name))
73
101
  : [];
74
- const batches = planDisclosure(candidates, removed, current, options.limits);
102
+ const batches = planDisclosure(candidates, removed, current, limits);
75
103
  if (batches.length === 0) {
76
104
  // A pruned history still needs its records re-linked for later comparisons.
77
105
  const folded = foldDisclosed(agent.session.deriveMessages(), options.sourceKind);
@@ -80,7 +108,7 @@ export function disclosureMessages(ctx, agent, admitted, executorCatalog, option
80
108
  return [];
81
109
  }
82
110
  const messages = batches.map(batch => createUserMessage({
83
- content: [{ type: 'text', text: renderDisclosure(batch) }],
111
+ content: [{ type: 'text', text: renderDisclosure(batch, strategy) }],
84
112
  source: { kind: options.sourceKind, form: 'catalog' },
85
113
  }));
86
114
  storeState(agent, applyDisclosure(current, batches));
@@ -93,16 +121,23 @@ export function disclosureMessages(ctx, agent, admitted, executorCatalog, option
93
121
  * @param options - disclosure settings.
94
122
  */
95
123
  export function registerDisclosure(ctx, options) {
96
- ctx.on('agent/pre-step', async ({ agent, signal }, next) => {
124
+ ctx.on('agent/pre-step', async ({ agent, signal, modelSelection }, next) => {
97
125
  const decision = await next();
98
126
  if (decision.kind === 'reject' || signal.aborted)
99
127
  return decision;
100
128
  try {
101
- // The executor recorded this step's admission when assembly described the head.
129
+ // The executor recorded this step's admission and strategy when assembly
130
+ // described the head, which happens before this listener runs.
102
131
  const admitted = options.admitted(agent);
103
132
  if (admitted === undefined)
104
133
  return decision;
105
- const messages = disclosureMessages(ctx, agent, admitted, options.catalogNames(agent), options);
134
+ const strategy = options.strategy(agent) ?? 'tail';
135
+ if (strategy === 'declare') {
136
+ reportOnce(agent, 'declare', () => {
137
+ ctx.logger.info('dsh-dynamic-tools: announcing definitions by name only on %s/%s; a loaded tool is declared in the next request', modelSelection.provider, modelSelection.model);
138
+ });
139
+ }
140
+ const messages = disclosureMessages(ctx, agent, admitted, options.catalogNames(agent), options, strategy);
106
141
  if (messages.length === 0)
107
142
  return decision;
108
143
  return { ...decision, messages: [...decision.messages, ...messages] };
@@ -38,9 +38,36 @@ export interface DisclosedState {
38
38
  readonly disclosed: ReadonlyMap<string, DisclosedEntry>;
39
39
  /** Names whose full definition the model has read, attached or loaded on demand. */
40
40
  readonly loaded: ReadonlySet<string>;
41
+ /**
42
+ * Definitions the model has read, in delivery order.
43
+ *
44
+ * The declare-on-load strategy turns these into tool-list declarations, so
45
+ * they outlive the announcement: a loaded tool stays declared even after the
46
+ * registry stops admitting it.
47
+ */
48
+ readonly definitions: ReadonlyMap<string, ToolSchemaLike>;
49
+ /**
50
+ * Names whose recorded definition block could not be parsed, in delivery
51
+ * order. The caller reports them: the definition is disclosed again, and the
52
+ * damage must not stay silent.
53
+ */
54
+ readonly damaged: readonly string[];
41
55
  }
42
56
  /** The empty state of a session that has disclosed nothing yet. */
43
57
  export declare const EMPTY_DISCLOSED: DisclosedState;
58
+ /**
59
+ * Definitions that no route can deliver because they exceed the schema cap.
60
+ *
61
+ * A `tail` route can still announce such a tool by name — the model calls it
62
+ * without reading the schema, and `tool_load` reports the cap. A `names` route
63
+ * has no such fallback: the tool can only run after its definition was loaded,
64
+ * so announcing it would promise a load that must fail.
65
+ *
66
+ * @param schemas - dynamic definitions admitted for this step.
67
+ * @param limits - validated disclosure limits.
68
+ * @returns names whose definition exceeds `maxSchemaBytes`.
69
+ */
70
+ export declare function oversizedNames(schemas: readonly ToolSchemaLike[], limits: DisclosureLimits): string[];
44
71
  /**
45
72
  * Plan the disclosures one step needs.
46
73
  *
@@ -55,6 +82,13 @@ export declare const EMPTY_DISCLOSED: DisclosedState;
55
82
  * @returns ordered batches, empty when the model already knows everything.
56
83
  */
57
84
  export declare function planDisclosure(admitted: readonly ToolSchemaLike[], removed: readonly string[], state: DisclosedState, limits: DisclosureLimits): DisclosureBatch[];
85
+ /**
86
+ * Record one delivered definition, clearing any earlier damage for that name.
87
+ * @param state - state before this delivery.
88
+ * @param schema - definition the model has now read.
89
+ * @returns the updated state.
90
+ */
91
+ export declare function withDefinition(state: DisclosedState, schema: ToolSchemaLike): DisclosedState;
58
92
  /**
59
93
  * Fold delivered batches into the delivered state.
60
94
  * @param previous - state before these batches.
package/lib/disclosure.js CHANGED
@@ -6,7 +6,27 @@
6
6
  */
7
7
  import { schemaBytes, toolSignature } from "./catalog.js";
8
8
  /** The empty state of a session that has disclosed nothing yet. */
9
- export const EMPTY_DISCLOSED = { disclosed: new Map(), loaded: new Set() };
9
+ export const EMPTY_DISCLOSED = {
10
+ disclosed: new Map(),
11
+ loaded: new Set(),
12
+ definitions: new Map(),
13
+ damaged: [],
14
+ };
15
+ /**
16
+ * Definitions that no route can deliver because they exceed the schema cap.
17
+ *
18
+ * A `tail` route can still announce such a tool by name — the model calls it
19
+ * without reading the schema, and `tool_load` reports the cap. A `names` route
20
+ * has no such fallback: the tool can only run after its definition was loaded,
21
+ * so announcing it would promise a load that must fail.
22
+ *
23
+ * @param schemas - dynamic definitions admitted for this step.
24
+ * @param limits - validated disclosure limits.
25
+ * @returns names whose definition exceeds `maxSchemaBytes`.
26
+ */
27
+ export function oversizedNames(schemas, limits) {
28
+ return schemas.filter(schema => schemaBytes(schema) > limits.maxSchemaBytes).map(schema => schema.name);
29
+ }
10
30
  /**
11
31
  * Plan the disclosures one step needs.
12
32
  *
@@ -31,7 +51,12 @@ export function planDisclosure(admitted, removed, state, limits) {
31
51
  if (entry.signature === toolSignature(schema))
32
52
  continue;
33
53
  }
34
- if (limits.mode === 'schema' && schemaBytes(schema) <= limits.maxSchemaBytes)
54
+ if (schemaBytes(schema) > limits.maxSchemaBytes) {
55
+ if (limits.mode === 'schema')
56
+ namesOnly.push(schema.name);
57
+ continue;
58
+ }
59
+ if (limits.mode === 'schema')
35
60
  attached.push(schema);
36
61
  else
37
62
  namesOnly.push(schema.name);
@@ -73,6 +98,22 @@ export function planDisclosure(admitted, removed, state, limits) {
73
98
  flush();
74
99
  return batches;
75
100
  }
101
+ /**
102
+ * Record one delivered definition, clearing any earlier damage for that name.
103
+ * @param state - state before this delivery.
104
+ * @param schema - definition the model has now read.
105
+ * @returns the updated state.
106
+ */
107
+ export function withDefinition(state, schema) {
108
+ const loaded = new Set(state.loaded).add(schema.name);
109
+ const definitions = new Map(state.definitions).set(schema.name, schema);
110
+ return {
111
+ disclosed: state.disclosed,
112
+ loaded,
113
+ definitions,
114
+ damaged: state.damaged.filter(name => name !== schema.name),
115
+ };
116
+ }
76
117
  /**
77
118
  * Fold delivered batches into the delivered state.
78
119
  * @param previous - state before these batches.
@@ -82,10 +123,14 @@ export function planDisclosure(admitted, removed, state, limits) {
82
123
  export function applyDisclosure(previous, batches) {
83
124
  const disclosed = new Map(previous.disclosed);
84
125
  const loaded = new Set(previous.loaded);
126
+ const definitions = new Map(previous.definitions);
127
+ const damaged = new Set(previous.damaged);
85
128
  for (const batch of batches) {
86
129
  for (const schema of batch.added) {
87
130
  disclosed.set(schema.name, { signature: toolSignature(schema), schema: true });
88
131
  loaded.add(schema.name);
132
+ definitions.set(schema.name, schema);
133
+ damaged.delete(schema.name);
89
134
  }
90
135
  for (const name of batch.names) {
91
136
  disclosed.set(name, { signature: null, schema: false });
@@ -93,7 +138,9 @@ export function applyDisclosure(previous, batches) {
93
138
  for (const name of batch.removed) {
94
139
  disclosed.delete(name);
95
140
  loaded.delete(name);
141
+ definitions.delete(name);
142
+ damaged.delete(name);
96
143
  }
97
144
  }
98
- return { disclosed, loaded };
145
+ return { disclosed, loaded, definitions, damaged: [...damaged] };
99
146
  }
package/lib/executor.d.ts CHANGED
@@ -7,19 +7,28 @@
7
7
  * through tail disclosure, but only while the step admits them: an unadmitted
8
8
  * call is reported as an executable denial before policy and approval run.
9
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
+ *
10
16
  * @module dsh-dynamic-tools/executor
11
17
  */
12
18
  import type { Context } from '@deepseek-ai/cordis';
13
19
  import type { Agent } from '@deepseek-ai/dsh-agent';
14
20
  import type { ToolBatchInput, ToolBatchResult, ToolDefinition, ToolExecutor, ToolModelInput } from '@deepseek-ai/dsh-tools';
15
- import { type ClassificationRules } from './catalog.ts';
21
+ import { type ClassificationRules, type ToolSchemaLike } from './catalog.ts';
16
22
  import type { DisclosedEntry } from './disclosure.ts';
23
+ import { type StrategyRules, type ToolStrategy } from './strategy.ts';
17
24
  /** Delivered disclosure state shared with the pre-step listener. */
18
25
  export interface DisclosureStateHandle {
19
26
  /** Definitions the model has been told about. */
20
27
  disclosed(): ReadonlyMap<string, DisclosedEntry>;
21
28
  /** Names whose definition was delivered through `tool_load`. */
22
29
  loaded(): ReadonlySet<string>;
30
+ /** Definitions the model has read, in delivery order. */
31
+ definitions(): ReadonlyMap<string, ToolSchemaLike>;
23
32
  }
24
33
  /** Runtime settings the executor reads on every step. */
25
34
  export interface ExecutorOptions {
@@ -29,6 +38,10 @@ export interface ExecutorOptions {
29
38
  readonly unavailableReasons: Readonly<Record<string, string>>;
30
39
  /** Concurrency used when the loop supplies none. */
31
40
  readonly maxParallelCalls: number;
41
+ /** Route matching rules for the declare-on-load strategy. */
42
+ readonly strategyRules: StrategyRules;
43
+ /** Name of the tool that delivers a definition on demand. */
44
+ readonly loadToolName: string;
32
45
  }
33
46
  /**
34
47
  * Executes the frozen declaration head plus admitted dynamic tools.
@@ -47,13 +60,18 @@ export declare class StableCatalogExecutor implements ToolExecutor {
47
60
  private lastAdmitted;
48
61
  /** Names the current batch's step admits. */
49
62
  private admittedNames;
63
+ /** Strategy settled by the current step's assembly, so every reader agrees. */
64
+ private stepStrategy;
65
+ /** Whether the missing-load-tool diagnostic was already reported. */
66
+ private loadWarningReported;
50
67
  constructor(ctx: Context, agent: Agent, rules: ClassificationRules, options: ExecutorOptions, state: DisclosureStateHandle);
51
- /** Names the frozen head declares; empty before the first assembly. */
68
+ /** Names the frozen head declares, plus every loaded tool on a declare route. */
52
69
  declaredNames(): ReadonlySet<string>;
53
70
  /** Definitions the current step admits, captured by the last assembly. */
54
71
  admittedDefinitions(): readonly ToolDefinition[];
55
72
  /**
56
- * Capture the head from the first assembly, then return it unchanged.
73
+ * Capture the head from the first assembly, then return it unchanged, plus
74
+ * every loaded definition on a declare route.
57
75
  * The first assembly's admission is exactly the declaration set the session
58
76
  * starts with, so the head matches what every later request would have
59
77
  * declared while the tool set is unchanged.
@@ -67,6 +85,36 @@ export declare class StableCatalogExecutor implements ToolExecutor {
67
85
  * @returns settled results in model order.
68
86
  */
69
87
  execute(input: ToolBatchInput): Promise<ToolBatchResult>;
88
+ /**
89
+ * How this step's route receives dynamic tools.
90
+ *
91
+ * The assembly that described this step's head fixes it once. Every later
92
+ * reader in the same step — declaration names, the load requirement, the
93
+ * disclosure listener — sees that one decision, so a model switch cannot make
94
+ * the head and the announcement disagree.
95
+ * @returns the recorded strategy, or the current route's before any assembly.
96
+ */
97
+ planStrategy(): ToolStrategy;
98
+ /**
99
+ * Capture the declaration head from the first assembly.
100
+ * @param tools - definitions the first assembly admits.
101
+ * @returns the frozen model-facing catalog.
102
+ */
103
+ private capture;
104
+ /**
105
+ * Append every loaded definition to the frozen head.
106
+ * A loaded tool the step still admits uses its live definition, so argument
107
+ * validation matches the call it will run; a tool that no longer admits keeps
108
+ * the definition the model read, because the head must not shrink.
109
+ * @param catalog - frozen declaration head.
110
+ * @returns the head followed by the loaded definitions, in load order.
111
+ */
112
+ private withDeclared;
113
+ /**
114
+ * Report once that a declare route cannot load anything because the frozen
115
+ * head does not declare the load tool.
116
+ */
117
+ private reportMissingLoadTool;
70
118
  /**
71
119
  * Resolve one call name: the step's admission first, then the registered
72
120
  * definition for a name the head declares or the model was told about.
@@ -83,4 +131,6 @@ export declare class StableCatalogExecutor implements ToolExecutor {
83
131
  * @returns the denial, or undefined to let dispatch proceed.
84
132
  */
85
133
  private reject;
134
+ /** Whether a dynamic tool must be loaded before it may run on this route. */
135
+ private requiresLoad;
86
136
  }