@deepseek-ai/dsh-tool-subagent 0.2.2-rc.4 → 0.2.3-alpha.1

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/index.js CHANGED
@@ -1,91 +1,85 @@
1
1
  import z from "@deepseek-ai/schemastery";
2
- import { defineTool } from "@deepseek-ai/dsh-tools";
3
- import { assertSubagentMaxDepth, delegationDepthOf, parentAgentOptionsForDelegation } from "@deepseek-ai/dsh-subagent";
4
- import { ReasoningEffortId } from "@deepseek-ai/dsh-llm";
5
- import { z as z$1 } from "zod";
2
+ import { ToolArgsError, ToolContextUnavailableError, defineTool } from "@deepseek-ai/dsh-tools";
3
+ import { SubagentError, assertSubagentMaxDepth, delegationDepthOf, parentAgentOptionsForDelegation } from "@deepseek-ai/dsh-subagent";
4
+ import { brandString } from "@deepseek-ai/dsh-brand";
6
5
  z.object({
7
6
  provider: z.string().min(1).required(),
8
7
  model: z.string().min(1).required()
9
8
  });
10
9
  /**
11
- * Stable identity for one provider/model pair.
12
- * @param route - Exact provider/model route.
13
- * @returns Opaque key for equality checks.
10
+ * Whether an optional string tool argument carries a value. Some models send
11
+ * `""` for optional fields they leave unset.
12
+ * @param value - Parsed argument value.
13
+ * @returns Whether the value is present and non-empty.
14
14
  */
