@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/lib/executor.js CHANGED
@@ -1,23 +1,5 @@
1
- /**
2
- * Frozen-catalog tool executor.
3
- *
4
- * The declaration head is captured once, when this executor is installed, and
5
- * returned unchanged for every later step, so a mid-conversation tool change
6
- * never rewrites the request prefix. Tools outside that head stay callable
7
- * through tail disclosure, but only while the step admits them: an unadmitted
8
- * call is reported as an executable denial before policy and approval run.
9
- *
10
- * 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
- *
16
- * @module dsh-dynamic-tools/executor
17
- */
18
- import { executeToolBatch, ToolExecutionPipeline } from '@deepseek-ai/dsh-tools/pipeline';
19
- import { projectToolSchema } from '@deepseek-ai/dsh-tools';
20
- import { classifyTool, extendCatalog, } from "./catalog.js";
1
+ /** 保持声明基线稳定,动态工具复用宿主执行管线,并按当步准入与已保存定义校验。 */
2
+ import { classifyTool, extendCatalog, toolSignature, } from "./catalog.js";
21
3
  import { loadFirstReason, unavailableReason } from "./render.js";
22
4
  import { selectStrategy } from "./strategy.js";
23
5
  /**
@@ -29,7 +11,8 @@ export class StableCatalogExecutor {
29
11
  rules;
30
12
  options;
31
13
  state;
32
- /** Declaration head, captured by the first assembly and never replaced. */
14
+ host;
15
+ /** 连续原生步骤共用基线;从其它策略进入时以已保存请求头重新建立基线。 */
33
16
  catalog;
34
17
  /** Names the head declares. */
35
18
  catalogNames = new Set();
