@deepseek-ai/dsh-tool-subagent 0.2.1-alpha.1 → 0.2.1-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
@@ -2,7 +2,7 @@ import z from "@deepseek-ai/schemastery";
2
2
  import { scopeChainOf, scopeOf } from "@deepseek-ai/dsh-scope";
3
3
  import { defineTool } from "@deepseek-ai/dsh-tools";
4
4
  import { SessionSeq } from "@deepseek-ai/dsh-session";
5
- import { assertSubagentMaxDepth, parentAgentOptionsForDelegation, settleRun } from "@deepseek-ai/dsh-subagent";
5
+ import { assertSubagentMaxDepth, delegationDepthOf, parentAgentOptionsForDelegation } from "@deepseek-ai/dsh-subagent";
6
6
  import { ReasoningEffortId } from "@deepseek-ai/dsh-llm";
7
7
  import { z as z$1 } from "zod";
8
8
  z.object({
@@ -195,6 +195,66 @@ function registerListSubagentModels(ctx, policy) {
195
195
  }
196
196
  }));
197
197
  }
198
+ //#endregion
199
+ //#region lib/types/preset-selection.js
200
+ /** Validates configured references and resolves model input against the allowlist. */
201
+ var SubagentPresetSelection = class {
202
+ config;
203
+ descriptions = [];
204
+ constructor(config) {
205
+ this.config = config;
206
+ const { agentPreset, allowedAgentPresets } = config;
207
+ if (allowedAgentPresets === void 0) return;
208
+ if (new Set(allowedAgentPresets).size !== allowedAgentPresets.length) throw new Error("tool-subagent: allowedAgentPresets contains duplicate preset ids");
209
+ if (agentPreset !== void 0 && !allowedAgentPresets.includes(agentPreset)) throw new Error("tool-subagent: agentPreset must be included in allowedAgentPresets");
210
+ }
211
+ /** Whether this tool requires the preset service and an independently composing provider. */
212
+ get configured() {
213
+ return this.config.agentPreset !== void 0 || this.config.allowedAgentPresets !== void 0;
214
+ }
215
+ /** Preset ids advertised in the model parameter. */
216
+ get choices() {
217
+ return this.config.allowedAgentPresets;
218
+ }
219
+ /** Model-visible selection guidance and configured preset descriptions. */
220
+ 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;
237
+ }
238
+ /**
239
+ * Reject independent selection for providers that inherit conversation history or lack support.
240
+ * @param provider - Currently registered delegation provider.
241
+ */
242
+ assertProvider(provider) {
243
+ if (this.configured && (!provider.capabilities.agentPreset || provider.inheritsParentContext)) throw new Error(`tool-subagent: provider "${provider.name}" does not support independent agent preset selection`);
244
+ }
245
+ /**
246
+ * Validate model input and apply the deployment default.
247
+ * @param request - Model-supplied tool arguments.
248
+ * @returns Selected preset id, or omission to inherit the parent.
249
+ */
250
+ resolve(request) {
251
+ const id = request.agent_preset;
252
+ if (id === void 0) return this.config.agentPreset;
253
+ if (this.choices === void 0) throw new Error("agent_preset selection is disabled for this tool instance");
254
+ if (typeof id !== "string" || !this.choices.includes(id)) throw new Error(`agent_preset must be one of: ${this.choices.join(", ")}`);
255
+ return id;
256
+ }
257
+ };
198
258
  /** Host-only projection of the durable model-selection policy. */
