@deepseek-ai/dsh-tool-subagent 0.2.1-rc.5 → 0.2.2-alpha.3

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,7 +1,5 @@
1
1
  import z from "@deepseek-ai/schemastery";
2
- import { scopeChainOf, scopeOf } from "@deepseek-ai/dsh-scope";
3
2
  import { defineTool } from "@deepseek-ai/dsh-tools";
4
- import { SessionSeq } from "@deepseek-ai/dsh-session";
5
3
  import { assertSubagentMaxDepth, delegationDepthOf, parentAgentOptionsForDelegation } from "@deepseek-ai/dsh-subagent";
6
4
  import { ReasoningEffortId } from "@deepseek-ai/dsh-llm";
7
5
  import { z as z$1 } from "zod";
@@ -83,18 +81,18 @@ function requestedAgentOptions(parentOptions, configured, request, enabled) {
83
81
  * Enforce a settings-owned route list at the operation that creates the child.
84
82
  * Pure inheritance remains outside this policy because no model-facing choice
85
83
  * occurred; any explicit route or effort field must resolve to an allowed route.
86
- * @param policy - Selection authority captured for this Session.
84
+ * @param policy - Session allowlist; omission permits only the current parent route.
87
85
  * @param parentOptions - Current parent values that supply missing child values.
88
86
  * @param requested - Effective child options after request/config merging.
89
87
  * @param request - Model-facing selection fields from the tool call.
90
88
  */
91
89
  function assertAllowedModelSelection(policy, parentOptions, requested, request) {
92
- if (policy === void 0 || !hasDelegationModelRequest(request)) return;
90
+ if (!hasDelegationModelRequest(request)) return;
93
91
  const provider = requested?.provider ?? parentOptions.provider;
94
92
  const model = requested?.model ?? parentOptions.model;
95
93
  if (provider === void 0 || model === void 0) throw new Error("cannot select child LLM values without an effective provider and model");
96
- if (policy.routes.some((route) => route.provider === provider && route.model === model)) return;
97
- throw new Error(`child LLM route "${provider}/${model}" is not allowed for this Session`);
94
+ if (policy === void 0 ? provider === parentOptions.provider && model === parentOptions.model : policy.routes.some((route) => route.provider === provider && route.model === model)) return;
95
+ 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 (including reasoning_effort) is limited to the parent route" : ""));
98
96
  }
99
97
  /**
100
98
  * Whether configured Agent options require route validation before delegation.
@@ -126,6 +124,35 @@ async function preflightChildLlmRoute(llm, parentOptions, requested, signal, inh
126
124
  ...reasoningEffort === void 0 ? {} : { reasoningEffort }
127
125
  }, signal);
128
126
  }
127
+ /**
128
+ * Host-only projection of the durable model-selection policy.
129
+ * Each independently mounted consumer registers this shared definition; the registry reference-counts it.
130
+ */
131
+ const subagentModelSelectionProjectionDefinition = {
132
+ key: "subagentModelSelectionPolicy",
133
+ stateVersion: 1,
134
+ stateSchema: z$1.array(z$1.object({
135
+ provider: z$1.string().min(1),
136
+ model: z$1.string().min(1)
137
+ }).strict()).min(1).nullable(),
138
+ init: () => null,
139
+ apply: (policy, event) => {
140
+ if (policy !== null || event.type !== "subagent/model-selection-policy") return policy;
141
+ const { allowedModels } = event.data;
142
+ assertAllowedModelRoutes(allowedModels);
143
+ if (allowedModels.length === 0) throw new Error("subagent/model-selection-policy requires at least one route");
144
+ return allowedModels;
145
+ }
146
+ };
147
+ /**
148
+ * Read the exact route list authorized for a Session.
149
+ * @param subagentModelSelectionProjectionHandle - registered policy state reader.
150
+ * @param session - session whose durable decision is read.
151
+ * @returns a detached route list, or undefined to restrict selection to the parent route.
152
+ */
153
+ function subagentModelSelectionPolicy(subagentModelSelectionProjectionHandle, session) {
154
+ return subagentModelSelectionProjectionHandle.stateOf(session)?.map((route) => ({ ...route }));
155
+ }
129
156
  //#endregion
130
157
  //#region lib/types/list-models.js
131
158
  /** Model-facing discovery of LLM routes available to child Agents. */
@@ -141,8 +168,21 @@ function registeredProvider(llm, policy, providerId) {
141
168
  function modelLine(provider, model) {
142
169
  return `${provider}/${model.id} — ${model.name}${model.description === void 0 ? "" : `: ${model.description}`}`;
143
170
  }
144
- /** Read the requested provider, advertised models, or exact-model efforts. */
145
- async function listSubagentModels(ctx, policy, request, signal) {
171
+ /** Read the requested provider, allowed models, or exact-model efforts. */
172
+ async function listSubagentModels(ctx, policyHandle, request, exec) {
173
+ if (exec.agent === void 0) throw new Error("list_subagent_models requires a calling agent");
174
+ const routes = subagentModelSelectionPolicy(policyHandle, exec.agent.session);
175
+ let policy = routes === void 0 ? void 0 : { routes };
176
+ const selectionEnabled = policy !== void 0;
177
+ if (policy === void 0) {
178
+ const { provider, model } = parentAgentOptionsForDelegation(exec.agent);
179
+ if (provider === void 0 || model === void 0) throw new Error("cannot discover child LLM routes without a parent provider and model");
180
+ policy = { routes: [{
181
+ provider,
182
+ model
183
+ }] };
184
+ }
185
+ const { signal } = exec;
146
186
  const llm = ctx.get("llm");
147
187
  if (llm === void 0) throw new Error("cannot discover child LLM routes because the `llm` service is unavailable");
148
188
  if (request.model !== void 0 && request.provider === void 0) throw new Error("`model` requires `provider`");
@@ -152,10 +192,12 @@ async function listSubagentModels(ctx, policy, request, signal) {
152
192
  }
153
193
  if (request.provider.length === 0) throw new Error("`provider` must be non-empty");
154
194
  const allowedRoutes = policy.routes.filter((route) => route.provider === request.provider);
155
- if (allowedRoutes.length === 0) throw new Error(`LLM provider "${request.provider}" is not allowed for this Session`);
195
+ const [firstRoute] = allowedRoutes;
196
+ if (firstRoute === void 0) throw new Error(`LLM provider "${request.provider}" is not allowed for this Session`);
156
197
  const provider = registeredProvider(llm, policy, request.provider);
157
198
  if (request.model === void 0) {
158
- const models = (await llm.listModels(provider.id)).filter((model) => allowedRoutes.some((route) => route.model === model.id));
199
+ 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)];
200
+ signal.throwIfAborted();
159
201
  return models.length === 0 ? `(no advertised models for ${provider.id})` : models.map((model) => modelLine(provider.id, model)).join("\n");
160
202
  }
161
203
  if (request.model.length === 0) throw new Error("`model` must be non-empty");
@@ -165,22 +207,22 @@ async function listSubagentModels(ctx, policy, request, signal) {
165
207
  return `${modelLine(provider.id, model)}\nReasoning efforts:\n${efforts}`;
166
208
  }
167
209
  /**
168
- * Register `list_subagent_models` for one owning delegation-tool instance.
169
- * @param ctx - Context whose tool registry owns the fixed discovery definition.
170
- * @param policy - Route policy captured for this Session.
210
+ * Register discovery of the calling Session’s authorized child models.
211
+ * @param ctx - Context carrying the tool registry and LLM service.
212
+ * @param policyHandle - retained reader for the Session’s authorized child routes.
171
213
  */
172
- function registerListSubagentModels(ctx, policy) {
214
+ function registerListSubagentModels(ctx, policyHandle) {
173
215
  ctx.tools.register(defineTool({
174
216
  name: "list_subagent_models",
175
- description: "Discover LLM routes for subagents without changing the current Agent. Call with no arguments to list registered providers, with `provider` to list its advertised models, or with `provider` and `model` to inspect that exact model and its reasoning efforts. Catalog membership is advisory: an adapter may accept an unlisted model id. Use the returned ids with a delegation tool's `provider`, `model`, and `reasoning_effort` fields.",
217
+ description: "Inspect subagent models without changing the current Agent. No arguments: providers; `provider`: allowed models; `provider` + `model`: that model and its reasoning efforts. Inspect options here before selecting a child provider and model; use returned ids for delegation.",
176
218
  parameters: {
177
219
  provider: {
178
220
  type: "string",
179
- description: "Registered LLM provider id. Omit to list providers."
221
+ description: "Registered LLM provider id."
180
222
  },
181
223
  model: {
182
224
  type: "string",
183
- description: "Exact model id to inspect. Requires provider; omit to list that provider's advertised models."
225
+ description: "Exact model id; requires provider."
184
226
  }
185
227
  },
186
228
  output: {
@@ -191,16 +233,15 @@ function registerListSubagentModels(ctx, policy) {
191
233
  }]
192
234
  },
193
235
  execute(args, exec) {
194
- return listSubagentModels(ctx, policy, args, exec.signal);
236
+ return listSubagentModels(ctx, policyHandle, args, exec);
195
237
  }
196
238
  }));
197
239
  }
198
240
  //#endregion
199
241
  //#region lib/types/preset-selection.js
200
- /** Validates configured references and resolves model input against the allowlist. */
242
+ /** Validates configured choices and resolves model input against the allowlist. */
201
243
  var SubagentPresetSelection = class {
202
244
  config;
203
- descriptions = [];
204
245
  constructor(config) {
205
246
  this.config = config;
206
247
  const { agentPreset, allowedAgentPresets } = config;
@@ -216,24 +257,9 @@ var SubagentPresetSelection = class {
216
257
  get choices() {
217
258
  return this.config.allowedAgentPresets;
218
259
  }
219
- /** Model-visible selection guidance and configured preset descriptions. */
260
+ /** Model-visible selection and default guidance. */
220
261
  get description() {
221
- return `Agent preset for this child. ${this.config.agentPreset === void 0 ? "Omit to inherit the parent agent's current preset." : `Omit to use ${this.config.agentPreset}.`}` + (this.descriptions.length === 0 ? "" : ` Available presets: ${this.descriptions.join("; ")}`);
222
- }
223
- /**
224
- * Read configured preset declarations before publishing the tool; mounting validates their activation.
225
- * @param ctx - Tool composition containing the preset service.
226
- */
227
- async validate(ctx) {
228
- const presets = ctx.get("agentPresets");
229
- if (presets === void 0) throw new Error("tool-subagent: agent preset selection requires the agent-presets service");
230
- const ids = new Set([...this.config.agentPreset === void 0 ? [] : [this.config.agentPreset], ...this.config.allowedAgentPresets ?? []]);
231
- const descriptions = [];
232
- for (const id of ids) {
233
- const preset = await presets.readDocument(id);
234
- if (this.choices?.includes(id) && preset.description !== void 0) descriptions.push(`${id}: ${preset.description}`);
235
- }
236
- this.descriptions = descriptions;
262
+ return `Agent preset for this child. ${this.config.agentPreset === void 0 ? "Omit to inherit the parent agent's current preset." : `Omit to use ${this.config.agentPreset}.`}`;
237
263
  }
238
264
  /**
239
265
  * Reject independent selection for providers that inherit conversation history or lack support.
@@ -255,42 +281,6 @@ var SubagentPresetSelection = class {
255
281
  return id;
256
282
  }
257
283
  };
258
- /** Host-only projection of the durable model-selection policy. */
259
- const subagentModelSelectionProjectionDefinition = {
260
- key: "subagentModelSelectionPolicy",
261
- stateVersion: 1,
262
- stateSchema: z$1.array(z$1.object({
263
- provider: z$1.string().min(1),
264
- model: z$1.string().min(1)
265
- }).strict()).min(1).nullable(),
266
- init: () => null,
267
- apply: (policy, event) => {
268
- if (policy !== null || event.type !== "subagent/model-selection-policy") return policy;
269
- const { allowedModels } = event.data;
270
- assertAllowedModelRoutes(allowedModels);
271
- if (allowedModels.length === 0) throw new Error("subagent/model-selection-policy requires at least one route");
272
- return allowedModels;
273
- }
274
- };
275
- /**
276
- * Read the exact route list captured for a model-selectable definition.
277
- * @param projections - registry that owns the policy projection.
278
- * @param session - session whose durable decision is read.
279
- * @returns a detached route list, or undefined for the fixed-route definition.
280
- */
281
- function subagentModelSelectionPolicy(projections, session) {
282
- return projections.stateOf(session, "subagentModelSelectionPolicy")?.map((route) => ({ ...route }));
283
- }
284
- /**
285
- * Append the route policy once, before its definition can reach a model request.
286
- * @param projections - registry that owns the policy projection.
287
- * @param session - session receiving the model-selectable definition.
288
- * @param allowedModels - exact routes the definition may select explicitly.
289
- */
290
- function recordSubagentModelSelection(projections, session, allowedModels) {
291
- if (subagentModelSelectionPolicy(projections, session) !== void 0) return;
292
- session.append("subagent/model-selection-policy", { allowedModels: allowedModels.map((route) => ({ ...route })) });
293
- }
294
284
  //#endregion
295
285
  //#region lib/types/index.js
296
286
  /**
@@ -311,7 +301,8 @@ const delegationTools = /* @__PURE__ */ new Set();
311
301
  const Config = z.object({
312
302
  provider: z.string().required(),
313
303
  toolName: z.string().default("subagent"),
314
- modelSelectionSettings: z.boolean().default(false),
304
+ modelSelection: z.boolean().default(false),
305
+ modelDiscovery: z.boolean().default(false),
315
306
  agentOptions: z.object({
316
307
  provider: z.string(),
317
308
  model: z.string(),
@@ -346,270 +337,188 @@ function providerWording(inheritsConversation) {
346
337
  }
347
338
  /**
348
339
  * Install one delegation-tool composition.
349
- * Standing preset choices are validated for each Agent before its tool is installed.
340
+ * The owning composition shares its registrations across Agents; child startup resolves the selected preset.
350
341
  * @param ctx - Context that owns the registrations.
351
342
  * @param config - delegation-tool configuration.
352
- * @param session - unpublished Session supplied by a direct Agent setup; omit for a standing composition.
343
+ * @returns when the plugin is ready.
353
344
  */
354
- async function apply(ctx, config, session) {
345
+ async function apply(ctx, config) {
355
346
  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)`);
356
347
  const presets = new SubagentPresetSelection(config);
357
348
  if (presets.configured && ctx.get("agentPresets") === void 0) throw new Error("tool-subagent: agent preset selection requires the agent-presets service");
358
349
  if (config.maxDepth !== "provider-managed") assertSubagentMaxDepth(config.maxDepth);
359
350
  const toolName = config.toolName ?? "subagent";
360
- const modelSelectionCapable = config.modelSelectionSettings === true;
361
- ctx.sessionProjections.register(subagentModelSelectionProjectionDefinition);
351
+ const modelSelectionEnabled = config.modelSelection === true;
352
+ const subagentModelSelectionProjectionHandle = await ctx.sessionProjections.register(subagentModelSelectionProjectionDefinition);
362
353
  const assertSubagentProviderConfiguration = (subagentProvider) => {
363
354
  presets.assertProvider(subagentProvider);
364
355
  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`);
365
356
  if (config.agentOptions !== void 0 && !subagentProvider.capabilities.agentOptions) throw new Error(`tool-subagent: provider "${subagentProvider.name}" does not support child agentOptions`);
366
- if (modelSelectionCapable && !subagentProvider.capabilities.agentOptions) throw new Error(`tool-subagent: provider "${subagentProvider.name}" does not support child model selection`);
357
+ if (modelSelectionEnabled && !subagentProvider.capabilities.agentOptions) throw new Error(`tool-subagent: provider "${subagentProvider.name}" does not support child model selection`);
367
358
  };
368
359
  ctx.on("subagent/provider-added", (subagentProvider) => {
369
360
  if (subagentProvider.name === config.provider) assertSubagentProviderConfiguration(subagentProvider);
370
361
  });
371
362
  const initialProvider = ctx.subagents.getProvider(config.provider);
372
363
  if (initialProvider !== void 0) assertSubagentProviderConfiguration(initialProvider);
373
- const install = (runtimeCtx, modelSelectionPolicy) => {
374
- const modelSelectionEnabled = modelSelectionPolicy !== void 0;
375
- if (modelSelectionPolicy !== void 0) registerListSubagentModels(runtimeCtx, modelSelectionPolicy);
376
- let mounted;
377
- const mount = (subagentProvider) => {
378
- assertSubagentProviderConfiguration(subagentProvider);
379
- const wording = providerWording(subagentProvider.inheritsParentContext);
380
- const providerRouteDefaults = subagentProvider.agentRouteDefaults;
381
- const choiceDescription = !modelSelectionEnabled ? "" : (providerRouteDefaults !== void 0 ? " Child LLM selection is optional. Omit `provider`, `model`, and `reasoning_effort` to use configured child defaults and this provider's route defaults. Supply `provider` and `model` together after using `list_subagent_models` to inspect advertised routes and efforts. Changing the effective route without naming an effort uses the selected model's default effort." : " Child LLM selection is optional. Omit `provider`, `model`, and `reasoning_effort` to use configured child defaults and inherit compatible missing values from the parent Agent. Supply `provider` and `model` together after using `list_subagent_models` to inspect advertised routes and efforts. Changing the effective route without naming an effort uses the selected model's default effort.") + (subagentProvider.inheritsParentContext ? " Changing the route can prevent provider-side reuse of the inherited conversation prefix." : "");
382
- const definition = defineTool({
383
- name: toolName,
384
- description: wording.description + " This tool starts an independently managed subagent and immediately returns its id. The runtime notifies you when it finishes." + (subagentProvider.prepareContinuable !== void 0 ? " The child reports results with `send_message`; use `send_message` to steer it while running or continue its conversation after it finishes." : " The completion notice includes its final answer. This backend does not accept follow-up messages.") + choiceDescription,
385
- parameters: {
386
- cwd: {
387
- type: "string",
388
- description: "Initial child working directory. Relative paths use your current directory; omitted inherits it. Later directory changes in either agent are independent."
389
- },
390
- description: {
364
+ if (config.modelDiscovery === true) registerListSubagentModels(ctx, subagentModelSelectionProjectionHandle);
365
+ let mounted;
366
+ const mount = (subagentProvider) => {
367
+ assertSubagentProviderConfiguration(subagentProvider);
368
+ const wording = providerWording(subagentProvider.inheritsParentContext);
369
+ const providerRouteDefaults = subagentProvider.agentRouteDefaults;
370
+ const selectionDescription = providerRouteDefaults !== void 0 ? " Supply `provider` and `model` together. Omitted values use child defaults, falling back to this backend's route defaults. When the effective route changes, an omitted `reasoning_effort` uses the model's default." : " Supply `provider` and `model` together. Omitted values use child defaults, falling back to compatible parent values. When the effective route changes, an omitted `reasoning_effort` uses the model's default.";
371
+ const definition = defineTool({
372
+ name: toolName,
373
+ description: wording.description + " This tool starts an independently managed subagent and immediately returns its id. The runtime notifies you when it finishes." + (subagentProvider.prepareContinuable !== void 0 ? " The child reports results with `send_message`; use `send_message` to steer it while running or continue its conversation after it finishes." : " The completion notice includes its final answer. 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." : ""),
374
+ parameters: {
375
+ cwd: {
376
+ type: "string",
377
+ description: "Initial child working directory. Relative paths use your current directory; omitted inherits it. Later directory changes in either agent are independent."
378
+ },
379
+ description: {
380
+ type: "string",
381
+ required: true,
382
+ description: "A short (3-5 word) description of the delegated task, for display."
383
+ },
384
+ prompt: {
385
+ type: "string",
386
+ required: true,
387
+ description: wording.promptDescription
388
+ },
389
+ ...presets.choices === void 0 ? {} : { agent_preset: {
390
+ type: "string",
391
+ enum: [...presets.choices],
392
+ description: presets.description
393
+ } },
394
+ ...modelSelectionEnabled ? {
395
+ provider: {
391
396
  type: "string",
392
- required: true,
393
- description: "A short (3-5 word) description of the delegated task, for display."
397
+ description: "Child LLM provider id."
394
398
  },
395
- prompt: {
399
+ model: {
396
400
  type: "string",
397
- required: true,
398
- description: wording.promptDescription
401
+ description: "Model id within that provider."
399
402
  },
400
- ...presets.choices === void 0 ? {} : { agent_preset: {
403
+ reasoning_effort: {
401
404
  type: "string",
402
- enum: [...presets.choices],
403
- description: presets.description
404
- } },
405
- ...modelSelectionEnabled ? {
406
- provider: {
407
- type: "string",
408
- description: providerRouteDefaults !== void 0 ? "LLM provider route for the child. Supply together with model; omit both to use configured child defaults or this provider's route defaults." : "LLM provider route for the child. Supply together with model; omit both to use configured child defaults or inherit the parent route."
409
- },
410
- model: {
405
+ description: "Model-specific reasoning effort id."
406
+ }
407
+ } : {}
408
+ },
409
+ output: {
410
+ schema: {
411
+ type: "object",
412
+ additionalProperties: false,
413
+ properties: {
414
+ kind: {
411
415
  type: "string",
412
- description: providerRouteDefaults !== void 0 ? "Model id interpreted by provider. Supply together with provider; omit both to use configured child defaults or this provider's route defaults." : "Model id interpreted by provider. Supply together with provider; omit both to use configured child defaults or inherit the parent route."
416
+ required: true,
417
+ const: "activation"
413
418
  },
414
- reasoning_effort: {
419
+ subagentId: {
415
420
  type: "string",
416
- description: providerRouteDefaults !== void 0 ? "Adapter-owned reasoning effort for the effective child route. Omit to use a compatible configured effort or the selected model's default." : "Adapter-owned reasoning effort for the effective child route. Omit to inherit a compatible configured/parent effort or use a newly selected model's default."
421
+ required: true
417
422
  }
418
- } : {}
419
- },
420
- output: {
421
- schema: {
422
- type: "object",
423
- additionalProperties: false,
424
- properties: {
425
- kind: {
426
- type: "string",
427
- required: true,
428
- const: "activation"
429
- },
430
- subagentId: {
431
- type: "string",
432
- required: true
433
- }
434
- }
435
- },
436
- render: (_args, value) => [{
437
- type: "text",
438
- text: `started subagent ${value.subagentId}`
439
- }]
440
- },
441
- isConcurrencySafe: () => true,
442
- async execute(args, exec) {
443
- const parent = exec.agent;
444
- if (!parent) throw new Error("subagent tool requires a calling agent (exec.agent was undefined)");
445
- const agentPreset = presets.resolve(args);
446
- const modelRequest = args;
447
- const parentOptions = parentAgentOptionsForDelegation(parent);
448
- const requiresRoutePreflight = hasDelegationModelRequest(modelRequest) || hasConfiguredLlmSelection(config.agentOptions);
449
- const requestedChildAgentOptions = requestedAgentOptions(parentOptions, requiresRoutePreflight && providerRouteDefaults !== void 0 ? {
450
- ...providerRouteDefaults,
451
- ...config.agentOptions
452
- } : config.agentOptions, modelRequest, modelSelectionEnabled);
453
- assertAllowedModelSelection(modelSelectionPolicy, parentOptions, requestedChildAgentOptions, modelRequest);
454
- if (requiresRoutePreflight) {
455
- const llm = runtimeCtx.get("llm");
456
- if (llm === void 0) throw new Error("cannot resolve the selected child LLM route because the `llm` service is unavailable");
457
- await preflightChildLlmRoute(llm, parentOptions, requestedChildAgentOptions, exec.signal, providerRouteDefaults === void 0);
458
- if (runtimeCtx.subagents.getProvider(config.provider) !== subagentProvider) throw new Error(`subagent provider "${config.provider}" changed while resolving the child LLM route; retry the delegation`);
459
423
  }
460
- exec.signal.throwIfAborted();
461
- const maxDepth = runtimeCtx.subagents.resolveMaxDepth(config.maxDepth);
462
- const request = {
463
- ...args.cwd === void 0 ? {} : { cwd: args.cwd },
464
- prompt: [{
465
- type: "text",
466
- text: args.prompt
467
- }],
468
- parent,
469
- ...agentPreset === void 0 ? {} : { agentPreset },
470
- ...requestedChildAgentOptions !== void 0 ? { agentOptions: requestedChildAgentOptions } : {},
471
- ...maxDepth !== void 0 ? { maxDepth } : {}
472
- };
473
- return {
474
- kind: "activation",
475
- subagentId: (await runtimeCtx.subagents.startActivation({
476
- provider: config.provider,
477
- label: args.description,
478
- request,
479
- signal: exec.signal,
480
- delivery: "parent"
481
- })).childId
482
- };
424
+ },
425
+ render: (_args, value) => [{
426
+ type: "text",
427
+ text: `started subagent ${value.subagentId}`
428
+ }]
429
+ },
430
+ isConcurrencySafe: () => true,
431
+ async execute(args, exec) {
432
+ const parent = exec.agent;
433
+ if (!parent) throw new Error("subagent tool requires a calling agent (exec.agent was undefined)");
434
+ const routes = subagentModelSelectionPolicy(subagentModelSelectionProjectionHandle, parent.session);
435
+ const modelSelectionPolicy = routes === void 0 ? void 0 : { routes };
436
+ const agentPreset = presets.resolve(args);
437
+ const modelRequest = args;
438
+ const parentOptions = parentAgentOptionsForDelegation(parent);
439
+ const requiresRoutePreflight = hasDelegationModelRequest(modelRequest) || hasConfiguredLlmSelection(config.agentOptions);
440
+ const requestedChildAgentOptions = requestedAgentOptions(parentOptions, requiresRoutePreflight && providerRouteDefaults !== void 0 ? {
441
+ ...providerRouteDefaults,
442
+ ...config.agentOptions
443
+ } : config.agentOptions, modelRequest, modelSelectionEnabled);
444
+ assertAllowedModelSelection(modelSelectionPolicy, parentOptions, requestedChildAgentOptions, modelRequest);
445
+ if (requiresRoutePreflight) {
446
+ const llm = ctx.get("llm");
447
+ if (llm === void 0) throw new Error("cannot resolve the selected child LLM route because the `llm` service is unavailable");
448
+ await preflightChildLlmRoute(llm, parentOptions, requestedChildAgentOptions, exec.signal, providerRouteDefaults === void 0);
449
+ if (ctx.subagents.getProvider(config.provider) !== subagentProvider) throw new Error(`subagent provider "${config.provider}" changed while resolving the child LLM route; retry the delegation`);
483
450
  }
484
- });
485
- mounted = {
486
- subagentProvider,
487
- definition,
488
- disposeTool: runtimeCtx.effect(() => {
489
- const unregister = runtimeCtx.tools.register(definition);
490
- delegationTools.add(definition);
491
- return () => {
492
- delegationTools.delete(definition);
493
- unregister();
494
- };
495
- })
496
- };
497
- };
498
- runtimeCtx.on("subagent/provider-added", (subagentProvider) => {
499
- if (subagentProvider.name === config.provider && mounted === void 0) mount(subagentProvider);
500
- });
501
- runtimeCtx.on("subagent/provider-removed", (name) => {
502
- if (name !== config.provider || mounted === void 0) return;
503
- mounted.disposeTool();
504
- mounted = void 0;
505
- });
506
- const present = runtimeCtx.subagents.getProvider(config.provider);
507
- if (present !== void 0) mount(present);
508
- else runtimeCtx.logger.info(`subagent provider "${config.provider}" not registered yet; the "${config.toolName ?? "subagent"}" tool will register when it appears`);
509
- runtimeCtx.systemPrompt.section({
510
- name: `tool:${toolName}`,
511
- order: runtimeCtx.systemPrompt.getSectionOrder("TOOL_SUBAGENT"),
512
- text: (context) => {
513
- if (mounted === void 0) return "";
514
- const visible = [...delegationTools].filter((tool) => runtimeCtx.tools.get(tool.name, context.scope) === tool).map((tool) => tool.name).sort();
515
- if (visible[0] !== toolName) return "";
516
- return `Start independent delegations with ${visible.map((name) => `\`${name}\``).join(" or ")} together in one assistant message and continue useful work while they run.`;
517
- }
518
- });
519
- runtimeCtx.systemPrompt.context({
520
- name: `tool:${toolName}:depth`,
521
- order: runtimeCtx.systemPrompt.getContextOrder("SUBAGENT_DELEGATION"),
522
- text: (context) => {
523
- if (context.agent === void 0 || mounted === void 0 || runtimeCtx.tools.get(toolName, context.scope) !== mounted.definition) return "";
524
- const maxDepth = runtimeCtx.subagents.resolveMaxDepth(config.maxDepth);
525
- if (maxDepth === void 0) return "";
526
- const depth = delegationDepthOf(context.agent);
527
- if (depth < maxDepth) return "";
528
- return `Delegation depth for \`${toolName}\`: current ${depth}, maximum ${maxDepth}, remaining levels 0. Do not call \`${toolName}\` at this depth; carry out the work directly.`;
451
+ exec.signal.throwIfAborted();
452
+ const maxDepth = ctx.subagents.resolveMaxDepth(config.maxDepth);
453
+ const request = {
454
+ ...args.cwd === void 0 ? {} : { cwd: args.cwd },
455
+ prompt: [{
456
+ type: "text",
457
+ text: args.prompt
458
+ }],
459
+ parent,
460
+ ...agentPreset === void 0 ? {} : { agentPreset },
461
+ ...requestedChildAgentOptions !== void 0 ? { agentOptions: requestedChildAgentOptions } : {},
462
+ ...maxDepth !== void 0 ? { maxDepth } : {}
463
+ };
464
+ return {
465
+ kind: "activation",
466
+ subagentId: (await ctx.subagents.startActivation({
467
+ provider: config.provider,
468
+ label: args.description,
469
+ request,
470
+ signal: exec.signal,
471
+ delivery: "parent"
472
+ })).childId
473
+ };
529
474
  }
530
475
  });
476
+ mounted = {
477
+ subagentProvider,
478
+ definition,
479
+ disposeTool: ctx.effect(() => {
480
+ const unregister = ctx.tools.register(definition);
481
+ delegationTools.add(definition);
482
+ return () => {
483
+ delegationTools.delete(definition);
484
+ unregister();
485
+ };
486
+ })
487
+ };
531
488
  };
532
- const compositionScope = scopeOf(ctx);
533
- if (presets.configured && (session !== void 0 || compositionScope === void 0)) await presets.validate(ctx);
534
- if (!modelSelectionCapable && (!presets.configured || session !== void 0 || compositionScope === void 0)) {
535
- install(ctx, void 0);
536
- return;
537
- }
538
- const settings = ctx.get("subagentModelSelection");
539
- if (modelSelectionCapable && settings === void 0) throw new Error("tool-subagent: `modelSelectionSettings` requires @deepseek-ai/dsh-tool-subagent/model-selection-settings in the Host scope");
540
- const selectForSession = (target) => {
541
- if (!modelSelectionCapable || settings === void 0) return void 0;
542
- const freshSession = target.firstLiveSeq === 0 && target.eventAt(SessionSeq(0))?.type !== "session/end-seed";
543
- let allowedModels = subagentModelSelectionPolicy(ctx.sessionProjections, target);
544
- if (allowedModels === void 0) {
545
- const parentId = target.header.origin === "subagent" ? target.header.parentSession : void 0;
546
- if (parentId !== void 0) {
547
- const sessions = ctx.get("sessions");
548
- if (sessions === void 0) throw new Error("tool-subagent: child model-selection inheritance requires the Session registry");
549
- const parent = sessions.get(parentId);
550
- allowedModels = parent === void 0 ? void 0 : subagentModelSelectionPolicy(ctx.sessionProjections, parent);
551
- } else if (freshSession) {
552
- const current = settings.current();
553
- allowedModels = current.enabled ? current.allowedModels : void 0;
554
- }
555
- }
556
- if (allowedModels !== void 0) recordSubagentModelSelection(ctx.sessionProjections, target, allowedModels);
557
- return allowedModels === void 0 ? void 0 : { routes: allowedModels };
558
- };
559
- if (session !== void 0) {
560
- install(ctx, selectForSession(session));
561
- return;
562
- }
563
- if (compositionScope === void 0) throw new Error("tool-subagent: standing `modelSelectionSettings` requires a scoped preset Context");
564
- const agents = ctx.get("agents");
565
- /* v8 ignore next -- shipped preset compositions always include the Agent registry. */
566
- if (agents === void 0) throw new Error("tool-subagent: standing `modelSelectionSettings` requires the Agent registry");
567
- const scopedInstalls = /* @__PURE__ */ new WeakMap();
568
- const installing = /* @__PURE__ */ new WeakSet();
569
- const belongsToComposition = (candidate) => scopeChainOf(scopeOf(candidate.ctx)).includes(compositionScope);
570
- const installScoped = (candidate) => {
571
- const existing = scopedInstalls.get(candidate);
572
- if (existing !== void 0) return existing;
573
- if (installing.has(candidate)) return;
574
- installing.add(candidate);
575
- let fiber;
576
- try {
577
- const policy = selectForSession(candidate.session);
578
- fiber = candidate.ctx.inject([
579
- "tools",
580
- "subagents",
581
- "systemPrompt"
582
- ], async (runtimeCtx) => {
583
- if (presets.configured) await presets.validate(ctx);
584
- install(runtimeCtx, policy);
585
- });
586
- } finally {
587
- installing.delete(candidate);
489
+ ctx.on("subagent/provider-added", (subagentProvider) => {
490
+ if (subagentProvider.name === config.provider && mounted === void 0) mount(subagentProvider);
491
+ });
492
+ ctx.on("subagent/provider-removed", (name) => {
493
+ if (name !== config.provider || mounted === void 0) return;
494
+ mounted.disposeTool();
495
+ mounted = void 0;
496
+ });
497
+ const present = ctx.subagents.getProvider(config.provider);
498
+ if (present !== void 0) mount(present);
499
+ else ctx.logger.info(`subagent provider "${config.provider}" not registered yet; the "${config.toolName ?? "subagent"}" tool will register when it appears`);
500
+ ctx.systemPrompt.section({
501
+ name: `tool:${toolName}`,
502
+ order: ctx.systemPrompt.getSectionOrder("TOOL_SUBAGENT"),
503
+ text: (context) => {
504
+ if (mounted === void 0) return "";
505
+ const visible = [...delegationTools].filter((tool) => ctx.tools.get(tool.name, context.scope) === tool).map((tool) => tool.name).sort();
506
+ if (visible[0] !== toolName) return "";
507
+ 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.`;
588
508
  }
589
- scopedInstalls.set(candidate, fiber);
590
- return fiber;
591
- };
592
- const removeScoped = (candidate) => {
593
- const fiber = scopedInstalls.get(candidate);
594
- if (fiber === void 0) return;
595
- scopedInstalls.delete(candidate);
596
- /* v8 ignore next 3 -- Cordis Fiber disposal contains registration cleanup failures; this is the final diagnostic sink. */
597
- fiber.dispose().catch((error) => {
598
- ctx.logger.warn(`tool-subagent: failed to remove recomposed Agent "${candidate.id}" definitions: ${String(error)}`);
599
- });
600
- };
601
- const reconcileComposedAgents = () => {
602
- for (const candidate of agents.list()) if (belongsToComposition(candidate)) installScoped(candidate);
603
- else removeScoped(candidate);
604
- };
605
- ctx.on("agent/created", async ({ agent: created }) => {
606
- await installScoped(created);
607
509
  });
608
- ctx.on("agent/disposed", ({ agent: disposed }) => {
609
- removeScoped(disposed);
510
+ ctx.systemPrompt.context({
511
+ name: `tool:${toolName}:depth`,
512
+ order: ctx.systemPrompt.getContextOrder("SUBAGENT_DELEGATION"),
513
+ text: (context) => {
514
+ if (context.agent === void 0 || mounted === void 0 || ctx.tools.get(toolName, context.scope) !== mounted.definition) return "";
515
+ const maxDepth = ctx.subagents.resolveMaxDepth(config.maxDepth);
516
+ if (maxDepth === void 0) return "";
517
+ const depth = delegationDepthOf(context.agent);
518
+ if (depth < maxDepth) return "";
519
+ return `Delegation depth for \`${toolName}\`: current ${depth}, maximum ${maxDepth}, remaining levels 0. Do not call \`${toolName}\` at this depth; carry out the work directly.`;
520
+ }
610
521
  });
611
- ctx.on("tools/change", reconcileComposedAgents);
612
- reconcileComposedAgents();
613
522
  }
614
523
  //#endregion
615
524
  export { Config, apply, inject, name };