15
- function modelRouteKey(route) {
16
- return `${route.provider}\0${route.model}`;
15
+ function hasText(value) {
16
+ return value !== void 0 && value !== "";
17
17
  }
18
18
  /**
19
- * Reject malformed or duplicate route policy entries at a durable or configuration boundary.
20
- * @param routes - Candidate exact routes to validate.
21
- * @returns an assertion that the candidate is a validated exact-route array.
19
+ * Read model-facing route fields from tool arguments, treating an empty string as an omitted field.
20
+ * @param args - Parsed tool arguments carrying the route fields.
21
+ * @returns The non-empty route fields.
22
22
  */
23
- function assertAllowedModelRoutes(routes) {
24
- if (!Array.isArray(routes)) throw new Error("subagent model selection requires an array of routes");
25
- const seen = /* @__PURE__ */ new Set();
26
- const candidates = routes;
27
- for (const candidate of candidates) {
28
- if (typeof candidate !== "object" || candidate === null || Array.isArray(candidate) || !("provider" in candidate) || typeof candidate.provider !== "string" || !("model" in candidate) || typeof candidate.model !== "string" || candidate.provider.length === 0 || candidate.model.length === 0) throw new Error("subagent model selection requires non-empty provider and model ids");
29
- const route = {
30
- provider: candidate.provider,
31
- model: candidate.model
32
- };
33
- const key = modelRouteKey(route);
34
- if (seen.has(key)) throw new Error(`subagent model selection repeats route "${route.provider}/${route.model}"`);
35
- seen.add(key);
36
- }
23
+ function delegationModelRequest(args) {
24
+ return {
25
+ ...hasText(args.provider) ? { provider: args.provider } : {},
26
+ ...hasText(args.model) ? { model: args.model } : {},
27
+ ...hasText(args.reasoning_effort) ? { reasoning_effort: args.reasoning_effort } : {}
28
+ };
37
29
  }
38
30
  /**
39
31
  * Whether a call explicitly selects any child LLM value.
40
- * @param request - Model-facing route fields from the tool call.
32
+ * @param request - Route fields read by {@link delegationModelRequest}.
41
33
  * @returns Whether at least one route or effort field is present.
42
34
  */
43
35
  function hasDelegationModelRequest(request) {
44
36
  return request.provider !== void 0 || request.model !== void 0 || request.reasoning_effort !== void 0;
45
37
  }
46
- /** Reject an empty model-facing route value at the tool JSON boundary. */
47
- function assertNonEmpty(value, field) {
48
- if (value !== void 0 && value.length === 0) throw new Error(`child LLM \`${field}\` must be non-empty`);
49
- }
38
+ /** Model-facing pointer to route discovery, appended to route-selection rejections. */
39
+ const ROUTE_DISCOVERY_HINT = " Call `list_subagent_models` to see the routes you may select.";
50
40
  /**
51
- * Validate explicit selection against the Session policy and merge it over child defaults.
41
+ * Validate explicit selection against the current Host setting and merge it over child defaults.
52
42
  * Explicit selection requires both provider and model; an omitted effort then
53
43
  * uses the selected model's default, even when the route is unchanged.
54
44
  * @param configured - Tool-instance child defaults.
55
- * @param request - Model-facing route override.
45
+ * @param request - Route fields read by {@link delegationModelRequest}.
56
46
  * @param enabled - Whether this tool instance permits model-facing selection.
57
- * @param policy - Session allowlist; omission permits only the current parent route.
58
- * @param parentOptions - Current parent route used when no policy is recorded.
47
+ * @param policy - Current Host allowlist; omission permits only the current parent route.
48
+ * @param parentOptions - Current parent route used when the Host setting is disabled or absent.
49
+ * @param routeDiscoveryVisible - Whether the caller can call `list_subagent_models`; rejections then point to it.
59
50
  * @returns Child Agent options, preserving omission when no layer contributes one.
51
+ * @throws {SubagentError} `MODEL_SELECTION_DISABLED` when this tool instance
52
+ * forbids selection, or `MODEL_ROUTE_NOT_ALLOWED` when the allowlist excludes the route.
53
+ * @throws {ToolArgsError} when `provider` and `model` are not supplied together.
60
54
  */
61
- function requestedAgentOptions(configured, request, enabled, policy, parentOptions) {
55
+ function requestedAgentOptions(configured, request, enabled, policy, parentOptions, routeDiscoveryVisible) {
62
56
  if (!hasDelegationModelRequest(request)) return configured;
63
- if (!enabled) throw new Error("child model selection is disabled for this tool instance");
64
- assertNonEmpty(request.provider, "provider");
65
- assertNonEmpty(request.model, "model");
66
- assertNonEmpty(request.reasoning_effort, "reasoning_effort");
67
- if (request.provider === void 0 || request.model === void 0) throw new Error(request.reasoning_effort === void 0 ? "child LLM `provider` and `model` must be supplied together" : "child LLM `reasoning_effort` requires both `provider` and `model`; supply both or omit all three fields");
57
+ if (!enabled) throw new SubagentError("child model selection is disabled for this tool instance", "MODEL_SELECTION_DISABLED");
58
+ const hint = routeDiscoveryVisible ? ROUTE_DISCOVERY_HINT : "";
59
+ if (request.provider === void 0 || request.model === void 0) throw new ToolArgsError([(request.reasoning_effort === void 0 ? "child LLM `provider` and `model` must be supplied together." : "child LLM `reasoning_effort` requires both `provider` and `model`; supply both or omit all three fields.") + hint]);
68
60
  assertAllowedModelSelection(policy, parentOptions, {
69
61
  provider: request.provider,
70
62
  model: request.model
71
- });
63
+ }, routeDiscoveryVisible);
72
64
  return {
73
65
  ...configured,
74
66
  provider: request.provider,
75
67
  model: request.model,
76
- reasoningEffort: request.reasoning_effort === void 0 ? void 0 : ReasoningEffortId(request.reasoning_effort)
68
+ reasoningEffort: request.reasoning_effort === void 0 ? void 0 : brandString(request.reasoning_effort)
77
69
  };
78
70
  }
79
71
  /**
80
- * Enforce Session authorization for a complete, explicitly selected child route.
81
- * @param policy - Session allowlist; omission permits only the current parent route.
82
- * @param parentOptions - Current parent route used when no policy is recorded.
72
+ * Enforce Host authorization for a complete, explicitly selected child route.
73
+ * @param policy - Current Host allowlist; omission permits only the current parent route.
74
+ * @param parentOptions - Current parent route used when the Host setting is disabled or absent.
83
75
  * @param route - Validated provider/model pair from the tool call.
76
+ * @param routeDiscoveryVisible - Whether the caller can call `list_subagent_models`; the rejection then points to it.
77
+ * @throws {SubagentError} `MODEL_ROUTE_NOT_ALLOWED` when the allowlist excludes the route.
84
78
  */
85
- function assertAllowedModelSelection(policy, parentOptions, route) {
79
+ function assertAllowedModelSelection(policy, parentOptions, route, routeDiscoveryVisible) {
86
80
  const { provider, model } = route;
87
81
  if (policy === void 0 ? provider === parentOptions.provider && model === parentOptions.model : policy.routes.some((route) => route.provider === provider && route.model === model)) return;
88
- throw new Error(`child LLM route "${provider}/${model}" is not allowed for this Session` + (policy === void 0 ? "; without a recorded model-selection policy, explicit selection is limited to the parent route" : ""));
82
+ throw new SubagentError(`child LLM route "${provider}/${model}" is not allowed by the current subagent model selection setting` + (policy === void 0 ? "; while subagent model selection is disabled, explicit selection is limited to the parent route" : "") + "." + (routeDiscoveryVisible ? ROUTE_DISCOVERY_HINT : ""), "MODEL_ROUTE_NOT_ALLOWED");
89
83
  }
90
84
  /**
91
85
  * Whether configured Agent options require route validation before delegation.
@@ -108,7 +102,7 @@ function hasConfiguredLlmSelection(options) {
108
102
  async function preflightChildLlmRoute(llm, parentOptions, requested, signal, inheritParentReasoningEffort = true) {
109
103
  const provider = requested?.provider ?? parentOptions.provider;
110
104
  const model = requested?.model ?? parentOptions.model;
111
- if (provider === void 0 || model === void 0) throw new Error("cannot select child LLM values without an effective provider and model");
105
+ if (provider === void 0 || model === void 0) throw new ToolContextUnavailableError("cannot select child LLM values without an effective provider and model");
112
106
  const routeChanged = provider !== parentOptions.provider || model !== parentOptions.model;
113
107
  const reasoningEffort = requested?.reasoningEffort ?? (inheritParentReasoningEffort && !routeChanged ? parentOptions.reasoningEffort : void 0);
114
108
  await llm.resolveCallConfig({
@@ -117,35 +111,6 @@ async function preflightChildLlmRoute(llm, parentOptions, requested, signal, inh
117
111
  ...reasoningEffort === void 0 ? {} : { reasoningEffort }
118
112
  }, signal);
119
113
  }
120
- /**
121
- * Host-only projection of the durable model-selection policy.
122
- * Each independently mounted consumer registers this shared definition; the registry reference-counts it.
123
- */
124
- const subagentModelSelectionProjectionDefinition = {
125
- key: "subagentModelSelectionPolicy",
126
- stateVersion: 1,
127
- stateSchema: z$1.array(z$1.object({
128
- provider: z$1.string().min(1),
129
- model: z$1.string().min(1)
130
- }).strict()).min(1).nullable(),
131
- init: () => null,
132
- apply: (policy, event) => {
133
- if (policy !== null || event.type !== "subagent/model-selection-policy") return policy;
134
- const { allowedModels } = event.data;
135
- assertAllowedModelRoutes(allowedModels);
136
- if (allowedModels.length === 0) throw new Error("subagent/model-selection-policy requires at least one route");
137
- return allowedModels;
138
- }
139
- };
140
- /**
141
- * Read the exact route list authorized for a Session.
142
- * @param subagentModelSelectionProjectionHandle - registered policy state reader.
143
- * @param session - session whose durable decision is read.
144
- * @returns a detached route list, or undefined to restrict selection to the parent route.
145
- */
146
- function subagentModelSelectionPolicy(subagentModelSelectionProjectionHandle, session) {
147
- return subagentModelSelectionProjectionHandle.stateOf(session)?.map((route) => ({ ...route }));
148
- }
149
114
  //#endregion
150
115
  //#region lib/types/list-models.js
151
116
  /** Model-facing discovery of LLM routes available to child Agents. */
@@ -154,22 +119,21 @@ function registeredProvider(llm, policy, providerId) {
154
119
  const providers = llm.listProviders();
155
120
  const provider = providers.find((candidate) => candidate.id === providerId);
156
121
  if (provider !== void 0) return provider;
157
- const available = providers.filter((candidate) => policy.routes.some((route) => route.provider === candidate.id)).map((candidate) => candidate.id).join(", ") || "(none)";
158
- throw new Error(`LLM provider "${providerId}" is not registered; available providers: ${available}`);
122
+ throw new SubagentError(`LLM provider "${providerId}" is not registered; available providers: ${providers.filter((candidate) => policy.routes.some((route) => route.provider === candidate.id)).map((candidate) => candidate.id).join(", ") || "(none)"}`, "LLM_PROVIDER_NOT_FOUND");
159
123
  }
160
124
  /** Render one advertised or resolved model. */
161
125
  function modelLine(provider, model) {
162
126
  return `${provider}/${model.id} — ${model.name}${model.description === void 0 ? "" : `: ${model.description}`}`;
163
127
  }
164
128
  /** Read the requested provider, allowed models, or exact-model efforts. */
165
- async function listSubagentModels(ctx, policyHandle, request, exec) {
166
- if (exec.agent === void 0) throw new Error("list_subagent_models requires a calling agent");
167
- const routes = subagentModelSelectionPolicy(policyHandle, exec.agent.session);
129
+ async function listSubagentModels(ctx, request, exec) {
130
+ if (exec.agent === void 0) throw new ToolContextUnavailableError("list_subagent_models requires a calling agent");
131
+ const routes = ctx.get("subagentModelSelection")?.allowedRoutes();
168
132
  let policy = routes === void 0 ? void 0 : { routes };
169
133
  const selectionEnabled = policy !== void 0;
170
134
  if (policy === void 0) {
171
135
  const { provider, model } = parentAgentOptionsForDelegation(exec.agent);
172
- if (provider === void 0 || model === void 0) throw new Error("cannot discover child LLM routes without a parent provider and model");
136
+ if (provider === void 0 || model === void 0) throw new ToolContextUnavailableError("cannot discover child LLM routes without a parent provider and model");
173
137
  policy = { routes: [{
174
138
  provider,
175
139
  model
@@ -177,41 +141,38 @@ async function listSubagentModels(ctx, policyHandle, request, exec) {
177
141
  }
178
142
  const { signal } = exec;
179
143
  const llm = ctx.get("llm");
180
- if (llm === void 0) throw new Error("cannot discover child LLM routes because the `llm` service is unavailable");
181
- if (request.model !== void 0 && request.provider === void 0) throw new Error("`model` requires `provider`");
144
+ if (llm === void 0) throw new ToolContextUnavailableError("cannot discover child LLM routes because the `llm` service is unavailable");
145
+ if (request.model !== void 0 && request.provider === void 0) throw new ToolArgsError(["`model` requires `provider`"]);
182
146
  if (request.provider === void 0) {
183
147
  const providers = llm.listProviders().filter((provider) => policy.routes.some((route) => route.provider === provider.id));
184
148
  return providers.length === 0 ? "(no LLM providers)" : providers.map((provider) => `${provider.id} — ${provider.name}`).join("\n");
185
149
  }
186
- if (request.provider.length === 0) throw new Error("`provider` must be non-empty");
187
150
  const allowedRoutes = policy.routes.filter((route) => route.provider === request.provider);
188
151
  const [firstRoute] = allowedRoutes;
189
- if (firstRoute === void 0) throw new Error(`LLM provider "${request.provider}" is not allowed for this Session`);
152
+ if (firstRoute === void 0) throw new SubagentError(`LLM provider "${request.provider}" is not allowed by the current subagent model selection setting`, "MODEL_ROUTE_NOT_ALLOWED");
190
153
  const provider = registeredProvider(llm, policy, request.provider);
191
154
  if (request.model === void 0) {
192
155
  const models = selectionEnabled ? (await llm.listModels(provider.id)).filter((model) => allowedRoutes.some((route) => route.model === model.id)) : [await llm.resolveModelInfo(provider.id, firstRoute.model, signal)];
193
156
  signal.throwIfAborted();
194
157
  return models.length === 0 ? `(no advertised models for ${provider.id})` : models.map((model) => modelLine(provider.id, model)).join("\n");
195
158
  }
196
- if (request.model.length === 0) throw new Error("`model` must be non-empty");
197
- if (!allowedRoutes.some((route) => route.model === request.model)) throw new Error(`child LLM route "${provider.id}/${request.model}" is not allowed for this Session`);
159
+ if (!allowedRoutes.some((route) => route.model === request.model)) throw new SubagentError(`child LLM route "${provider.id}/${request.model}" is not allowed by the current subagent model selection setting`, "MODEL_ROUTE_NOT_ALLOWED");
198
160
  const model = await llm.resolveModelInfo(provider.id, request.model, signal);
199
161
  const efforts = model.reasoning?.efforts.map((effort) => `${effort.id}${model.reasoning?.defaultEffort === effort.id ? " (default)" : ""} — ${effort.name}` + (effort.description === void 0 ? "" : `: ${effort.description}`)).join("\n") || "(no advertised reasoning efforts)";
200
162
  return `${modelLine(provider.id, model)}\nReasoning efforts:\n${efforts}`;
201
163
  }
202
164
  /**
203
- * Register discovery of the calling Session’s authorized child models.
204
- * @param ctx - Context carrying the tool registry and LLM service.
205
- * @param policyHandle - retained reader for the Session’s authorized child routes.
165
+ * Register discovery of the child models the Host setting authorizes.
166
+ * @param ctx - Context carrying the tool registry, LLM service, and optional Host model-selection setting.
206
167
  */
207
- function registerListSubagentModels(ctx, policyHandle) {
168
+ function registerListSubagentModels(ctx) {
208
169
  ctx.tools.register(defineTool({
209
170
  name: "list_subagent_models",
210
- description: "Inspect the routes available for explicit subagent model selection. No arguments: authorized providers. `provider`: that provider's authorized models. `provider` + `model`: that model and its reasoning efforts. Query when choosing an explicit child route or reasoning effort. Omit optional fields rather than sending empty strings.",
171
+ description: "Inspect the routes available for explicit subagent model selection. No arguments: authorized providers. `provider`: that provider's authorized models. `provider` + `model`: that model and its reasoning efforts.",
211
172
  parameters: {
212
173
  provider: {
213
174
  type: "string",
214
- description: "Registered LLM provider id."
175
+ description: "Provider id from the no-argument listing."
215
176
  },
216
177
  model: {
217
178
  type: "string",
@@ -227,12 +188,16 @@ function registerListSubagentModels(ctx, policyHandle) {
227
188
  },
228
189
  isConcurrencySafe: () => true,
229
190
  execute(args, exec) {
230
- return listSubagentModels(ctx, policyHandle, args, exec);
191
+ return listSubagentModels(ctx, {
192
+ ...hasText(args.provider) ? { provider: args.provider } : {},
193
+ ...hasText(args.model) ? { model: args.model } : {}
194
+ }, exec);
231
195
  }
232
196
  }));
233
197
  }
234
198
  //#endregion
235
199
  //#region lib/types/preset-selection.js
200
+ /** Deployment-owned preset choices for one delegation tool. */
236
201
  /** Validates configured choices and resolves model input against the allowlist. */
237
202
  var SubagentPresetSelection = class {
238
203
  config;
@@ -266,12 +231,14 @@ var SubagentPresetSelection = class {
266
231
  * Validate model input and apply the deployment default.
267
232
  * @param request - Model-supplied tool arguments.
268
233
  * @returns Selected preset id, or omission to inherit the parent.
234
+ * @throws {SubagentError} `PRESET_SELECTION_DISABLED` when this tool exposes no
235
+ * preset choice, or `PRESET_NOT_ALLOWED` when the id is outside the allowlist.
269
236
  */
270
237
  resolve(request) {
271
238
  const id = request.agent_preset;
272
239
  if (id === void 0) return this.config.agentPreset;
273
- if (this.choices === void 0) throw new Error("agent_preset selection is disabled for this tool instance");
274
- if (typeof id !== "string" || !this.choices.includes(id)) throw new Error(`agent_preset must be one of: ${this.choices.join(", ")}`);
240
+ if (this.choices === void 0) throw new SubagentError("agent_preset selection is disabled for this tool instance", "PRESET_SELECTION_DISABLED");
241
+ if (typeof id !== "string" || !this.choices.includes(id)) throw new SubagentError(`agent_preset must be one of: ${this.choices.join(", ")}`, "PRESET_NOT_ALLOWED");
275
242
  return id;
276
243
  }
277
244
  };
@@ -288,8 +255,7 @@ const name = "tool-subagent";
288
255
  const inject = [
289
256
  "tools",
290
257
  "subagents",
291
- "systemPrompt",
292
- "sessionProjections"
258
+ "systemPrompt"
293
259
  ];
294
260
  const delegationTools = /* @__PURE__ */ new Set();
295
261
  const Config = z.object({
@@ -334,16 +300,14 @@ function providerWording(inheritsConversation) {
334
300
  * The owning composition shares its registrations across Agents; child startup resolves the selected preset.
335
301
  * @param ctx - Context that owns the registrations.
336
302
  * @param config - delegation-tool configuration.
337
- * @returns when the plugin is ready.
338
303
  */
339
- async function apply(ctx, config) {
304
+ function apply(ctx, config) {
340
305
  for (const field of ["persona", "toolFilter"]) if (Object.hasOwn(config, field)) throw new Error(`tool-subagent: ${field} is no longer supported; configure persona and tool plugins in an Agent Preset and select it with agentPreset (spawn only)`);
341
306
  const presets = new SubagentPresetSelection(config);
342
307
  if (presets.configured && ctx.get("agentPresets") === void 0) throw new Error("tool-subagent: agent preset selection requires the agent-presets service");
343
308
  if (config.maxDepth !== "provider-managed") assertSubagentMaxDepth(config.maxDepth);
344
309
  const toolName = config.toolName ?? "subagent";
345
310
  const modelSelectionEnabled = config.modelSelection === true;
346
- const subagentModelSelectionProjectionHandle = await ctx.sessionProjections.register(subagentModelSelectionProjectionDefinition);
347
311
  const assertSubagentProviderConfiguration = (subagentProvider) => {
348
312
  presets.assertProvider(subagentProvider);
349
313
  if (ctx.subagents.resolveMaxDepth(config.maxDepth) !== void 0 && !subagentProvider.capabilities.depthLimit) throw new Error(`tool-subagent: provider "${subagentProvider.name}" cannot enforce maxDepth (no depthLimit capability) — set maxDepth: 'provider-managed' to leave the recursion budget to the provider`);
@@ -355,21 +319,18 @@ async function apply(ctx, config) {
355
319
  });
356
320
  const initialProvider = ctx.subagents.getProvider(config.provider);
357
321
  if (initialProvider !== void 0) assertSubagentProviderConfiguration(initialProvider);
358
- if (config.modelDiscovery === true) registerListSubagentModels(ctx, subagentModelSelectionProjectionHandle);
322
+ if (config.modelDiscovery === true) registerListSubagentModels(ctx);
359
323
  let mounted;
360
324
  const mount = (subagentProvider) => {
361
325
  assertSubagentProviderConfiguration(subagentProvider);
362
326
  const wording = providerWording(subagentProvider.inheritsParentContext);
363
327
  const providerRouteDefaults = subagentProvider.agentRouteDefaults;
364
- const selectionDescription = providerRouteDefaults !== void 0 ? " Omit `provider`, `model`, and `reasoning_effort` to use child defaults, falling back to this backend's route defaults." : " Omit `provider`, `model`, and `reasoning_effort` to use child defaults, falling back to compatible parent values.";
328
+ const defaultRoute = providerRouteDefaults !== void 0 || hasConfiguredLlmSelection(config.agentOptions) ? "the default model configured for this tool" : "your current model and reasoning effort";
329
+ const providerSource = config.modelDiscovery === true ? " Use a provider id listed by `list_subagent_models`." : "";
365
330
  const definition = defineTool({
366
331
  name: toolName,
367
- description: wording.description + " This tool starts an independently managed subagent and immediately returns its name. If you are still online when it finishes, the runtime automatically delivers its completion notice. The notice includes the final answer unless the child sent you a message just before finishing." + (subagentProvider.prepareContinuable !== void 0 ? " Use `send_message` to steer it while running or continue its conversation after it finishes." : " This backend does not accept follow-up messages.") + (modelSelectionEnabled ? selectionDescription : "") + (modelSelectionEnabled && subagentProvider.inheritsParentContext ? " Changing the route can prevent provider-side reuse of the inherited conversation prefix." : ""),
332
+ description: wording.description + " This tool starts an independently managed subagent and immediately returns its name. If you are still online when it finishes, the runtime automatically delivers its completion notice. The notice includes the final answer unless the child sent you a message just before finishing." + (subagentProvider.prepareContinuable !== void 0 ? " Use `send_message` to steer it while running or continue its conversation after it finishes." : " This backend does not accept follow-up messages.") + (modelSelectionEnabled && subagentProvider.inheritsParentContext ? " Changing the route can prevent provider-side reuse of the inherited conversation prefix." : ""),
368
333
  parameters: {
369
- cwd: {
370
- type: "string",
371
- description: "Initial child working directory. Relative paths use your current directory; omitted inherits it. Later directory changes in either agent are independent."
372
- },
373
334
  description: {
374
335
  type: "string",
375
336
  required: true,
@@ -392,7 +353,7 @@ async function apply(ctx, config) {
392
353
  ...modelSelectionEnabled ? {
393
354
  provider: {
394
355
  type: "string",
395
- description: "Child LLM provider id; requires `model`."
356
+ description: `LLM provider id for the subagent; requires \`model\`. Set only when the task needs a different model; omit \`provider\`, \`model\`, and \`reasoning_effort\` to run the subagent on ${defaultRoute}.${providerSource}`
396
357
  },
397
358
  model: {
398
359
  type: "string",
@@ -400,7 +361,7 @@ async function apply(ctx, config) {
400
361
  },
401
362
  reasoning_effort: {
402
363
  type: "string",
403
- description: "Reasoning effort id; requires `provider` and `model`. Omit to use the selected model's default, even when it matches the parent or configured route."
364
+ description: "Reasoning effort id; requires `provider` and `model`. Omit to use that model's default effort."
404
365
  }
405
366
  } : {}
406
367
  },
@@ -432,28 +393,27 @@ async function apply(ctx, config) {
432
393
  isConcurrencySafe: () => true,
433
394
  async execute(args, exec) {
434
395
  const parent = exec.agent;
435
- if (!parent) throw new Error("subagent tool requires a calling agent (exec.agent was undefined)");
436
- const routes = subagentModelSelectionPolicy(subagentModelSelectionProjectionHandle, parent.session);
437
- const modelSelectionPolicy = routes === void 0 ? void 0 : { routes };
396
+ if (!parent) throw new ToolContextUnavailableError("subagent tool requires a calling agent (exec.agent was undefined)");
438
397
  const agentPreset = presets.resolve(args);
439
- const modelRequest = args;
398
+ const modelRequest = delegationModelRequest(args);
399
+ const routes = modelSelectionEnabled && hasDelegationModelRequest(modelRequest) ? ctx.get("subagentModelSelection")?.allowedRoutes() : void 0;
400
+ const modelSelectionPolicy = routes === void 0 ? void 0 : { routes };
440
401
  const parentOptions = parentAgentOptionsForDelegation(parent);
441
402
  const requiresRoutePreflight = hasDelegationModelRequest(modelRequest) || hasConfiguredLlmSelection(config.agentOptions);
442
403
  const requestedChildAgentOptions = requestedAgentOptions(requiresRoutePreflight && providerRouteDefaults !== void 0 ? {
443
404
  ...providerRouteDefaults,
444
405
  ...config.agentOptions
445
- } : config.agentOptions, modelRequest, modelSelectionEnabled, modelSelectionPolicy, parentOptions);
406
+ } : config.agentOptions, modelRequest, modelSelectionEnabled, modelSelectionPolicy, parentOptions, ctx.tools.get("list_subagent_models", parent, exec.toolSet) !== void 0);
446
407
  if (requiresRoutePreflight) {
447
408
  const llm = ctx.get("llm");
448
- if (llm === void 0) throw new Error("cannot resolve the selected child LLM route because the `llm` service is unavailable");
409
+ if (llm === void 0) throw new ToolContextUnavailableError("cannot resolve the selected child LLM route because the `llm` service is unavailable");
449
410
  const inheritParentReasoningEffort = providerRouteDefaults === void 0 && !hasDelegationModelRequest(modelRequest);
450
411
  await preflightChildLlmRoute(llm, parentOptions, requestedChildAgentOptions, exec.signal, inheritParentReasoningEffort);
451
- if (ctx.subagents.getProvider(config.provider) !== subagentProvider) throw new Error(`subagent provider "${config.provider}" changed while resolving the child LLM route; retry the delegation`);
412
+ if (ctx.subagents.getProvider(config.provider) !== subagentProvider) throw new SubagentError(`subagent provider "${config.provider}" changed while resolving the child LLM route; retry the delegation`, "PROVIDER_CHANGED");
452
413
  }
453
414
  exec.signal.throwIfAborted();
454
415
  const maxDepth = ctx.subagents.resolveMaxDepth(config.maxDepth);
455
416
  const request = {
456
- ...args.cwd === void 0 ? {} : { cwd: args.cwd },
457
417
  prompt: [{
458
418
  type: "text",
459
419
  text: args.prompt
@@ -503,11 +463,12 @@ async function apply(ctx, config) {
503
463
  ctx.systemPrompt.section({
504
464
  name: `tool:${toolName}`,
505
465
  order: ctx.systemPrompt.getSectionOrder("TOOL_SUBAGENT"),
466
+ retirement: `The ${toolName} tool is no longer available. Its instructions no longer apply.`,
506
467
  text: (context) => {
507
468
  if (mounted === void 0) return "";
508
469
  const visible = [...delegationTools].filter((tool) => ctx.tools.get(tool.name, context.scope) === tool).map((tool) => tool.name).sort();
509
470
  if (visible[0] !== toolName) return "";
510
- return `Start independent delegations with ${visible.map((name) => `\`${name}\``).join(" or ")} together in one assistant message and continue useful work while they run. When only waiting for their results remains, end your turn instead of sleeping or polling; the next result starts a new turn. Collect the subagent results required to complete the task before giving the user a final answer.\n\nBash, formatters, code generators, and scripts can overwrite concurrent edits without conflict detection; coordinate their changes explicitly. The agent integrating the work must review the final diff and run relevant tests.`;
471
+ return `Start independent delegations with ${visible.map((name) => `\`${name}\``).join(" or ")} together in one assistant message and continue useful work while they run. The concurrency limit of all the subagents is ${ctx.subagents.maxActiveSubagents}. When only waiting for their results remains, end your turn instead of sleeping or polling; the next result starts a new turn. Collect the subagent results required to complete the task before giving the user a final answer.\n\nBash, formatters, code generators, and scripts can overwrite concurrent edits without conflict detection; coordinate their changes explicitly. The agent integrating the work must review the final diff and run relevant tests.`;
511
472
  }
512
473
  });
513
474
  ctx.systemPrompt.context({
@@ -1,8 +1,8 @@
1
1
  import { Service } from "@deepseek-ai/cordis";
2
+ import { SubagentError } from "@deepseek-ai/dsh-subagent";
2
3
  import z from "@deepseek-ai/schemastery";
3
- import { SessionSeq } from "@deepseek-ai/dsh-session";
4
- import { z as z$1 } from "zod";
5
- import "@deepseek-ai/dsh-llm";
4
+ import "@deepseek-ai/dsh-brand";
5
+ import "@deepseek-ai/dsh-tools";
6
6
  //#region lib/types/model-selection.js
7
7
  /** Schema shared by the Host setting and its deployment base. */
8
8
  const AllowedModelRouteSchema = z.object({
@@ -21,57 +21,28 @@ function modelRouteKey(route) {
21
21
  * Reject malformed or duplicate route policy entries at a durable or configuration boundary.
22
22
  * @param routes - Candidate exact routes to validate.
23
23
  * @returns an assertion that the candidate is a validated exact-route array.
24
+ * @throws {SubagentError} `INVALID_MODEL_SELECTION_SETTINGS` for malformed or repeated routes.
24
25
  */
25
26
  function assertAllowedModelRoutes(routes) {
26
- if (!Array.isArray(routes)) throw new Error("subagent model selection requires an array of routes");
27
+ if (!Array.isArray(routes)) throw new SubagentError("subagent model selection requires an array of routes", "INVALID_MODEL_SELECTION_SETTINGS");
27
28
  const seen = /* @__PURE__ */ new Set();
28
29
  const candidates = routes;
29
30
  for (const candidate of candidates) {
30
- if (typeof candidate !== "object" || candidate === null || Array.isArray(candidate) || !("provider" in candidate) || typeof candidate.provider !== "string" || !("model" in candidate) || typeof candidate.model !== "string" || candidate.provider.length === 0 || candidate.model.length === 0) throw new Error("subagent model selection requires non-empty provider and model ids");
31
+ if (typeof candidate !== "object" || candidate === null || Array.isArray(candidate) || !("provider" in candidate) || typeof candidate.provider !== "string" || !("model" in candidate) || typeof candidate.model !== "string" || candidate.provider.length === 0 || candidate.model.length === 0) throw new SubagentError("subagent model selection requires non-empty provider and model ids", "INVALID_MODEL_SELECTION_SETTINGS");
31
32
  const route = {
32
33
  provider: candidate.provider,
33
34
  model: candidate.model
34
35
  };
35
36
  const key = modelRouteKey(route);
36
- if (seen.has(key)) throw new Error(`subagent model selection repeats route "${route.provider}/${route.model}"`);
37
+ if (seen.has(key)) throw new SubagentError(`subagent model selection repeats route "${route.provider}/${route.model}"`, "INVALID_MODEL_SELECTION_SETTINGS");
37
38
  seen.add(key);
38
39
  }
39
40
  }
40
- /**
41
- * Host-only projection of the durable model-selection policy.
42
- * Each independently mounted consumer registers this shared definition; the registry reference-counts it.
43
- */
44
- const subagentModelSelectionProjectionDefinition = {
45
- key: "subagentModelSelectionPolicy",
46
- stateVersion: 1,
47
- stateSchema: z$1.array(z$1.object({
48
- provider: z$1.string().min(1),
49
- model: z$1.string().min(1)
50
- }).strict()).min(1).nullable(),
51
- init: () => null,
52
- apply: (policy, event) => {
53
- if (policy !== null || event.type !== "subagent/model-selection-policy") return policy;
54
- const { allowedModels } = event.data;
55
- assertAllowedModelRoutes(allowedModels);
56
- if (allowedModels.length === 0) throw new Error("subagent/model-selection-policy requires at least one route");
57
- return allowedModels;
58
- }
59
- };
60
- /**
61
- * Read the exact route list authorized for a Session.
62
- * @param subagentModelSelectionProjectionHandle - registered policy state reader.
63
- * @param session - session whose durable decision is read.
64
- * @returns a detached route list, or undefined to restrict selection to the parent route.
65
- */
66
- function subagentModelSelectionPolicy(subagentModelSelectionProjectionHandle, session) {
67
- return subagentModelSelectionProjectionHandle.stateOf(session)?.map((route) => ({ ...route }));
68
- }
69
41
  //#endregion
70
42
  //#region lib/types/model-selection-settings.js
71
- /** Host settings owner that records Session authorization before the first model request. */
43
+ /** Host settings owner whose current value authorizes explicit child routes in every Session. */
72
44
  var SubagentModelSelectionConfig = class extends Service {
73
45
  config;
74
- static inject = ["sessionProjections", "sessions"];
75
46
  static Config = z.object({
76
47
  enabled: z.boolean().default(false).volatile(),
77
48
  allowedModels: z.array(AllowedModelRouteSchema).default([]).volatile()
@@ -80,40 +51,19 @@ var SubagentModelSelectionConfig = class extends Service {
80
51
  super(ctx, "subagentModelSelection");
81
52
  this.config = config;
82
53
  }
83
- async [Service.init]() {
84
- const ctx = this.ctx;
85
- const policyReady = ctx.sessionProjections.register(subagentModelSelectionProjectionDefinition);
86
- ctx.on("agent/created", async ({ agent }) => {
87
- const policy = await policyReady;
88
- ctx.fiber.assertActive();
89
- const target = agent.session;
90
- if (subagentModelSelectionPolicy(policy, target) !== void 0) return;
91
- let allowedModels;
92
- const parentId = target.header.origin === "subagent" ? target.header.parentSession : void 0;
93
- if (parentId !== void 0) {
94
- const parent = ctx.sessions.get(parentId);
95
- if (parent !== void 0) allowedModels = subagentModelSelectionPolicy(policy, parent);
96
- } else if (target.firstLiveSeq === 0 && target.eventAt(SessionSeq(0))?.type !== "session/end-seed") {
97
- const current = this.current();
98
- allowedModels = current.enabled ? current.allowedModels : void 0;
99
- }
100
- if (allowedModels !== void 0) target.append("subagent/model-selection-policy", { allowedModels });
101
- });
102
- await policyReady;
103
- }
104
54
  /**
105
- * Read a detached selection preference for the next fresh top-level Session.
106
- * @returns the enabled state and exact allowed routes.
55
+ * Read the routes the setting currently authorizes. Each call samples the
56
+ * live setting, so an edit applies to the next delegation in every Session.
57
+ * @returns a detached route list, or undefined when the setting is disabled.
58
+ * @throws {SubagentError} `INVALID_MODEL_SELECTION_SETTINGS` when the enabled setting has no route,
59
+ * or its routes are malformed or repeated. Disabled settings do not read or validate routes.
107
60
  */
108
- current() {
109
- const enabled = this.config.enabled.get();
61
+ allowedRoutes() {
62
+ if (!this.config.enabled.get()) return void 0;
110
63
  const allowedModels = this.config.allowedModels.get();
111
64
  assertAllowedModelRoutes(allowedModels);
112
- if (enabled && allowedModels.length === 0) throw new Error("enabled subagent model selection requires at least one allowed model");
113
- return {
114
- enabled,
115
- allowedModels: allowedModels.map((route) => ({ ...route }))
116
- };
65
+ if (allowedModels.length === 0) throw new SubagentError("enabled subagent model selection requires at least one allowed model", "INVALID_MODEL_SELECTION_SETTINGS");
66
+ return allowedModels.map((route) => ({ ...route }));
117
67
  }
118
68
  };
119
69
  const name = "subagent-model-selection-settings";
@@ -9,6 +9,7 @@ import type { Context } from '@deepseek-ai/cordis';
9
9
  import z from '@deepseek-ai/schemastery';
10
10
  import type { AgentOptions } from '@deepseek-ai/dsh-agent';
11
11
  import { type PresetSelectionConfig } from './preset-selection.ts';
12
+ import './model-selection-state.ts';
12
13
  export declare const name = "tool-subagent";
13
14
  export declare const inject: string[];
14
15
  /** Config: which registered provider this tool delegates to, plus child defaults. */
@@ -22,8 +23,8 @@ export interface Config extends PresetSelectionConfig {
22
23
  toolName?: string;
23
24
  /**
24
25
  * Expose optional child `provider`, `model`, and `reasoning_effort` fields.
25
- * Requires provider `agentOptions` support. Execution enforces the Session
26
- * policy, or restricts explicit selection to the current parent route.
26
+ * Requires provider `agentOptions` support. Each call enforces the current
27
+ * Host setting, or restricts explicit selection to the current parent route.
27
28
  */
28
29
  modelSelection?: boolean;
29
30
  /**
@@ -54,7 +55,6 @@ export declare const Config: z<Config>;
54
55
  * The owning composition shares its registrations across Agents; child startup resolves the selected preset.
55
56
  * @param ctx - Context that owns the registrations.
56
57
  * @param config - delegation-tool configuration.
57
- * @returns when the plugin is ready.
58
58
  */
59
- export declare function apply(ctx: Context, config: Config): Promise<void>;
59
+ export declare function apply(ctx: Context, config: Config): void;
60
60
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,CAAC,MAAM,0BAA0B,CAAA;AAIxC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAA;AAiB1D,OAAO,EAA2B,KAAK,qBAAqB,EAA+B,MAAM,uBAAuB,CAAA;AAMxH,eAAO,MAAM,IAAI,kBAAkB,CAAA;AACnC,eAAO,MAAM,MAAM,UAA+D,CAAA;AAMlF,qFAAqF;AACrF,MAAM,WAAW,MAAO,SAAQ,qBAAqB;IACnD,gFAAgF;IAChF,QAAQ,EAAE,MAAM,CAAA;IAChB;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB;;;;OAIG;IACH,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB;;;;OAIG;IACH,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB;;OAEG;IACH,YAAY,CAAC,EAAE,YAAY,CAAA;IAC3B;;;;;;;;;OASG;IACH,QAAQ,CAAC,EAAE,MAAM,GAAG,kBAAkB,CAAA;CACvC;AAED,eAAO,MAAM,MAAM,EAAE,CAAC,CAAC,MAAM,CAoB3B,CAAA;AAwCF;;;;;;GAMG;AACH,wBAAsB,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAoPvE"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,CAAC,MAAM,0BAA0B,CAAA;AAIxC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAA;AAmB1D,OAAO,EAA2B,KAAK,qBAAqB,EAA+B,MAAM,uBAAuB,CAAA;AAExH,OAAO,4BAA4B,CAAA;AAGnC,eAAO,MAAM,IAAI,kBAAkB,CAAA;AACnC,eAAO,MAAM,MAAM,UAAyC,CAAA;AAM5D,qFAAqF;AACrF,MAAM,WAAW,MAAO,SAAQ,qBAAqB;IACnD,gFAAgF;IAChF,QAAQ,EAAE,MAAM,CAAA;IAChB;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB;;;;OAIG;IACH,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB;;;;OAIG;IACH,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB;;OAEG;IACH,YAAY,CAAC,EAAE,YAAY,CAAA;IAC3B;;;;;;;;;OASG;IACH,QAAQ,CAAC,EAAE,MAAM,GAAG,kBAAkB,CAAA;CACvC;AAED,eAAO,MAAM,MAAM,EAAE,CAAC,CAAC,MAAM,CAoB3B,CAAA;AAwCF;;;;;GAKG;AACH,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAuPxD"}