199
259
  const subagentModelSelectionProjectionDefinition = {
200
260
  key: "subagentModelSelectionPolicy",
@@ -236,10 +296,8 @@ function recordSubagentModelSelection(projections, session, allowedModels) {
236
296
  /**
237
297
  * Model-facing delegation through one configured `ctx.subagents` provider.
238
298
  * Provider lifecycle controls tool registration and context-sensitive schema
239
- * wording. Foreground calls always dispose the run after collection.
240
- * Background policy is selected by this plugin's configuration: one-shot
241
- * calls own a plain Task, while continuable calls use
242
- * `ctx.subagents.startContinuable()`.
299
+ * wording. Every delegation starts a managed activation and returns its child
300
+ * id; the subagent runtime owns result delivery and resource cleanup.
243
301
  * @module @deepseek-ai/dsh-tool-subagent
244
302
  */
245
303
  const name = "tool-subagent";
@@ -249,86 +307,21 @@ const inject = [
249
307
  "systemPrompt",
250
308
  "sessionProjections"
251
309
  ];
310
+ const delegationTools = /* @__PURE__ */ new Set();
252
311
  const Config = z.object({
253
312
  provider: z.string().required(),
254
313
  toolName: z.string().default("subagent"),
255
314
  modelSelectionSettings: z.boolean().default(false),
256
- enableRunInBackground: z.boolean().default(true),
257
- backgroundMode: z.union(["one-shot", "continuable"]).default("one-shot"),
258
315
  agentOptions: z.object({
259
316
  provider: z.string(),
260
317
  model: z.string(),
261
318
  reasoningEffort: z.string().min(1),
262
319
  maxTokens: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER)
263
320
  }).default(void 0),
264
- persona: z.string(),
265
- toolFilter: z.object({
266
- allow: z.array(z.string()).default(void 0),
267
- deny: z.array(z.string()).default(void 0)
268
- }).default(void 0),
321
+ agentPreset: z.string().min(1),
322
+ allowedAgentPresets: z.array(z.string().min(1)).min(1).default(void 0),
269
323
  maxDepth: z.union([z.natural().max(Number.MAX_SAFE_INTEGER), z.const("provider-managed")])
270
324
  });
271
- /** Render text blocks from the canonical JSON block array without trusting arbitrary values. */
272
- function outputValueText(values) {
273
- return values.filter((value) => typeof value === "object" && value !== null && !Array.isArray(value) && value.type === "text" && typeof value.text === "string").map((value) => value.text).join("");
274
- }
275
- /** Settle pending startup without rejecting the task producer contract. */
276
- async function settleStart(start, signal) {
277
- try {
278
- return await settleRun(await start);
279
- } catch (error) {
280
- return signal.aborted && !(error instanceof AggregateError) ? { status: "killed" } : {
281
- status: "failed",
282
- detail: String(error)
283
- };
284
- }
285
- }
286
- /** A non-`completed` stop reason means the child did not finish cleanly. */
287
- function stopReasonError(result) {
288
- switch (result.stopReason) {
289
- case "completed": return;
290
- case "aborted": return "subagent run was cancelled";
291
- case "error": return "subagent run failed";
292
- case "max-tokens": return "subagent run hit its token limit before finishing";
293
- case "refusal": return "subagent declined the task";
294
- default: return `subagent run ended abnormally (${String(result.stopReason)})`;
295
- }
296
- }
297
- /**
298
- * Append provider-authored failure detail and the child's preserved partial
299
- * answer to a stop-reason error, keeping diagnostic text separate from the
300
- * child's assistant output.
301
- * @param error - the stop-reason headline.
302
- * @param result - the child's terminal result.
303
- * @returns the headline, diagnostic, and partial text that are present.
304
- */
305
- function withDiagnosticAndPartialText(error, result) {
306
- const diagnostic = result.diagnostic === void 0 ? "" : `\nDiagnostic: ${result.diagnostic}`;
307
- const text = result.output.filter((block) => block.type === "text").map((block) => block.text).join("");
308
- return `${error}${diagnostic}${text.length === 0 ? "" : `\nPartial output before the run ended:\n${text}`}`;
309
- }
310
- /**
311
- * Collect and release one foreground run without letting disposal replace an
312
- * independent result failure.
313
- */
314
- async function settleForegroundRun(run) {
315
- const [execution] = await Promise.allSettled([run.result.then((result) => {
316
- const error = stopReasonError(result);
317
- if (error !== void 0) throw new Error(withDiagnosticAndPartialText(error, result));
318
- return {
319
- kind: "foreground",
320
- runId: run.id,
321
- output: result.output
322
- };
323
- })]);
324
- const [disposal] = await Promise.allSettled([Promise.resolve().then(() => run.dispose())]);
325
- if (execution.status === "rejected") {
326
- if (disposal.status === "rejected") throw new AggregateError([execution.reason, disposal.reason], `subagent run failed: ${String(execution.reason)}; dispose failed: ${String(disposal.reason)}`);
327
- throw execution.reason;
328
- }
329
- if (disposal.status === "rejected") throw disposal.reason;
330
- return execution.value;
331
- }
332
325
  /**
333
326
  * Model-facing wording from the provider's conversation-history descriptor
334
327
  * ({@link SubagentProvider.inheritsParentContext}).
@@ -351,33 +344,26 @@ function providerWording(inheritsConversation) {
351
344
  promptDescription: "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs."
352
345
  };
353
346
  }
354
- /** Resolve the model's optional scheduling request into one execution route. */
355
- function resolveDelegationRun(request, options) {
356
- if (!options.backgroundEnabled) {
357
- if (request.run_in_background === true) throw new Error("run_in_background is disabled for this tool instance (enableRunInBackground: false)");
358
- return { runInBackground: false };
359
- }
360
- return { runInBackground: request.run_in_background ?? options.continuable };
361
- }
362
347
  /**
363
348
  * Install one delegation-tool composition.
349
+ * Standing preset choices are validated for each Agent before its tool is installed.
364
350
  * @param ctx - Context that owns the registrations.
365
351
  * @param config - delegation-tool configuration.
366
352
  * @param session - unpublished Session supplied by a direct Agent setup; omit for a standing composition.
367
353
  */
368
- function apply(ctx, config, session) {
354
+ async function apply(ctx, config, session) {
355
+ 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
+ const presets = new SubagentPresetSelection(config);
357
+ if (presets.configured && ctx.get("agentPresets") === void 0) throw new Error("tool-subagent: agent preset selection requires the agent-presets service");
369
358
  if (config.maxDepth !== "provider-managed") assertSubagentMaxDepth(config.maxDepth);
370
- if (config.toolFilter !== void 0 && config.toolFilter.allow === void 0 && config.toolFilter.deny === void 0) throw new Error("tool-subagent: `toolFilter` is configured but names neither `allow` nor `deny` — remove the key or fill the filter");
371
- const backgroundEnabled = config.enableRunInBackground !== false;
372
- const continuable = (config.backgroundMode ?? "one-shot") === "continuable";
373
359
  const toolName = config.toolName ?? "subagent";
374
360
  const modelSelectionCapable = config.modelSelectionSettings === true;
375
361
  ctx.sessionProjections.register(subagentModelSelectionProjectionDefinition);
376
362
  const assertSubagentProviderConfiguration = (subagentProvider) => {
363
+ presets.assertProvider(subagentProvider);
377
364
  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`);
378
365
  if (config.agentOptions !== void 0 && !subagentProvider.capabilities.agentOptions) throw new Error(`tool-subagent: provider "${subagentProvider.name}" does not support child agentOptions`);
379
366
  if (modelSelectionCapable && !subagentProvider.capabilities.agentOptions) throw new Error(`tool-subagent: provider "${subagentProvider.name}" does not support child model selection`);
380
- if (continuable && subagentProvider.prepareContinuable === void 0) throw new Error(`tool-subagent: provider "${subagentProvider.name}" does not support \`backgroundMode: continuable\``);
381
367
  };
382
368
  ctx.on("subagent/provider-added", (subagentProvider) => {
383
369
  if (subagentProvider.name === config.provider) assertSubagentProviderConfiguration(subagentProvider);
@@ -393,173 +379,120 @@ function apply(ctx, config, session) {
393
379
  const wording = providerWording(subagentProvider.inheritsParentContext);
394
380
  const providerRouteDefaults = subagentProvider.agentRouteDefaults;
395
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." : "");
396
- mounted = {
397
- subagentProvider,
398
- disposeTool: runtimeCtx.tools.register(defineTool({
399
- name: toolName,
400
- description: wording.description + (backgroundEnabled ? continuable ? " It runs in the background by default and returns a subagent id you can continue with `send_message`; you are notified when the run settles." : " This call waits for the result by default." : " This call waits for the subagent and returns its result.") + choiceDescription,
401
- parameters: {
402
- description: {
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: {
391
+ type: "string",
392
+ required: true,
393
+ description: "A short (3-5 word) description of the delegated task, for display."
394
+ },
395
+ prompt: {
396
+ type: "string",
397
+ required: true,
398
+ description: wording.promptDescription
399
+ },
400
+ ...presets.choices === void 0 ? {} : { agent_preset: {
401
+ type: "string",
402
+ enum: [...presets.choices],
403
+ description: presets.description
404
+ } },
405
+ ...modelSelectionEnabled ? {
406
+ provider: {
403
407
  type: "string",
404
- required: true,
405
- description: "A short (3-5 word) description of the delegated task, for display."
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."
406
409
  },
407
- prompt: {
410
+ model: {
408
411
  type: "string",
409
- required: true,
410
- description: wording.promptDescription
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."
411
413
  },
412
- ...modelSelectionEnabled ? {
413
- provider: {
414
- type: "string",
415
- 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."
416
- },
417
- model: {
414
+ reasoning_effort: {
415
+ 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."
417
+ }
418
+ } : {}
419
+ },
420
+ output: {
421
+ schema: {
422
+ type: "object",
423
+ additionalProperties: false,
424
+ properties: {
425
+ kind: {
418
426
  type: "string",
419
- 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."
427
+ required: true,
428
+ const: "activation"
420
429
  },
421
- reasoning_effort: {
430
+ subagentId: {
422
431
  type: "string",
423
- 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."
432
+ required: true
424
433
  }
425
- } : {},
426
- ...backgroundEnabled ? { run_in_background: {
427
- type: "boolean",
428
- description: continuable ? "Defaults to true. Set false only when your next action depends on the result." : "Run as a background job and return its id (collect with job_output, stop with job_kill). Defaults to false."
429
- } } : {}
434
+ }
430
435
  },
431
- output: {
432
- schema: { oneOf: [
433
- {
434
- type: "object",
435
- additionalProperties: false,
436
- properties: {
437
- kind: {
438
- type: "string",
439
- required: true,
440
- const: "background"
441
- },
442
- jobId: {
443
- type: "string",
444
- required: true
445
- }
446
- }
447
- },
448
- {
449
- type: "object",
450
- additionalProperties: false,
451
- properties: {
452
- kind: {
453
- type: "string",
454
- required: true,
455
- const: "continuable"
456
- },
457
- subagentId: {
458
- type: "string",
459
- required: true
460
- }
461
- }
462
- },
463
- {
464
- type: "object",
465
- additionalProperties: false,
466
- properties: {
467
- kind: {
468
- type: "string",
469
- required: true,
470
- const: "foreground"
471
- },
472
- runId: {
473
- type: "string",
474
- required: true
475
- },
476
- output: {
477
- type: "array",
478
- required: true,
479
- items: { type: "json" }
480
- }
481
- }
482
- }
483
- ] },
484
- render: (_args, value) => [{
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
+ }
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: [{
485
465
  type: "text",
486
- text: value.kind === "background" ? `started background subagent job ${value.jobId}` : value.kind === "continuable" ? `started subagent ${value.subagentId}` : outputValueText(value.output)
487
- }]
488
- },
489
- isConcurrencySafe: () => true,
490
- async execute(args, exec) {
491
- const parent = exec.agent;
492
- if (!parent) throw new Error("subagent tool requires a calling agent (exec.agent was undefined)");
493
- const modelRequest = args;
494
- const parentOptions = parentAgentOptionsForDelegation(parent);
495
- const requiresRoutePreflight = hasDelegationModelRequest(modelRequest) || hasConfiguredLlmSelection(config.agentOptions);
496
- const requestedChildAgentOptions = requestedAgentOptions(parentOptions, requiresRoutePreflight && providerRouteDefaults !== void 0 ? {
497
- ...providerRouteDefaults,
498
- ...config.agentOptions
499
- } : config.agentOptions, modelRequest, modelSelectionEnabled);
500
- assertAllowedModelSelection(modelSelectionPolicy, parentOptions, requestedChildAgentOptions, modelRequest);
501
- if (requiresRoutePreflight) {
502
- const llm = runtimeCtx.get("llm");
503
- if (llm === void 0) throw new Error("cannot resolve the selected child LLM route because the `llm` service is unavailable");
504
- await preflightChildLlmRoute(llm, parentOptions, requestedChildAgentOptions, exec.signal, providerRouteDefaults === void 0);
505
- if (runtimeCtx.subagents.getProvider(config.provider) !== subagentProvider) throw new Error(`subagent provider "${config.provider}" changed while resolving the child LLM route; retry the delegation`);
506
- }
507
- exec.signal.throwIfAborted();
508
- const maxDepth = runtimeCtx.subagents.resolveMaxDepth(config.maxDepth);
509
- const request = {
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,
510
477
  label: args.description,
511
- prompt: [{
512
- type: "text",
513
- text: args.prompt
514
- }],
515
- parent,
516
- ...requestedChildAgentOptions !== void 0 ? { agentOptions: requestedChildAgentOptions } : {},
517
- ...config.persona !== void 0 ? { persona: config.persona } : {},
518
- ...config.toolFilter !== void 0 ? { toolFilter: config.toolFilter } : {},
519
- ...maxDepth !== void 0 ? { maxDepth } : {}
520
- };
521
- if (resolveDelegationRun(args, {
522
- backgroundEnabled,
523
- continuable
524
- }).runInBackground) {
525
- if (continuable) return {
526
- kind: "continuable",
527
- subagentId: (await runtimeCtx.subagents.startContinuable({
528
- provider: config.provider,
529
- label: args.description,
530
- request,
531
- signal: exec.signal
532
- })).childId
533
- };
534
- const jobs = runtimeCtx.get("jobs");
535
- if (jobs === void 0) throw new Error("background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs");
536
- return {
537
- kind: "background",
538
- jobId: jobs.start({
539
- kind: "subagent",
540
- label: args.description,
541
- owner: parent.id,
542
- run: () => {
543
- const controller = new AbortController();
544
- return {
545
- cancel: (reason) => {
546
- controller.abort(reason ?? "background subagent task killed");
547
- },
548
- done: settleStart(runtimeCtx.subagents.start(config.provider, {
549
- ...request,
550
- signal: controller.signal
551
- }), controller.signal)
552
- };
553
- }
554
- })
555
- };
556
- }
557
- return settleForegroundRun(await runtimeCtx.subagents.start(config.provider, {
558
- ...request,
559
- signal: exec.signal
560
- }));
561
- }
562
- }))
478
+ request,
479
+ signal: exec.signal,
480
+ delivery: "parent"
481
+ })).childId
482
+ };
483
+ }
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
+ })
563
496
  };
564
497
  };
565
498
  runtimeCtx.on("subagent/provider-added", (subagentProvider) => {
@@ -573,19 +506,39 @@ function apply(ctx, config, session) {
573
506
  const present = runtimeCtx.subagents.getProvider(config.provider);
574
507
  if (present !== void 0) mount(present);
575
508
  else runtimeCtx.logger.info(`subagent provider "${config.provider}" not registered yet; the "${config.toolName ?? "subagent"}" tool will register when it appears`);
576
- if (backgroundEnabled && continuable) runtimeCtx.systemPrompt.section({
509
+ runtimeCtx.systemPrompt.section({
577
510
  name: `tool:${toolName}`,
578
511
  order: runtimeCtx.systemPrompt.getSectionOrder("TOOL_SUBAGENT"),
579
- text: (context) => mounted === void 0 || runtimeCtx.tools.get(toolName, context.scope) === void 0 ? "" : `Start independent ${toolName} delegations together in one assistant message and continue useful work while they run.`
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. When only waiting for their results remains, end your turn instead of sleeping or polling; the next result starts a new turn.`;
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.`;
529
+ }
580
530
  });
581
531
  };
582
- if (config.modelSelectionSettings !== true) {
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)) {
583
535
  install(ctx, void 0);
584
536
  return;
585
537
  }
586
538
  const settings = ctx.get("subagentModelSelection");
587
- if (settings === void 0) throw new Error("tool-subagent: `modelSelectionSettings` requires @deepseek-ai/dsh-tool-subagent/model-selection-settings in the Host scope");
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");
588
540
  const selectForSession = (target) => {
541
+ if (!modelSelectionCapable || settings === void 0) return void 0;
589
542
  const freshSession = target.firstLiveSeq === 0 && target.eventAt(SessionSeq(0))?.type !== "session/end-seed";
590
543
  let allowedModels = subagentModelSelectionPolicy(ctx.sessionProjections, target);
591
544
  if (allowedModels === void 0) {
@@ -607,7 +560,6 @@ function apply(ctx, config, session) {
607
560
  install(ctx, selectForSession(session));
608
561
  return;
609
562
  }
610
- const compositionScope = scopeOf(ctx);
611
563
  if (compositionScope === void 0) throw new Error("tool-subagent: standing `modelSelectionSettings` requires a scoped preset Context");
612
564
  const agents = ctx.get("agents");
613
565
  /* v8 ignore next -- shipped preset compositions always include the Agent registry. */
@@ -627,7 +579,8 @@ function apply(ctx, config, session) {
627
579
  "tools",
628
580
  "subagents",
629
581
  "systemPrompt"
630
- ], (runtimeCtx) => {
582
+ ], async (runtimeCtx) => {
583
+ if (presets.configured) await presets.validate(ctx);
631
584
  install(runtimeCtx, policy);
632
585
  });
633
586
  } finally {
@@ -1,20 +1,19 @@
1
1
  /**
2
2
  * Model-facing delegation through one configured `ctx.subagents` provider.
3
3
  * Provider lifecycle controls tool registration and context-sensitive schema
4
- * wording. Foreground calls always dispose the run after collection.
5
- * Background policy is selected by this plugin's configuration: one-shot
6
- * calls own a plain Task, while continuable calls use
7
- * `ctx.subagents.startContinuable()`.
4
+ * wording. Every delegation starts a managed activation and returns its child
5
+ * id; the subagent runtime owns result delivery and resource cleanup.
8
6
  * @module @deepseek-ai/dsh-tool-subagent
9
7
  */
10
8
  import type { Context } from '@deepseek-ai/cordis';
11
9
  import z from '@deepseek-ai/schemastery';
12
10
  import type { AgentOptions } from '@deepseek-ai/dsh-agent';
13
11
  import type { Session } from '@deepseek-ai/dsh-session';
12
+ import { type PresetSelectionConfig } from './preset-selection.ts';
14
13
  export declare const name = "tool-subagent";
15
14
  export declare const inject: string[];
16
15
  /** Config: which registered provider this tool delegates to, plus child defaults. */
17
- export interface Config {
16
+ export interface Config extends PresetSelectionConfig {
18
17
  /** The `ctx.subagents` provider name to start runs on (e.g. `spawn`, `acp`). */
19
18
  provider: string;
20
19
  /**
@@ -27,38 +26,10 @@ export interface Config {
27
26
  * Session and inherit that decision in its child Sessions.
28
27
  */
29
28
  modelSelectionSettings?: boolean;
30
- /**
31
- * Expose `run_in_background` (default true). Disabled instances omit the
32
- * parameter and reject forced background calls.
33
- */
34
- enableRunInBackground?: boolean;
35
- /**
36
- * Background execution policy (default `one-shot`). `one-shot` defaults calls
37
- * to foreground; `continuable` defaults them to background, requires a provider
38
- * with the `prepareContinuable` capability, and returns the durable child id.
39
- * Follow-up adapters remain independently optional.
40
- */
41
- backgroundMode?: 'one-shot' | 'continuable';
42
29
  /**
43
30
  * Agent options applied to every child; omitted fields use child-loop defaults.
44
31
  */
45
32
  agentOptions?: AgentOptions;
46
- /**
47
- * Per-child persona that shadows `deployment:persona-prefix`. Requires the
48
- * provider's `persona` capability; omission preserves the deployment persona.
49
- */
50
- persona?: string;
51
- /**
52
- * Tool filter applied to every child. Filtered tools disappear from its
53
- * prompt and reject execution. Requires the provider's `toolFilter`
54
- * capability; unknown names fail startup.
55
- */
56
- toolFilter?: {
57
- /** Global tool names the child keeps; everything else is removed. */
58
- allow?: string[];
59
- /** Global tool names removed from the child. */
60
- deny?: string[];
61
- };
62
33
  /**
63
34
  * Maximum child depth: a non-negative safe integer (`0` forbids delegation),
64
35
  * or `'provider-managed'` to send no cap. A numeric cap
@@ -74,9 +45,10 @@ export interface Config {
74
45
  export declare const Config: z<Config>;
75
46
  /**
76
47
  * Install one delegation-tool composition.
48
+ * Standing preset choices are validated for each Agent before its tool is installed.
77
49
  * @param ctx - Context that owns the registrations.
78
50
  * @param config - delegation-tool configuration.
79
51
  * @param session - unpublished Session supplied by a direct Agent setup; omit for a standing composition.
80
52
  */
81
- export declare function apply(ctx: Context, config: Config, session?: Session): void;
53
+ export declare function apply(ctx: Context, config: Config, session?: Session): Promise<void>;
82
54
  //# sourceMappingURL=index.d.ts.map