@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/README.md +68 -116
- package/icon.svg +6 -6
- package/lib/disclose.d.ts +8 -58
- package/lib/disclose.js +53 -140
- package/lib/executor.d.ts +13 -24
- package/lib/executor.js +62 -42
- package/lib/history.d.ts +9 -0
- package/lib/history.js +22 -0
- package/lib/host.d.ts +16 -0
- package/lib/host.js +15 -0
- package/lib/index.d.ts +13 -15
- package/lib/index.js +54 -20
- package/lib/install.d.ts +4 -0
- package/lib/install.js +15 -9
- package/lib/responses.d.ts +37 -0
- package/lib/responses.js +157 -0
- package/lib/source.d.ts +14 -0
- package/lib/source.js +2 -0
- package/lib/strategy.d.ts +9 -17
- package/lib/strategy.js +11 -19
- package/lib/tool-load.d.ts +9 -19
- package/lib/tool-load.js +15 -32
- package/package.json +12 -6
- package/src/disclose.ts +51 -174
- package/src/executor.ts +48 -40
- package/src/history.ts +25 -0
- package/src/host.ts +23 -0
- package/src/index.ts +55 -22
- package/src/install.ts +13 -9
- package/src/responses.ts +154 -0
- package/src/source.ts +16 -1
- package/src/strategy.ts +14 -20
- package/src/tool-load.ts +21 -33
package/src/disclose.ts
CHANGED
|
@@ -1,199 +1,76 @@
|
|
|
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
|
-
* 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
|
-
*
|
|
13
|
-
* @module dsh-dynamic-tools/disclose
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
1
|
import type { Context } from '@deepseek-ai/cordis'
|
|
17
2
|
import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent'
|
|
18
|
-
import { createUserMessage } from '@deepseek-ai/dsh-llm'
|
|
19
3
|
import type { UserMessage } from '@deepseek-ai/dsh-llm'
|
|
20
|
-
import { projectToolSchema } from '@deepseek-ai/dsh-tools'
|
|
21
4
|
import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
|
|
22
5
|
import type { ToolSchemaLike } from './catalog.ts'
|
|
23
|
-
import {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
type DisclosedState,
|
|
28
|
-
type DisclosureLimits,
|
|
29
|
-
} from './disclosure.ts'
|
|
30
|
-
import { foldDisclosed } from './fold.ts'
|
|
6
|
+
import { oversizedNames, planDisclosure, type DisclosureLimits } from './disclosure.ts'
|
|
7
|
+
import type { DisclosureHistory } from './history.ts'
|
|
8
|
+
import type { HostBindings } from './host.ts'
|
|
9
|
+
import { additionMessage, canLoadNative, planResponsesDisclosure } from './responses.ts'
|
|
31
10
|
import { renderDisclosure } from './render.ts'
|
|
32
11
|
import type { SourceKind } from './source.ts'
|
|
33
12
|
import type { ToolStrategy } from './strategy.ts'
|
|
34
13
|
|
|
35
|
-
/**
|
|
14
|
+
/** 披露依赖当前步准入与已保存历史,不维护预提交的加载状态。 */
|
|
36
15
|
export interface DiscloseOptions {
|
|
37
|
-
|
|
16
|
+
readonly host: HostBindings
|
|
17
|
+
readonly history: DisclosureHistory
|
|
38
18
|
readonly sourceKind: SourceKind
|
|
39
|
-
/** Validated disclosure limits. */
|
|
40
19
|
readonly limits: DisclosureLimits
|
|
41
|
-
|
|
20
|
+
readonly requireLoad: boolean
|
|
42
21
|
readonly announceRemovals: boolean
|
|
43
|
-
/** Strategy this step's executor settled, per installed agent. */
|
|
44
22
|
readonly strategy: (agent: Agent) => ToolStrategy | undefined
|
|
45
|
-
/** Names the frozen head declares, per installed agent. */
|
|
46
23
|
readonly catalogNames: (agent: Agent) => ReadonlySet<string>
|
|
47
|
-
/** Definitions this step admits, recorded by the executor's last assembly. */
|
|
48
24
|
readonly admitted: (agent: Agent) => readonly ToolDefinition[] | undefined
|
|
49
25
|
}
|
|
50
26
|
|
|
51
|
-
/**
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
* @param kind - message source kind owned by this plugin.
|
|
62
|
-
* @returns the folded state.
|
|
63
|
-
*/
|
|
64
|
-
export function currentState(agent: Agent, kind: SourceKind): DisclosedState {
|
|
65
|
-
const held = stateByAgent.get(agent)
|
|
66
|
-
if (held !== undefined) return held
|
|
67
|
-
const folded = foldDisclosed(agent.session.deriveMessages(), kind)
|
|
68
|
-
stateByAgent.set(agent, folded)
|
|
69
|
-
return folded
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/**
|
|
73
|
-
* Replace the process-local state after a disclosure or a load.
|
|
74
|
-
* @param agent - agent whose session was updated.
|
|
75
|
-
* @param state - new state.
|
|
76
|
-
*/
|
|
77
|
-
export function storeState(agent: Agent, state: DisclosedState): void {
|
|
78
|
-
stateByAgent.set(agent, state)
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/**
|
|
82
|
-
* Report a per-agent diagnostic once, so a repeated condition does not repeat
|
|
83
|
-
* its log line on every step.
|
|
84
|
-
* @param agent - agent the condition belongs to.
|
|
85
|
-
* @param key - stable key for this condition.
|
|
86
|
-
* @param report - emitter, called only for a key not reported before.
|
|
87
|
-
*/
|
|
88
|
-
function reportOnce(agent: Agent, key: string, report: () => void): void {
|
|
89
|
-
const reported = reportedByAgent.get(agent) ?? new Set<string>()
|
|
90
|
-
if (reported.has(key)) return
|
|
91
|
-
reported.add(key)
|
|
92
|
-
reportedByAgent.set(agent, reported)
|
|
93
|
-
report()
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
function schemasOutsideCatalog(
|
|
97
|
-
definitions: readonly ToolDefinition[],
|
|
98
|
-
catalogNames: ReadonlySet<string>,
|
|
99
|
-
): ToolSchemaLike[] {
|
|
100
|
-
return definitions
|
|
101
|
-
.filter(definition => !catalogNames.has(definition.name))
|
|
102
|
-
.map(definition => projectToolSchema(definition, true))
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
/**
|
|
106
|
-
* Append this step's disclosure messages.
|
|
107
|
-
*
|
|
108
|
-
* Only definitions the step actually admits are candidates. A registered tool
|
|
109
|
-
* whose `when` condition is false is unavailable right now: announcing it would
|
|
110
|
-
* invite a call that can only be denied, so it is not disclosed at all.
|
|
111
|
-
*
|
|
112
|
-
* @param ctx - plugin context for diagnostics.
|
|
113
|
-
* @param agent - agent entering the step.
|
|
114
|
-
* @param admitted - definitions this step admits.
|
|
115
|
-
* @param executorCatalog - names the frozen head declares.
|
|
116
|
-
* @param options - disclosure settings.
|
|
117
|
-
* @param strategy - how this step's route receives dynamic tools.
|
|
118
|
-
* @returns the messages to append, in order.
|
|
119
|
-
*/
|
|
120
|
-
export function disclosureMessages(
|
|
121
|
-
ctx: Context,
|
|
122
|
-
agent: Agent,
|
|
123
|
-
admitted: readonly ToolDefinition[],
|
|
124
|
-
executorCatalog: ReadonlySet<string>,
|
|
125
|
-
options: DiscloseOptions,
|
|
126
|
-
strategy: ToolStrategy,
|
|
127
|
-
): readonly UserMessage[] {
|
|
128
|
-
const candidates = schemasOutsideCatalog(admitted, executorCatalog)
|
|
129
|
-
const current = currentState(agent, options.sourceKind)
|
|
130
|
-
for (const name of current.damaged) {
|
|
131
|
-
reportOnce(agent, `damaged:${name}`, () => {
|
|
132
|
-
ctx.logger.warn('dsh-dynamic-tools: recorded definition for "%s" could not be parsed; disclosing it again', name)
|
|
133
|
-
})
|
|
134
|
-
}
|
|
135
|
-
const limits: DisclosureLimits = strategy === 'declare' ? { ...options.limits, mode: 'names' } : options.limits
|
|
136
|
-
if (limits.mode === 'names') {
|
|
137
|
-
for (const name of oversizedNames(candidates, limits)) {
|
|
138
|
-
reportOnce(agent, `oversized:${name}`, () => {
|
|
139
|
-
ctx.logger.warn(
|
|
140
|
-
'dsh-dynamic-tools: "%s" exceeds maxSchemaBytes (%d) and cannot be loaded on this route; it is not announced',
|
|
141
|
-
name,
|
|
142
|
-
limits.maxSchemaBytes,
|
|
143
|
-
)
|
|
144
|
-
})
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
const available = new Set(candidates.map(schema => schema.name))
|
|
148
|
-
const removed = options.announceRemovals
|
|
149
|
-
? [...current.disclosed.keys()].filter(name => !available.has(name) && !executorCatalog.has(name))
|
|
150
|
-
: []
|
|
151
|
-
const batches = planDisclosure(candidates, removed, current, limits)
|
|
152
|
-
if (batches.length === 0) {
|
|
153
|
-
// A pruned history still needs its records re-linked for later comparisons.
|
|
154
|
-
const folded = foldDisclosed(agent.session.deriveMessages(), options.sourceKind)
|
|
155
|
-
if (folded.disclosed.size !== current.disclosed.size) storeState(agent, folded)
|
|
156
|
-
return []
|
|
157
|
-
}
|
|
158
|
-
const messages = batches.map(batch => createUserMessage({
|
|
159
|
-
content: [{ type: 'text', text: renderDisclosure(batch, strategy) }],
|
|
160
|
-
source: { kind: options.sourceKind, form: 'catalog' },
|
|
161
|
-
}))
|
|
162
|
-
storeState(agent, applyDisclosure(current, batches))
|
|
163
|
-
ctx.logger.debug('dsh-dynamic-tools: disclosed %d batch(es) at step start', batches.length)
|
|
164
|
-
return messages
|
|
27
|
+
/** 原生定义单独成消息,文字通知不与 additional_tools 共用同一消息位置。 */
|
|
28
|
+
function nativeMessages(agent: Agent, candidates: readonly ToolSchemaLike[], options: DiscloseOptions): readonly UserMessage[] {
|
|
29
|
+
const plan = planResponsesDisclosure(candidates, options.history.read(agent, 'responses'), options.limits, options.requireLoad)
|
|
30
|
+
return [
|
|
31
|
+
...plan.additions.map(schemas => additionMessage(options.host, schemas)),
|
|
32
|
+
...plan.notices.map(({ notice, text }) => options.host.createUserMessage({
|
|
33
|
+
content: [{ type: 'text', text }],
|
|
34
|
+
source: { kind: options.sourceKind, form: 'catalog', responsesToolNotice: notice },
|
|
35
|
+
})),
|
|
36
|
+
]
|
|
165
37
|
}
|
|
166
38
|
|
|
167
|
-
/**
|
|
168
|
-
* Register the pre-step listener that appends disclosures.
|
|
169
|
-
* @param ctx - plugin context owning the listener.
|
|
170
|
-
* @param options - disclosure settings.
|
|
171
|
-
*/
|
|
39
|
+
/** 其它 pre-step 处理完成后生成待提交消息,异常沿宿主失败管线报告。 */
|
|
172
40
|
export function registerDisclosure(ctx: Context, options: DiscloseOptions): void {
|
|
173
|
-
|
|
41
|
+
const reported = new WeakMap<Agent, Set<string>>()
|
|
42
|
+
const report = (agent: Agent, key: string, emit: () => void): void => {
|
|
43
|
+
const keys = reported.get(agent) ?? new Set<string>()
|
|
44
|
+
if (keys.has(key)) { return }
|
|
45
|
+
reported.set(agent, keys.add(key))
|
|
46
|
+
emit()
|
|
47
|
+
}
|
|
48
|
+
ctx.on('agent/pre-step', async ({ agent, signal }, next): Promise<PreStepDecision> => {
|
|
174
49
|
const decision = await next()
|
|
175
|
-
if (decision.kind === 'reject' || signal.aborted) return decision
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
50
|
+
if (decision.kind === 'reject' || signal.aborted) { return decision }
|
|
51
|
+
const admitted = options.admitted(agent)
|
|
52
|
+
if (!admitted) { return decision }
|
|
53
|
+
const strategy = options.strategy(agent) ?? 'tail'
|
|
54
|
+
const catalog = options.catalogNames(agent)
|
|
55
|
+
const all = admitted.map(definition => options.host.projectToolSchema(definition, true))
|
|
56
|
+
const candidates = all.filter(schema => !catalog.has(schema.name))
|
|
57
|
+
const state = options.history.read(agent, strategy)
|
|
58
|
+
const limits = strategy === 'declare' || options.requireLoad ? { ...options.limits, mode: 'names' as const } : options.limits
|
|
59
|
+
for (const name of state.damaged) { report(agent, `damaged:${name}`, () => ctx.logger.warn('dsh-dynamic-tools: 定义 %s 损坏,将重新披露', name)) }
|
|
60
|
+
const oversized = strategy === 'responses' ? candidates.filter(schema => !canLoadNative(schema, limits)).map(schema => schema.name) : oversizedNames(candidates, limits)
|
|
61
|
+
for (const name of oversized) { report(agent, `oversized:${name}`, () => ctx.logger.warn('dsh-dynamic-tools: %s 超过声明大小限制,tool_load 将报告 tooLarge', name)) }
|
|
62
|
+
let messages: readonly UserMessage[]
|
|
63
|
+
if (strategy === 'responses') {
|
|
64
|
+
// 首次请求的静态工具尚未写入 header,避免把它们重复追加。
|
|
65
|
+
messages = nativeMessages(agent, agent.session.requestHeader() ? all : candidates, options)
|
|
66
|
+
} else {
|
|
67
|
+
const available = new Set(candidates.map(schema => schema.name))
|
|
68
|
+
const removed = options.announceRemovals ? [...state.disclosed.keys()].filter(name => !available.has(name) && !catalog.has(name)) : []
|
|
69
|
+
messages = planDisclosure(candidates, removed, state, limits).map(batch => options.host.createUserMessage({
|
|
70
|
+
content: [{ type: 'text', text: renderDisclosure(batch, strategy) }],
|
|
71
|
+
source: { kind: options.sourceKind, form: 'catalog' },
|
|
72
|
+
}))
|
|
197
73
|
}
|
|
74
|
+
return messages.length ? { ...decision, messages: [...decision.messages, ...messages] } : decision
|
|
198
75
|
})
|
|
199
76
|
}
|
package/src/executor.ts
CHANGED
|
@@ -1,25 +1,8 @@
|
|
|
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
|
-
*/
|
|
1
|
+
/** 保持声明基线稳定,动态工具复用宿主执行管线,并按当步准入与已保存定义校验。 */
|
|
18
2
|
|
|
19
3
|
import type { Context } from '@deepseek-ai/cordis'
|
|
20
4
|
import type { Agent } from '@deepseek-ai/dsh-agent'
|
|
21
|
-
import {
|
|
22
|
-
import { projectToolSchema } from '@deepseek-ai/dsh-tools'
|
|
5
|
+
import type { HostBindings } from './host.ts'
|
|
23
6
|
import type {
|
|
24
7
|
ResolvedToolSet,
|
|
25
8
|
ToolBatchInput,
|
|
@@ -32,6 +15,7 @@ import type { ScopeKey } from '@deepseek-ai/dsh-scope'
|
|
|
32
15
|
import {
|
|
33
16
|
classifyTool,
|
|
34
17
|
extendCatalog,
|
|
18
|
+
toolSignature,
|
|
35
19
|
type ClassificationRules,
|
|
36
20
|
type ToolSchemaLike,
|
|
37
21
|
} from './catalog.ts'
|
|
@@ -67,7 +51,7 @@ export interface ExecutorOptions {
|
|
|
67
51
|
* Executes the frozen declaration head plus admitted dynamic tools.
|
|
68
52
|
*/
|
|
69
53
|
export class StableCatalogExecutor implements ToolExecutor {
|
|
70
|
-
/**
|
|
54
|
+
/** 连续原生步骤共用基线;从其它策略进入时以已保存请求头重新建立基线。 */
|
|
71
55
|
private catalog: readonly ToolSchemaLike[] | undefined
|
|
72
56
|
/** Names the head declares. */
|
|
73
57
|
private readonly catalogNames = new Set<string>()
|
|
@@ -77,6 +61,7 @@ export class StableCatalogExecutor implements ToolExecutor {
|
|
|
77
61
|
private admittedNames: ReadonlySet<string> = new Set()
|
|
78
62
|
/** Strategy settled by the current step's assembly, so every reader agrees. */
|
|
79
63
|
private stepStrategy: ToolStrategy | undefined
|
|
64
|
+
private stepRoute: { readonly provider: string, readonly model: string } | undefined
|
|
80
65
|
/** Whether the missing-load-tool diagnostic was already reported. */
|
|
81
66
|
private loadWarningReported = false
|
|
82
67
|
|
|
@@ -86,13 +71,14 @@ export class StableCatalogExecutor implements ToolExecutor {
|
|
|
86
71
|
private readonly rules: ClassificationRules,
|
|
87
72
|
private readonly options: ExecutorOptions,
|
|
88
73
|
private readonly state: DisclosureStateHandle,
|
|
74
|
+
private readonly host: HostBindings,
|
|
89
75
|
) {}
|
|
90
76
|
|
|
91
77
|
/** Names the frozen head declares, plus every loaded tool on a declare route. */
|
|
92
78
|
declaredNames(): ReadonlySet<string> {
|
|
93
|
-
if (this.planStrategy() !== 'declare') return this.catalogNames
|
|
79
|
+
if (this.planStrategy() !== 'declare') { return this.catalogNames }
|
|
94
80
|
const names = new Set(this.catalogNames)
|
|
95
|
-
for (const name of this.state.definitions().keys()) names.add(name)
|
|
81
|
+
for (const name of this.state.definitions().keys()) { names.add(name) }
|
|
96
82
|
return names
|
|
97
83
|
}
|
|
98
84
|
|
|
@@ -102,19 +88,28 @@ export class StableCatalogExecutor implements ToolExecutor {
|
|
|
102
88
|
}
|
|
103
89
|
|
|
104
90
|
/**
|
|
105
|
-
*
|
|
106
|
-
*
|
|
107
|
-
* The first assembly's admission is exactly the declaration set the session
|
|
108
|
-
* starts with, so the head matches what every later request would have
|
|
109
|
-
* declared while the tool set is unchanged.
|
|
91
|
+
* 原生策略恢复已保存基线并冻结本步路由;连续步骤返回同一工具头部。
|
|
92
|
+
* declare 仍把已加载定义加入顶层,切回原生时按该已保存头部建立新基线。
|
|
110
93
|
* @param tools - definitions this step admits, in registry order.
|
|
111
94
|
* @returns the frozen model-facing catalog.
|
|
112
95
|
*/
|
|
113
96
|
describe(tools: readonly ToolDefinition[]): ToolModelInput {
|
|
114
97
|
this.lastAdmitted = tools
|
|
115
|
-
|
|
98
|
+
const previousStrategy = this.stepStrategy
|
|
99
|
+
const selection = this.agent.model.current()
|
|
100
|
+
this.stepRoute = selection === undefined ? undefined : { provider: selection.provider, model: selection.model }
|
|
101
|
+
this.stepStrategy = selectStrategy(selection, this.options.strategyRules)
|
|
102
|
+
if (this.stepStrategy === 'responses' && previousStrategy !== 'responses') {
|
|
103
|
+
const header = this.agent.session.requestHeader()
|
|
104
|
+
if (header !== undefined) {
|
|
105
|
+
const recorded = header.tools ?? []
|
|
106
|
+
this.catalog = this.host.deepFreeze(structuredClone(recorded))
|
|
107
|
+
this.catalogNames.clear()
|
|
108
|
+
for (const schema of recorded) { this.catalogNames.add(schema.name) }
|
|
109
|
+
}
|
|
110
|
+
}
|
|
116
111
|
const catalog = this.catalog ?? this.capture(tools)
|
|
117
|
-
if (this.stepStrategy !== 'declare') return { schemas: [...catalog] }
|
|
112
|
+
if (this.stepStrategy !== 'declare') { return { schemas: [...catalog] } }
|
|
118
113
|
this.reportMissingLoadTool()
|
|
119
114
|
return { schemas: this.withDeclared(catalog) }
|
|
120
115
|
}
|
|
@@ -126,11 +121,11 @@ export class StableCatalogExecutor implements ToolExecutor {
|
|
|
126
121
|
*/
|
|
127
122
|
execute(input: ToolBatchInput): Promise<ToolBatchResult> {
|
|
128
123
|
this.admittedNames = new Set((input.toolSet?.view(this.agent) ?? new Map<string, ToolDefinition>()).keys())
|
|
129
|
-
const pipeline = new ToolExecutionPipeline(this.ctx, {
|
|
124
|
+
const pipeline = new this.host.ToolExecutionPipeline(this.ctx, {
|
|
130
125
|
get: (name: string, scope: ScopeKey | undefined, toolSet: ResolvedToolSet | undefined) => this.resolve(name, scope, toolSet),
|
|
131
126
|
reject: (name: string) => this.reject(name),
|
|
132
127
|
})
|
|
133
|
-
return executeToolBatch(input, pipeline, () => input.maxParallelToolCalls ?? this.options.maxParallelCalls)
|
|
128
|
+
return this.host.executeToolBatch(input, pipeline, () => input.maxParallelToolCalls ?? this.options.maxParallelCalls)
|
|
134
129
|
}
|
|
135
130
|
|
|
136
131
|
/**
|
|
@@ -146,6 +141,11 @@ export class StableCatalogExecutor implements ToolExecutor {
|
|
|
146
141
|
return this.stepStrategy ?? selectStrategy(this.agent.model.current(), this.options.strategyRules)
|
|
147
142
|
}
|
|
148
143
|
|
|
144
|
+
/** 配置保存仅影响下次组装,发送时必须仍是本步捕获的原生路由。 */
|
|
145
|
+
matchesResponsesRoute(request: { readonly provider: string, readonly model: string }): boolean {
|
|
146
|
+
return this.stepStrategy === 'responses' && this.stepRoute?.provider === request.provider && this.stepRoute.model === request.model
|
|
147
|
+
}
|
|
148
|
+
|
|
149
149
|
/**
|
|
150
150
|
* Capture the declaration head from the first assembly.
|
|
151
151
|
* @param tools - definitions the first assembly admits.
|
|
@@ -154,9 +154,9 @@ export class StableCatalogExecutor implements ToolExecutor {
|
|
|
154
154
|
private capture(tools: readonly ToolDefinition[]): readonly ToolSchemaLike[] {
|
|
155
155
|
const catalog = Object.freeze(tools
|
|
156
156
|
.filter(definition => classifyTool(definition.name, this.rules) === 'inline')
|
|
157
|
-
.map(definition =>
|
|
157
|
+
.map(definition => this.host.deepFreeze(this.host.projectToolSchema(definition, true))))
|
|
158
158
|
this.catalog = catalog
|
|
159
|
-
for (const schema of catalog) this.catalogNames.add(schema.name)
|
|
159
|
+
for (const schema of catalog) { this.catalogNames.add(schema.name) }
|
|
160
160
|
return catalog
|
|
161
161
|
}
|
|
162
162
|
|
|
@@ -172,9 +172,9 @@ export class StableCatalogExecutor implements ToolExecutor {
|
|
|
172
172
|
const live = new Map(this.lastAdmitted.map(definition => [definition.name, definition]))
|
|
173
173
|
const declared: ToolSchemaLike[] = []
|
|
174
174
|
for (const [name, recorded] of this.state.definitions()) {
|
|
175
|
-
if (this.catalogNames.has(name)) continue
|
|
175
|
+
if (this.catalogNames.has(name)) { continue }
|
|
176
176
|
const current = live.get(name)
|
|
177
|
-
declared.push(Object.freeze(current === undefined ? recorded : projectToolSchema(current, true)))
|
|
177
|
+
declared.push(Object.freeze(current === undefined ? recorded : this.host.projectToolSchema(current, true)))
|
|
178
178
|
}
|
|
179
179
|
return extendCatalog(catalog, declared)
|
|
180
180
|
}
|
|
@@ -184,7 +184,7 @@ export class StableCatalogExecutor implements ToolExecutor {
|
|
|
184
184
|
* head does not declare the load tool.
|
|
185
185
|
*/
|
|
186
186
|
private reportMissingLoadTool(): void {
|
|
187
|
-
if (this.loadWarningReported || this.catalogNames.has(this.options.loadToolName)) return
|
|
187
|
+
if (this.loadWarningReported || this.catalogNames.has(this.options.loadToolName)) { return }
|
|
188
188
|
this.loadWarningReported = true
|
|
189
189
|
this.ctx.logger.warn(
|
|
190
190
|
'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',
|
|
@@ -207,8 +207,9 @@ export class StableCatalogExecutor implements ToolExecutor {
|
|
|
207
207
|
toolSet: ResolvedToolSet | undefined,
|
|
208
208
|
): ToolDefinition | undefined {
|
|
209
209
|
const admitted = toolSet?.view(scope).get(name)
|
|
210
|
-
if (admitted !== undefined) return admitted
|
|
211
|
-
if (!this.catalogNames.has(name) && !this.state.disclosed().has(name)
|
|
210
|
+
if (admitted !== undefined) { return admitted }
|
|
211
|
+
if (!this.catalogNames.has(name) && !this.state.disclosed().has(name)
|
|
212
|
+
&& !(this.planStrategy() === 'responses' && this.state.definitions().has(name))) { return undefined }
|
|
212
213
|
return this.ctx.tools.definitions(this.agent).find(definition => definition.name === name)
|
|
213
214
|
}
|
|
214
215
|
|
|
@@ -220,10 +221,17 @@ export class StableCatalogExecutor implements ToolExecutor {
|
|
|
220
221
|
*/
|
|
221
222
|
private reject(name: string): Error | undefined {
|
|
222
223
|
if (this.admittedNames.has(name)) {
|
|
223
|
-
if (this.
|
|
224
|
+
if (this.planStrategy() === 'responses') {
|
|
225
|
+
const current = this.lastAdmitted.find(definition => definition.name === name)
|
|
226
|
+
const declared = this.state.definitions().get(name) ?? this.catalog?.find(schema => schema.name === name)
|
|
227
|
+
if (!current || !declared || toolSignature(this.host.projectToolSchema(current, true)) !== toolSignature(declared)) { return new Error(loadFirstReason(name)) }
|
|
228
|
+
return undefined
|
|
229
|
+
}
|
|
230
|
+
if (this.catalogNames.has(name) || !this.requiresLoad()) { return undefined }
|
|
224
231
|
return this.state.loaded().has(name) ? undefined : new Error(loadFirstReason(name))
|
|
225
232
|
}
|
|
226
|
-
if (!this.catalogNames.has(name) && !this.state.disclosed().has(name)
|
|
233
|
+
if (!this.catalogNames.has(name) && !this.state.disclosed().has(name)
|
|
234
|
+
&& !(this.planStrategy() === 'responses' && this.state.definitions().has(name))) { return undefined }
|
|
227
235
|
return new Error(unavailableReason(name, this.options.unavailableReasons[name]))
|
|
228
236
|
}
|
|
229
237
|
|
package/src/history.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Agent } from '@deepseek-ai/dsh-agent'
|
|
2
|
+
import type { DisclosedState } from './disclosure.ts'
|
|
3
|
+
import { foldDisclosed } from './fold.ts'
|
|
4
|
+
import { foldResponses } from './responses.ts'
|
|
5
|
+
import { SOURCE_KIND } from './source.ts'
|
|
6
|
+
import type { ToolStrategy } from './strategy.ts'
|
|
7
|
+
|
|
8
|
+
/** 缓存只依赖已提交的日志位置与有效历史代次,预披露和 deferContext 不写入状态。 */
|
|
9
|
+
export class DisclosureHistory {
|
|
10
|
+
private readonly cache = new WeakMap<Agent, { seq: number, generation: number, strategy: ToolStrategy, state: DisclosedState }>()
|
|
11
|
+
|
|
12
|
+
/** 每次读取检查有效历史代次,避免 compaction 后沿用已移除的声明。 */
|
|
13
|
+
read(agent: Agent, strategy: ToolStrategy): DisclosedState {
|
|
14
|
+
const seq = agent.session.seq
|
|
15
|
+
const generation = agent.session.surface.contentGeneration
|
|
16
|
+
const cached = this.cache.get(agent)
|
|
17
|
+
if (cached?.seq === seq && cached.generation === generation && cached.strategy === strategy) { return cached.state }
|
|
18
|
+
const messages = agent.session.deriveMessages()
|
|
19
|
+
const state = strategy === 'responses'
|
|
20
|
+
? foldResponses(messages, agent.session.requestHeader()?.tools ?? [])
|
|
21
|
+
: foldDisclosed(messages, SOURCE_KIND)
|
|
22
|
+
this.cache.set(agent, { seq, generation, strategy, state })
|
|
23
|
+
return state
|
|
24
|
+
}
|
|
25
|
+
}
|
package/src/host.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
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
|
+
|
|
6
|
+
/** 绑定当前 loader 实例,工具投影和执行始终使用同一宿主的实现。 */
|
|
7
|
+
export function hostBindings(loader: HostAPI) {
|
|
8
|
+
if (typeof loader.llm.registerResponsesToolAdditions !== 'function') {
|
|
9
|
+
throw new Error('dsh-dynamic-tools: 当前 dsh-loader 缺少 registerResponsesToolAdditions,请更新配套 loader')
|
|
10
|
+
}
|
|
11
|
+
return {
|
|
12
|
+
defineTool: loader.dsh.tools.defineTool as typeof Tools.defineTool,
|
|
13
|
+
projectToolSchema: loader.dsh.tools.projectToolSchema as typeof Tools.projectToolSchema,
|
|
14
|
+
ToolContextUnavailableError: loader.dsh.tools.ToolContextUnavailableError as typeof Tools.ToolContextUnavailableError,
|
|
15
|
+
ToolExecutionPipeline: loader.dsh.tools.ToolExecutionPipeline as typeof Pipeline.ToolExecutionPipeline,
|
|
16
|
+
executeToolBatch: loader.dsh.tools.executeToolBatch as typeof Pipeline.executeToolBatch,
|
|
17
|
+
createUserMessage: loader.llm.createUserMessage as typeof Llm.createUserMessage,
|
|
18
|
+
deepFreeze: loader.llm.deepFreeze,
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** 每次安装独享的宿主函数引用,避免跨实例共享模块级可变状态。 */
|
|
23
|
+
export type HostBindings = ReturnType<typeof hostBindings>
|
package/src/index.ts
CHANGED
|
@@ -1,18 +1,7 @@
|
|
|
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
|
-
*/
|
|
1
|
+
/** 冻结工具头部,按路由选择 Responses 原生追加、按需声明或尾部文本披露。 */
|
|
14
2
|
|
|
15
|
-
import z from '
|
|
3
|
+
import z from 'schemastery'
|
|
4
|
+
import type { HostAPI, CordisContext } from '@dsh-plugin/dsh-loader'
|
|
16
5
|
import type { Context } from '@deepseek-ai/cordis'
|
|
17
6
|
import type { Agent } from '@deepseek-ai/dsh-agent'
|
|
18
7
|
import type { ClassificationRules } from './catalog.ts'
|
|
@@ -22,12 +11,15 @@ import { installAgent, type InstallOptions } from './install.ts'
|
|
|
22
11
|
import { SOURCE_KIND } from './source.ts'
|
|
23
12
|
import { DEFAULT_DECLARE_MODELS, type StrategyRules, type ToolStrategy } from './strategy.ts'
|
|
24
13
|
import { createToolLoad, TOOL_LOAD_NAME } from './tool-load.ts'
|
|
14
|
+
import { hostBindings } from './host.ts'
|
|
15
|
+
import { DisclosureHistory } from './history.ts'
|
|
16
|
+
import { projectResponsesRecords, type ResponsesMessage } from './responses.ts'
|
|
25
17
|
|
|
26
18
|
/** Cordis plugin name. */
|
|
27
19
|
export const name = '@dsh-plugin/dsh-dynamic-tools'
|
|
28
20
|
|
|
29
21
|
/** Services the plugin registers into. */
|
|
30
|
-
export const inject = ['tools', 'systemPrompt']
|
|
22
|
+
export const inject = ['dshLoader', 'tools', 'agents', 'agentPresets', 'systemPrompt', 'llm']
|
|
31
23
|
|
|
32
24
|
/** Tool-selection and disclosure settings. */
|
|
33
25
|
export interface Config {
|
|
@@ -63,6 +55,10 @@ export interface Config {
|
|
|
63
55
|
/** Provider-route patterns restricted to that handling; empty matches every provider. */
|
|
64
56
|
providers: string[]
|
|
65
57
|
}
|
|
58
|
+
responses: {
|
|
59
|
+
/** 仅显式配置的 HTTP/SSE Responses 路由使用 additional_tools。 */
|
|
60
|
+
routes: { provider: string, models: string[] }[]
|
|
61
|
+
}
|
|
66
62
|
/** Model-facing reason reported when a declared tool is not admitted. */
|
|
67
63
|
unavailableReasons: Record<string, string>
|
|
68
64
|
/** Concurrency used when the loop supplies no limit. */
|
|
@@ -103,6 +99,12 @@ export const Config: z<Config> = z.object({
|
|
|
103
99
|
providers: z.array(z.string()).default([])
|
|
104
100
|
.description('Provider-route patterns restricted to that handling; empty matches every provider.'),
|
|
105
101
|
}).default({}),
|
|
102
|
+
responses: z.object({
|
|
103
|
+
routes: z.array(z.object({
|
|
104
|
+
provider: z.string().required(),
|
|
105
|
+
models: z.array(z.string()).default([]),
|
|
106
|
+
})).default([]),
|
|
107
|
+
}).default({}),
|
|
106
108
|
unavailableReasons: z.dict(z.string()).default({
|
|
107
109
|
exit_plan_mode: 'Plan mode is not active in this session. Ask the user to switch to plan mode, then call it again.',
|
|
108
110
|
}).description('Model-facing reason reported when a declared tool is not admitted.'),
|
|
@@ -118,12 +120,13 @@ export const Config: z<Config> = z.object({
|
|
|
118
120
|
function resolveSettings(config: Config): {
|
|
119
121
|
rules: ClassificationRules
|
|
120
122
|
strategyRules: StrategyRules
|
|
121
|
-
install: Omit<InstallOptions, 'executors' | 'reported'>
|
|
122
|
-
disclose: Omit<DiscloseOptions, 'strategy' | 'catalogNames' | 'admitted'>
|
|
123
|
+
install: Omit<InstallOptions, 'executors' | 'reported' | 'host' | 'history'>
|
|
124
|
+
disclose: Omit<DiscloseOptions, 'strategy' | 'catalogNames' | 'admitted' | 'host' | 'history'>
|
|
123
125
|
} {
|
|
124
126
|
const strategyRules: StrategyRules = {
|
|
125
127
|
models: config.declareOnLoad.models,
|
|
126
128
|
providers: config.declareOnLoad.providers,
|
|
129
|
+
get responses() { return config.responses.routes },
|
|
127
130
|
}
|
|
128
131
|
// A route that declares loaded tools needs the loader in its head, so a
|
|
129
132
|
// deployment cannot classify it onto the tail and lose the only path in.
|
|
@@ -159,6 +162,7 @@ function resolveSettings(config: Config): {
|
|
|
159
162
|
maxMessageBytes: config.disclosure.maxMessageBytes,
|
|
160
163
|
},
|
|
161
164
|
announceRemovals: config.disclosure.announceRemovals,
|
|
165
|
+
requireLoad: config.disclosure.requireLoad,
|
|
162
166
|
},
|
|
163
167
|
}
|
|
164
168
|
}
|
|
@@ -168,17 +172,45 @@ function resolveSettings(config: Config): {
|
|
|
168
172
|
* @param ctx - plugin context owning every registration.
|
|
169
173
|
* @param config - validated plugin configuration.
|
|
170
174
|
*/
|
|
171
|
-
export function apply(ctx: Context, config: Config): void {
|
|
175
|
+
export async function apply(ctx: Context & { dshLoader: HostAPI }, config: Config): Promise<void> {
|
|
176
|
+
const loader = ctx.dshLoader
|
|
177
|
+
const host = hostBindings(loader)
|
|
178
|
+
const history = new DisclosureHistory()
|
|
179
|
+
const owner = ctx as unknown as CordisContext
|
|
180
|
+
const preferences = await loader.config.register<{ responses: Config['responses'] }>(owner, {
|
|
181
|
+
id: 'dsh-dynamic-tools', packageName: name, title: '动态工具',
|
|
182
|
+
fields: [{ type: 'object', key: 'responses', label: 'Responses 原生声明', fields: [{
|
|
183
|
+
type: 'array', key: 'routes', label: '启用路由', default: config.responses.routes.map(route => ({ provider: route.provider, models: [...route.models] })),
|
|
184
|
+
description: '仅填写支持 additional_tools 的 Responses HTTP/SSE 路由。provider 精确匹配,models 支持 *,空数组匹配全部模型。',
|
|
185
|
+
item: { type: 'object', label: '路由', fields: [
|
|
186
|
+
{ type: 'text', key: 'provider', label: 'Provider ID', required: true },
|
|
187
|
+
{ type: 'array', key: 'models', label: '模型规则', default: [], item: { type: 'text', label: '模型规则' } },
|
|
188
|
+
] },
|
|
189
|
+
}] }],
|
|
190
|
+
})
|
|
191
|
+
config = { ...config, responses: preferences.get().value.responses }
|
|
192
|
+
preferences.watch(({ value }) => { config.responses = value.responses })
|
|
172
193
|
const settings = resolveSettings(config)
|
|
173
194
|
const executors = new WeakMap<Agent, StableCatalogExecutor>()
|
|
174
195
|
const release = new WeakMap<Agent, () => void>()
|
|
175
196
|
const reported = new WeakSet<Agent>()
|
|
176
|
-
const installOptions: InstallOptions = { ...settings.install, executors, reported }
|
|
197
|
+
const installOptions: InstallOptions = { ...settings.install, executors, reported, host, history }
|
|
177
198
|
const strategyOf = (agent: Agent): ToolStrategy | undefined => executors.get(agent)?.planStrategy()
|
|
178
199
|
const declaredNamesOf = (agent: Agent): ReadonlySet<string> => executors.get(agent)?.declaredNames() ?? new Set()
|
|
200
|
+
const admitted = (agent: Agent) => executors.get(agent)?.admittedDefinitions()
|
|
201
|
+
|
|
202
|
+
loader.llm.registerResponsesToolAdditions(owner, request => {
|
|
203
|
+
if (!request.sessionId || request.purpose !== undefined) { return undefined }
|
|
204
|
+
const agent = ctx.agents.list().find(agent => agent.session.id === request.sessionId)
|
|
205
|
+
const executor = agent && executors.get(agent)
|
|
206
|
+
if (!executor || executor.planStrategy() !== 'responses') { return undefined }
|
|
207
|
+
if (!executor.matchesResponsesRoute(request)) { throw new Error('dsh-dynamic-tools: 原生声明已按本步路由准备,但发送路由发生变化;请在下一步重新选择模型') }
|
|
208
|
+
return projectResponsesRecords(request.messages as readonly ResponsesMessage[])
|
|
209
|
+
})
|
|
179
210
|
|
|
180
|
-
ctx.effect(() => ctx.tools.register(createToolLoad(
|
|
211
|
+
ctx.effect(() => ctx.tools.register(createToolLoad({
|
|
181
212
|
sourceKind: SOURCE_KIND,
|
|
213
|
+
host, history, admitted,
|
|
182
214
|
limits: settings.disclose.limits,
|
|
183
215
|
strategy: strategyOf,
|
|
184
216
|
declaredNames: declaredNamesOf,
|
|
@@ -197,13 +229,14 @@ export function apply(ctx: Context, config: Config): void {
|
|
|
197
229
|
|
|
198
230
|
if (config.installExistingAgents) {
|
|
199
231
|
const agents = ctx.get('agents')
|
|
200
|
-
for (const agent of agents?.list() ?? []) installAgent(ctx, agent, installOptions, release)
|
|
232
|
+
for (const agent of agents?.list() ?? []) { installAgent(ctx, agent, installOptions, release) }
|
|
201
233
|
}
|
|
202
234
|
|
|
203
235
|
registerDisclosure(ctx, {
|
|
204
236
|
...settings.disclose,
|
|
237
|
+
host, history,
|
|
205
238
|
strategy: strategyOf,
|
|
206
239
|
catalogNames: declaredNamesOf,
|
|
207
|
-
admitted
|
|
240
|
+
admitted,
|
|
208
241
|
})
|
|
209
242
|
}
|