@@ -39,22 +22,26 @@ export class StableCatalogExecutor {
39
22
  admittedNames = new Set();
40
23
  /** Strategy settled by the current step's assembly, so every reader agrees. */
41
24
  stepStrategy;
25
+ stepRoute;
42
26
  /** Whether the missing-load-tool diagnostic was already reported. */
43
27
  loadWarningReported = false;
44
- constructor(ctx, agent, rules, options, state) {
28
+ constructor(ctx, agent, rules, options, state, host) {
45
29
  this.ctx = ctx;
46
30
  this.agent = agent;
47
31
  this.rules = rules;
48
32
  this.options = options;
49
33
  this.state = state;
34
+ this.host = host;
50
35
  }
51
36
  /** Names the frozen head declares, plus every loaded tool on a declare route. */
52
37
  declaredNames() {
53
- if (this.planStrategy() !== 'declare')
38
+ if (this.planStrategy() !== 'declare') {
54
39
  return this.catalogNames;
40
+ }
55
41
  const names = new Set(this.catalogNames);
56
- for (const name of this.state.definitions().keys())
42
+ for (const name of this.state.definitions().keys()) {
57
43
  names.add(name);
44
+ }
58
45
  return names;
59
46
  }
60
47
  /** Definitions the current step admits, captured by the last assembly. */
@@ -62,20 +49,32 @@ export class StableCatalogExecutor {
62
49
  return this.lastAdmitted;
63
50
  }
64
51
  /**
65
- * Capture the head from the first assembly, then return it unchanged, plus
66
- * every loaded definition on a declare route.
67
- * The first assembly's admission is exactly the declaration set the session
68
- * starts with, so the head matches what every later request would have
69
- * declared while the tool set is unchanged.
52
+ * 原生策略恢复已保存基线并冻结本步路由;连续步骤返回同一工具头部。
53
+ * declare 仍把已加载定义加入顶层,切回原生时按该已保存头部建立新基线。
70
54
  * @param tools - definitions this step admits, in registry order.
71
55
  * @returns the frozen model-facing catalog.
72
56
  */
73
57
  describe(tools) {
74
58
  this.lastAdmitted = tools;
75
- this.stepStrategy = selectStrategy(this.agent.model.current(), this.options.strategyRules);
59
+ const previousStrategy = this.stepStrategy;
60
+ const selection = this.agent.model.current();
61
+ this.stepRoute = selection === undefined ? undefined : { provider: selection.provider, model: selection.model };
62
+ this.stepStrategy = selectStrategy(selection, this.options.strategyRules);
63
+ if (this.stepStrategy === 'responses' && previousStrategy !== 'responses') {
64
+ const header = this.agent.session.requestHeader();
65
+ if (header !== undefined) {
66
+ const recorded = header.tools ?? [];
67
+ this.catalog = this.host.deepFreeze(structuredClone(recorded));
68
+ this.catalogNames.clear();
69
+ for (const schema of recorded) {
70
+ this.catalogNames.add(schema.name);
71
+ }
72
+ }
73
+ }
76
74
  const catalog = this.catalog ?? this.capture(tools);
77
- if (this.stepStrategy !== 'declare')
75
+ if (this.stepStrategy !== 'declare') {
78
76
  return { schemas: [...catalog] };
77
+ }
79
78
  this.reportMissingLoadTool();
80
79
  return { schemas: this.withDeclared(catalog) };
81
80
  }
@@ -86,11 +85,11 @@ export class StableCatalogExecutor {
86
85
  */
87
86
  execute(input) {
88
87
  this.admittedNames = new Set((input.toolSet?.view(this.agent) ?? new Map()).keys());
89
- const pipeline = new ToolExecutionPipeline(this.ctx, {
88
+ const pipeline = new this.host.ToolExecutionPipeline(this.ctx, {
90
89
  get: (name, scope, toolSet) => this.resolve(name, scope, toolSet),
91
90
  reject: (name) => this.reject(name),
92
91
  });
93
- return executeToolBatch(input, pipeline, () => input.maxParallelToolCalls ?? this.options.maxParallelCalls);
92
+ return this.host.executeToolBatch(input, pipeline, () => input.maxParallelToolCalls ?? this.options.maxParallelCalls);
94
93
  }
95
94
  /**
96
95
  * How this step's route receives dynamic tools.
@@ -104,6 +103,10 @@ export class StableCatalogExecutor {
104
103
  planStrategy() {
105
104
  return this.stepStrategy ?? selectStrategy(this.agent.model.current(), this.options.strategyRules);
106
105
  }
106
+ /** 配置保存仅影响下次组装,发送时必须仍是本步捕获的原生路由。 */
107
+ matchesResponsesRoute(request) {
108
+ return this.stepStrategy === 'responses' && this.stepRoute?.provider === request.provider && this.stepRoute.model === request.model;
109
+ }
107
110
  /**
108
111
  * Capture the declaration head from the first assembly.
109
112
  * @param tools - definitions the first assembly admits.
@@ -112,10 +115,11 @@ export class StableCatalogExecutor {
112
115
  capture(tools) {
113
116
  const catalog = Object.freeze(tools
114
117
  .filter(definition => classifyTool(definition.name, this.rules) === 'inline')
115
- .map(definition => Object.freeze(projectToolSchema(definition, true))));
118
+ .map(definition => this.host.deepFreeze(this.host.projectToolSchema(definition, true))));
116
119
  this.catalog = catalog;
117
- for (const schema of catalog)
120
+ for (const schema of catalog) {
118
121
  this.catalogNames.add(schema.name);
122
+ }
119
123
  return catalog;
120
124
  }
121
125
  /**
@@ -130,10 +134,11 @@ export class StableCatalogExecutor {
130
134
  const live = new Map(this.lastAdmitted.map(definition => [definition.name, definition]));
131
135
  const declared = [];
132
136
  for (const [name, recorded] of this.state.definitions()) {
133
- if (this.catalogNames.has(name))
137
+ if (this.catalogNames.has(name)) {
134
138
  continue;
139
+ }
135
140
  const current = live.get(name);
136
- declared.push(Object.freeze(current === undefined ? recorded : projectToolSchema(current, true)));
141
+ declared.push(Object.freeze(current === undefined ? recorded : this.host.projectToolSchema(current, true)));
137
142
  }
138
143
  return extendCatalog(catalog, declared);
139
144
  }
@@ -142,8 +147,9 @@ export class StableCatalogExecutor {
142
147
  * head does not declare the load tool.
143
148
  */
144
149
  reportMissingLoadTool() {
145
- if (this.loadWarningReported || this.catalogNames.has(this.options.loadToolName))
150
+ if (this.loadWarningReported || this.catalogNames.has(this.options.loadToolName)) {
146
151
  return;
152
+ }
147
153
  this.loadWarningReported = true;
148
154
  this.ctx.logger.warn('dsh-dynamic-tools: agent "%s" declares loaded tools in its tool list, but "%s" is absent from its frozen head; dynamic tools cannot be loaded in this session', this.agent.id, this.options.loadToolName);
149
155
  }
@@ -157,10 +163,13 @@ export class StableCatalogExecutor {
157
163
  */
158
164
  resolve(name, scope, toolSet) {
159
165
  const admitted = toolSet?.view(scope).get(name);
160
- if (admitted !== undefined)
166
+ if (admitted !== undefined) {
161
167
  return admitted;
162
- if (!this.catalogNames.has(name) && !this.state.disclosed().has(name))
168
+ }
169
+ if (!this.catalogNames.has(name) && !this.state.disclosed().has(name)
170
+ && !(this.planStrategy() === 'responses' && this.state.definitions().has(name))) {
163
171
  return undefined;
172
+ }
164
173
  return this.ctx.tools.definitions(this.agent).find(definition => definition.name === name);
165
174
  }
166
175
  /**
@@ -171,12 +180,23 @@ export class StableCatalogExecutor {
171
180
  */
172
181
  reject(name) {
173
182
  if (this.admittedNames.has(name)) {
174
- if (this.catalogNames.has(name) || !this.requiresLoad())
183
+ if (this.planStrategy() === 'responses') {
184
+ const current = this.lastAdmitted.find(definition => definition.name === name);
185
+ const declared = this.state.definitions().get(name) ?? this.catalog?.find(schema => schema.name === name);
186
+ if (!current || !declared || toolSignature(this.host.projectToolSchema(current, true)) !== toolSignature(declared)) {
187
+ return new Error(loadFirstReason(name));
188
+ }
189
+ return undefined;
190
+ }
191
+ if (this.catalogNames.has(name) || !this.requiresLoad()) {
175
192
  return undefined;
193
+ }
176
194
  return this.state.loaded().has(name) ? undefined : new Error(loadFirstReason(name));
177
195
  }
178
- if (!this.catalogNames.has(name) && !this.state.disclosed().has(name))
196
+ if (!this.catalogNames.has(name) && !this.state.disclosed().has(name)
197
+ && !(this.planStrategy() === 'responses' && this.state.definitions().has(name))) {
179
198
  return undefined;
199
+ }
180
200
  return new Error(unavailableReason(name, this.options.unavailableReasons[name]));
181
201
  }
182
202
  /** Whether a dynamic tool must be loaded before it may run on this route. */
@@ -0,0 +1,9 @@
1
+ import type { Agent } from '@deepseek-ai/dsh-agent';
2
+ import type { DisclosedState } from './disclosure.ts';
3
+ import type { ToolStrategy } from './strategy.ts';
4
+ /** 缓存只依赖已提交的日志位置与有效历史代次,预披露和 deferContext 不写入状态。 */
5
+ export declare class DisclosureHistory {
6
+ private readonly cache;
7
+ /** 每次读取检查有效历史代次,避免 compaction 后沿用已移除的声明。 */
8
+ read(agent: Agent, strategy: ToolStrategy): DisclosedState;
9
+ }
package/lib/history.js ADDED
@@ -0,0 +1,22 @@
1
+ import { foldDisclosed } from "./fold.js";
2
+ import { foldResponses } from "./responses.js";
3
+ import { SOURCE_KIND } from "./source.js";
4
+ /** 缓存只依赖已提交的日志位置与有效历史代次,预披露和 deferContext 不写入状态。 */
5
+ export class DisclosureHistory {
6
+ cache = new WeakMap();
7
+ /** 每次读取检查有效历史代次,避免 compaction 后沿用已移除的声明。 */
8
+ read(agent, strategy) {
9
+ const seq = agent.session.seq;
10
+ const generation = agent.session.surface.contentGeneration;
11
+ const cached = this.cache.get(agent);
12
+ if (cached?.seq === seq && cached.generation === generation && cached.strategy === strategy) {
13
+ return cached.state;
14
+ }
15
+ const messages = agent.session.deriveMessages();
16
+ const state = strategy === 'responses'
17
+ ? foldResponses(messages, agent.session.requestHeader()?.tools ?? [])
18
+ : foldDisclosed(messages, SOURCE_KIND);
19
+ this.cache.set(agent, { seq, generation, strategy, state });
20
+ return state;
21
+ }
22
+ }
package/lib/host.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ import type { HostAPI } from '@dsh-plugin/dsh-loader';
2
+ import type * as Tools from '@deepseek-ai/dsh-tools';
3
+ import type * as Pipeline from '@deepseek-ai/dsh-tools/pipeline';
4
+ import type * as Llm from '@deepseek-ai/dsh-llm';
5
+ /** 绑定当前 loader 实例,工具投影和执行始终使用同一宿主的实现。 */
6
+ export declare function hostBindings(loader: HostAPI): {
7
+ defineTool: typeof Tools.defineTool;
8
+ projectToolSchema: typeof Tools.projectToolSchema;
9
+ ToolContextUnavailableError: typeof Tools.ToolContextUnavailableError;
10
+ ToolExecutionPipeline: typeof Pipeline.ToolExecutionPipeline;
11
+ executeToolBatch: typeof Pipeline.executeToolBatch;
12
+ createUserMessage: typeof Llm.createUserMessage;
13
+ deepFreeze: <T>(value: T) => T;
14
+ };
15
+ /** 每次安装独享的宿主函数引用,避免跨实例共享模块级可变状态。 */
16
+ export type HostBindings = ReturnType<typeof hostBindings>;
package/lib/host.js ADDED
@@ -0,0 +1,15 @@
1
+ /** 绑定当前 loader 实例,工具投影和执行始终使用同一宿主的实现。 */
2
+ export function hostBindings(loader) {
3
+ if (typeof loader.llm.registerResponsesToolAdditions !== 'function') {
4
+ throw new Error('dsh-dynamic-tools: 当前 dsh-loader 缺少 registerResponsesToolAdditions,请更新配套 loader');
5
+ }
6
+ return {
7
+ defineTool: loader.dsh.tools.defineTool,
8
+ projectToolSchema: loader.dsh.tools.projectToolSchema,
9
+ ToolContextUnavailableError: loader.dsh.tools.ToolContextUnavailableError,
10
+ ToolExecutionPipeline: loader.dsh.tools.ToolExecutionPipeline,
11
+ executeToolBatch: loader.dsh.tools.executeToolBatch,
12
+ createUserMessage: loader.llm.createUserMessage,
13
+ deepFreeze: loader.llm.deepFreeze,
14
+ };
15
+ }
package/lib/index.d.ts CHANGED
@@ -1,17 +1,6 @@
1
- /**
2
- * Freeze the tool declaration head and disclose later tools at the conversation
3
- * tail.
4
- *
5
- * A model request whose tool list changes forces the agent loop to resend the
6
- * complete system prompt and declarations, which discards the provider's cached
7
- * prefix. This plugin keeps the head constant: the first step's declaration set
8
- * is captured, later admissions are delivered as recorded user messages, and a
9
- * call to a tool the step does not admit fails through an executable denial
10
- * instead of running.
11
- *
12
- * @module dsh-dynamic-tools
13
- */
14
- import z from '@deepseek-ai/schemastery';
1
+ /** 冻结工具头部,按路由选择 Responses 原生追加、按需声明或尾部文本披露。 */
2
+ import z from 'schemastery';
3
+ import type { HostAPI } from '@dsh-plugin/dsh-loader';
15
4
  import type { Context } from '@deepseek-ai/cordis';
16
5
  /** Cordis plugin name. */
17
6
  export declare const name = "@dsh-plugin/dsh-dynamic-tools";
@@ -51,6 +40,13 @@ export interface Config {
51
40
  /** Provider-route patterns restricted to that handling; empty matches every provider. */
52
41
  providers: string[];
53
42
  };
43
+ responses: {
44
+ /** 仅显式配置的 HTTP/SSE Responses 路由使用 additional_tools。 */
45
+ routes: {
46
+ provider: string;
47
+ models: string[];
48
+ }[];
49
+ };
54
50
  /** Model-facing reason reported when a declared tool is not admitted. */
55
51
  unavailableReasons: Record<string, string>;
56
52
  /** Concurrency used when the loop supplies no limit. */
@@ -63,4 +59,6 @@ export declare const Config: z<Config>;
63
59
  * @param ctx - plugin context owning every registration.
64
60
  * @param config - validated plugin configuration.
65
61
  */
66
- export declare function apply(ctx: Context, config: Config): void;
62
+ export declare function apply(ctx: Context & {
63
+ dshLoader: HostAPI;
64
+ }, config: Config): Promise<void>;
package/lib/index.js CHANGED
@@ -1,26 +1,17 @@
1
- /**
2
- * Freeze the tool declaration head and disclose later tools at the conversation
3
- * tail.
4
- *
5
- * A model request whose tool list changes forces the agent loop to resend the
6
- * complete system prompt and declarations, which discards the provider's cached
7
- * prefix. This plugin keeps the head constant: the first step's declaration set
8
- * is captured, later admissions are delivered as recorded user messages, and a
9
- * call to a tool the step does not admit fails through an executable denial
10
- * instead of running.
11
- *
12
- * @module dsh-dynamic-tools
13
- */
14
- import z from '@deepseek-ai/schemastery';
1
+ /** 冻结工具头部,按路由选择 Responses 原生追加、按需声明或尾部文本披露。 */
2
+ import z from 'schemastery';
15
3
  import { registerDisclosure } from "./disclose.js";
16
4
  import { installAgent } from "./install.js";
17
5
  import { SOURCE_KIND } from "./source.js";
18
6
  import { DEFAULT_DECLARE_MODELS } from "./strategy.js";
19
7
  import { createToolLoad, TOOL_LOAD_NAME } from "./tool-load.js";
8
+ import { hostBindings } from "./host.js";
9
+ import { DisclosureHistory } from "./history.js";
10
+ import { projectResponsesRecords } from "./responses.js";
20
11
  /** Cordis plugin name. */
21
12
  export const name = '@dsh-plugin/dsh-dynamic-tools';
22
13
  /** Services the plugin registers into. */
23
- export const inject = ['tools', 'systemPrompt'];
14
+ export const inject = ['dshLoader', 'tools', 'agents', 'agentPresets', 'systemPrompt', 'llm'];
24
15
  /** Schemastery validation; invalid values fail at load. */
25
16
  export const Config = z.object({
26
17
  installExistingAgents: z.boolean().default(true)
@@ -55,6 +46,12 @@ export const Config = z.object({
55
46
  providers: z.array(z.string()).default([])
56
47
  .description('Provider-route patterns restricted to that handling; empty matches every provider.'),
57
48
  }).default({}),
49
+ responses: z.object({
50
+ routes: z.array(z.object({
51
+ provider: z.string().required(),
52
+ models: z.array(z.string()).default([]),
53
+ })).default([]),
54
+ }).default({}),
58
55
  unavailableReasons: z.dict(z.string()).default({
59
56
  exit_plan_mode: 'Plan mode is not active in this session. Ask the user to switch to plan mode, then call it again.',
60
57
  }).description('Model-facing reason reported when a declared tool is not admitted.'),
@@ -70,6 +67,7 @@ function resolveSettings(config) {
70
67
  const strategyRules = {
71
68
  models: config.declareOnLoad.models,
72
69
  providers: config.declareOnLoad.providers,
70
+ get responses() { return config.responses.routes; },
73
71
  };
74
72
  // A route that declares loaded tools needs the loader in its head, so a
75
73
  // deployment cannot classify it onto the tail and lose the only path in.
@@ -105,6 +103,7 @@ function resolveSettings(config) {
105
103
  maxMessageBytes: config.disclosure.maxMessageBytes,
106
104
  },
107
105
  announceRemovals: config.disclosure.announceRemovals,
106
+ requireLoad: config.disclosure.requireLoad,
108
107
  },
109
108
  };
110
109
  }
@@ -113,16 +112,49 @@ function resolveSettings(config) {
113
112
  * @param ctx - plugin context owning every registration.
114
113
  * @param config - validated plugin configuration.
115
114
  */
116
- export function apply(ctx, config) {
115
+ export async function apply(ctx, config) {
116
+ const loader = ctx.dshLoader;
117
+ const host = hostBindings(loader);
118
+ const history = new DisclosureHistory();
119
+ const owner = ctx;
120
+ const preferences = await loader.config.register(owner, {
121
+ id: 'dsh-dynamic-tools', packageName: name, title: '动态工具',
122
+ fields: [{ type: 'object', key: 'responses', label: 'Responses 原生声明', fields: [{
123
+ type: 'array', key: 'routes', label: '启用路由', default: config.responses.routes.map(route => ({ provider: route.provider, models: [...route.models] })),
124
+ description: '仅填写支持 additional_tools 的 Responses HTTP/SSE 路由。provider 精确匹配,models 支持 *,空数组匹配全部模型。',
125
+ item: { type: 'object', label: '路由', fields: [
126
+ { type: 'text', key: 'provider', label: 'Provider ID', required: true },
127
+ { type: 'array', key: 'models', label: '模型规则', default: [], item: { type: 'text', label: '模型规则' } },
128
+ ] },
129
+ }] }],
130
+ });
131
+ config = { ...config, responses: preferences.get().value.responses };
132
+ preferences.watch(({ value }) => { config.responses = value.responses; });
117
133
  const settings = resolveSettings(config);
118
134
  const executors = new WeakMap();
119
135
  const release = new WeakMap();
120
136
  const reported = new WeakSet();
121
- const installOptions = { ...settings.install, executors, reported };
137
+ const installOptions = { ...settings.install, executors, reported, host, history };
122
138
  const strategyOf = (agent) => executors.get(agent)?.planStrategy();
123
139
  const declaredNamesOf = (agent) => executors.get(agent)?.declaredNames() ?? new Set();
124
- ctx.effect(() => ctx.tools.register(createToolLoad(ctx, {
140
+ const admitted = (agent) => executors.get(agent)?.admittedDefinitions();
141
+ loader.llm.registerResponsesToolAdditions(owner, request => {
142
+ if (!request.sessionId || request.purpose !== undefined) {
143
+ return undefined;
144
+ }
145
+ const agent = ctx.agents.list().find(agent => agent.session.id === request.sessionId);
146
+ const executor = agent && executors.get(agent);
147
+ if (!executor || executor.planStrategy() !== 'responses') {
148
+ return undefined;
149
+ }
150
+ if (!executor.matchesResponsesRoute(request)) {
151
+ throw new Error('dsh-dynamic-tools: 原生声明已按本步路由准备,但发送路由发生变化;请在下一步重新选择模型');
152
+ }
153
+ return projectResponsesRecords(request.messages);
154
+ });
155
+ ctx.effect(() => ctx.tools.register(createToolLoad({
125
156
  sourceKind: SOURCE_KIND,
157
+ host, history, admitted,
126
158
  limits: settings.disclose.limits,
127
159
  strategy: strategyOf,
128
160
  declaredNames: declaredNamesOf,
@@ -138,13 +170,15 @@ export function apply(ctx, config) {
138
170
  });
139
171
  if (config.installExistingAgents) {
140
172
  const agents = ctx.get('agents');
141
- for (const agent of agents?.list() ?? [])
173
+ for (const agent of agents?.list() ?? []) {
142
174
  installAgent(ctx, agent, installOptions, release);
175
+ }
143
176
  }
144
177
  registerDisclosure(ctx, {
145
178
  ...settings.disclose,
179
+ host, history,
146
180
  strategy: strategyOf,
147
181
  catalogNames: declaredNamesOf,
148
- admitted: agent => executors.get(agent)?.admittedDefinitions(),
182
+ admitted,
149
183
  });
150
184
  }
package/lib/install.d.ts CHANGED
@@ -13,9 +13,13 @@ import type { Context } from '@deepseek-ai/cordis';
13
13
  import type { Agent } from '@deepseek-ai/dsh-agent';
14
14
  import type { ClassificationRules } from './catalog.ts';
15
15
  import { StableCatalogExecutor, type ExecutorOptions } from './executor.ts';
16
+ import type { DisclosureHistory } from './history.ts';
17
+ import type { HostBindings } from './host.ts';
16
18
  import type { SourceKind } from './source.ts';
17
19
  /** Settings shared by every installed agent. */
18
20
  export interface InstallOptions {
21
+ readonly host: HostBindings;
22
+ readonly history: DisclosureHistory;
19
23
  /** Message source kind owned by this plugin. */
20
24
  readonly sourceKind: SourceKind;
21
25
  /** Classification rules for the frozen head. */
package/lib/install.js CHANGED
@@ -10,12 +10,12 @@
10
10
  * @module dsh-dynamic-tools/install
11
11
  */
12
12
  import { StableCatalogExecutor } from "./executor.js";
13
- import { currentState } from "./disclose.js";
14
13
  /** Read the preset id an agent runs under, when a registry is composed. */
15
14
  function presetOf(ctx, agent) {
16
15
  const registry = ctx.get('agentPresets');
17
- if (registry === undefined)
16
+ if (registry === undefined) {
18
17
  return undefined;
18
+ }
19
19
  return registry.presetForSession(agent.session) ?? undefined;
20
20
  }
21
21
  /**
@@ -26,8 +26,9 @@ function presetOf(ctx, agent) {
26
26
  * @param release - disposer registry, so agent disposal can release the executor.
27
27
  */
28
28
  export function installAgent(ctx, agent, options, release) {
29
- if (options.executors.has(agent))
29
+ if (options.executors.has(agent)) {
30
30
  return;
31
+ }
31
32
  const preset = presetOf(ctx, agent);
32
33
  if (preset !== undefined && options.skipPresets.includes(preset)) {
33
34
  if (!options.reported.has(agent)) {
@@ -37,11 +38,11 @@ export function installAgent(ctx, agent, options, release) {
37
38
  return;
38
39
  }
39
40
  const holder = {
40
- disclosed: () => currentState(agent, options.sourceKind).disclosed,
41
- loaded: () => currentState(agent, options.sourceKind).loaded,
42
- definitions: () => currentState(agent, options.sourceKind).definitions,
41
+ disclosed: () => options.history.read(agent, executor.planStrategy()).disclosed,
42
+ loaded: () => options.history.read(agent, executor.planStrategy()).loaded,
43
+ definitions: () => options.history.read(agent, executor.planStrategy()).definitions,
43
44
  };
44
- const executor = new StableCatalogExecutor(ctx, agent, options.rules, options.executor, holder);
45
+ const executor = new StableCatalogExecutor(ctx, agent, options.rules, options.executor, holder, options.host);
45
46
  try {
46
47
  const dispose = ctx.effect(() => {
47
48
  const uninstall = agent.ctx.tools.setExecutor(executor);
@@ -53,16 +54,21 @@ export function installAgent(ctx, agent, options, release) {
53
54
  }, 'dsh-dynamic-tools: install frozen-catalog executor');
54
55
  let released = false;
55
56
  release.set(agent, () => {
56
- if (released)
57
+ if (released) {
57
58
  return;
59
+ }
58
60
  released = true;
59
61
  release.delete(agent);
60
62
  dispose();
61
63
  });
62
64
  }
63
65
  catch (error) {
64
- if (options.reported.has(agent))
66
+ if (executor.planStrategy() === 'responses') {
67
+ throw error;
68
+ }
69
+ if (options.reported.has(agent)) {
65
70
  return;
71
+ }
66
72
  options.reported.add(agent);
67
73
  ctx.logger.warn('dsh-dynamic-tools: cannot install for agent "%s": %o', agent.id, error);
68
74
  }
@@ -0,0 +1,37 @@
1
+ import type { ResponsesToolAddition, ResponsesToolAdditionRecord } from '@dsh-plugin/dsh-loader';
2
+ import type { UserMessage } from '@deepseek-ai/dsh-llm';
3
+ import { type ToolSchemaLike } from './catalog.ts';
4
+ import type { DisclosedState, DisclosureLimits, DisclosureBatch } from './disclosure.ts';
5
+ import type { FoldableMessage } from './fold.ts';
6
+ import type { HostBindings } from './host.ts';
7
+ import { type ResponsesToolNotice } from './source.ts';
8
+ /** 有效历史中带原生声明或公告元数据的消息投影。 */
9
+ export interface ResponsesMessage extends FoldableMessage {
10
+ readonly id?: string;
11
+ readonly source?: {
12
+ readonly kind?: string;
13
+ readonly responsesToolAddition?: ResponsesToolAddition;
14
+ readonly responsesToolNotice?: ResponsesToolNotice;
15
+ };
16
+ }
17
+ /** 固定正文编码供持久化与发送时双向核验,不依赖可变注册表。 */
18
+ export declare function renderAddition(addition: ResponsesToolAddition): string;
19
+ /** 声明先保存到宿主消息,随后才可计入已加载状态。 */
20
+ export declare function additionMessage(host: HostBindings, schemas: readonly ToolSchemaLike[]): UserMessage;
21
+ /** UUID 固定长度,预算包含标识与原生函数包装。 */
22
+ export declare function additionBytes(schemas: readonly ToolSchemaLike[]): number;
23
+ /** 单个定义必须同时适合 schema 预算和持久化消息预算。 */
24
+ export declare function canLoadNative(schema: ToolSchemaLike, limits: DisclosureLimits): boolean;
25
+ /** 按最终 UTF-8 文本大小分批,定义、名字与移除通知分别记录。 */
26
+ export declare function planResponsesDisclosure(candidates: readonly ToolSchemaLike[], state: DisclosedState, limits: DisclosureLimits, requireLoad: boolean): {
27
+ additions: ToolSchemaLike[][];
28
+ notices: {
29
+ batch: DisclosureBatch;
30
+ notice: ResponsesToolNotice;
31
+ text: string;
32
+ }[];
33
+ };
34
+ /** 只接受插件来源的版本化记录,普通文本中的 schema 从不成为声明。 */
35
+ export declare function projectResponsesRecords(messages: readonly ResponsesMessage[]): ResponsesToolAdditionRecord[];
36
+ /** 声明保留历史最新定义;移除通知只撤销可见状态,执行准入另由当步工具集决定。 */
37
+ export declare function foldResponses(messages: readonly ResponsesMessage[], baseline?: readonly ToolSchemaLike[]): DisclosedState;