@dsh-plugin/dsh-dynamic-tools 0.0.0-stage → 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 ADDED
@@ -0,0 +1,165 @@
1
+  GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/README.md CHANGED
@@ -1,3 +1,111 @@
1
- # Temporary Holding Version
1
+ # Dynamic tools
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 冻结会话首步的工具声明头部,把之后才出现的工具以对话尾部消息下发。这样中途的工具变化不再改写请求前缀,模型提供方的缓存可以继续复用。
4
+
5
+ ## 解决什么问题
6
+
7
+ DSH 的 `agent-loop` 在工具集发生变化、且当前路由没有声明 `toolUpdate` 能力时,会开启新的请求序列并重发完整系统提示词与工具声明。`openai-responses` 系列路由的 `supportsAdditionalTools` 在 `dsh-llm-pi-ai` 中被固定为 `withhold`,无法在 profile 里打开,所以在这类路由上:
8
+
9
+ - 进入计划模式时原生 `exit_plan_mode` 被准入 → 工具表变化 → 整个前缀失效;
10
+ - MCP 服务器晚连接、插件热插拔、条件工具转为可用,都会造成同样的失效。
11
+
12
+ 本插件把声明头部固定下来:首步的声明集合被冻结,之后出现或被准入的工具通过尾部消息交给模型,模型仍可直接按名调用。
13
+
14
+ ## 机制
15
+
16
+ 1. **冻结头部**:每个 Agent 在首步组装时捕获其准入定义,剔除配置为动态的名字,深冻结后每一步原样返回。头部之后不再变化。
17
+ 2. **尾部披露**:`agent/pre-step` 在其它监听器之后运行,把"本步已准入但不在头部"的工具以一条用户消息披露;消息里既有名字清单,也有完整定义(`disclosure.mode: schema`),并带上"可直接按名调用"的说明。定义变化按签名检测后重披露,工具失去准入时追加 `<tools_removed>`。只注册、`when` 判为不可用的工具不会被公告——否则模型会去调用一个注定被拒的工具。
18
+ 3. **声明≠准入**:头部里的工具若本步未被准入(`when` 判定为假),调用会在策略与审批之前返回一条可执行错误,绝不执行。工具被撤下时 `UNKNOWN_TOOL`。
19
+ 4. **可见即记录**:披露消息带 `source.kind = dynamic-tools`,resume、fork、compaction 后由历史折叠重建;被压缩遮蔽的内容会在下一次开始时重发。
20
+ 5. **按需加载**:`disclosure.mode: names` 时只报名字,模型调用 `tool_load` 取完整定义;`disclosure.requireLoad` 可要求动态工具必须先加载才能执行。
21
+
22
+ 披露消息形状:
23
+
24
+ ```
25
+ <system-reminder>
26
+ <tools_added>
27
+ - exit_plan_mode: Use only in plan mode. …
28
+ </tools_added>
29
+
30
+ <tool_definition name="exit_plan_mode">
31
+ {"name":"exit_plan_mode","description":"…","parameters":{…}}
32
+ </tool_definition>
33
+
34
+ These tools are callable directly by name even though they are not in your tool list; match the definitions above.
35
+ </system-reminder>
36
+ ```
37
+
38
+ ## 安装
39
+
40
+ ```powershell
41
+ npm install --ignore-scripts --legacy-peer-deps
42
+ npm run typecheck
43
+ npm run build
44
+ npm test
45
+ ```
46
+
47
+ 源码在 `src/`,运行时加载提交在仓库里的 `lib/`。所有 `@deepseek-ai/*` 都是 `peerDependencies`:以目录链接方式安装时,Harness 只把祖先 `package.json` 中声明为 peer 的名字解析到安装副本;`devDependencies` 只供 `tsc` 使用。`npm test` 用 Node 24+ 的原生类型剥离直接运行 `tests/*.test.ts`,只需在源码改动后重新构建。
48
+
49
+ 通过 `plugin_manager` 的 `install_bundle` 安装本目录;`cordis.patch.yml` 插入一行 Host 入口:
50
+
51
+ ```yaml
52
+ - insert:
53
+ - id: dynamic-tools
54
+ name: '@dsh-plugin/dsh-dynamic-tools'
55
+ ```
56
+
57
+ 以目录链接方式安装后,重新执行 `npm run build` **不会**让正在运行的实例换用新产物:模块 URL 不变,Node 的 ESM 缓存不会重新读盘,热重载也不重新导入它。改完源码并构建后需重启 dsh 实例,新会话才会加载新的 `lib/`。
58
+
59
+ ## 配置
60
+
61
+ ```yaml
62
+ - id: dynamic-tools
63
+ name: '@dsh-plugin/dsh-dynamic-tools'
64
+ config:
65
+ dynamic:
66
+ names: ['exit_plan_mode']
67
+ prefixes: ['mcp__']
68
+ disclosure:
69
+ mode: schema
70
+ ```
71
+
72
+ | 字段 | 默认 | 说明 |
73
+ |---|---|---|
74
+ | `installExistingAgents` | `true` | 加载时对已存在的 Agent 补装 |
75
+ | `skipPresets` | `['ptc']` | 这些预设自带执行器,本插件不接管(PTC 只能看到 `run_code`) |
76
+ | `dynamic.names` | `['exit_plan_mode']` | 永不进入头部的精确工具名 |
77
+ | `dynamic.prefixes` | `[]` | 同上,按前缀匹配(如 `mcp__`) |
78
+ | `dynamic.inlineNames` | `[]` | 强制进入头部,覆盖上面两条 |
79
+ | `disclosure.mode` | `schema` | `schema` 附完整定义;`names` 只报名字,需用 `tool_load` |
80
+ | `disclosure.requireLoad` | `false` | 动态工具必须先 `tool_load` 才能执行 |
81
+ | `disclosure.maxToolsPerMessage` | `8` | 单条披露消息的工具数 |
82
+ | `disclosure.maxSchemaBytes` | `6000` | 单个定义上限,超出转为名字公告 |
83
+ | `disclosure.maxMessageBytes` | `20000` | 单条消息上限,超出拆条 |
84
+ | `disclosure.announceRemovals` | `true` | 工具失去准入时追加 `<tools_removed>` |
85
+ | `unavailableReasons` | `{ exit_plan_mode: … }` | 头部工具未准入时的模型可见原因 |
86
+ | `maxParallelCalls` | `10` | 循环未给出并发上限时使用 |
87
+
88
+ 分类只看名字,因为注册时的 `when` 条件对插件不可见;未列入 `dynamic` 的工具默认进入头部。工具一旦进入头部就保持声明,即使当前不可调用——这正是缓存稳定的代价与保证。
89
+
90
+ ## 模型体验
91
+
92
+ ### 模型看到什么
93
+
94
+ 头部声明保持不变。动态工具在本步首次被准入时以一条 `<system-reminder>` 出现:名字 + 描述 + 完整 JSON 定义 + "可直接按名调用"的说明;移除时出现 `<tools_removed>`。`names` 模式下模型需先调 `tool_load`,定义在其结果之后作为用户消息到达。
95
+
96
+ ### Token 影响
97
+
98
+ 头部每步大小固定;披露只在工具真正增减时追加一次。相比每步重发全部声明,动态工具越多、会话越长,节省越明显。定义上限保护单条消息不被超大 schema 撑大。
99
+
100
+ ### KV Cache 影响
101
+
102
+ 前缀在会话内保持字节稳定:工具声明、系统提示词都不再随工具状态变化。这是本插件的全部目的——实测进入计划模式后,切换点的缓存命中读数保持在同一量级而不是归零。代价是模型必须先读到披露消息才能调用新工具,且披露本身会新增若干 token。
103
+
104
+ ## 已知限制
105
+
106
+ - **首次捕获时机**:头部在 Agent 首步组装时捕获。若插件在会话中途安装,或 resume 后注册集合与历史头部不同,会出现一次头部变化,此后稳定。
107
+ - **PTC 预设不接管**:PTC 只能用 `run_code`,其 SDK 文本随工具集变化;冻结 `tools:sdk` 不在本版范围。命中 `skipPresets` 时插件对该 Agent 完全让位并记录一次 info 日志。
108
+ - **分类靠配置**:`when` 条件不可见,无法自动识别"条件工具";动态名单需要按名称或前缀配置。
109
+ - **重放外观**:披露消息在 Chat 里显示为普通用户上下文;重放时工具卡片使用通用样式。
110
+ - **拒绝文案**:默认只预置 `exit_plan_mode` 的原因,其它头部工具的拒绝信息是通用文案,可通过 `unavailableReasons` 覆盖。
111
+ - **无 UI 控制**:没有开关面板,所有行为通过 profile 配置。
@@ -0,0 +1,8 @@
1
+ # The dsh-dynamic-tools bundle patch: inserts this plugin into the profile entry
2
+ # list. Declared by `dsh.bundle.patch` in package.json, so `dsh plugin add`
3
+ # reconciles the package into `dsh.profile.bundles` and the profile boot
4
+ # applies this layer automatically — no manual cordis.patch.yml edit needed.
5
+ - insert:
6
+ # Stable id so later layers can patch/disable this row by id.
7
+ - id: dynamic-tools
8
+ name: '@dsh-plugin/dsh-dynamic-tools'
package/docs/DETAIL.md ADDED
@@ -0,0 +1 @@
1
+ ![A frozen tool list beside a conversation that receives a new tool definition as a trailing message](preview.svg)
@@ -0,0 +1,25 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="640" height="300" viewBox="0 0 640 300" role="img" aria-label="A frozen tool declaration head beside a conversation that receives a new tool definition as a trailing message">
2
+ <rect x="32" y="46" width="248" height="208" rx="14" fill="#176b5b" fill-opacity="0.08" stroke="#176b5b" stroke-width="3"/>
3
+ <rect x="64" y="78" width="184" height="18" rx="9" fill="#176b5b" fill-opacity="0.8"/>
4
+ <rect x="64" y="112" width="184" height="18" rx="9" fill="#176b5b" fill-opacity="0.55"/>
5
+ <rect x="64" y="146" width="184" height="18" rx="9" fill="#176b5b" fill-opacity="0.35"/>
6
+ <rect x="196" y="186" width="52" height="40" rx="8" fill="none" stroke="#176b5b" stroke-width="3"/>
7
+ <path d="M208 186v-10a14 14 0 0 1 28 0v10" fill="none" stroke="#176b5b" stroke-width="3"/>
8
+ <circle cx="222" cy="202" r="4" fill="#176b5b"/>
9
+ <path d="M222 206v8" fill="none" stroke="#176b5b" stroke-width="3" stroke-linecap="round"/>
10
+
11
+ <path d="M300 150h56" fill="none" stroke="#db6b2c" stroke-width="4" stroke-linecap="round"/>
12
+ <path d="M348 142l12 8-12 8" fill="none" stroke="#db6b2c" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
13
+
14
+ <rect x="372" y="46" width="236" height="208" rx="14" fill="#db6b2c" fill-opacity="0.07" stroke="#db6b2c" stroke-width="3"/>
15
+ <rect x="396" y="72" width="188" height="66" rx="12" fill="none" stroke="#db6b2c" stroke-width="3"/>
16
+ <path d="M396 96h188" fill="none" stroke="#db6b2c" stroke-width="2" stroke-opacity="0.5"/>
17
+ <rect x="414" y="84" width="64" height="12" rx="6" fill="#db6b2c" fill-opacity="0.6"/>
18
+ <rect x="414" y="108" width="140" height="8" rx="4" fill="#db6b2c" fill-opacity="0.35"/>
19
+ <rect x="414" y="122" width="104" height="8" rx="4" fill="#db6b2c" fill-opacity="0.35"/>
20
+
21
+ <rect x="396" y="154" width="188" height="76" rx="12" fill="#db6b2c" fill-opacity="0.16" stroke="#db6b2c" stroke-width="3" stroke-dasharray="8 6"/>
22
+ <rect x="414" y="168" width="72" height="12" rx="6" fill="#db6b2c" fill-opacity="0.7"/>
23
+ <path d="M420 202h52M420 214h96" fill="none" stroke="#db6b2c" stroke-width="4" stroke-linecap="round" stroke-opacity="0.6"/>
24
+ <path d="M534 196h24M546 184v24" fill="none" stroke="#db6b2c" stroke-width="4" stroke-linecap="round"/>
25
+ </svg>
package/icon.svg ADDED
@@ -0,0 +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"/>
7
+ </svg>
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Pure classification and signature helpers for the frozen tool catalog.
3
+ * No Harness imports: these run under the Node type-stripping loader in tests.
4
+ *
5
+ * @module dsh-dynamic-tools/catalog
6
+ */
7
+ /** Model-facing tool schema fields this plugin reads without Harness types. */
8
+ export interface ToolSchemaLike {
9
+ readonly name: string;
10
+ readonly description: string;
11
+ readonly parameters: Record<string, unknown>;
12
+ }
13
+ /** How one registered tool name is disclosed. */
14
+ export type ToolClass = 'inline' | 'dynamic';
15
+ /** Rules that decide which tools belong in the frozen declaration head. */
16
+ export interface ClassificationRules {
17
+ /** Exact names that never enter the frozen catalog. */
18
+ readonly dynamicNames: readonly string[];
19
+ /** Name prefixes that never enter the frozen catalog. */
20
+ readonly dynamicPrefixes: readonly string[];
21
+ /** Exact names forced into the catalog, overriding the rules above. */
22
+ readonly inlineNames: readonly string[];
23
+ }
24
+ /**
25
+ * Decide how one tool name is disclosed.
26
+ * @param name - registered tool name.
27
+ * @param rules - configured classification rules.
28
+ * @returns `inline` for the frozen catalog, `dynamic` for tail disclosure.
29
+ */
30
+ export declare function classifyTool(name: string, rules: ClassificationRules): ToolClass;
31
+ /**
32
+ * Identity of one tool definition for change detection.
33
+ * Same-name registrations that differ only in key order share a signature.
34
+ * @param schema - model-facing schema of the definition.
35
+ * @returns a comparable signature string.
36
+ */
37
+ export declare function toolSignature(schema: ToolSchemaLike): string;
38
+ /**
39
+ * Split the registered definitions into the frozen catalog and tail disclosures.
40
+ * @param definitions - every definition visible to the agent at capture time.
41
+ * @param rules - configured classification rules.
42
+ * @returns inline schemas for the head and configured dynamic schemas.
43
+ */
44
+ export declare function splitCatalog(definitions: readonly ToolSchemaLike[], rules: ClassificationRules): {
45
+ inline: ToolSchemaLike[];
46
+ dynamic: ToolSchemaLike[];
47
+ };
48
+ /**
49
+ * JSON size of one definition as it would be disclosed.
50
+ * @param schema - model-facing schema of the definition.
51
+ * @returns UTF-8 byte length of its JSON encoding.
52
+ */
53
+ export declare function schemaBytes(schema: ToolSchemaLike): number;
package/lib/catalog.js ADDED
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Pure classification and signature helpers for the frozen tool catalog.
3
+ * No Harness imports: these run under the Node type-stripping loader in tests.
4
+ *
5
+ * @module dsh-dynamic-tools/catalog
6
+ */
7
+ /**
8
+ * Decide how one tool name is disclosed.
9
+ * @param name - registered tool name.
10
+ * @param rules - configured classification rules.
11
+ * @returns `inline` for the frozen catalog, `dynamic` for tail disclosure.
12
+ */
13
+ export function classifyTool(name, rules) {
14
+ if (rules.inlineNames.includes(name))
15
+ return 'inline';
16
+ if (rules.dynamicNames.includes(name))
17
+ return 'dynamic';
18
+ if (rules.dynamicPrefixes.some(prefix => name.startsWith(prefix)))
19
+ return 'dynamic';
20
+ return 'inline';
21
+ }
22
+ /** Deterministic JSON text with object keys sorted, so equal schemas compare equal. */
23
+ function stableJson(value) {
24
+ if (value === null || typeof value !== 'object')
25
+ return JSON.stringify(value) ?? 'null';
26
+ if (Array.isArray(value))
27
+ return `[${value.map(stableJson).join(',')}]`;
28
+ const entries = Object.keys(value).sort()
29
+ .map(key => `${JSON.stringify(key)}:${stableJson(value[key])}`);
30
+ return `{${entries.join(',')}}`;
31
+ }
32
+ /**
33
+ * Identity of one tool definition for change detection.
34
+ * Same-name registrations that differ only in key order share a signature.
35
+ * @param schema - model-facing schema of the definition.
36
+ * @returns a comparable signature string.
37
+ */
38
+ export function toolSignature(schema) {
39
+ return `${schema.name}\u0000${schema.description}\u0000${stableJson(schema.parameters)}`;
40
+ }
41
+ /**
42
+ * Split the registered definitions into the frozen catalog and tail disclosures.
43
+ * @param definitions - every definition visible to the agent at capture time.
44
+ * @param rules - configured classification rules.
45
+ * @returns inline schemas for the head and configured dynamic schemas.
46
+ */
47
+ export function splitCatalog(definitions, rules) {
48
+ const inline = [];
49
+ const dynamic = [];
50
+ for (const definition of definitions) {
51
+ if (classifyTool(definition.name, rules) === 'inline')
52
+ inline.push(definition);
53
+ else
54
+ dynamic.push(definition);
55
+ }
56
+ return { inline, dynamic };
57
+ }
58
+ const encoder = new TextEncoder();
59
+ /**
60
+ * JSON size of one definition as it would be disclosed.
61
+ * @param schema - model-facing schema of the definition.
62
+ * @returns UTF-8 byte length of its JSON encoding.
63
+ */
64
+ export function schemaBytes(schema) {
65
+ return encoder.encode(JSON.stringify(schema)).length;
66
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Trailing disclosure of dynamic tool definitions.
3
+ *
4
+ * Runs after the step's own pre-step listeners settle and appends recorded user
5
+ * messages, so the request head never changes. The disclosed set follows the
6
+ * registry, not the step's admission: a tool the model may not call right now
7
+ * is still worth naming, because the call itself reports why it is unavailable.
8
+ *
9
+ * @module dsh-dynamic-tools/disclose
10
+ */
11
+ import type { Context } from '@deepseek-ai/cordis';
12
+ import type { Agent } from '@deepseek-ai/dsh-agent';
13
+ import type { UserMessage } from '@deepseek-ai/dsh-llm';
14
+ import type { ToolDefinition } from '@deepseek-ai/dsh-tools';
15
+ import { type DisclosedState, type DisclosureLimits } from './disclosure.ts';
16
+ import type { SourceKind } from './source.ts';
17
+ /** Everything the pre-step listener needs to plan one step's disclosure. */
18
+ export interface DiscloseOptions {
19
+ /** Message source kind owned by this plugin. */
20
+ readonly sourceKind: SourceKind;
21
+ /** Validated disclosure limits. */
22
+ readonly limits: DisclosureLimits;
23
+ /** Whether names that disappear from the registry are announced. */
24
+ readonly announceRemovals: boolean;
25
+ /** Names the frozen head declares, per installed agent. */
26
+ readonly catalogNames: (agent: Agent) => ReadonlySet<string>;
27
+ /** Definitions this step admits, recorded by the executor's last assembly. */
28
+ readonly admitted: (agent: Agent) => readonly ToolDefinition[] | undefined;
29
+ }
30
+ /**
31
+ * Read the session's delivered state, rebuilding it from durable messages when
32
+ * the process-local holder is missing (resume, fork, compaction).
33
+ * @param agent - agent whose session is read.
34
+ * @param kind - message source kind owned by this plugin.
35
+ * @returns the folded state.
36
+ */
37
+ export declare function currentState(agent: Agent, kind: SourceKind): DisclosedState;
38
+ /**
39
+ * Replace the process-local state after a disclosure or a load.
40
+ * @param agent - agent whose session was updated.
41
+ * @param state - new state.
42
+ */
43
+ 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
+ /**
50
+ * Append this step's disclosure messages.
51
+ *
52
+ * Only definitions the step actually admits are candidates. A registered tool
53
+ * whose `when` condition is false is unavailable right now: announcing it would
54
+ * invite a call that can only be denied, so it is not disclosed at all.
55
+ *
56
+ * @param ctx - plugin context for diagnostics.
57
+ * @param agent - agent entering the step.
58
+ * @param admitted - definitions this step admits.
59
+ * @param executorCatalog - names the frozen head declares.
60
+ * @param options - disclosure settings.
61
+ * @returns the messages to append, in order.
62
+ */
63
+ export declare function disclosureMessages(ctx: Context, agent: Agent, admitted: readonly ToolDefinition[], executorCatalog: ReadonlySet<string>, options: DiscloseOptions): readonly UserMessage[];
64
+ /**
65
+ * Register the pre-step listener that appends disclosures.
66
+ * @param ctx - plugin context owning the listener.
67
+ * @param options - disclosure settings.
68
+ */
69
+ export declare function registerDisclosure(ctx: Context, options: DiscloseOptions): void;
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Trailing disclosure of dynamic tool definitions.
3
+ *
4
+ * Runs after the step's own pre-step listeners settle and appends recorded user
5
+ * messages, so the request head never changes. The disclosed set follows the
6
+ * registry, not the step's admission: a tool the model may not call right now
7
+ * is still worth naming, because the call itself reports why it is unavailable.
8
+ *
9
+ * @module dsh-dynamic-tools/disclose
10
+ */
11
+ import { createUserMessage } from '@deepseek-ai/dsh-llm';
12
+ import { projectToolSchema } from '@deepseek-ai/dsh-tools';
13
+ import { applyDisclosure, planDisclosure } from "./disclosure.js";
14
+ import { foldDisclosed } from "./fold.js";
15
+ import { renderDisclosure } from "./render.js";
16
+ /** Per-Agent delivery state without retaining agents. */
17
+ const stateByAgent = new WeakMap();
18
+ /**
19
+ * Read the session's delivered state, rebuilding it from durable messages when
20
+ * the process-local holder is missing (resume, fork, compaction).
21
+ * @param agent - agent whose session is read.
22
+ * @param kind - message source kind owned by this plugin.
23
+ * @returns the folded state.
24
+ */
25
+ export function currentState(agent, kind) {
26
+ const holder = stateByAgent.get(agent);
27
+ if (holder !== undefined)
28
+ return holder.state;
29
+ const folded = foldDisclosed(agent.session.deriveMessages(), kind);
30
+ stateByAgent.set(agent, { state: folded });
31
+ return folded;
32
+ }
33
+ /**
34
+ * Replace the process-local state after a disclosure or a load.
35
+ * @param agent - agent whose session was updated.
36
+ * @param state - new state.
37
+ */
38
+ export function storeState(agent, state) {
39
+ stateByAgent.set(agent, { state });
40
+ }
41
+ /**
42
+ * Drop process-local state so the next read folds the durable messages again.
43
+ * @param agent - agent whose session was compacted or replaced.
44
+ */
45
+ export function invalidateState(agent) {
46
+ stateByAgent.delete(agent);
47
+ }
48
+ function schemasOutsideCatalog(definitions, catalogNames) {
49
+ return definitions
50
+ .filter(definition => !catalogNames.has(definition.name))
51
+ .map(definition => projectToolSchema(definition, true));
52
+ }
53
+ /**
54
+ * Append this step's disclosure messages.
55
+ *
56
+ * Only definitions the step actually admits are candidates. A registered tool
57
+ * whose `when` condition is false is unavailable right now: announcing it would
58
+ * invite a call that can only be denied, so it is not disclosed at all.
59
+ *
60
+ * @param ctx - plugin context for diagnostics.
61
+ * @param agent - agent entering the step.
62
+ * @param admitted - definitions this step admits.
63
+ * @param executorCatalog - names the frozen head declares.
64
+ * @param options - disclosure settings.
65
+ * @returns the messages to append, in order.
66
+ */
67
+ export function disclosureMessages(ctx, agent, admitted, executorCatalog, options) {
68
+ const candidates = schemasOutsideCatalog(admitted, executorCatalog);
69
+ const current = currentState(agent, options.sourceKind);
70
+ const available = new Set(candidates.map(schema => schema.name));
71
+ const removed = options.announceRemovals
72
+ ? [...current.disclosed.keys()].filter(name => !available.has(name) && !executorCatalog.has(name))
73
+ : [];
74
+ const batches = planDisclosure(candidates, removed, current, options.limits);
75
+ if (batches.length === 0) {
76
+ // A pruned history still needs its records re-linked for later comparisons.
77
+ const folded = foldDisclosed(agent.session.deriveMessages(), options.sourceKind);
78
+ if (folded.disclosed.size !== current.disclosed.size)
79
+ storeState(agent, folded);
80
+ return [];
81
+ }
82
+ const messages = batches.map(batch => createUserMessage({
83
+ content: [{ type: 'text', text: renderDisclosure(batch) }],
84
+ source: { kind: options.sourceKind, form: 'catalog' },
85
+ }));
86
+ storeState(agent, applyDisclosure(current, batches));
87
+ ctx.logger.debug('dsh-dynamic-tools: disclosed %d batch(es) at step start', batches.length);
88
+ return messages;
89
+ }
90
+ /**
91
+ * Register the pre-step listener that appends disclosures.
92
+ * @param ctx - plugin context owning the listener.
93
+ * @param options - disclosure settings.
94
+ */
95
+ export function registerDisclosure(ctx, options) {
96
+ ctx.on('agent/pre-step', async ({ agent, signal }, next) => {
97
+ const decision = await next();
98
+ if (decision.kind === 'reject' || signal.aborted)
99
+ return decision;
100
+ try {
101
+ // The executor recorded this step's admission when assembly described the head.
102
+ const admitted = options.admitted(agent);
103
+ if (admitted === undefined)
104
+ return decision;
105
+ const messages = disclosureMessages(ctx, agent, admitted, options.catalogNames(agent), options);
106
+ if (messages.length === 0)
107
+ return decision;
108
+ return { ...decision, messages: [...decision.messages, ...messages] };
109
+ }
110
+ catch (error) {
111
+ ctx.logger.warn('dsh-dynamic-tools: failed to disclose tool definitions at step start: %o', error);
112
+ return decision;
113
+ }
114
+ });
115
+ }