@deepseek-ai/dsh-subagent 0.2.2-rc.1 → 0.2.2-rc.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.
Files changed (108) hide show
  1. package/README.i18n.yaml +46 -28
  2. package/README.md +52 -23
  3. package/README.zh.md +52 -23
  4. package/lib/index.js +845 -902
  5. package/lib/typert.host.js +91 -125
  6. package/lib/typert.remote-client.d.ts +3 -3
  7. package/lib/typert.remote-client.d.ts.map +1 -0
  8. package/lib/typert.remote-client.js +17 -63
  9. package/lib/types/activation.d.ts +17 -25
  10. package/lib/types/activation.d.ts.map +1 -0
  11. package/lib/types/activation.js +1 -1
  12. package/lib/types/activation.js.map +1 -0
  13. package/lib/types/archive-admission.d.ts +11 -4
  14. package/lib/types/archive-admission.d.ts.map +1 -0
  15. package/lib/types/archive-admission.js +39 -115
  16. package/lib/types/archive-admission.js.map +1 -0
  17. package/lib/types/assistant-output.d.ts.map +1 -0
  18. package/lib/types/assistant-output.js.map +1 -0
  19. package/lib/types/catalog.d.ts +27 -7
  20. package/lib/types/catalog.d.ts.map +1 -0
  21. package/lib/types/catalog.js +31 -8
  22. package/lib/types/catalog.js.map +1 -0
  23. package/lib/types/child-agent.d.ts +7 -17
  24. package/lib/types/child-agent.d.ts.map +1 -0
  25. package/lib/types/child-agent.js +6 -4
  26. package/lib/types/child-agent.js.map +1 -0
  27. package/lib/types/client.d.ts.map +1 -0
  28. package/lib/types/client.js.map +1 -0
  29. package/lib/types/continuation-messages.d.ts +13 -10
  30. package/lib/types/continuation-messages.d.ts.map +1 -0
  31. package/lib/types/continuation-messages.js +22 -22
  32. package/lib/types/continuation-messages.js.map +1 -0
  33. package/lib/types/control-types.d.ts +7 -28
  34. package/lib/types/control-types.d.ts.map +1 -0
  35. package/lib/types/control-types.js.map +1 -0
  36. package/lib/types/control.d.ts +0 -4
  37. package/lib/types/control.d.ts.map +1 -0
  38. package/lib/types/control.js +1 -5
  39. package/lib/types/control.js.map +1 -0
  40. package/lib/types/depth.d.ts.map +1 -0
  41. package/lib/types/depth.js.map +1 -0
  42. package/lib/types/descriptor.d.ts +1 -1
  43. package/lib/types/descriptor.d.ts.map +1 -0
  44. package/lib/types/descriptor.js +1 -1
  45. package/lib/types/descriptor.js.map +1 -0
  46. package/lib/types/error.d.ts.map +1 -0
  47. package/lib/types/error.js.map +1 -0
  48. package/lib/types/index.d.ts +74 -97
  49. package/lib/types/index.d.ts.map +1 -0
  50. package/lib/types/index.js +125 -146
  51. package/lib/types/index.js.map +1 -0
  52. package/lib/types/lifecycle.d.ts +9 -38
  53. package/lib/types/lifecycle.d.ts.map +1 -0
  54. package/lib/types/lifecycle.js +5 -31
  55. package/lib/types/lifecycle.js.map +1 -0
  56. package/lib/types/list-children.d.ts +12 -0
  57. package/lib/types/list-children.d.ts.map +1 -0
  58. package/lib/types/list-children.js +35 -6
  59. package/lib/types/list-children.js.map +1 -0
  60. package/lib/types/manager.d.ts +96 -112
  61. package/lib/types/manager.d.ts.map +1 -0
  62. package/lib/types/manager.js +471 -568
  63. package/lib/types/manager.js.map +1 -0
  64. package/lib/types/names.d.ts +56 -0
  65. package/lib/types/names.d.ts.map +1 -0
  66. package/lib/types/names.js +96 -0
  67. package/lib/types/names.js.map +1 -0
  68. package/lib/types/out-of-process.d.ts.map +1 -0
  69. package/lib/types/out-of-process.js.map +1 -0
  70. package/lib/types/projection-types.d.ts +18 -6
  71. package/lib/types/projection-types.d.ts.map +1 -0
  72. package/lib/types/projection-types.js.map +1 -0
  73. package/lib/types/projection.d.ts +2 -2
  74. package/lib/types/projection.d.ts.map +1 -0
  75. package/lib/types/projection.js.map +1 -0
  76. package/lib/types/structured.d.ts +1 -1
  77. package/lib/types/structured.d.ts.map +1 -0
  78. package/lib/types/structured.js +2 -2
  79. package/lib/types/structured.js.map +1 -0
  80. package/lib/types/types.d.ts +34 -28
  81. package/lib/types/types.d.ts.map +1 -0
  82. package/lib/types/types.js +2 -4
  83. package/lib/types/types.js.map +1 -0
  84. package/package.json +54 -54
  85. package/src/activation.ts +184 -0
  86. package/src/archive-admission.ts +84 -0
  87. package/src/assistant-output.ts +75 -0
  88. package/src/catalog.ts +194 -0
  89. package/src/child-agent.ts +280 -0
  90. package/src/client.ts +8 -0
  91. package/src/continuation-messages.ts +176 -0
  92. package/src/control-types.ts +127 -0
  93. package/src/control.ts +103 -0
  94. package/src/depth.ts +51 -0
  95. package/src/descriptor.ts +269 -0
  96. package/src/error.ts +15 -0
  97. package/src/index.ts +604 -0
  98. package/src/lifecycle.ts +116 -0
  99. package/src/list-children.ts +168 -0
  100. package/src/manager.ts +1359 -0
  101. package/src/names.ts +113 -0
  102. package/src/out-of-process.ts +217 -0
  103. package/src/projection-types.ts +109 -0
  104. package/src/projection.ts +184 -0
  105. package/src/structured.ts +155 -0
  106. package/src/types.ts +364 -0
  107. package/lib/types/internal.d.ts +0 -58
  108. package/lib/types/internal.js +0 -58
package/lib/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Service } from "@deepseek-ai/cordis";
2
2
  import z from "@deepseek-ai/schemastery";
3
+ import { brandString } from "@deepseek-ai/dsh-brand";
3
4
  import { scopeTarget } from "@deepseek-ai/dsh-scope";
4
5
  import { ToolArgsError, assertObjectJsonSchema, validateJsonSchemaValue } from "@deepseek-ai/dsh-tools";
5
6
  import { canonicalClientTimeZone } from "@deepseek-ai/dsh-util-time";
@@ -7,10 +8,9 @@ import { Remote, RemoteError, TypertRemoteService, principalOf } from "@deepseek
7
8
  import { AttachmentError } from "@deepseek-ai/dsh-attachment";
8
9
  import { z as z$1 } from "zod";
9
10
  import { HarnessError, ReasoningEffortId, boundContextSummary, contentHasImage, createUserMessage, errorChain, joinAssistantStreamText } from "@deepseek-ai/dsh-llm";
10
- import { randomUUID } from "node:crypto";
11
11
  import { foldConsumedWork } from "@deepseek-ai/dsh-agent";
12
+ import { randomUUID } from "node:crypto";
12
13
  import { isAbsolute, resolve } from "node:path";
13
- import { brandString } from "@deepseek-ai/dsh-brand";
14
14
  import { SessionLogOffset, SessionSeq } from "@deepseek-ai/dsh-session";
15
15
  import { assertNever, snapshotJsonValue } from "@deepseek-ai/dsh-util-values";
16
16
  import { appendChunkedList, chunkedListSchema, iterateChunkedList } from "@deepseek-ai/dsh-chunked-list";
@@ -39,16 +39,10 @@ var SubagentError = class extends HarnessError {
39
39
  const SESSION_ID_SCHEMA = z$1.string().min(1);
40
40
  const CONTROL_ID_SCHEMAS = {
41
41
  "subagent.prompt": z$1.object({
42
- parentSessionId: SESSION_ID_SCHEMA,
43
42
  childSessionId: SESSION_ID_SCHEMA,
44
- mode: z$1.literal("continuable"),
45
43
  delivery: z$1.enum(["queue", "steer"])
46
44
  }),
47
- "subagent.interrupt": z$1.object({
48
- parentSessionId: SESSION_ID_SCHEMA,
49
- childSessionId: SESSION_ID_SCHEMA,
50
- mode: z$1.literal("continuable")
51
- })
45
+ "subagent.interrupt": z$1.object({ childSessionId: SESSION_ID_SCHEMA })
52
46
  };
53
47
  /**
54
48
  * Apply the subagent payload checks that are stricter than generated
@@ -77,7 +71,7 @@ function rejectPrompt(error, childSessionId, signal) {
77
71
  if (error instanceof SubagentError) switch (error.code) {
78
72
  case "MODEL_DOES_NOT_SUPPORT_IMAGES": throw new RemoteError("subagent/attachment-invalid", error.message, { reason: error.code }, { cause: error });
79
73
  case "NOT_RESUMABLE": throw new RemoteError("subagent/not-resumable", "subagent cannot be resumed", { childSessionId }, { cause: error });
80
- case "UNAUTHORIZED": throw new RemoteError("subagent/unauthorized", "subagent does not belong to this parent", { childSessionId }, { cause: error });
74
+ case "UNAUTHORIZED": throw new RemoteError("subagent/unauthorized", "subagent membership in the active tree could not be verified", { childSessionId }, { cause: error });
81
75
  case "DRAINING":
82
76
  case "ACTIVATION_CLOSING":
83
77
  case "ACTIVATION_LIMIT_REACHED":
@@ -122,32 +116,12 @@ function assertSubagentMaxDepth(maxDepth) {
122
116
  if (maxDepth !== void 0 && (typeof maxDepth !== "number" || !Number.isSafeInteger(maxDepth) || maxDepth < 0 || Object.is(maxDepth, -0))) throw new TypeError("subagent maxDepth must be a non-negative safe integer");
123
117
  }
124
118
  //#endregion
125
- //#region lib/types/types.js
126
- /**
127
- * The seam's consumer-facing contracts: request, result, and capability types
128
- * for {@link SubagentProvider}, plus the `subagent/start` and `subagent/end`
129
- * payloads that plugins and hosts observe. Internal control interfaces belong
130
- * with their implementation — the lifecycle observer in `./lifecycle.ts`, the
131
- * manager host in `./manager.ts` — so this module stays the published
132
- * surface rather than a bag of everything type-shaped.
133
- *
134
- * @module @deepseek-ai/dsh-subagent/types
135
- */
136
- /**
137
- * Brand a string as a {@link SubagentRunId}.
138
- * @param id - the raw run id.
139
- * @returns the same string, branded.
140
- */
141
- function SubagentRunId(id) {
142
- return id;
143
- }
144
- //#endregion
145
119
  //#region lib/types/lifecycle.js
146
120
  /**
147
- * Lifecycle-edge publication for managed subagent activations.
121
+ * Contained lifecycle notifications for subagents.
148
122
  *
149
- * Public event payloads live in `./types.ts`; the package-private observer
150
- * retains only the identity shared by each start/end pair.
123
+ * The service owns scoped dispatch and listener containment; the manager
124
+ * supplies event payloads from each activation.
151
125
  *
152
126
  * @module @deepseek-ai/dsh-subagent/lifecycle
153
127
  */
@@ -157,8 +131,8 @@ function SubagentRunId(id) {
157
131
  * returned promise is logged without starving peer listeners, changing the run,
158
132
  * or — for provider removal, which fires from a disposer — breaking teardown.
159
133
  * @param ctx - the service's own context, owning dispatch and the logger.
160
- * @param carrier - resolve the scoped dispatch carrier for one delegating parent.
161
- * @returns the emitter both observers and the provider registry publish through.
134
+ * @param carrier - resolve the scoped dispatch carrier for one subagent tree root.
135
+ * @returns the emitter the manager and provider registry publish through.
162
136
  */
163
137
  function createLifecycleEmitter(ctx, carrier) {
164
138
  return (name, info, parent) => {
@@ -178,35 +152,6 @@ function createLifecycleEmitter(ctx, carrier) {
178
152
  };
179
153
  }
180
154
  /**
181
- * Build the observer for one local or external activation's residency epoch. Creation failure before residency emits no lifecycle edge.
182
- * @param emit - the contained lifecycle emitter.
183
- * @param provider - the provider name recorded in the durable descriptor.
184
- * @param childId - the durable child session id.
185
- * @param parent - the exact live direct parent keying scoped dispatch.
186
- * @returns the observer whose edges this epoch publishes.
187
- */
188
- function createActivationObserver(emit, provider, childId, parent) {
189
- const identity = {
190
- runId: SubagentRunId(randomUUID()),
191
- provider,
192
- id: childId,
193
- local: false
194
- };
195
- return {
196
- start: (child) => {
197
- identity.local = child !== void 0;
198
- emit("subagent/start", identity, parent);
199
- },
200
- settle: ({ stopReason, output }) => {
201
- emit("subagent/end", {
202
- ...identity,
203
- stopReason,
204
- ...output.length === 0 ? {} : { lastAssistantMessage: output }
205
- }, parent);
206
- }
207
- };
208
- }
209
- /**
210
155
  * Why this child's epoch ended, for the terminal lifecycle edge and the
211
156
  * manager's own parent delivery. The child's own log is authoritative:
212
157
  * teardown succeeding says nothing about whether the model errored, hit its
@@ -364,10 +309,11 @@ function childSessionMeta(parent, childDepth, isSeeded, selectedPreset) {
364
309
  const SUBAGENT_DELEGATION_CONTEXT = "You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.";
365
310
  /**
366
311
  * Compose a child before publication and restore historical descriptor overrides.
367
- * Explicit selection mounts the named preset; omission synchronously joins the
368
- * parent's current generation. Registrations belong to the child's scope.
312
+ * Explicit selection mounts the named preset. Omission joins a supplied creator's
313
+ * current generation; a restored child without a saved preset uses host composition.
314
+ * Registrations belong to the child's scope.
369
315
  * @param childCtx - the child agent's scoped creation context.
370
- * @param parent - the delegating parent used when no preset is selected.
316
+ * @param parent - creator for fresh delegation; absent during target-only restoration.
371
317
  * @param composition - independent preset and any overrides read from a historical descriptor.
372
318
  * @returns A promise when mounting an independent preset; otherwise completes synchronously.
373
319
  */
@@ -379,7 +325,7 @@ function applyChildComposition(childCtx, parent, composition) {
379
325
  applyChildOverrides(childCtx, composition);
380
326
  });
381
327
  }
382
- childCtx.get("agentPresets")?.composeFrom(childCtx, parent.ctx);
328
+ if (parent !== void 0) childCtx.get("agentPresets")?.composeFrom(childCtx, parent.ctx);
383
329
  applyChildOverrides(childCtx, composition);
384
330
  }
385
331
  function applyChildOverrides(childCtx, composition) {
@@ -441,7 +387,7 @@ function appendDelegatedPolicyOverrides(childSession, overrides) {
441
387
  *
442
388
  * @module @deepseek-ai/dsh-subagent/continuation-messages
443
389
  */
444
- /** Build durable attribution for one adjacent-Agent message. */
390
+ /** Build durable attribution for one Agent message. */
445
391
  function agentMessageSource(sender) {
446
392
  return {
447
393
  kind: "agent-message",
@@ -450,43 +396,42 @@ function agentMessageSource(sender) {
450
396
  };
451
397
  }
452
398
  /**
453
- * Build the model-visible and durable representation of one adjacent-Agent message.
399
+ * Build the model-visible and durable representation of one Agent message.
454
400
  * @param sender - exact live Agent that authored the message.
401
+ * @param senderName - the sender's model-facing name in its subagent tree.
455
402
  * @param content - model-visible message blocks supplied by the sender.
456
403
  * @returns the durable user-message representation delivered to the recipient.
457
404
  */
458
- function createAgentMessage(sender, content) {
405
+ function createAgentMessage(sender, senderName, content) {
459
406
  return createUserMessage({
460
407
  content: [{
461
408
  type: "text",
462
- text: `Agent ${sender.id} sent a message: `
409
+ text: `Agent ${senderName} sent a message: `
463
410
  }, ...content],
464
411
  source: agentMessageSource(sender)
465
412
  });
466
413
  }
467
414
  /**
468
- * Append adjacent-Agent return guidance to a continuable child's initial task.
469
- * @param parentId - durable parent session id named in the guidance.
415
+ * Append automatic result-delivery guidance to a parent-delivered child's initial task.
470
416
  * @param prompt - initial model-visible task blocks.
471
- * @returns task blocks followed by the continuable return guidance.
417
+ * @returns task blocks followed by the result-delivery guidance.
472
418
  */
473
- function withContinuableReturnGuidance(parentId, prompt) {
474
- const encodedParentId = JSON.stringify(parentId);
419
+ function withResultDeliveryGuidance(prompt) {
475
420
  return [...prompt, {
476
421
  type: "text",
477
- text: `Your parent agent id is ${encodedParentId}. Before you finish, send your result to that agent with send_message({ agent_id: ${encodedParentId}, message: "<self-contained result>" }). The parent shares your workspace but does not automatically receive your transcript, tool output, or reasoning. Send earlier messages as well when a finding changes what the parent should do next; sending a message does not end your turn.`
422
+ text: "Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."
478
423
  }];
479
424
  }
480
425
  /**
481
426
  * One line telling a parent that a background child is finished and why, in
482
427
  * the parent's own task vocabulary.
483
- * @param childId - the durable child the parent knows by id.
428
+ * @param childName - the model-facing name the parent knows the child by.
484
429
  * @param stopReason - how the child's last ordinary turn ended.
485
430
  * @param continuable - whether the child accepts a later message.
486
431
  * @returns the model-facing opening line of the settlement notice.
487
432
  */
488
- function settlementSummary(childId, stopReason, continuable) {
489
- const subject = `Background subagent ${childId}`;
433
+ function settlementSummary(childName, stopReason, continuable) {
434
+ const subject = `Background subagent ${childName}`;
490
435
  switch (stopReason) {
491
436
  case "completed": return continuable ? `${subject} finished and will do no further work unless you send it more.` : `${subject} finished. It cannot receive follow-up messages.`;
492
437
  case "aborted": return `${subject} was stopped before it finished.`;
@@ -501,15 +446,16 @@ function settlementSummary(childId, stopReason, continuable) {
501
446
  }
502
447
  /**
503
448
  * Build the runtime-owned settlement notice from the child's nonempty closing text.
504
- * @param childId - durable child session id named in the notice.
449
+ * @param childId - durable child session id recorded as the sender.
450
+ * @param childName - model-facing child name used in the notice text.
505
451
  * @param terminal - recorded terminal state for the settled Activation.
506
452
  * @param continuable - whether the child can accept another task.
507
- * @param omitClosingText - replace the closing text with a note that the child's
508
- * last message to the parent already carries it.
453
+ * @param omitClosingText - replace the closing text when the child's last action
454
+ * was a message to its direct parent.
509
455
  * @returns the durable user-message representation delivered to the parent.
510
456
  */
511
- function createSettlementMessage(childId, terminal, continuable = true, omitClosingText = false) {
512
- const summary = settlementSummary(childId, terminal.stopReason, continuable);
457
+ function createSettlementMessage(childId, childName, terminal, continuable = true, omitClosingText = false) {
458
+ const summary = settlementSummary(childName, terminal.stopReason, continuable);
513
459
  const closingText = terminal.output.flatMap((block) => block.type === "text" && block.text.length > 0 ? [block] : []);
514
460
  return createUserMessage({
515
461
  content: [
@@ -540,11 +486,84 @@ function createSettlementMessage(childId, terminal, continuable = true, omitClos
540
486
  kind: "subagent-settled",
541
487
  form: "notice",
542
488
  summary: boundContextSummary(summary),
489
+ stopReason: terminal.stopReason,
543
490
  senderSessionId: childId
544
491
  }
545
492
  });
546
493
  }
547
494
  //#endregion
495
+ //#region lib/types/archive-admission.js
496
+ /**
497
+ * The `subagent` family of the Workspace registry's archive admission: which
498
+ * subagent descendants of a Session are still inside a turn, and how they
499
+ * stop when the Session is archived with its work. Archived ancestors also
500
+ * block later model steps, including when their Sessions have been released.
501
+ *
502
+ * @module @deepseek-ai/dsh-subagent
503
+ */
504
+ /**
505
+ * Answer `workspace/session-activity` with the running subagent descendants of
506
+ * the asked Session, and `workspace/session-stop` by cancelling each of them
507
+ * as their parent would. Reject subsequent steps beneath archived ancestors.
508
+ * All listeners live as long as `ctx`'s fiber.
509
+ * @param ctx - context carrying the Agent registry.
510
+ * @param residentAncestors - verified creation ancestors for an exact managed Agent, absent before publication or for unmanaged Agents.
511
+ * @param identityOf - ready service-owned descriptor identity reader; absent or invalid descriptors yield no identity.
512
+ */
513
+ function installSubagentArchiveAdmission(ctx, residentAncestors, identityOf) {
514
+ const ancestorsOf = (agent) => residentAncestors(agent) ?? headerAncestors(ctx, agent);
515
+ const runningDescendants = (sessionId) => ctx.agents.list().filter((agent) => agent.status === "running" && ancestorsOf(agent).includes(sessionId));
516
+ ctx.on("workspace/session-activity", async ({ sessionId }, next) => {
517
+ const running = runningDescendants(sessionId);
518
+ const rest = await next();
519
+ if (running.length === 0) return rest;
520
+ return [{
521
+ kind: "subagent",
522
+ items: running.map((child) => describe(child, identityOf(child.session)))
523
+ }, ...rest];
524
+ });
525
+ ctx.on("workspace/session-stop", ({ sessionId }) => {
526
+ for (const child of runningDescendants(sessionId)) try {
527
+ child.cancel({ kind: "parent" });
528
+ } catch (error) {
529
+ ctx.logger.warn(`subagent: cancelling "${child.id}" for an archived Session failed: ${String(error)}`);
530
+ }
531
+ });
532
+ ctx.on("agent/pre-step", ({ agent }, next) => {
533
+ const archived = ctx.get("workspaceRegistry")?.archivedSessionIds;
534
+ return archived !== void 0 && ancestorsOf(agent).some((id) => archived.includes(id)) ? Promise.resolve({ kind: "reject" }) : next();
535
+ });
536
+ }
537
+ /**
538
+ * Header-only ancestry for Agents without a published Activation. Include an
539
+ * offline direct creator; ordinary forks stop the chain and cycles terminate.
540
+ */
541
+ function headerAncestors(ctx, agent) {
542
+ const ancestors = [];
543
+ const visited = new Set([agent.id]);
544
+ let header = agent.session.header;
545
+ while (header.origin === "subagent" && header.parentSession !== void 0 && !visited.has(header.parentSession)) {
546
+ const parentId = header.parentSession;
547
+ ancestors.push(parentId);
548
+ visited.add(parentId);
549
+ const parent = ctx.agents.get(parentId)?.session;
550
+ if (parent === void 0) break;
551
+ header = parent.header;
552
+ }
553
+ return ancestors;
554
+ }
555
+ /**
556
+ * Report the child's current projected label only when its descriptor belongs
557
+ * to the child's own log; inherited, absent, or invalid identities yield the id alone.
558
+ */
559
+ function describe(child, identity) {
560
+ const label = identity !== void 0 && child.session.isOwnSeq(identity.seq) ? identity.label : void 0;
561
+ return label === void 0 ? { id: child.id } : {
562
+ id: child.id,
563
+ label
564
+ };
565
+ }
566
+ //#endregion
548
567
  //#region lib/types/descriptor.js
549
568
  /**
550
569
  * The durable subagent-child descriptor: the versioned, model-hidden
@@ -562,7 +581,7 @@ function createSettlementMessage(childId, terminal, continuable = true, omitClos
562
581
  * to one activation's result contract rather than durable child composition.
563
582
  * Per-activation knobs such as `maxTokens` are omitted for the same reason as
564
583
  * `outputSchema`: they budget one activation. Cold resume requires the exact
565
- * live parent for authorization but reconstructs child options only from the
584
+ * live subagent tree root for authorization but reconstructs child options only from the
566
585
  * durable descriptor, so it neither restores the prior budget nor inherits
567
586
  * the parent's current one; the resumed route's defaults apply instead.
568
587
  *
@@ -705,6 +724,91 @@ function foldSubagentDescriptor(events) {
705
724
  if (event === void 0) return void 0;
706
725
  return parseSubagentDescriptor(event.data);
707
726
  }
727
+ //#endregion
728
+ //#region lib/types/names.js
729
+ /**
730
+ * Model-facing agent names. Each child's name is unique among its creator's
731
+ * children and is recorded in the creator's catalog; a member's full name is
732
+ * the slash-separated path of names from the root, whose own name is `lead`.
733
+ *
734
+ * @module @deepseek-ai/dsh-subagent/names
735
+ */
736
+ /** The root agent's fixed name; no child may take it. */
737
+ const ROOT_AGENT_NAME = "lead";
738
+ /** One lower-case segment of at most 32 characters, so a 36-character UUID never matches. */
739
+ const NAME_PATTERN = /^[a-z][a-z0-9-]{0,31}$/u;
740
+ /**
741
+ * Whether a string is a valid child name.
742
+ * @param value - candidate name segment.
743
+ * @returns true for 1–32 lower-case letters, digits, or hyphens starting with a letter, other than `lead`.
744
+ */
745
+ function isAgentName(value) {
746
+ return NAME_PATTERN.test(value) && value !== "lead";
747
+ }
748
+ /**
749
+ * Append a child's name to its creator's path. The root's path is the empty string.
750
+ * @param parentPath - the creator's path, or undefined when an ancestor below the root has no name.
751
+ * @param name - the child's catalog name, absent on historical entries.
752
+ * @returns the child's path, or undefined when any link is unnamed.
753
+ */
754
+ function joinAgentPath(parentPath, name) {
755
+ if (parentPath === void 0 || name === void 0) return void 0;
756
+ return parentPath === "" ? name : `${parentPath}/${name}`;
757
+ }
758
+ /**
759
+ * Select the model-facing name of one tree member.
760
+ * @param path - the member's path; `''` for the root and undefined for unnamed history.
761
+ * @param id - the member's Session id, used when no complete path exists.
762
+ * @returns `lead`, the full path, or the Session id.
763
+ */
764
+ function agentAddress(path, id) {
765
+ if (path === "") return ROOT_AGENT_NAME;
766
+ return path ?? id;
767
+ }
768
+ /**
769
+ * Remove the last name from a descendant path.
770
+ * @param path - a non-empty descendant path.
771
+ * @returns the creator's path; `''` when the creator is the root.
772
+ */
773
+ function parentAgentPath(path) {
774
+ const separator = path.lastIndexOf("/");
775
+ return separator < 0 ? "" : path.slice(0, separator);
776
+ }
777
+ /** Names claimed by in-flight creations, keyed by the exact live creator. */
778
+ var SiblingNameReservations = class {
779
+ pending = /* @__PURE__ */ new Map();
780
+ /**
781
+ * Claim a name synchronously before startup awaits, so concurrent siblings cannot share it.
782
+ * @param parent - exact live creator whose catalog receives the name.
783
+ * @param committed - names already recorded in the creator's catalog.
784
+ * @param requested - requested name; omission selects the first free `agent-N`.
785
+ * @returns the claimed name and its release.
786
+ * @throws {@link SubagentError} `INVALID_AGENT_NAME` or `DUPLICATE_AGENT_NAME`.
787
+ */
788
+ reserve(parent, committed, requested) {
789
+ const pending = this.pending.get(parent) ?? /* @__PURE__ */ new Set();
790
+ const taken = (name) => committed.has(name) || pending.has(name);
791
+ let name;
792
+ if (requested === void 0) {
793
+ let ordinal = 1;
794
+ while (taken(`agent-${ordinal}`)) ordinal++;
795
+ name = `agent-${ordinal}`;
796
+ } else {
797
+ if (!isAgentName(requested)) throw new SubagentError(`agent name ${JSON.stringify(requested)} is invalid; use 1-32 lower-case letters, digits, or hyphens starting with a letter, other than "${ROOT_AGENT_NAME}"`, "INVALID_AGENT_NAME");
798
+ if (taken(requested)) throw new SubagentError(`agent name ${JSON.stringify(requested)} is already used by another subagent you created; choose another name`, "DUPLICATE_AGENT_NAME");
799
+ name = requested;
800
+ }
801
+ pending.add(name);
802
+ this.pending.set(parent, pending);
803
+ return {
804
+ name,
805
+ release: () => {
806
+ pending.delete(name);
807
+ if (pending.size === 0 && this.pending.get(parent) === pending) this.pending.delete(parent);
808
+ }
809
+ };
810
+ }
811
+ };
708
812
  const sessionIdSchema = z$1.string();
709
813
  const oneShotCatalogSchema = z$1.object({
710
814
  version: z$1.union([z$1.literal(0), z$1.literal(1)]),
@@ -728,11 +832,22 @@ const unknownCatalogSchema = oneShotCatalogSchema.extend({
728
832
  version: z$1.literal(1),
729
833
  mode: z$1.literal("unknown")
730
834
  });
835
+ const nameSchema = z$1.string().refine(isAgentName, "invalid agent name");
836
+ const namedContinuableCatalogSchema = continuableCatalogSchema.extend({
837
+ version: z$1.literal(3),
838
+ name: nameSchema
839
+ });
840
+ const namedExternalCatalogSchema = externalCatalogSchema.extend({
841
+ version: z$1.literal(3),
842
+ name: nameSchema
843
+ });
731
844
  const eventDataSchema = z$1.union([
732
845
  oneShotCatalogSchema,
733
846
  externalCatalogSchema,
734
847
  continuableCatalogSchema,
735
- unknownCatalogSchema
848
+ unknownCatalogSchema,
849
+ namedContinuableCatalogSchema,
850
+ namedExternalCatalogSchema
736
851
  ]);
737
852
  const viewSchema = z$1.array(z$1.union([
738
853
  oneShotCatalogSchema.omit({
@@ -749,7 +864,8 @@ const viewSchema = z$1.array(z$1.union([
749
864
  childCreatedAt: true
750
865
  }).extend({
751
866
  id: sessionIdSchema,
752
- createdAt: externalCatalogSchema.shape.childCreatedAt
867
+ createdAt: externalCatalogSchema.shape.childCreatedAt,
868
+ name: nameSchema.optional()
753
869
  }),
754
870
  continuableCatalogSchema.omit({
755
871
  version: true,
@@ -757,7 +873,8 @@ const viewSchema = z$1.array(z$1.union([
757
873
  childCreatedAt: true
758
874
  }).extend({
759
875
  id: sessionIdSchema,
760
- createdAt: continuableCatalogSchema.shape.childCreatedAt
876
+ createdAt: continuableCatalogSchema.shape.childCreatedAt,
877
+ name: nameSchema.optional()
761
878
  }),
762
879
  unknownCatalogSchema.omit({
763
880
  version: true,
@@ -789,7 +906,7 @@ function subagentCatalogEntries(state) {
789
906
  }
790
907
  return entries;
791
908
  }
792
- /** Parent-owned direct-child catalog projection; invalid own facts reject restoration. */
909
+ /** Parent-owned catalog; version-6 checkpoints retain unnamed facts, and invalid own facts reject restoration. */
793
910
  const subagentCatalogProjectionDefinition = {
794
911
  key: "subagentCatalog",
795
912
  stateSchema,
@@ -812,56 +929,63 @@ const subagentCatalogProjectionDefinition = {
812
929
  * @param parent - durable direct parent receiving the discovery fact.
813
930
  * @param child - established child's immutable Session metadata.
814
931
  * @param descriptor - mode-discriminated creation label frozen with the child.
932
+ * @param name - the child's name, reserved unique among the parent's children.
815
933
  */
816
- function establishCatalogChild(parent, child, descriptor) {
934
+ function establishCatalogChild(parent, child, descriptor, name) {
817
935
  parent.append("subagent/catalog", {
818
- version: 0,
936
+ version: 3,
819
937
  childId: child.id,
820
938
  childCreatedAt: child.createdAt,
821
939
  mode: descriptor.mode,
822
- label: descriptor.label
940
+ label: descriptor.label,
941
+ name
823
942
  });
824
943
  }
825
- /** Catalog payload version emitted by external execution creation. */
826
- const EXTERNAL_SUBAGENT_CATALOG_VERSION = 2;
827
944
  /**
828
945
  * Record an external execution without a local child Session.
829
946
  * @param parent - durable direct parent receiving the discovery fact.
830
947
  * @param childId - identity returned by the external provider.
831
948
  * @param label - display label assigned by the caller.
949
+ * @param name - the child's name, reserved unique among the parent's children.
832
950
  */
833
- function establishExternalCatalogChild(parent, childId, label) {
951
+ function establishExternalCatalogChild(parent, childId, label, name) {
834
952
  parent.append("subagent/catalog", {
835
- version: EXTERNAL_SUBAGENT_CATALOG_VERSION,
953
+ version: 3,
836
954
  childId,
837
955
  childCreatedAt: Date.now(),
838
956
  mode: "external",
839
- label
957
+ label,
958
+ name
840
959
  });
841
960
  }
842
- //#endregion
843
- //#region lib/types/internal.js
844
961
  /**
845
- * Continuation integration markers and host adapters outside the public
846
- * Service Definition and model-facing Agent messaging contract.
847
- * @module @deepseek-ai/dsh-subagent/internal
962
+ * Collect the names recorded in one parent's catalog.
963
+ * @param entries - the parent's current catalog rows.
964
+ * @returns names of every named child; historical entries contribute none.
848
965
  */
849
- /** Process-stable identity carried only by the standard adjacent-Agent messaging tool. */
850
- const adjacentAgentSendMessageTool = Symbol.for("dsh.subagent.adjacentAgentSendMessageTool");
966
+ function catalogNames(entries) {
967
+ const names = /* @__PURE__ */ new Set();
968
+ for (const entry of entries) if ("name" in entry) names.add(entry.name);
969
+ return names;
970
+ }
971
+ //#endregion
972
+ //#region lib/types/types.js
851
973
  /**
852
- * Test whether one visible definition is the standard adjacent-Agent messaging tool.
853
- * @param definition - the scope-resolved `send_message` candidate.
854
- * @returns whether the definition carries the internal standard-tool identity.
974
+ * The seam's consumer-facing contracts: request, result, and capability types
975
+ * for {@link SubagentProvider}, plus the `subagent/start` and `subagent/end`
976
+ * payloads that plugins and hosts observe. Internal control interfaces, such
977
+ * as the manager host, belong with their implementation.
978
+ *
979
+ * @module @deepseek-ai/dsh-subagent/types
855
980
  */
856
- function isAdjacentAgentSendMessageTool(definition) {
857
- return definition !== void 0 && definition[adjacentAgentSendMessageTool] === true;
858
- }
859
981
  /**
860
- * Process-stable symbol-keyed host delivery shared by the bundled runtime
861
- * entry and this unbundled internal subpath.
862
- * @internal
982
+ * Brand a string as a {@link SubagentRunId}.
983
+ * @param id - the raw run id.
984
+ * @returns the same string, branded.
863
985
  */
864
- const deliverSubagentPrompt = Symbol.for("dsh.subagent.deliverPrompt");
986
+ function SubagentRunId(id) {
987
+ return id;
988
+ }
865
989
  //#endregion
866
990
  //#region lib/types/structured.js
867
991
  /**
@@ -889,7 +1013,7 @@ const STRUCTURED_OUTPUT_INSTRUCTION = `When you have your final answer, you MUST
889
1013
  * @param childCtx - the child agent's scope context (`setup`'s argument).
890
1014
  * @param schema - the trusted, already-asserted schema subset to enforce (see
891
1015
  * `assertObjectJsonSchema` in dsh-tools).
892
- * @param canComplete - whether accepted input and owned child work have finished.
1016
+ * @param canComplete - whether accepted input has been processed.
893
1017
  * @returns the attachment handle (read `captured()` after the child settles).
894
1018
  */
895
1019
  function attachStructuredRuntime(childCtx, schema, canComplete) {
@@ -931,7 +1055,7 @@ function attachStructuredRuntime(childCtx, schema, canComplete) {
931
1055
  execute(args, exec) {
932
1056
  const violations = validateJsonSchemaValue(schema, args);
933
1057
  if (violations.length > 0) throw new ToolArgsError(violations);
934
- if (!canComplete()) throw new Error("Wait for all delegated child tasks to finish and process pending messages before submitting structured output.");
1058
+ if (!canComplete()) throw new Error("Process pending messages before submitting structured output.");
935
1059
  staged.set(exec, { value: args });
936
1060
  exec.concludeTurn();
937
1061
  return Promise.resolve({ recorded: true });
@@ -1041,7 +1165,7 @@ function finalAssistantOutput(events) {
1041
1165
  /** Execution-period records, capacity slots, child serialization, and local output capture.
1042
1166
  * @module @deepseek-ai/dsh-subagent/activation
1043
1167
  */
1044
- /** Process-local slots shared through uninterrupted continuable parent links. */
1168
+ /** Process-local capacity shared by every member of a subagent tree. */
1045
1169
  var ActivationPool = class {
1046
1170
  slots = /* @__PURE__ */ new Set();
1047
1171
  /**
@@ -1147,11 +1271,11 @@ var ChildLock = class {
1147
1271
  /**
1148
1272
  * Owns subagent startup, message admission, cold resume, and execution lifetimes.
1149
1273
  * One child lock orders input acceptance and closure; one activation map owns
1150
- * capacity, parent relationships, and resource release across all providers.
1274
+ * capacity, runtime ownership, and resource release across all providers.
1151
1275
  *
1152
1276
  * @module @deepseek-ai/dsh-subagent/manager
1153
1277
  */
1154
- var __addDisposableResource$2 = function(env, value, async) {
1278
+ var __addDisposableResource$1 = function(env, value, async) {
1155
1279
  if (value !== null && value !== void 0) {
1156
1280
  if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
1157
1281
  var dispose, inner;
@@ -1180,7 +1304,7 @@ var __addDisposableResource$2 = function(env, value, async) {
1180
1304
  } else if (async) env.stack.push({ async: true });
1181
1305
  return value;
1182
1306
  };
1183
- var __disposeResources$2 = (function(SuppressedError) {
1307
+ var __disposeResources$1 = (function(SuppressedError) {
1184
1308
  return function(env) {
1185
1309
  function fail(e) {
1186
1310
  env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
@@ -1228,18 +1352,15 @@ var SubagentManager = class {
1228
1352
  locks = new ChildLock();
1229
1353
  /** Structural Cordis owner of every Activation handle. */
1230
1354
  ownerCtx;
1231
- /**
1232
- * Exact roots whose host teardown has begun, with the live lineage members
1233
- * observed under each root. Entries remain until that exact root leaves the
1234
- * Agent registry, closing admission throughout its host's teardown without
1235
- * poisoning a later same-id replacement.
1236
- */
1237
- closingScopes = /* @__PURE__ */ new Map();
1355
+ /** Exact subagent tree roots whose host teardown has closed admission. */
1356
+ closingRoots = /* @__PURE__ */ new Set();
1357
+ /** Sibling names held by creations that have not committed their catalog entry. */
1358
+ names = new SiblingNameReservations();
1238
1359
  draining = false;
1239
1360
  /**
1240
1361
  * Build one manager inside the service's Agent-injected context.
1241
1362
  * @param ctx - context providing Agents, Sessions, and teardown ownership.
1242
- * @param host - provider dispatch and lifecycle observation owned by the service.
1363
+ * @param host - descriptor reads and lifecycle publication owned by the service.
1243
1364
  * @param maxActiveSubagents - the current configured child capacity.
1244
1365
  */
1245
1366
  constructor(ctx, host, maxActiveSubagents) {
@@ -1248,8 +1369,16 @@ var SubagentManager = class {
1248
1369
  this.maxActiveSubagents = maxActiveSubagents;
1249
1370
  const scope = ctx.plugin(function activationOwner() {});
1250
1371
  this.ownerCtx = scope.ctx;
1372
+ installSubagentArchiveAdmission(ctx, (agent) => {
1373
+ const activation = this.resident.get(agent.id);
1374
+ return activation !== void 0 && activationAgent(activation) === agent ? activation.ancestors : void 0;
1375
+ }, (session) => host.identityOf(session));
1251
1376
  ctx.on("agent/disposed", ({ agent }) => {
1252
- this.closingScopes.delete(agent);
1377
+ this.closingRoots.delete(agent);
1378
+ const activation = this.resident.get(agent.id);
1379
+ if (activation?.kind === "local" && activation.handle.agent === agent) this.close(activation, () => this.finishDisposal(activation, false)).catch((error) => {
1380
+ this.reportTeardownFailure(activation, error);
1381
+ });
1253
1382
  });
1254
1383
  ctx.effect(function* () {
1255
1384
  yield scope.dispose;
@@ -1259,7 +1388,7 @@ var SubagentManager = class {
1259
1388
  /**
1260
1389
  * Interrupt one live continuable child's current turn under the supplied authority.
1261
1390
  * @param targetSessionId - the durable child session id to interrupt.
1262
- * @param authority - the human parent address or exact live ancestor Agent.
1391
+ * @param authority - a trusted user operation or exact live ancestor Agent.
1263
1392
  */
1264
1393
  interrupt(targetSessionId, authority) {
1265
1394
  if (authority.kind === "ancestor") {
@@ -1269,9 +1398,7 @@ var SubagentManager = class {
1269
1398
  }
1270
1399
  const activation = this.resident.get(targetSessionId);
1271
1400
  if (activation === void 0) return;
1272
- if (authority.kind === "user") {
1273
- if (activation.parent.id !== authority.parentSessionId) throw new SubagentError(`subagent "${targetSessionId}" belongs to another parent session`, "UNAUTHORIZED");
1274
- } else if (!activation.ancestry.has(authority.agent)) throw new SubagentError(`subagent "${targetSessionId}" is not a live descendant of agent "${authority.agent.id}"`, "UNAUTHORIZED");
1401
+ if (authority.kind === "ancestor" && (this.rootOf(authority.agent) !== activation.root || !activation.ancestors.includes(authority.agent.id))) throw new SubagentError(`subagent "${targetSessionId}" is not a live descendant of agent "${authority.agent.id}"`, "UNAUTHORIZED");
1275
1402
  if (activation.closing !== void 0) return;
1276
1403
  const kind = authority.kind === "user" ? "user" : "parent";
1277
1404
  if (activation.kind === "local") activation.handle.agent.cancel({ kind }, { keepInbox: true });
@@ -1282,28 +1409,25 @@ var SubagentManager = class {
1282
1409
  }
1283
1410
  /**
1284
1411
  * Close admission, await every already-admitted materialization through
1285
- * publication or rollback, then dispose the stable live Activation graph
1286
- * child-first.
1412
+ * publication or rollback, then dispose every agent in the subagent tree.
1287
1413
  */
1288
1414
  async drain() {
1289
1415
  this.draining = true;
1290
1416
  for (const pending of this.materializations) pending.controller.abort();
1291
1417
  await Promise.all([...this.materializations].map((materialization) => materialization.settled));
1292
- const owned = /* @__PURE__ */ new Set();
1293
- for (const activation of this.resident.values()) for (const child of activation.ownedChildren) owned.add(child);
1294
- const roots = [...this.resident.values()].filter((activation) => !owned.has(activation.childId));
1295
- await this.disposeRoots(roots, "activation(s)");
1418
+ await this.disposeRoots([...this.resident.values()], "activation(s)");
1296
1419
  }
1297
1420
  /**
1298
- * Join progressing child work, leaving idle parked inboxes resident.
1299
- * @param parent - exact live parent whose descendants are observed.
1300
- * @returns whether work was joined and the host must recheck parent completion.
1421
+ * Join progressing subagent tree work for its root, leaving idle parked inboxes resident.
1422
+ * @param root - exact live subagent tree root; ordinary members return false.
1423
+ * @returns whether work was joined and the host must recheck root completion.
1301
1424
  */
1302
- async waitForChildren(parent) {
1425
+ async waitForTreeWork(root) {
1426
+ if (this.rootOf(root) !== root) return false;
1303
1427
  let observed = false;
1304
1428
  while (true) {
1305
- const pending = [...this.materializations].filter((item) => item.lineage.includes(parent));
1306
- const children = [...this.resident.values()].filter((item) => activationAgent(item) !== parent && item.ancestry.has(parent));
1429
+ const pending = [...this.materializations].filter((item) => item.root === root);
1430
+ const children = [...this.resident.values()].filter((item) => item.root === root);
1307
1431
  observed ||= children.some((item) => item.kind === "local" && item.handle.agent.status !== "idle");
1308
1432
  await Promise.all(children.flatMap((item) => item.kind === "local" ? [item.handle.agent.whenIdle()] : []));
1309
1433
  const waits = pending.map((item) => item.settled);
@@ -1316,10 +1440,6 @@ var SubagentManager = class {
1316
1440
  waits.push(item.handle.agent.whenIdle());
1317
1441
  continue;
1318
1442
  }
1319
- if (item.ownedChildren.size > 0) {
1320
- if ([...item.ownedChildren].some((id) => !this.resident.has(id))) waits.push(item.poke.promise);
1321
- continue;
1322
- }
1323
1443
  const inbox = item.handle.agent.inbox;
1324
1444
  if (item.failureAt === void 0 && (inbox.nextTurn.length > 0 || inbox.nextStep.length > 0)) continue;
1325
1445
  waits.push(Promise.race([item.result.promise.catch(() => void 0), item.poke.promise]));
@@ -1329,114 +1449,84 @@ var SubagentManager = class {
1329
1449
  await Promise.all(waits);
1330
1450
  continue;
1331
1451
  }
1332
- if ([...this.materializations].some((item) => item.lineage.includes(parent) && !pending.includes(item)) || [...this.resident.values()].some((item) => activationAgent(item) !== parent && item.ancestry.has(parent) && !children.includes(item))) continue;
1452
+ if ([...this.materializations].some((item) => item.root === root && !pending.includes(item)) || [...this.resident.values()].some((item) => item.root === root && !children.includes(item))) continue;
1333
1453
  return observed;
1334
1454
  }
1335
1455
  }
1336
1456
  /**
1337
- * Stop the managed descendants of exact live host-owned parents.
1338
- * @param parents - exact live roots whose managed descendants must stop.
1457
+ * Stop every member of the selected subagent trees; ordinary members do not close a subagent tree.
1458
+ * @param parents - exact live subagent tree roots whose instances must stop.
1339
1459
  */
1340
1460
  async drainDescendants(parents) {
1341
- const roots = new Set(parents.filter((parent) => this.ctx.agents.get(parent.id) === parent));
1342
- if (roots.size === 0) return;
1343
- for (const root of roots) this.closingMembers(root).add(root);
1344
- const targets = [];
1345
- for (const activation of this.resident.values()) {
1346
- const child = activationAgent(activation);
1347
- const lineage = this.liveLineage(child ?? activation.parent);
1348
- const owners = [...roots].filter((root) => child !== root && activation.ancestry.has(root));
1349
- if (owners.length === 0) continue;
1350
- targets.push(activation);
1351
- for (const owner of owners) {
1352
- const members = this.closingMembers(owner);
1353
- if (child !== void 0) members.add(child);
1354
- for (const agent of lineage) members.add(agent);
1355
- }
1356
- }
1357
- const materializations = [...this.materializations].filter((materialization) => {
1358
- const owners = [...roots].filter((root) => materialization.lineage.includes(root));
1359
- for (const owner of owners) {
1360
- const members = this.closingMembers(owner);
1361
- for (const agent of materialization.lineage) members.add(agent);
1362
- }
1363
- if (owners.length > 0) materialization.controller.abort();
1364
- return owners.length > 0;
1365
- });
1366
- const ownedTargets = /* @__PURE__ */ new Set();
1367
- for (const activation of targets) for (const child of activation.ownedChildren) ownedTargets.add(child);
1368
- const targetRoots = targets.filter((activation) => !ownedTargets.has(activation.childId));
1369
- for (const activation of targets) this.dispose(activation).catch(() => void 0);
1370
- await Promise.all(materializations.map((materialization) => materialization.settled));
1371
- await this.disposeRoots(targetRoots, "scoped activation(s)");
1372
- }
1373
- /**
1374
- * Release selected resident direct children of one exact live parent.
1375
- * @param parent - exact live direct parent authorizing the selected release.
1376
- * @param childIds - durable direct-child ids to release when resident.
1377
- */
1378
- async drainChildren(parent, childIds) {
1379
- if (this.ctx.agents.get(parent.id) !== parent) throw new SubagentError("selected child teardown requires the exact live parent agent", "UNAUTHORIZED");
1380
- const targets = [];
1381
- for (const childId of new Set(childIds)) {
1382
- const activation = this.resident.get(childId);
1383
- if (activation === void 0) continue;
1384
- if (activation.parent.id !== parent.id || !activation.ancestry.has(parent)) throw new SubagentError(`subagent "${childId}" is not a direct child of agent "${parent.id}"`, "UNAUTHORIZED");
1385
- targets.push(activation);
1386
- }
1387
- for (const activation of targets) this.dispose(activation).catch(() => void 0);
1388
- await this.disposeRoots(targets, "selected activation(s)");
1461
+ const roots = new Set(parents.filter((root) => this.ctx.agents.get(root.id) === root && this.rootOf(root) === root));
1462
+ for (const root of roots) this.closingRoots.add(root);
1463
+ const pending = [...this.materializations].filter((item) => roots.has(item.root));
1464
+ for (const item of pending) item.controller.abort();
1465
+ const targets = [...this.resident.values()].filter((item) => roots.has(item.root));
1466
+ const disposal = this.disposeRoots(targets, "scoped activation(s)");
1467
+ const [disposed] = await Promise.allSettled([disposal, ...pending.map((item) => item.settled)]);
1468
+ if (disposed.status === "rejected") throw disposed.reason;
1389
1469
  }
1390
1470
  /**
1391
1471
  * Start one continuable background child and resolve at initial inbox acceptance.
1392
1472
  * Every earlier failure disposes any created handle and rolls back Activation
1393
- * and parent ownership without returning either id.
1473
+ * and its capacity slot without returning either id.
1394
1474
  * @param spec - provider, delegation request, and caller cancellation.
1475
+ * @param prepare - creation contribution bound to the checked provider.
1395
1476
  * @returns the durable child id and accepted initial prompt message id.
1396
1477
  */
1397
- async startLocal(spec) {
1398
- const request = spec.request;
1399
- const parent = request.parent;
1478
+ async startLocal(spec, prepare) {
1479
+ const parent = spec.parent;
1400
1480
  this.assertAdmitting(parent);
1401
- const persistence = spec.delivery === "caller" ? this.ctx.get("sessionPersistence") : this.requirePersistence();
1402
- assertSubagentMaxDepth(request.maxDepth);
1403
- const childId = spec.childId ?? brandString(randomUUID());
1404
- this.assertChildIdAvailable(childId);
1405
- const childDepth = resolveChildDepth(parent, request.maxDepth);
1406
- const agentOptions = resolveChildAgentOptions(parent, request.agentOptions, childDepth);
1407
- const agentProvider = agentOptions.provider;
1408
- const agentModel = agentOptions.model;
1409
- const agentReasoningEffort = agentOptions.reasoningEffort;
1410
- const descriptor = snapshotSubagentDescriptor({
1411
- mode: "continuable",
1412
- provider: spec.provider,
1413
- label: spec.label,
1414
- ...agentProvider !== void 0 ? { agentProvider } : {},
1415
- ...agentModel !== void 0 ? { agentModel } : {},
1416
- ...agentReasoningEffort !== void 0 ? { agentReasoningEffort } : {}
1417
- });
1418
- const delegatedPolicies = captureDelegatedPolicyOverrides(parent);
1419
- const releaseHold = this.holdOwnership(parent, childId);
1481
+ const ancestry = this.ancestryForChild(parent);
1482
+ const reservation = this.reserveName(parent, spec.name);
1483
+ const path = joinAgentPath(this.pathOf(parent, ancestry.root), reservation.name);
1420
1484
  try {
1421
- const cwd = await this.resolveDirectory(request, spec.signal);
1422
- const prepared = await this.host.prepareContinuable(spec.provider, {
1485
+ return await this.startLocalNamed(spec, prepare, ancestry, reservation, path);
1486
+ } finally {
1487
+ reservation.release();
1488
+ }
1489
+ }
1490
+ /** Create one local child under a name reserved before any await. */
1491
+ startLocalNamed(spec, prepare, ancestry, reservation, path) {
1492
+ const parent = spec.parent;
1493
+ return this.trackStartup(ancestry.root, spec.signal, async (signal) => {
1494
+ const persistence = spec.delivery === "caller" ? this.ctx.get("sessionPersistence") : this.requirePersistence();
1495
+ const childId = spec.childId ?? brandString(randomUUID());
1496
+ this.assertChildIdAvailable(childId);
1497
+ const childDepth = resolveChildDepth(parent, spec.maxDepth);
1498
+ const agentOptions = resolveChildAgentOptions(parent, spec.agentOptions, childDepth);
1499
+ const agentProvider = agentOptions.provider;
1500
+ const agentModel = agentOptions.model;
1501
+ const agentReasoningEffort = agentOptions.reasoningEffort;
1502
+ const descriptor = snapshotSubagentDescriptor({
1503
+ mode: "continuable",
1504
+ provider: spec.provider,
1505
+ label: spec.label,
1506
+ ...agentProvider !== void 0 ? { agentProvider } : {},
1507
+ ...agentModel !== void 0 ? { agentModel } : {},
1508
+ ...agentReasoningEffort !== void 0 ? { agentReasoningEffort } : {}
1509
+ });
1510
+ const delegatedPolicies = captureDelegatedPolicyOverrides(parent);
1511
+ const cwd = await this.resolveDirectory(spec, signal);
1512
+ const prepared = await prepare({
1423
1513
  sessionId: childId,
1424
1514
  cwd,
1425
1515
  parent,
1426
- signal: spec.signal
1516
+ signal
1427
1517
  });
1428
- spec.signal.throwIfAborted();
1518
+ signal.throwIfAborted();
1429
1519
  this.assertAdmitting(parent);
1430
1520
  const inheritedEventCount = SessionLogOffset(prepared.seed?.length ?? 0);
1431
1521
  const seed = prepared.seed;
1432
1522
  let established;
1433
1523
  const messageId = await this.locks.run(childId, async () => {
1434
- spec.signal.throwIfAborted();
1524
+ signal.throwIfAborted();
1435
1525
  this.assertAdmitting(parent);
1436
1526
  this.assertChildIdAvailable(childId);
1437
1527
  if (spec.childId !== void 0) {
1438
- const persisted = await persistence?.stat(childId, { signal: spec.signal });
1439
- spec.signal.throwIfAborted();
1528
+ const persisted = await persistence?.stat(childId, { signal });
1529
+ signal.throwIfAborted();
1440
1530
  this.assertAdmitting(parent);
1441
1531
  this.assertChildIdAvailable(childId);
1442
1532
  if (persisted !== void 0) throw new SubagentError(`subagent "${childId}" already exists`, "DUPLICATE_CHILD");
@@ -1445,30 +1535,35 @@ var SubagentManager = class {
1445
1535
  kind: "local",
1446
1536
  childId,
1447
1537
  provider: spec.provider,
1448
- parent,
1538
+ ...ancestry,
1539
+ path,
1449
1540
  create: {
1541
+ parent,
1450
1542
  cwd,
1451
1543
  seed,
1452
- meta: childSessionMeta(parent, childDepth, prepared.seed !== void 0, request.agentPreset),
1544
+ meta: childSessionMeta(parent, childDepth, prepared.seed !== void 0, spec.agentPreset),
1453
1545
  inheritedEventCount,
1454
1546
  delegatedPolicies,
1455
1547
  descriptor
1456
1548
  },
1457
1549
  agentOptions,
1458
- composition: { agentPreset: request.agentPreset },
1459
- signal: spec.signal,
1550
+ composition: { agentPreset: spec.agentPreset },
1551
+ signal,
1460
1552
  delivery: spec.delivery,
1461
- outputSchema: spec.request.outputSchema
1553
+ outputSchema: spec.outputSchema
1462
1554
  });
1463
1555
  established = activation;
1464
- const child = requireLocalActivation(activation).handle.agent;
1465
- const childHeader = child.session.header;
1466
- return await this.submitMaterialized(activation, spec.delivery !== "caller" && isAdjacentAgentSendMessageTool(this.ctx.get("tools")?.get("send_message", child)) ? withContinuableReturnGuidance(parent.id, request.prompt) : request.prompt, {
1556
+ const childHeader = requireLocalActivation(activation).handle.agent.session.header;
1557
+ return await this.submitMaterialized(activation, spec.delivery !== "caller" ? withResultDeliveryGuidance(spec.prompt) : spec.prompt, {
1467
1558
  source: { kind: "user" },
1468
- signal: spec.signal,
1469
- delivery: "queue"
1470
- }, parent, () => {
1471
- establishCatalogChild(parent.session, childHeader, descriptor);
1559
+ signal,
1560
+ delivery: "queue",
1561
+ authorize: () => {
1562
+ this.assertAdmitting(parent);
1563
+ }
1564
+ }, ancestry.root, () => {
1565
+ this.assertAdmitting(parent);
1566
+ establishCatalogChild(parent.session, childHeader, descriptor, reservation.name);
1472
1567
  });
1473
1568
  });
1474
1569
  return {
@@ -1476,55 +1571,63 @@ var SubagentManager = class {
1476
1571
  childId,
1477
1572
  messageId
1478
1573
  };
1479
- } catch (error) {
1480
- releaseHold();
1481
- throw error;
1482
- }
1574
+ });
1483
1575
  }
1484
1576
  /**
1485
1577
  * Start an external backend under activation ownership.
1486
1578
  * @param spec - task, provider, cancellation, and delivery policy.
1579
+ * @param start - execution bound to the checked provider.
1487
1580
  * @returns the accepted activation and its result/disposal capabilities.
1488
1581
  */
1489
- async startExternal(spec) {
1490
- const parent = spec.request.parent;
1582
+ async startExternal(spec, start) {
1583
+ const { delivery, name: requestedName, parent } = spec;
1491
1584
  this.assertAdmitting(parent);
1492
- const pendingId = brandString(randomUUID());
1493
- const releaseHold = this.holdOwnership(parent, pendingId);
1494
- let activation;
1585
+ const ancestry = this.ancestryForChild(parent);
1586
+ if (delivery === "caller" && requestedName !== void 0) throw new SubagentError("agent names require a cataloged child; caller-delivered external runs are not cataloged", "UNSUPPORTED_CAPABILITY");
1587
+ const reservation = delivery === "parent" ? this.reserveName(parent, requestedName) : void 0;
1588
+ const path = joinAgentPath(this.pathOf(parent, ancestry.root), reservation?.name);
1495
1589
  try {
1496
- const cwd = await this.resolveDirectory(spec.request, spec.signal);
1497
- activation = await this.materialize({
1498
- kind: "external",
1499
- childId: pendingId,
1500
- provider: spec.provider,
1501
- parent,
1502
- signal: spec.signal,
1503
- delivery: spec.delivery,
1504
- start: (signal) => this.host.startExternal(spec.provider, {
1505
- ...spec.request,
1506
- cwd,
1507
- label: spec.label,
1508
- signal
1509
- })
1510
- });
1511
- this.assertAdmitting(parent);
1512
- this.assertLiveParent(parent, activation.childId);
1513
- spec.signal.throwIfAborted();
1514
- if (spec.delivery === "parent") establishExternalCatalogChild(parent.session, activation.childId, spec.label);
1515
- this.announce(activation);
1516
- return this.receipt(activation);
1517
- } catch (error) {
1518
- if (activation !== void 0) try {
1519
- await this.dispose(activation);
1520
- } catch (cleanupError) {
1521
- this.ctx.logger.warn(`subagent "${activation.childId}" admission rollback failed: ${failureMessage(cleanupError)}`);
1522
- }
1523
- throw error;
1590
+ return await this.startExternalNamed(spec, start, ancestry, reservation, path);
1524
1591
  } finally {
1525
- releaseHold();
1592
+ reservation?.release();
1526
1593
  }
1527
1594
  }
1595
+ /** Start one external execution, cataloging parent-delivered runs under their reserved name. */
1596
+ startExternalNamed(spec, start, ancestry, reservation, path) {
1597
+ const { provider, delivery, childId: _childId, name: _name, ...request } = spec;
1598
+ const parent = request.parent;
1599
+ return this.trackStartup(ancestry.root, spec.signal, async (signal) => {
1600
+ let activation;
1601
+ try {
1602
+ const cwd = await this.resolveDirectory(spec, signal);
1603
+ activation = await this.materialize({
1604
+ kind: "external",
1605
+ provider,
1606
+ ...ancestry,
1607
+ path,
1608
+ signal,
1609
+ delivery,
1610
+ start: (signal) => start({
1611
+ ...request,
1612
+ cwd,
1613
+ signal
1614
+ })
1615
+ });
1616
+ this.assertAdmitting(parent);
1617
+ signal.throwIfAborted();
1618
+ if (reservation !== void 0) establishExternalCatalogChild(parent.session, activation.childId, spec.label, reservation.name);
1619
+ this.accept(activation);
1620
+ return this.receipt(activation);
1621
+ } catch (error) {
1622
+ if (activation !== void 0) try {
1623
+ await this.dispose(activation);
1624
+ } catch (cleanupError) {
1625
+ this.ctx.logger.warn(`subagent "${activation.childId}" admission rollback failed: ${failureMessage(cleanupError)}`);
1626
+ }
1627
+ throw error;
1628
+ }
1629
+ });
1630
+ }
1528
1631
  /** Capture the explicit or inherited directory while the parent still owns startup. */
1529
1632
  async resolveDirectory(request, signal) {
1530
1633
  const cwd = request.cwd !== void 0 && isAbsolute(request.cwd) ? request.cwd : resolve(await this.ctx.workingDirectory.ensure(request.parent, signal), request.cwd ?? ".");
@@ -1532,60 +1635,156 @@ var SubagentManager = class {
1532
1635
  return cwd;
1533
1636
  }
1534
1637
  /**
1535
- * Deliver one model-authored message to a direct continuable child or to the
1536
- * sender's direct parent. A missing direct child cold-resumes through the
1537
- * ordinary continuation lifecycle.
1538
- * @param sender - exact live Agent authorizing and originating the message.
1539
- * @param targetId - durable direct-parent or direct-child session id.
1540
- * @param content - model-authored content to deliver.
1541
- * @param options - caller cancellation before acceptance.
1542
- * @returns the accepted message's inbox id.
1638
+ * Resolve the live subagent tree root from runtime ownership, independent of creator residency.
1639
+ * @param caller - exact live Agent selecting the subagent tree.
1640
+ * @returns the live subagent tree root.
1641
+ * @throws when the caller has no active runtime owner.
1642
+ */
1643
+ rootOf(caller) {
1644
+ if (this.ctx.agents.get(caller.id) !== caller) throw new SubagentError("subagent tree access requires the exact live caller", "UNAUTHORIZED");
1645
+ const identity = this.host.identityOf(caller.session);
1646
+ const delegated = caller.session.header.origin === "subagent" || identity != null && caller.session.isOwnSeq(identity.seq);
1647
+ const activation = this.resident.get(caller.id);
1648
+ if (activation !== void 0 && activationAgent(activation) === caller && this.ctx.agents.get(activation.root.id) === activation.root) return activation.root;
1649
+ if (delegated || activation !== void 0) throw new SubagentError("agent has no active runtime owner", "UNAUTHORIZED");
1650
+ return caller;
1651
+ }
1652
+ /** Capture creation ancestry separately from the root that owns the new instance. */
1653
+ ancestryForChild(creator) {
1654
+ return {
1655
+ root: this.rootOf(creator),
1656
+ ancestors: [...this.resident.get(creator.id)?.ancestors ?? [], creator.id]
1657
+ };
1658
+ }
1659
+ /** Claim a sibling name against the creator's committed catalog and in-flight siblings. */
1660
+ reserveName(parent, requested) {
1661
+ return this.names.reserve(parent, catalogNames(this.host.catalogOf(parent.session)), requested);
1662
+ }
1663
+ /** Path of an exact live tree member: `''` for the root, undefined for unnamed history. */
1664
+ pathOf(member, root) {
1665
+ return member === root ? "" : this.resident.get(member.id)?.path;
1666
+ }
1667
+ /**
1668
+ * Report the model-facing names of a live member and its direct creator.
1669
+ * @param agent - exact live root or resident tree member.
1670
+ * @returns `lead` for the root, otherwise the member's and creator's names or Session ids.
1671
+ * @throws when the caller has no active runtime owner.
1672
+ */
1673
+ namesOf(agent) {
1674
+ const root = this.rootOf(agent);
1675
+ if (root === agent) return { self: ROOT_AGENT_NAME };
1676
+ const activation = this.resident.get(agent.id);
1677
+ const parentId = activation.ancestors.at(-1);
1678
+ const parentPath = activation.path === void 0 ? parentId === root.id ? "" : this.resident.get(parentId)?.path : parentAgentPath(activation.path);
1679
+ return {
1680
+ self: agentAddress(activation.path, agent.id),
1681
+ parent: agentAddress(parentPath, parentId)
1682
+ };
1683
+ }
1684
+ /**
1685
+ * Deliver to another agent in the subagent tree, restoring only the target when absent.
1686
+ * @param sender - exact live root or resident continuable Agent.
1687
+ * @param targetId - another member's durable Session id.
1688
+ * @param content - model-authored message blocks.
1689
+ * @param options - cancellation before inbox acceptance.
1690
+ * @returns the accepted inbox message id.
1543
1691
  */
1544
1692
  async sendMessage(sender, targetId, content, options) {
1545
- if (this.ctx.agents.get(sender.id) !== sender) throw new SubagentError("message delivery requires the exact live sender agent", "UNAUTHORIZED");
1693
+ options.signal.throwIfAborted();
1694
+ const root = this.rootOf(sender);
1695
+ if (sender.id === targetId) throw new SubagentError("send_message requires another agent in the subagent tree", "UNAUTHORIZED");
1546
1696
  this.assertAdmitting(sender);
1547
- const senderActivation = this.resident.get(sender.id);
1548
- if (senderActivation !== void 0 && senderActivation.kind === "local" && senderActivation.handle.agent === sender && senderActivation.parent.id === targetId) {
1549
- options.signal.throwIfAborted();
1550
- return this.sendToParent(senderActivation, sender, content);
1551
- }
1552
- if (sender.session.header.parentSession === targetId) throw new SubagentError(`agent "${sender.id}" is not a resident continuable child and cannot send to parent "${targetId}"`, "UNAUTHORIZED");
1553
- return this.deliverToChild(sender, targetId, content, {
1697
+ const message = createAgentMessage(sender, agentAddress(this.pathOf(sender, root), sender.id), content);
1698
+ const activation = this.resident.get(sender.id);
1699
+ return this.deliverToMember(root, targetId, [...message.content], {
1554
1700
  signal: options.signal,
1555
- delivery: "steer"
1701
+ delivery: "steer",
1702
+ source: message.source,
1703
+ authorize: () => {
1704
+ this.assertAdmitting(sender);
1705
+ },
1706
+ onAccepted: () => {
1707
+ if (activation?.kind === "local" && activation.ancestors.at(-1) === targetId) activation.omitClosingText = true;
1708
+ }
1556
1709
  });
1557
1710
  }
1558
- /**
1559
- * Queue one human-authored prompt as a distinct direct-child turn.
1560
- * @param parent - exact live direct parent authorizing delivery.
1561
- * @param childId - durable direct-child session id.
1562
- * @param content - model-visible prompt blocks.
1563
- * @param source - durable attribution for the human prompt.
1564
- * @param signal - caller cancellation before inbox acceptance.
1565
- * @returns the accepted durable message id.
1566
- */
1567
- async queuePrompt(parent, childId, content, source, signal) {
1568
- return this.deliverToChild(parent, childId, content, {
1569
- source,
1570
- signal,
1571
- delivery: "queue"
1572
- });
1711
+ /** Resolve the live owner through verified creation edges without activating ancestors. */
1712
+ async resolveCreationAncestry(source, signal, root) {
1713
+ const ancestors = [];
1714
+ const names = [];
1715
+ const seen = new Set([source.header.id]);
1716
+ let { header, projections, inheritedEventCount } = source;
1717
+ const pathFromRoot = () => names.reduce(joinAgentPath, "");
1718
+ while (true) {
1719
+ const env_1 = {
1720
+ stack: [],
1721
+ error: void 0,
1722
+ hasError: false
1723
+ };
1724
+ try {
1725
+ signal.throwIfAborted();
1726
+ const parentId = header.parentSession;
1727
+ const identity = projections?.values.subagent;
1728
+ if (parentId === void 0 || identity == null || identity.seq < inheritedEventCount) break;
1729
+ if (seen.has(parentId)) throw new SubagentError("cyclic subagent creation ancestry", "UNAUTHORIZED");
1730
+ seen.add(parentId);
1731
+ const parent = __addDisposableResource$1(env_1, await this.observeContinuation(parentId, signal), false);
1732
+ const entry = parent.projections?.values.subagentCatalog?.find((entry) => entry.id === header.id);
1733
+ if (entry === void 0) throw new SubagentError("subagent is absent from its creator catalog", "UNAUTHORIZED");
1734
+ ancestors.unshift(parentId);
1735
+ names.unshift("name" in entry ? entry.name : void 0);
1736
+ if (parentId === root?.id) return {
1737
+ root,
1738
+ ancestors,
1739
+ path: pathFromRoot()
1740
+ };
1741
+ ({header, projections, inheritedEventCount} = parent);
1742
+ } catch (e_1) {
1743
+ env_1.error = e_1;
1744
+ env_1.hasError = true;
1745
+ } finally {
1746
+ __disposeResources$1(env_1);
1747
+ }
1748
+ }
1749
+ if (root === void 0 && ancestors.length > 0 && header.origin !== "subagent") {
1750
+ const owner = this.ctx.agents.get(header.id);
1751
+ if (owner === void 0 || this.rootOf(owner) !== owner) throw new SubagentError("subagent tree root is not live", "CONTINUATION_UNAVAILABLE");
1752
+ return {
1753
+ root: owner,
1754
+ ancestors,
1755
+ path: pathFromRoot()
1756
+ };
1757
+ }
1758
+ throw new SubagentError(`agent "${source.header.id}" is not a member of this subagent tree`, "UNAUTHORIZED");
1573
1759
  }
1574
1760
  /**
1575
- * Steer one host-authored prompt to a direct continuable child.
1576
- * @param parent - exact live direct parent authorizing delivery.
1577
- * @param childId - durable direct-child session id.
1761
+ * Deliver one host-authored prompt through the target's live subagent tree root.
1762
+ * Remote callers must be authorized for the target Session before invoking this operation.
1763
+ * @param childId - durable continuable subagent session id.
1578
1764
  * @param content - model-visible prompt blocks.
1579
- * @param source - durable attribution for the host prompt.
1580
- * @param signal - caller cancellation before inbox acceptance.
1765
+ * @param options - inbox destination, durable attribution, and cancellation before acceptance.
1581
1766
  * @returns the accepted durable message id.
1582
1767
  */
1583
- async steerPrompt(parent, childId, content, source, signal) {
1584
- return this.deliverToChild(parent, childId, content, {
1585
- source,
1586
- signal,
1587
- delivery: "steer"
1588
- });
1768
+ async deliverPrompt(childId, content, options) {
1769
+ options.signal.throwIfAborted();
1770
+ let root = this.resident.get(childId)?.root;
1771
+ if (root === void 0) {
1772
+ const env_2 = {
1773
+ stack: [],
1774
+ error: void 0,
1775
+ hasError: false
1776
+ };
1777
+ try {
1778
+ const source = __addDisposableResource$1(env_2, await this.observeContinuation(childId, options.signal), false);
1779
+ ({root} = await this.resolveCreationAncestry(source, options.signal));
1780
+ } catch (e_2) {
1781
+ env_2.error = e_2;
1782
+ env_2.hasError = true;
1783
+ } finally {
1784
+ __disposeResources$1(env_2);
1785
+ }
1786
+ }
1787
+ return this.deliverToMember(root, childId, content, options);
1589
1788
  }
1590
1789
  /** Admit local input synchronously before any teardown can begin. */
1591
1790
  deliver(activation, message, delivery) {
@@ -1603,32 +1802,6 @@ var SubagentManager = class {
1603
1802
  if (this.resident.has(childId) || this.ctx.agents.get(childId) !== void 0 || this.ctx.get("sessions")?.get(childId) !== void 0) throw new SubagentError(`subagent "${childId}" already exists`, "DUPLICATE_CHILD");
1604
1803
  }
1605
1804
  /**
1606
- * Pre-register `childId` in a continuation-managed parent's owned set so the
1607
- * parent cannot settle while a caller is still establishing or resuming that
1608
- * child. Returns a releaser for the failure path; it removes only a hold
1609
- * this call added, and leaves ownership in place once a live Activation for
1610
- * the child exists.
1611
- * @param parent - the live direct parent the operation is admitted under.
1612
- * @param childId - the durable child the operation addresses.
1613
- * @returns the failure-path releaser; a no-op when nothing was added.
1614
- */
1615
- holdOwnership(parent, childId) {
1616
- const parentActivation = this.resident.get(parent.id);
1617
- if (parentActivation === void 0 || activationAgent(parentActivation) !== parent) return () => {};
1618
- if (parentActivation.closing !== void 0) throw new SubagentError(`subagent parent "${parent.id}" is being disposed; the child was not established`, "ACTIVATION_CLOSING");
1619
- if (parentActivation.ownedChildren.has(childId)) return () => {};
1620
- parentActivation.ownedChildren.add(childId);
1621
- return () => {
1622
- const live = this.resident.get(childId);
1623
- /* v8 ignore next 4 -- reaching this arm needs another delivery to establish the child
1624
- * between this operation's failure and its releaser running, which no test can schedule
1625
- * deterministically: the ownership edge then belongs to that live Activation, so the
1626
- * conservative keep leaves it for finishDisposal's releaseOwnership. */
1627
- if (live !== void 0 && live.closing === void 0) return;
1628
- if (parentActivation.ownedChildren.delete(childId)) this.wake(parentActivation);
1629
- };
1630
- }
1631
- /**
1632
1805
  * Apply activation admission to a resident parent before delivering input.
1633
1806
  * @param parent - exact live Agent receiving the message.
1634
1807
  * @param message - durable user message to deliver.
@@ -1648,27 +1821,16 @@ var SubagentManager = class {
1648
1821
  else parent.followup(message);
1649
1822
  }
1650
1823
  /**
1651
- * Reject new admission once the manager or this exact parent tree began draining.
1652
- * @param agent - exact live Agent whose lineage determines admission.
1824
+ * Reject new work from closing members or subagent trees.
1825
+ * @param agent - exact live caller whose instance and subagent tree must admit work.
1653
1826
  */
1654
1827
  assertAdmitting(agent) {
1655
1828
  const closing = this.closingTeardownFor(agent);
1656
- if (closing === void 0) return;
1657
- throw new SubagentError(closing === "manager" ? "subagents are draining; the operation was not admitted" : `subagents below parent "${closing.id}" are draining; the operation was not admitted`, "DRAINING");
1658
- }
1659
- /**
1660
- * Authorize one operation against the durable direct-parent lineage.
1661
- * @param parent - exact live Agent claiming direct-parent authority.
1662
- * @param childId - durable child session id addressed by the operation.
1663
- * @param parentSession - durable direct-parent id recorded by the child.
1664
- */
1665
- authorizeLineage(parent, childId, parentSession) {
1666
- this.assertLiveParent(parent, childId);
1667
- if (parentSession !== parent.id) throw new SubagentError(`subagent "${childId}" belongs to another parent session`, "UNAUTHORIZED");
1668
- }
1669
- /** Reject parent authority after the live registry entry changes. */
1670
- assertLiveParent(parent, childId) {
1671
- if (this.ctx.agents.get(parent.id) !== parent) throw new SubagentError(`subagent "${childId}" delivery requires the exact live parent agent`, "UNAUTHORIZED");
1829
+ if (closing === void 0) {
1830
+ if (this.resident.get(agent.id)?.closing !== void 0) throw new SubagentError(`subagent "${agent.id}" is closing`, "ACTIVATION_CLOSING");
1831
+ return;
1832
+ }
1833
+ throw new SubagentError(closing === "manager" ? "subagents are draining; the operation was not admitted" : `subagent tree "${closing.id}" is draining; the operation was not admitted`, "DRAINING");
1672
1834
  }
1673
1835
  /**
1674
1836
  * Create or resume one child Agent and publish its Activation.
@@ -1676,25 +1838,28 @@ var SubagentManager = class {
1676
1838
  * @returns the published process-local Activation.
1677
1839
  */
1678
1840
  materialize(inputs) {
1679
- this.assertAdmitting(inputs.parent);
1841
+ this.assertAdmitting(inputs.root);
1680
1842
  inputs.signal.throwIfAborted();
1681
- const lineage = this.liveLineage(inputs.parent);
1682
- const pool = this.resident.get(inputs.parent.id)?.pool ?? this.rootPool(inputs.parent);
1683
- const releaseSlot = pool.reserve(this.maxActiveSubagents());
1843
+ const releaseSlot = this.rootPool(inputs.root).reserve(this.maxActiveSubagents());
1844
+ return this.materializeTracked(inputs, releaseSlot).catch((error) => {
1845
+ releaseSlot();
1846
+ throw error;
1847
+ });
1848
+ }
1849
+ /** Keep subagent tree shutdown and host waits joined to preparation, publication, and rollback. */
1850
+ trackStartup(root, signal, start) {
1851
+ this.assertAdmitting(root);
1852
+ signal.throwIfAborted();
1684
1853
  const settled = Promise.withResolvers();
1685
1854
  const controller = new AbortController();
1686
1855
  const materialization = {
1687
- lineage,
1856
+ root,
1688
1857
  settled: settled.promise,
1689
1858
  controller
1690
1859
  };
1691
1860
  this.materializations.add(materialization);
1692
- return this.materializeTracked({
1693
- ...inputs,
1694
- signal: AbortSignal.any([inputs.signal, controller.signal])
1695
- }, lineage, pool, releaseSlot).catch((error) => {
1696
- releaseSlot();
1697
- if (error instanceof Error && error.name === "AbortError") this.assertAdmitting(inputs.parent);
1861
+ return start(AbortSignal.any([signal, controller.signal])).catch((error) => {
1862
+ if (error instanceof Error && error.name === "AbortError") this.assertAdmitting(root);
1698
1863
  throw error;
1699
1864
  }).finally(() => {
1700
1865
  this.materializations.delete(materialization);
@@ -1729,35 +1894,13 @@ var SubagentManager = class {
1729
1894
  }))).filter((failure) => failure !== void 0);
1730
1895
  if (reasons.length > 0) throw new SubagentError(`subagent teardown failed for ${reasons.length} ${failureSubject}: ` + reasons.map((reason) => failureMessage(reason)).join("; "), "ACTIVATION_TEARDOWN_FAILED");
1731
1896
  }
1732
- /** Return the retained member set for one exact scoped-teardown root. */
1733
- closingMembers(root) {
1734
- const existing = this.closingScopes.get(root);
1735
- if (existing !== void 0) return existing;
1736
- const members = /* @__PURE__ */ new Set();
1737
- this.closingScopes.set(root, members);
1738
- return members;
1739
- }
1740
- /** Return the exact currently resolvable ancestry from `agent` upward. */
1741
- liveLineage(agent) {
1742
- const lineage = [agent];
1743
- const seen = new Set([agent.id]);
1744
- let parentSession = agent.session.header.parentSession;
1745
- while (parentSession !== void 0) {
1746
- const parent = this.ctx.agents.get(parentSession);
1747
- if (parent === void 0 || seen.has(parent.id)) break;
1748
- lineage.push(parent);
1749
- seen.add(parent.id);
1750
- parentSession = parent.session.header.parentSession;
1751
- }
1752
- return lineage;
1753
- }
1754
- /** Return the teardown that closed continuable admission for this agent's lineage. */
1897
+ /** Return the subagent tree teardown that closed admission for this exact Agent. */
1755
1898
  closingTeardownFor(agent) {
1756
1899
  if (this.draining) return "manager";
1757
- const lineage = this.liveLineage(agent);
1758
- for (const [root, members] of this.closingScopes) if (members.has(agent) || lineage.includes(root)) return root;
1900
+ const root = this.rootOf(agent);
1901
+ return this.closingRoots.has(root) ? root : void 0;
1759
1902
  }
1760
- /** Resolve a root's pool once; descendants inherit their resident parent's pool directly. */
1903
+ /** Share one capacity pool across every instance in a subagent tree. */
1761
1904
  rootPool(parent) {
1762
1905
  let pool = this.rootPools.get(parent);
1763
1906
  if (pool === void 0) {
@@ -1767,9 +1910,8 @@ var SubagentManager = class {
1767
1910
  return pool;
1768
1911
  }
1769
1912
  /** Perform one tracked materialization through publication or rollback. */
1770
- async materializeTracked(inputs, parentLineage, pool, releaseSlot) {
1771
- const { provider, parent } = inputs;
1772
- let childId = inputs.childId;
1913
+ async materializeTracked(inputs, releaseSlot) {
1914
+ const { provider, root } = inputs;
1773
1915
  inputs.signal.throwIfAborted();
1774
1916
  let resource;
1775
1917
  if (inputs.kind === "external") {
@@ -1786,9 +1928,8 @@ var SubagentManager = class {
1786
1928
  controller
1787
1929
  };
1788
1930
  run.result.catch(() => void 0);
1789
- childId = run.id;
1790
1931
  try {
1791
- this.assertChildIdAvailable(childId);
1932
+ this.assertChildIdAvailable(run.id);
1792
1933
  } catch (error) {
1793
1934
  await run.dispose();
1794
1935
  throw error;
@@ -1797,10 +1938,10 @@ var SubagentManager = class {
1797
1938
  inputs.signal.removeEventListener("abort", cancelStartup);
1798
1939
  }
1799
1940
  } else {
1800
- const { create } = inputs;
1941
+ const { create, childId } = inputs;
1801
1942
  let structured;
1802
1943
  const setup = async (childCtx, child) => {
1803
- if (inputs.composition.agentPreset !== void 0) await applyChildComposition(childCtx, parent, inputs.composition);
1944
+ if (inputs.composition.agentPreset !== void 0) await applyChildComposition(childCtx, create?.parent, inputs.composition);
1804
1945
  if (create !== void 0) {
1805
1946
  if (inputs.composition.agentPreset !== void 0) child.session.append("agent-preset/selected", { agentPreset: inputs.composition.agentPreset });
1806
1947
  child.session.append("subagent/descriptor", create.descriptor);
@@ -1809,18 +1950,16 @@ var SubagentManager = class {
1809
1950
  if (workingDirectory === void 0) throw new Error("local subagents require the working-directory service");
1810
1951
  await workingDirectory.set(child, create.cwd, inputs.signal);
1811
1952
  }
1812
- if (inputs.composition.agentPreset === void 0) await applyChildComposition(childCtx, parent, inputs.composition);
1813
- if (inputs.outputSchema !== void 0) structured = attachStructuredRuntime(childCtx, inputs.outputSchema, () => this.resident.get(childId)?.ownedChildren.size === 0 && child.inbox.nextStep.length === 0 && child.inbox.nextTurn.length === 0);
1953
+ if (inputs.composition.agentPreset === void 0) await applyChildComposition(childCtx, create?.parent, inputs.composition);
1954
+ if (inputs.outputSchema !== void 0) structured = attachStructuredRuntime(childCtx, inputs.outputSchema, () => child.inbox.nextStep.length === 0 && child.inbox.nextTurn.length === 0);
1814
1955
  };
1815
1956
  const handle = create === void 0 ? await this.ownerCtx.agents.resume({
1816
1957
  resumeSessionId: childId,
1817
- parentAgent: parent,
1818
1958
  agentOptions: inputs.agentOptions,
1819
1959
  signal: inputs.signal,
1820
1960
  setup
1821
1961
  }) : await this.ownerCtx.agents.create({
1822
1962
  sessionId: childId,
1823
- parentAgent: parent,
1824
1963
  meta: create.meta,
1825
1964
  ...create.seed === void 0 ? {} : { seed: create.seed },
1826
1965
  inheritedEventCount: create.inheritedEventCount,
@@ -1838,28 +1977,26 @@ var SubagentManager = class {
1838
1977
  omitClosingText: false
1839
1978
  };
1840
1979
  }
1841
- const observer = this.host.observeActivation(provider, childId, parent);
1980
+ const childId = resource.kind === "local" ? resource.handle.agent.id : resource.run.id;
1842
1981
  const activation = {
1843
- pool,
1844
1982
  releaseSlot,
1845
1983
  childId,
1984
+ runId: SubagentRunId(randomUUID()),
1985
+ provider,
1846
1986
  ...resource,
1847
- parent,
1987
+ root,
1988
+ ancestors: inputs.ancestors,
1989
+ path: inputs.path,
1848
1990
  delivery: inputs.delivery ?? "parent",
1849
1991
  result: Promise.withResolvers(),
1850
1992
  closing: void 0,
1851
- ancestry: new WeakSet(resource.kind === "external" ? parentLineage : [resource.handle.agent, ...parentLineage]),
1852
- ownedChildren: /* @__PURE__ */ new Set(),
1853
- observer,
1854
- announced: false
1993
+ accepted: false
1855
1994
  };
1856
1995
  activation.result.promise.catch(() => void 0);
1857
1996
  this.resident.set(childId, activation);
1858
1997
  try {
1859
- this.assertAdmitting(parent);
1998
+ this.assertAdmitting(root);
1860
1999
  inputs.signal.throwIfAborted();
1861
- if (this.ctx.agents.get(parent.id) !== parent) throw new SubagentError("subagent parent is no longer live", "UNAUTHORIZED");
1862
- this.acquireOwnership(parent, childId);
1863
2000
  const wakeSettlement = () => {
1864
2001
  this.wake(activation);
1865
2002
  };
@@ -1875,7 +2012,7 @@ var SubagentManager = class {
1875
2012
  if (event.type === "tool/call") activation.omitClosingText = false;
1876
2013
  });
1877
2014
  }
1878
- observer.start(activationAgent(activation));
2015
+ this.host.emitLifecycle("subagent/start", this.runInfo(activation), root);
1879
2016
  } catch (error) {
1880
2017
  /* v8 ignore next -- rollback failure must not mask the admission failure
1881
2018
  * that prevented this operation from returning an accepted message id. */
@@ -1884,13 +2021,19 @@ var SubagentManager = class {
1884
2021
  }
1885
2022
  return activation;
1886
2023
  }
1887
- /**
1888
- * Begin settlement observation after initial acceptance is recorded.
1889
- * @param activation - accepted activation to observe.
1890
- */
1891
- announce(activation) {
1892
- if (activation.announced) return;
1893
- activation.announced = true;
2024
+ /** Identity shared by one residency epoch's start/end pair, including cold resumes. */
2025
+ runInfo(activation) {
2026
+ return {
2027
+ runId: activation.runId,
2028
+ provider: activation.provider,
2029
+ parentSessionId: activation.ancestors.at(-1),
2030
+ id: activation.childId,
2031
+ local: activation.kind === "local"
2032
+ };
2033
+ }
2034
+ /** Record acceptance and begin settlement observation before returning the receipt. */
2035
+ accept(activation) {
2036
+ activation.accepted = true;
1894
2037
  if (activation.kind === "local") this.watchLocalSettlement(activation);
1895
2038
  else {
1896
2039
  const finish = () => this.close(activation, () => this.finishDisposal(activation, false));
@@ -1907,23 +2050,10 @@ var SubagentManager = class {
1907
2050
  } finally {
1908
2051
  this.resident.delete(activation.childId);
1909
2052
  activation.releaseSlot();
1910
- this.releaseOwnership(activation.childId);
1911
2053
  activation.result.reject(error);
1912
2054
  }
1913
2055
  });
1914
2056
  }
1915
- /** Register the child in a continuation-managed parent's owned set. */
1916
- acquireOwnership(parent, childId) {
1917
- const parentActivation = this.resident.get(parent.id);
1918
- if (parentActivation === void 0) return;
1919
- if (parentActivation.closing !== void 0) throw new SubagentError(`subagent parent "${parent.id}" is being disposed; the child was not established`, "ACTIVATION_CLOSING");
1920
- parentActivation.ownedChildren.add(childId);
1921
- this.wake(parentActivation);
1922
- }
1923
- /** Remove one child from its live owner's set and let that owner re-check settlement. */
1924
- releaseOwnership(childId) {
1925
- for (const candidate of this.resident.values()) if (candidate.ownedChildren.delete(childId)) this.wake(candidate);
1926
- }
1927
2057
  /** Let a settlement watcher re-check residency after relevant state changes. */
1928
2058
  wake(activation) {
1929
2059
  if (activation.kind === "external") return;
@@ -1978,16 +2108,15 @@ var SubagentManager = class {
1978
2108
  reportTeardownFailure(activation, error) {
1979
2109
  this.ctx.logger.warn(`subagent "${activation.childId}" activation teardown failed: ${failureMessage(error)}`);
1980
2110
  }
1981
- /** Check pending input and owned children before closing admission. */
2111
+ /** Check pending input before closing admission. */
1982
2112
  settlementState(activation, observation) {
1983
2113
  if (activation.closing !== void 0) return "closed";
1984
2114
  if (activation.poke !== observation) return "retry";
1985
2115
  const inbox = activation.handle.agent.inbox;
1986
- if (activation.ownedChildren.size > 0) return "wait";
1987
2116
  if (activation.failureAt === void 0 && (inbox.nextTurn.length > 0 || inbox.nextStep.length > 0)) return "wait";
1988
2117
  return "ready";
1989
2118
  }
1990
- /** Propagate stop synchronously and await descendant startup rollback before release. */
2119
+ /** Stop and release one instance without affecting its creation descendants. */
1991
2120
  async finishDisposal(activation, stop) {
1992
2121
  this.wake(activation);
1993
2122
  const { childId } = activation;
@@ -2011,22 +2140,7 @@ var SubagentManager = class {
2011
2140
  } else {
2012
2141
  if (stop) {
2013
2142
  activation.handle.agent.cancel({ kind: "parent" });
2014
- const idle = activation.handle.agent.whenIdle();
2015
- const children = [...activation.ownedChildren].map((child) => this.resident.get(child)).filter((child) => child !== void 0);
2016
- const pending = [...this.materializations].filter((item) => item.lineage.includes(activation.handle.agent));
2017
- const childDisposals = children.map((child) => this.dispose(child));
2018
- for (const item of pending) item.controller.abort();
2019
- childDisposals.push(...pending.map((item) => item.settled));
2020
- const reasons = (await Promise.all(childDisposals.map(async (disposal) => {
2021
- try {
2022
- await disposal;
2023
- return;
2024
- } catch (error) {
2025
- return error;
2026
- }
2027
- }))).filter((reason) => reason !== void 0);
2028
- if (reasons.length > 0) failures.push(new SubagentError(`subagent "${childId}" child teardown failed: ${reasons.map((reason) => failureMessage(reason)).join("; ")}`, "ACTIVATION_TEARDOWN_FAILED"));
2029
- await idle;
2143
+ await activation.handle.agent.whenIdle();
2030
2144
  await this.flushFinalState(activation);
2031
2145
  }
2032
2146
  result = captureLocalResult(activation);
@@ -2044,6 +2158,10 @@ var SubagentManager = class {
2044
2158
  let failure;
2045
2159
  if (failures.length === 1) failure = failures[0];
2046
2160
  else if (failures.length > 1) failure = new SubagentError(`subagent "${childId}" activation teardown failed at ${failures.length} boundaries: ` + failures.map((item) => detail(item)).join("; "), "ACTIVATION_TEARDOWN_FAILED", { cause: new AggregateError(failures) });
2161
+ if (failure !== void 0 && result.stopReason === "completed" && child !== void 0 && (child.inbox.nextStep.length > 0 || child.inbox.nextTurn.length > 0)) result = {
2162
+ ...result,
2163
+ stopReason: "error"
2164
+ };
2047
2165
  this.resident.delete(childId);
2048
2166
  activation.releaseSlot();
2049
2167
  const terminal = failure === void 0 ? result : {
@@ -2051,19 +2169,23 @@ var SubagentManager = class {
2051
2169
  stopReason: "error"
2052
2170
  };
2053
2171
  this.notifySettlement(activation, result);
2054
- this.releaseOwnership(childId);
2055
- activation.observer.settle(terminal);
2172
+ this.host.emitLifecycle("subagent/end", {
2173
+ ...this.runInfo(activation),
2174
+ stopReason: terminal.stopReason,
2175
+ ...terminal.output.length === 0 ? {} : { lastAssistantMessage: terminal.output }
2176
+ }, activation.root);
2056
2177
  if (resultFailure === void 0) activation.result.resolve(result);
2057
2178
  else activation.result.reject(resultFailure.error);
2058
2179
  if (failure !== void 0) throw failure;
2059
2180
  }
2060
2181
  /** Deliver the captured execution result to the durable direct parent after cleanup. */
2061
2182
  notifySettlement(activation, terminal) {
2062
- if (!activation.announced || activation.delivery === "caller") return;
2183
+ if (!activation.accepted || activation.delivery === "caller") return;
2063
2184
  try {
2064
- const parent = this.ctx.agents.get(activation.parent.id);
2065
- if (parent !== activation.parent) return;
2066
- const message = createSettlementMessage(activation.childId, terminal, activation.kind === "local", activation.kind === "local" && activation.omitClosingText);
2185
+ const parentId = activation.ancestors.at(-1);
2186
+ const parent = this.ctx.agents.get(parentId);
2187
+ if (parent === void 0 || parent.ctx.fiber.state !== 2 || this.rootOf(parent) !== activation.root) return;
2188
+ const message = createSettlementMessage(activation.childId, agentAddress(activation.path, activation.childId), terminal, activation.kind === "local", activation.kind === "local" && activation.omitClosingText);
2067
2189
  if (this.closingTeardownFor(parent) !== void 0) {
2068
2190
  parent.inject(message);
2069
2191
  return;
@@ -2085,128 +2207,106 @@ var SubagentManager = class {
2085
2207
  receipt(activation) {
2086
2208
  return {
2087
2209
  childId: activation.childId,
2210
+ name: agentAddress(activation.path, activation.childId),
2088
2211
  result: activation.result.promise,
2089
2212
  dispose: () => this.dispose(activation)
2090
2213
  };
2091
2214
  }
2092
- /** Route one parent-originated delivery through residency and cold resume. */
2093
- async deliverToChild(parent, childId, content, options) {
2094
- this.assertAdmitting(parent);
2095
- const releaseHold = this.holdOwnership(parent, childId);
2096
- try {
2097
- return await this.deliverFollowup(parent, childId, content, options);
2098
- } catch (error) {
2099
- releaseHold();
2100
- throw error;
2101
- }
2102
- }
2103
- /** The delivery loop behind {@link deliverToChild}, run under the parent hold. */
2104
- async deliverFollowup(parent, childId, content, options) {
2215
+ /** Serialize target restoration and inbox admission; closure is awaited outside the lock. */
2216
+ async deliverToMember(root, childId, content, options) {
2105
2217
  while (true) {
2106
- const live = await this.locks.run(childId, async () => {
2218
+ this.assertAdmitting(root);
2219
+ options.signal.throwIfAborted();
2220
+ const result = await this.locks.run(childId, async () => {
2221
+ if (childId === root.id) {
2222
+ if (contentHasImage(content)) await this.assertImageCapable(root, options.signal);
2223
+ options.signal.throwIfAborted();
2224
+ options.authorize?.();
2225
+ this.assertAdmitting(root);
2226
+ const message = createUserMessage({
2227
+ content,
2228
+ source: options.source
2229
+ });
2230
+ this.sendWaking(root, message, options.delivery);
2231
+ options.onAccepted?.();
2232
+ return { messageId: message.id };
2233
+ }
2107
2234
  const activation = this.resident.get(childId);
2108
- if (activation === void 0) return this.coldResume(parent, childId, content, options);
2109
- requireLocalActivation(activation);
2110
- const disposal = activation.closing;
2111
- /* v8 ignore next 3 -- the send-versus-dispose cutoff needs a delivery to
2112
- * observe the transaction inside the same critical section that opened it. */
2113
- if (disposal !== void 0) return disposal.then(() => void 0, () => void 0);
2114
- if (contentHasImage(content)) {
2115
- await this.assertImageCapable(requireLocalActivation(activation).handle.agent, options.signal);
2116
- if (activation.closing !== void 0) {
2117
- await Promise.allSettled([activation.closing]);
2118
- return;
2119
- }
2235
+ if (activation === void 0) {
2236
+ const restored = await this.restoreTarget(root, childId, options.signal);
2237
+ return { messageId: await this.submitMaterialized(restored, content, options, root) };
2120
2238
  }
2121
- const messageId = this.submitAdmitted(activation, content, options, parent);
2122
- this.announce(activation);
2123
- return messageId;
2239
+ if (activation.root !== root) throw new SubagentError("target belongs to another subagent tree", "UNAUTHORIZED");
2240
+ requireLocalActivation(activation);
2241
+ if (activation.closing === void 0 && contentHasImage(content)) await this.assertImageCapable(requireLocalActivation(activation).handle.agent, options.signal);
2242
+ if (activation.closing !== void 0) return { closing: activation.closing };
2243
+ return { messageId: this.submitAdmitted(activation, content, options, root) };
2124
2244
  });
2125
- /* v8 ignore start -- only a delivery that lost the disposal cutoff retries. */
2126
- if (live !== void 0) return live;
2127
- this.assertAdmitting(parent);
2128
- options.signal.throwIfAborted();
2245
+ if ("messageId" in result) return result.messageId;
2246
+ await Promise.allSettled([result.closing]);
2129
2247
  }
2130
2248
  }
2131
- /** Deliver one resident continuable child's message to its live direct parent. */
2132
- sendToParent(activation, sender, content) {
2133
- /* v8 ignore next 6 -- only synchronous re-entrant teardown can open this
2134
- * transaction between exact-agent authorization and this no-await span. */
2135
- if (activation.closing !== void 0) throw new SubagentError(`subagent "${sender.id}" activation is being disposed; the message was not delivered`, "ACTIVATION_CLOSING");
2136
- const parent = this.ctx.agents.get(activation.parent.id);
2137
- if (parent !== activation.parent) throw new SubagentError("direct parent is not live; the message was not delivered", "PARENT_UNAVAILABLE");
2138
- const message = createAgentMessage(sender, content);
2139
- this.sendAgentMessage(parent, message);
2140
- activation.omitClosingText = true;
2141
- return message.id;
2142
- }
2143
- /** Send one Agent message while translating only the target's own rejection. */
2144
- sendAgentMessage(parent, message) {
2249
+ /** Read continuation history, preserving cancellation and reporting unavailable storage. */
2250
+ async observeContinuation(childId, signal) {
2251
+ const query = this.requireSessionQuery();
2145
2252
  try {
2146
- this.sendWaking(parent, message, "steer");
2253
+ return await query.observeSession(childId, { signal });
2147
2254
  } catch (error) {
2148
- throw new SubagentError("direct parent is not live; the message was not delivered", "PARENT_UNAVAILABLE", { cause: error });
2255
+ signal.throwIfAborted();
2256
+ throw new SubagentError(`subagent "${childId}" is unavailable`, "NOT_RESUMABLE", { cause: error });
2149
2257
  }
2150
2258
  }
2151
- /**
2152
- * Cold-resume a persisted child and submit the waiting turn. The descriptor
2153
- * supplies every reconstruction input; no subagent provider is dispatched.
2154
- */
2155
- async coldResume(parent, childId, content, options) {
2156
- const env_1 = {
2157
- stack: [],
2158
- error: void 0,
2159
- hasError: false
2160
- };
2161
- try {
2162
- const query = this.requireSessionQuery();
2163
- let observation;
2164
- try {
2165
- observation = await query.observeSession(childId, { signal: options.signal });
2166
- } catch (error) {
2167
- options.signal.throwIfAborted();
2168
- throw new SubagentError(`subagent "${childId}" is unavailable`, "NOT_RESUMABLE", { cause: error });
2169
- }
2170
- const source = __addDisposableResource$2(env_1, observation, false);
2171
- this.assertAdmitting(parent);
2172
- this.authorizeLineage(parent, childId, source.header.parentSession);
2173
- const ownEvents = source.events.slice(source.inheritedEventCount);
2174
- const descriptor = foldSubagentDescriptor(ownEvents);
2175
- if (descriptor === void 0 || descriptor.mode !== "continuable") throw new SubagentError(`subagent "${childId}" has no supported continuation state and cannot be resumed; choose a different target`, "NOT_RESUMABLE");
2176
- let activation;
2259
+ /** Reconstruct only the target under its subagent tree root; the caller owns acceptance or rollback. */
2260
+ async restoreTarget(root, childId, signal) {
2261
+ return this.trackStartup(root, signal, async (signal) => {
2262
+ const env_3 = {
2263
+ stack: [],
2264
+ error: void 0,
2265
+ hasError: false
2266
+ };
2177
2267
  try {
2178
- const independentlySelected = hasIndependentPresetSelection(ownEvents);
2179
- const agentPreset = independentlySelected ? source.projections?.values.agentPreset : void 0;
2180
- if (independentlySelected && typeof agentPreset !== "string") throw new SubagentError(`subagent "${childId}" has no agent preset projection for restoration`, "NOT_RESUMABLE");
2181
- activation = await this.materialize({
2182
- kind: "local",
2183
- childId,
2184
- provider: descriptor.provider,
2185
- parent,
2186
- agentOptions: {
2187
- ...descriptor.agentProvider !== void 0 ? { provider: descriptor.agentProvider } : {},
2188
- ...descriptor.agentModel !== void 0 ? { model: descriptor.agentModel } : {},
2189
- ...descriptor.agentReasoningEffort !== void 0 ? { reasoningEffort: ReasoningEffortId(descriptor.agentReasoningEffort) } : {}
2190
- },
2191
- composition: {
2192
- agentPreset: agentPreset ?? void 0,
2193
- persona: descriptor.persona,
2194
- toolFilter: descriptor.toolFilter
2195
- },
2196
- signal: options.signal
2197
- });
2198
- } catch (error) {
2199
- options.signal.throwIfAborted();
2200
- if (error instanceof SubagentError) throw error;
2201
- throw new SubagentError(`subagent "${childId}" is unavailable`, "NOT_RESUMABLE", { cause: error });
2268
+ const source = __addDisposableResource$1(env_3, await this.observeContinuation(childId, signal), false);
2269
+ this.assertAdmitting(root);
2270
+ const descriptor = foldSubagentDescriptor(source.events.slice(source.inheritedEventCount));
2271
+ if (descriptor === void 0 || descriptor.mode !== "continuable") throw new SubagentError(`subagent "${childId}" has no supported continuation state and cannot be resumed; choose a different target`, "NOT_RESUMABLE");
2272
+ const { ancestors, path } = await this.resolveCreationAncestry(source, signal, root);
2273
+ let activation;
2274
+ try {
2275
+ const projectedPreset = source.projections?.values.agentPreset;
2276
+ if (projectedPreset === void 0 && source.events.some((event) => event.type === "agent-preset/selected")) throw new SubagentError(`subagent "${childId}" has no agent preset projection for restoration`, "NOT_RESUMABLE");
2277
+ const agentPreset = projectedPreset ?? source.header.agentPreset;
2278
+ activation = await this.materialize({
2279
+ kind: "local",
2280
+ childId,
2281
+ provider: descriptor.provider,
2282
+ root,
2283
+ ancestors,
2284
+ path,
2285
+ agentOptions: {
2286
+ ...descriptor.agentProvider !== void 0 ? { provider: descriptor.agentProvider } : {},
2287
+ ...descriptor.agentModel !== void 0 ? { model: descriptor.agentModel } : {},
2288
+ ...descriptor.agentReasoningEffort !== void 0 ? { reasoningEffort: ReasoningEffortId(descriptor.agentReasoningEffort) } : {}
2289
+ },
2290
+ composition: {
2291
+ agentPreset: agentPreset ?? void 0,
2292
+ persona: descriptor.persona,
2293
+ toolFilter: descriptor.toolFilter
2294
+ },
2295
+ signal
2296
+ });
2297
+ } catch (error) {
2298
+ signal.throwIfAborted();
2299
+ if (error instanceof SubagentError) throw error;
2300
+ throw new SubagentError(`subagent "${childId}" is unavailable`, "NOT_RESUMABLE", { cause: error });
2301
+ }
2302
+ return activation;
2303
+ } catch (e_3) {
2304
+ env_3.error = e_3;
2305
+ env_3.hasError = true;
2306
+ } finally {
2307
+ __disposeResources$1(env_3);
2202
2308
  }
2203
- return await this.submitMaterialized(activation, content, options, parent);
2204
- } catch (e_1) {
2205
- env_1.error = e_1;
2206
- env_1.hasError = true;
2207
- } finally {
2208
- __disposeResources$2(env_1);
2209
- }
2309
+ });
2210
2310
  }
2211
2311
  /** Admit a materialized child, commit its creation fact, and release it on failure. */
2212
2312
  async submitMaterialized(activation, content, options, parent, commit) {
@@ -2217,7 +2317,7 @@ var SubagentManager = class {
2217
2317
  }
2218
2318
  const messageId = this.submitAdmitted(activation, content, options, parent);
2219
2319
  commit?.();
2220
- this.announce(activation);
2320
+ this.accept(activation);
2221
2321
  return messageId;
2222
2322
  } catch (error) {
2223
2323
  try {
@@ -2230,19 +2330,19 @@ var SubagentManager = class {
2230
2330
  }
2231
2331
  /** Build and submit one message across the final synchronous admission cutoff. */
2232
2332
  submitAdmitted(activation, content, options, parent) {
2233
- const message = options.source === void 0 ? createAgentMessage(parent, content) : createUserMessage({
2333
+ const message = createUserMessage({
2234
2334
  content,
2235
2335
  source: options.source
2236
2336
  });
2237
2337
  options.signal.throwIfAborted();
2338
+ options.authorize?.();
2238
2339
  this.assertAdmitting(parent);
2239
- this.authorizeLineage(parent, activation.childId, activation.parent.id);
2240
- this.acquireOwnership(parent, activation.childId);
2241
2340
  try {
2242
2341
  this.deliver(activation, message, options.delivery);
2243
2342
  } finally {
2244
2343
  this.wake(activation);
2245
2344
  }
2345
+ options.onAccepted?.();
2246
2346
  return message.id;
2247
2347
  }
2248
2348
  /** Refuse image content for a child whose fixed model accepts text only. */
@@ -2268,15 +2368,6 @@ var SubagentManager = class {
2268
2368
  return query;
2269
2369
  }
2270
2370
  };
2271
- /** Creation-time selection precedes the own descriptor; historical forks can select after it. */
2272
- function hasIndependentPresetSelection(events) {
2273
- for (const event of events) {
2274
- if (event.type === "subagent/descriptor") return false;
2275
- if (event.type === "agent-preset/selected") return true;
2276
- }
2277
- /* v8 ignore next -- coldResume rejects logs without a supported own descriptor before this lookup. */
2278
- return false;
2279
- }
2280
2371
  //#endregion
2281
2372
  //#region lib/types/list-children.js
2282
2373
  /**
@@ -2284,7 +2375,7 @@ function hasIndependentPresetSelection(events) {
2284
2375
  * Each catalog read releases its Session observation before the next branch.
2285
2376
  * @module @deepseek-ai/dsh-subagent
2286
2377
  */
2287
- var __addDisposableResource$1 = function(env, value, async) {
2378
+ var __addDisposableResource = function(env, value, async) {
2288
2379
  if (value !== null && value !== void 0) {
2289
2380
  if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
2290
2381
  var dispose, inner;
@@ -2313,7 +2404,7 @@ var __addDisposableResource$1 = function(env, value, async) {
2313
2404
  } else if (async) env.stack.push({ async: true });
2314
2405
  return value;
2315
2406
  };
2316
- var __disposeResources$1 = (function(SuppressedError) {
2407
+ var __disposeResources = (function(SuppressedError) {
2317
2408
  return function(env) {
2318
2409
  function fail(e) {
2319
2410
  env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
@@ -2359,14 +2450,14 @@ async function listChildren(ctx, parentSessionId, signal) {
2359
2450
  try {
2360
2451
  const query = ctx.get("sessionQuery");
2361
2452
  if (query === void 0) throw new SubagentError("listing subagents requires the sessionQuery service (load @deepseek-ai/dsh-session-query)", "SUBAGENT_CONTROL_QUERY_UNAVAILABLE");
2362
- const entries = __addDisposableResource$1(env_1, await query.observeSession(parentSessionId, { ...signal === void 0 ? {} : { signal } }), false).projections?.values.subagentCatalog;
2453
+ const entries = __addDisposableResource(env_1, await query.observeSession(parentSessionId, { ...signal === void 0 ? {} : { signal } }), false).projections?.values.subagentCatalog;
2363
2454
  if (entries === void 0) throw new SubagentError("listing subagents requires the registered subagentCatalog projection", "SUBAGENT_CONTROL_PROJECTIONS_UNAVAILABLE");
2364
2455
  return entries;
2365
2456
  } catch (e_1) {
2366
2457
  env_1.error = e_1;
2367
2458
  env_1.hasError = true;
2368
2459
  } finally {
2369
- __disposeResources$1(env_1);
2460
+ __disposeResources(env_1);
2370
2461
  }
2371
2462
  }
2372
2463
  /**
@@ -2395,14 +2486,21 @@ async function listDescendants(ctx, rootSessionId, signal) {
2395
2486
  const stack = (await readChildren(rootSessionId)).map((entry) => ({
2396
2487
  entry,
2397
2488
  parentId: rootSessionId,
2398
- depth: 1
2489
+ depth: 1,
2490
+ parentPath: ""
2399
2491
  })).reverse();
2400
2492
  const visited = new Set([rootSessionId]);
2401
2493
  const result = [];
2402
2494
  for (let position = stack.pop(); position !== void 0; position = stack.pop()) {
2403
- const { entry, parentId, depth } = position;
2495
+ const { entry, parentId, depth, parentPath } = position;
2404
2496
  if (visited.has(entry.id)) continue;
2405
2497
  visited.add(entry.id);
2498
+ const path = joinAgentPath(parentPath, "name" in entry ? entry.name : void 0);
2499
+ const at = {
2500
+ parentId,
2501
+ depth,
2502
+ ...path === void 0 ? {} : { path }
2503
+ };
2406
2504
  let children;
2407
2505
  try {
2408
2506
  children = entry.mode === "external" ? [] : await readChildren(entry.id);
@@ -2412,8 +2510,7 @@ async function listDescendants(ctx, rootSessionId, signal) {
2412
2510
  result.push({
2413
2511
  kind: "diagnostic",
2414
2512
  id: entry.id,
2415
- parentId,
2416
- depth,
2513
+ ...at,
2417
2514
  reason: code === "SESSION_QUERY_CORRUPT_SESSION" || code === "SESSION_QUERY_SOURCE_CONFLICT" ? "corrupt" : "unavailable"
2418
2515
  });
2419
2516
  continue;
@@ -2421,8 +2518,7 @@ async function listDescendants(ctx, rootSessionId, signal) {
2421
2518
  if (entry.mode === "unknown") result.push({
2422
2519
  kind: "diagnostic",
2423
2520
  id: entry.id,
2424
- parentId,
2425
- depth,
2521
+ ...at,
2426
2522
  reason: "unsupported"
2427
2523
  });
2428
2524
  else {
@@ -2430,8 +2526,7 @@ async function listDescendants(ctx, rootSessionId, signal) {
2430
2526
  result.push({
2431
2527
  ...identity,
2432
2528
  kind: "child",
2433
- parentId,
2434
- depth,
2529
+ ...at,
2435
2530
  activity: sessions.get(entry.id) === void 0 ? "inactive" : "running",
2436
2531
  hasChildren: children.length > 0
2437
2532
  });
@@ -2439,169 +2534,38 @@ async function listDescendants(ctx, rootSessionId, signal) {
2439
2534
  for (const child of [...children].reverse()) stack.push({
2440
2535
  entry: child,
2441
2536
  parentId: entry.id,
2442
- depth: depth + 1
2537
+ depth: depth + 1,
2538
+ parentPath: path
2443
2539
  });
2444
2540
  }
2445
2541
  return result;
2446
2542
  }
2543
+ /**
2544
+ * Resolve a slash-separated name by reading only the catalogs along its path.
2545
+ * @param ctx - context carrying the Session query service.
2546
+ * @param rootSessionId - tree root whose catalog holds the first name.
2547
+ * @param name - candidate full name relative to the root.
2548
+ * @param signal - cancellation forwarded to each catalog read.
2549
+ * @returns the named member's Session id, or undefined when the text is not a name in this tree.
2550
+ * @throws {@link SubagentError} when a catalog dependency is unavailable; Session read failures propagate.
2551
+ */
2552
+ async function resolveAgentPath(ctx, rootSessionId, name, signal) {
2553
+ const segments = name.split("/");
2554
+ if (!segments.every(isAgentName)) return void 0;
2555
+ let current = rootSessionId;
2556
+ for (const [index, segment] of segments.entries()) {
2557
+ const child = (await listChildren(ctx, current, signal)).find((entry) => "name" in entry && entry.name === segment);
2558
+ if (child === void 0) return void 0;
2559
+ if (index < segments.length - 1 && child.mode !== "continuable" && child.mode !== "one-shot") return void 0;
2560
+ current = child.id;
2561
+ }
2562
+ return current;
2563
+ }
2447
2564
  /** Stop the complete traversal when its caller cancels. */
2448
2565
  function assertListingNotCancelled(signal) {
2449
2566
  if (signal?.aborted) throw new SubagentError("subagent listing was cancelled", "CANCELLED");
2450
2567
  }
2451
2568
  //#endregion
2452
- //#region lib/types/archive-admission.js
2453
- /**
2454
- * The `subagent` family of the Workspace registry's archive admission: which
2455
- * subagent descendants of a Session are still inside a turn, and how they
2456
- * stop when the Session is archived with its work.
2457
- *
2458
- * @module @deepseek-ai/dsh-subagent
2459
- */
2460
- var __addDisposableResource = function(env, value, async) {
2461
- if (value !== null && value !== void 0) {
2462
- if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
2463
- var dispose, inner;
2464
- if (async) {
2465
- if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
2466
- dispose = value[Symbol.asyncDispose];
2467
- }
2468
- if (dispose === void 0) {
2469
- if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
2470
- dispose = value[Symbol.dispose];
2471
- if (async) inner = dispose;
2472
- }
2473
- if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
2474
- if (inner) dispose = function() {
2475
- try {
2476
- inner.call(this);
2477
- } catch (e) {
2478
- return Promise.reject(e);
2479
- }
2480
- };
2481
- env.stack.push({
2482
- value,
2483
- dispose,
2484
- async
2485
- });
2486
- } else if (async) env.stack.push({ async: true });
2487
- return value;
2488
- };
2489
- var __disposeResources = (function(SuppressedError) {
2490
- return function(env) {
2491
- function fail(e) {
2492
- env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
2493
- env.hasError = true;
2494
- }
2495
- var r, s = 0;
2496
- function next() {
2497
- while (r = env.stack.pop()) try {
2498
- if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
2499
- if (r.dispose) {
2500
- var result = r.dispose.call(r.value);
2501
- if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
2502
- fail(e);
2503
- return next();
2504
- });
2505
- } else s |= 1;
2506
- } catch (e) {
2507
- fail(e);
2508
- }
2509
- if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
2510
- if (env.hasError) throw env.error;
2511
- }
2512
- return next();
2513
- };
2514
- })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
2515
- var e = new Error(message);
2516
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
2517
- });
2518
- /**
2519
- * Answer `workspace/session-activity` with the running subagent descendants of
2520
- * the asked Session, and `workspace/session-stop` by cancelling each of them
2521
- * as their parent would. Both listeners live as long as `ctx`'s fiber.
2522
- * @param ctx - context carrying the Agent registry; the Session query service is optional and only supplies labels.
2523
- */
2524
- function installSubagentArchiveAdmission(ctx) {
2525
- ctx.on("workspace/session-activity", async ({ sessionId }, next) => {
2526
- const running = runningDescendants(ctx, sessionId);
2527
- const rest = await next();
2528
- if (running.length === 0) return rest;
2529
- return [{
2530
- kind: "subagent",
2531
- items: await Promise.all(running.map((child) => describe(ctx, child)))
2532
- }, ...rest];
2533
- });
2534
- ctx.on("workspace/session-stop", ({ sessionId }) => {
2535
- for (const child of runningDescendants(ctx, sessionId)) try {
2536
- child.cancel({ kind: "parent" });
2537
- } catch (error) {
2538
- ctx.logger.warn(`subagent: cancelling "${child.id}" for an archived Session failed: ${String(error)}`);
2539
- }
2540
- });
2541
- }
2542
- /**
2543
- * Live subagent descendants inside a turn, by durable lineage: a child whose
2544
- * header names its parent and carries the subagent origin this package
2545
- * records, at any depth. A fork shares the lineage field without the origin
2546
- * and is an independent conversation, so it never holds its source. Lineage
2547
- * is read as data, so a damaged header chain that loops is visited once.
2548
- */
2549
- function runningDescendants(ctx, rootId) {
2550
- const childrenOf = /* @__PURE__ */ new Map();
2551
- for (const agent of ctx.agents.list()) {
2552
- const { parentSession, origin } = agent.session.header;
2553
- if (parentSession === void 0 || origin !== "subagent") continue;
2554
- const siblings = childrenOf.get(parentSession) ?? [];
2555
- siblings.push(agent);
2556
- childrenOf.set(parentSession, siblings);
2557
- }
2558
- const running = [];
2559
- const pending = [rootId];
2560
- const visited = /* @__PURE__ */ new Set();
2561
- while (pending.length > 0) {
2562
- const parentId = pending.shift();
2563
- if (visited.has(parentId)) continue;
2564
- visited.add(parentId);
2565
- for (const child of childrenOf.get(parentId) ?? []) {
2566
- if (child.status === "running") running.push(child);
2567
- pending.push(child.id);
2568
- }
2569
- }
2570
- return running;
2571
- }
2572
- /**
2573
- * The child's activity item: its id, plus the durable creation label its
2574
- * descriptor carries, read through a live Session observation. Without the
2575
- * Session query service, or with a descriptor that is absent or unreadable,
2576
- * the item names the child by id alone.
2577
- */
2578
- async function describe(ctx, child) {
2579
- const query = ctx.get("sessionQuery");
2580
- if (query === void 0) return { id: child.id };
2581
- try {
2582
- const env_1 = {
2583
- stack: [],
2584
- error: void 0,
2585
- hasError: false
2586
- };
2587
- try {
2588
- const observation = __addDisposableResource(env_1, await query.observeSession(child.id, { projectionMode: "none" }), false);
2589
- const label = foldSubagentDescriptor(observation.events.slice(observation.inheritedEventCount))?.label;
2590
- return label === void 0 ? { id: child.id } : {
2591
- id: child.id,
2592
- label
2593
- };
2594
- } catch (e_1) {
2595
- env_1.error = e_1;
2596
- env_1.hasError = true;
2597
- } finally {
2598
- __disposeResources(env_1);
2599
- }
2600
- } catch {
2601
- return { id: child.id };
2602
- }
2603
- }
2604
- //#endregion
2605
2569
  //#region lib/types/projection.js
2606
2570
  /**
2607
2571
  * Pure session projections for subagent identity (mode/label) and active-turn
@@ -2953,12 +2917,18 @@ let SubagentRuntime = (() => {
2953
2917
  let _classSuper = TypertRemoteService;
2954
2918
  let _instanceExtraInitializers = [];
2955
2919
  let _prompt_decorators;
2956
- let _interruptByParent_decorators;
2920
+ let _interruptByUser_decorators;
2957
2921
  return class SubagentRuntime extends _classSuper {
2958
2922
  static {
2959
2923
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
2960
- _prompt_decorators = [Remote("prompt")];
2961
- _interruptByParent_decorators = [Remote("interruptByParent")];
2924
+ _prompt_decorators = [Remote({
2925
+ name: "prompt",
2926
+ resources: { session: (request) => request.childSessionId }
2927
+ })];
2928
+ _interruptByUser_decorators = [Remote({
2929
+ name: "interruptByUser",
2930
+ resources: { session: (childSessionId) => childSessionId }
2931
+ })];
2962
2932
  __esDecorate(this, null, _prompt_decorators, {
2963
2933
  kind: "method",
2964
2934
  name: "prompt",
@@ -2970,14 +2940,14 @@ let SubagentRuntime = (() => {
2970
2940
  },
2971
2941
  metadata: _metadata
2972
2942
  }, null, _instanceExtraInitializers);
2973
- __esDecorate(this, null, _interruptByParent_decorators, {
2943
+ __esDecorate(this, null, _interruptByUser_decorators, {
2974
2944
  kind: "method",
2975
- name: "interruptByParent",
2945
+ name: "interruptByUser",
2976
2946
  static: false,
2977
2947
  private: false,
2978
2948
  access: {
2979
- has: (obj) => "interruptByParent" in obj,
2980
- get: (obj) => obj.interruptByParent
2949
+ has: (obj) => "interruptByUser" in obj,
2950
+ get: (obj) => obj.interruptByUser
2981
2951
  },
2982
2952
  metadata: _metadata
2983
2953
  }, null, _instanceExtraInitializers);
@@ -3006,13 +2976,18 @@ let SubagentRuntime = (() => {
3006
2976
  super(ctx, "subagents");
3007
2977
  this.config = config;
3008
2978
  this.emitLifecycle = createLifecycleEmitter(this.ctx, (parent) => scopeTarget(this, parent));
2979
+ }
2980
+ async [Service.init]() {
2981
+ const ctx = this.ctx;
2982
+ const catalogProjection = await ctx.sessionProjections.register(subagentCatalogProjectionDefinition);
2983
+ await ctx.sessionProjections.register(subagentTimingProjectionDefinition);
2984
+ const identityProjection = await ctx.sessionProjections.register(subagentIdentityProjectionDefinition);
2985
+ if (ctx.fiber.uid === null) return;
3009
2986
  ctx.inject(["agents"], (childCtx) => {
3010
2987
  const manager = new SubagentManager(childCtx, {
3011
- startExternal: (name, request) => {
3012
- return this.expectProvider(name).start(request);
3013
- },
3014
- prepareContinuable: (name, request) => this.prepareContinuable(name, request),
3015
- observeActivation: (provider, childId, parent) => this.observeActivation(provider, childId, parent)
2988
+ identityOf: (session) => identityProjection.stateOf(session).identity,
2989
+ catalogOf: (session) => subagentCatalogProjectionDefinition.wire.view(catalogProjection.stateOf(session)),
2990
+ emitLifecycle: this.emitLifecycle
3016
2991
  }, () => this.config.maxActiveSubagents.get());
3017
2992
  this.manager = manager;
3018
2993
  childCtx.effect(() => () => {
@@ -3020,15 +2995,6 @@ let SubagentRuntime = (() => {
3020
2995
  if (this.manager === manager) this.manager = void 0;
3021
2996
  }, "subagents.managerBinding()");
3022
2997
  });
3023
- ctx.inject(["agents"], (agentsCtx) => {
3024
- installSubagentArchiveAdmission(agentsCtx);
3025
- });
3026
- }
3027
- async [Service.init]() {
3028
- const { sessionProjections } = this.ctx;
3029
- await sessionProjections.register(subagentCatalogProjectionDefinition);
3030
- await sessionProjections.register(subagentTimingProjectionDefinition);
3031
- await sessionProjections.register(subagentIdentityProjectionDefinition);
3032
2998
  }
3033
2999
  /**
3034
3000
  * Resolve a delegation tool's depth policy against the current user setting.
@@ -3047,64 +3013,98 @@ let SubagentRuntime = (() => {
3047
3013
  * @param spec - task, backend, and result recipient.
3048
3014
  * @returns identities, execution result, and exact-activation disposal. A reserved
3049
3015
  * childId requires a local backend and guarantees an accepted messageId.
3016
+ * @throws PROVIDER_CHANGED if the selected provider is removed or replaced before dispatch.
3050
3017
  */
3051
3018
  async startActivation(spec) {
3052
3019
  const provider = this.expectProvider(spec.provider);
3053
3020
  if (spec.childId !== void 0 && provider.prepareContinuable === void 0) throw new SubagentError("reserved child ids require a local backend", "UNSUPPORTED_CAPABILITY");
3054
- assertSubagentMaxDepth(spec.request.maxDepth);
3055
- this.assertCapabilities(provider, {
3056
- ...spec.request,
3057
- signal: spec.signal
3058
- });
3021
+ assertSubagentMaxDepth(spec.maxDepth);
3022
+ this.assertCapabilities(provider, spec);
3059
3023
  const manager = this.requireManager();
3060
- if (this.ctx.get("agents")?.get(spec.request.parent.id) !== spec.request.parent) throw new SubagentError("subagent creation requires the exact live parent agent", "UNAUTHORIZED");
3061
- if (spec.request.outputSchema !== void 0) assertObjectJsonSchema(spec.request.outputSchema);
3062
- return provider.prepareContinuable === void 0 ? manager.startExternal(spec) : manager.startLocal(spec);
3024
+ if (this.ctx.get("agents")?.get(spec.parent.id) !== spec.parent) throw new SubagentError("subagent creation requires the exact live parent agent", "UNAUTHORIZED");
3025
+ if (spec.outputSchema !== void 0) assertObjectJsonSchema(spec.outputSchema);
3026
+ const prepare = provider.prepareContinuable?.bind(provider);
3027
+ if (prepare !== void 0) return manager.startLocal(spec, (request) => {
3028
+ this.assertProviderCurrent(provider);
3029
+ return prepare(request);
3030
+ });
3031
+ const start = provider.start.bind(provider);
3032
+ return manager.startExternal(spec, (request) => {
3033
+ this.assertProviderCurrent(provider);
3034
+ return start(request);
3035
+ });
3036
+ }
3037
+ /**
3038
+ * Resolve the root shared by an Agent and its other agents in its subagent tree.
3039
+ * @param caller - exact live Agent whose subagent ancestry selects the tree.
3040
+ * @returns the live root; ordinary Session forks lead independent trees.
3041
+ * @throws when the caller or its runtime owner is unavailable.
3042
+ */
3043
+ rootOf(caller) {
3044
+ return this.requireManager().rootOf(caller);
3063
3045
  }
3064
3046
  /**
3065
- * Join progressing descendants without cancelling them. Idle descendants whose
3066
- * inboxes require a later wake stay resident and do not delay host completion.
3067
- * @param parent - the exact parent whose descendant work is observed.
3068
- * @returns whether work was joined; hosts recheck parent idle after true.
3047
+ * Report the model-facing names of a live tree member and its direct creator.
3048
+ * The root is `lead`; a descendant is the slash-separated path of names from
3049
+ * the root, or its Session id when it or a creator below the root has no name.
3050
+ * @param agent - exact live root or resident tree member.
3051
+ * @returns the member's name and, for a descendant, its creator's name.
3052
+ * @throws when the caller or its runtime owner is unavailable.
3069
3053
  */
3070
- async waitForChildren(parent) {
3071
- return this.manager?.waitForChildren(parent) ?? false;
3054
+ namesOf(agent) {
3055
+ return this.requireManager().namesOf(agent);
3072
3056
  }
3073
3057
  /**
3074
- * Steer one model-authored message to the sender's direct parent or direct
3075
- * continuable child. A running target admits it at the nearest step boundary;
3076
- * an idle target starts a turn, and an absent direct child cold-resumes from
3077
- * persistence. The service derives durable sender attribution from the exact
3078
- * live sender. Caller cancellation stops only pre-acceptance work.
3079
- * @param sender - exact live Agent authorizing and originating the message.
3080
- * @param targetId - durable direct-parent or direct-child session id.
3058
+ * Resolve a model-supplied agent reference within the caller's tree. `lead`
3059
+ * selects the root and a slash-separated path is looked up through the
3060
+ * catalogs along it. Any other text that is not a name in the tree is
3061
+ * returned as a Session id, because a single token can be one; a
3062
+ * slash-separated address never is, so an unmatched path fails instead of
3063
+ * reaching a member lookup as an unknown id. Resolution grants no authority:
3064
+ * messaging, interruption, and assignment authorize the result.
3065
+ * @param caller - exact live Agent whose tree root anchors the lookup.
3066
+ * @param name - `lead`, a full name from the root, or a Session id.
3067
+ * @param signal - cancellation forwarded to each catalog read.
3068
+ * @returns the referenced Session id.
3069
+ * @throws {@link SubagentError} `AGENT_NAME_NOT_FOUND` when a path names no member;
3070
+ * when the caller's root is unavailable; or when a catalog along the path cannot be read.
3071
+ */
3072
+ async resolveName(caller, name, signal) {
3073
+ const root = this.rootOf(caller);
3074
+ if (name === "lead") return root.id;
3075
+ const resolved = await resolveAgentPath(this.ctx, root.id, name, signal);
3076
+ if (resolved !== void 0) return resolved;
3077
+ if (name.includes("/")) throw new SubagentError(`agent name ${JSON.stringify(name)} was not found in this subagent tree; use list_agents to see the names`, "AGENT_NAME_NOT_FOUND");
3078
+ return brandString(name);
3079
+ }
3080
+ /**
3081
+ * Join progressing subagent tree work for its root. Idle members with parked input
3082
+ * stay resident without delaying host completion. Ordinary members return false.
3083
+ * @param root - exact live subagent tree root whose member work is awaited.
3084
+ * @returns whether work was joined; hosts recheck root idle after true.
3085
+ */
3086
+ async waitForTreeWork(root) {
3087
+ return this.manager?.waitForTreeWork(root) ?? false;
3088
+ }
3089
+ /**
3090
+ * Steer one model-authored message to another member of the same subagent tree.
3091
+ * A running target receives it at its next step; an idle target starts a turn.
3092
+ * A cold target resumes under its runtime subagent tree root without restoring
3093
+ * its creation ancestors. Sender identity is rechecked before inbox acceptance; cancellation
3094
+ * stops only pre-acceptance work and never retracts an accepted message.
3095
+ * @param sender - exact live root or resident continuable Agent originating the message.
3096
+ * @param targetId - another root or continuable member's durable Session id.
3081
3097
  * @param content - model-authored content to deliver.
3082
3098
  * @param options - caller cancellation before inbox acceptance.
3083
3099
  * @returns the accepted message's inbox id.
3084
- * @throws when continuation services are unavailable, adjacency is rejected,
3085
- * or the message was not admitted.
3100
+ * @throws when the target is outside the tree, cannot resume, or rejects input.
3086
3101
  */
3087
3102
  async sendMessage(sender, targetId, content, options) {
3088
3103
  return this.requireManager().sendMessage(sender, targetId, content, options);
3089
3104
  }
3090
3105
  /**
3091
- * Deliver one host-protocol message to a direct continuable child.
3092
- * Symbol-keyed so host adapters can preserve their own source descriptors without
3093
- * widening the public Service Definition or impersonating an Agent sender.
3094
- * @param parent - exact live direct parent authorizing delivery.
3095
- * @param childId - durable direct-child session id.
3096
- * @param content - host-authored content to deliver.
3097
- * @param source - durable host-protocol source descriptor.
3098
- * @param signal - caller cancellation before inbox acceptance.
3099
- * @param delivery - Queue as a distinct turn or Steer at the nearest step.
3100
- * @returns the accepted message's inbox id.
3101
- */
3102
- [deliverSubagentPrompt](parent, childId, content, source, signal, delivery) {
3103
- return delivery === "steer" ? this.requireManager().steerPrompt(parent, childId, content, source, signal) : this.requireManager().queuePrompt(parent, childId, content, source, signal);
3104
- }
3105
- /**
3106
- * Interrupt one live child's current execution under a human parent
3107
- * address or an exact live ancestor Agent. Fire-and-return: the cancel
3106
+ * Interrupt one live child's current execution under a trusted user
3107
+ * operation or an exact live ancestor Agent. Fire-and-return: the cancel
3108
3108
  * signal is issued before this returns, but the target may keep running
3109
3109
  * until it observes the signal. Unclaimed pending inbox work, the Activation,
3110
3110
  * and published descendants are preserved; claimed work is not requeued.
@@ -3113,7 +3113,7 @@ let SubagentRuntime = (() => {
3113
3113
  * is an accepted no-op, as is a manager-less composition, which cannot own a
3114
3114
  * live Activation.
3115
3115
  * @param targetSessionId - the durable child session id to interrupt.
3116
- * @param authority - the human parent address or exact live ancestor Agent.
3116
+ * @param authority - a trusted user operation or exact live ancestor Agent.
3117
3117
  * @throws {SubagentError} `UNAUTHORIZED` when the authority does not own the
3118
3118
  * live target.
3119
3119
  */
@@ -3121,13 +3121,11 @@ let SubagentRuntime = (() => {
3121
3121
  this.manager?.interrupt(targetSessionId, authority);
3122
3122
  }
3123
3123
  /**
3124
- * Close subagent admission below exact live parent Agents, stop only their
3125
- * visible descendant Activations synchronously, then await admitted scoped
3126
- * materializations and release those forests child-first. The scoped cutoff
3127
- * lasts until each exact parent leaves the registry; unrelated parent trees
3128
- * remain live.
3129
- * @param parents - exact host-owned parent Agents entering teardown.
3130
- * @returns once every retained descendant activation released its execution handle.
3124
+ * Close admission and stop all instances in the selected subagent trees, then await
3125
+ * pending startup and cleanup. Ordinary members are ignored. The cutoff lasts
3126
+ * until each exact root leaves the registry; unrelated subagent trees remain live.
3127
+ * @param parents - exact live subagent tree roots entering teardown.
3128
+ * @returns once all admitted startup and member cleanup have settled.
3131
3129
  * @throws an aggregate error after all branches settle when any failed.
3132
3130
  */
3133
3131
  async drainDescendants(parents) {
@@ -3136,33 +3134,6 @@ let SubagentRuntime = (() => {
3136
3134
  await manager.drainDescendants(parents);
3137
3135
  }
3138
3136
  /**
3139
- * Release selected resident direct children of one exact live
3140
- * parent. Other children of the same parent remain admitted and resident.
3141
- * Absent targets and a manager-less composition are accepted no-ops.
3142
- * @param parent - exact live direct parent authorizing the selected release.
3143
- * @param childIds - durable direct-child ids to release when resident.
3144
- * @returns once every selected activation released its execution handle.
3145
- * @throws {SubagentError} `UNAUTHORIZED` when a resident target belongs to a
3146
- * different parent or the supplied parent identity is stale.
3147
- */
3148
- async drainChildren(parent, childIds) {
3149
- const manager = this.manager;
3150
- if (manager === void 0) return;
3151
- await manager.drainChildren(parent, childIds);
3152
- }
3153
- /**
3154
- * Read the parent's durable direct-child catalog without loading or resuming an Agent.
3155
- * The service owns and releases the live-preferred Session observation.
3156
- * @param parentSessionId - parent whose direct children are requested.
3157
- * @param signal - cancellation forwarded to the Session query.
3158
- * @returns catalog children in parent event order.
3159
- * @throws {@link SubagentError} when query or catalog projection is unavailable.
3160
- * @throws SessionQueryError when the parent cannot be read or the query is cancelled.
3161
- */
3162
- listChildren(parentSessionId, signal) {
3163
- return listChildren(this.ctx, parentSessionId, signal);
3164
- }
3165
- /**
3166
3137
  * Recursively list reachable parent catalogs in stable pre-order, preserving
3167
3138
  * each catalog's event order. Each row carries its catalog parent and depth;
3168
3139
  * external children are leaves; one-shot and unknown-mode children remain
@@ -3182,8 +3153,8 @@ let SubagentRuntime = (() => {
3182
3153
  return listDescendants(this.ctx, rootSessionId, signal);
3183
3154
  }
3184
3155
  /**
3185
- * Deliver one browser-authored message to a continuable child through the
3186
- * exact live direct parent, retaining the caller-minted request identity and
3156
+ * Deliver one browser-authored message to a continuable child through its
3157
+ * live subagent tree root, retaining the caller-minted request identity and
3187
3158
  * validated browser zone on the accepted message. Success identifies the
3188
3159
  * message the child's inbox accepted; later execution is independent of this
3189
3160
  * call. Queue delivery targets a later turn; steer delivery targets the
@@ -3191,21 +3162,20 @@ let SubagentRuntime = (() => {
3191
3162
  * Image parts are admitted and persisted through the attachment store
3192
3163
  * before delivery, and the child's model must accept image input.
3193
3164
  * Cold resume at capacity rejects with `subagent/delivery-unavailable`.
3194
- * @param request - durable address, delivery, minted identity, content, and optional browser zone.
3165
+ * Access is checked on the target Session before attachment admission or restoration.
3166
+ * @param request - target id, delivery, minted identity, content, and optional browser zone.
3195
3167
  * @param signal - carrier cancellation, owning the call until inbox acceptance.
3196
3168
  * @returns the accepted message's inbox identity.
3197
3169
  * @throws {RemoteError} `gateway/bad-request`, `subagent/attachment-invalid`,
3198
- * `subagent/invalid-time-zone`, `subagent/parent-unavailable`,
3170
+ * `subagent/invalid-time-zone`,
3199
3171
  * `subagent/not-resumable`, `subagent/unauthorized`,
3200
3172
  * `subagent/delivery-unavailable`, `gateway/cancelled`, or `gateway/internal`.
3201
3173
  */
3202
3174
  async prompt(request, signal) {
3203
- const { parentSessionId, childSessionId, clientTimeZone, delivery } = request;
3175
+ const { childSessionId, clientTimeZone, delivery } = request;
3204
3176
  validateControlRequest("subagent.prompt", request);
3205
3177
  const canonicalTimeZone = clientTimeZone === void 0 ? void 0 : canonicalClientTimeZone(clientTimeZone);
3206
3178
  if (clientTimeZone !== void 0 && canonicalTimeZone === void 0) throw new RemoteError("subagent/invalid-time-zone", "clientTimeZone must be UTC or a valid IANA Area/Location name", { value: clientTimeZone });
3207
- const parent = this.ctx.get("agents")?.get(parentSessionId);
3208
- if (parent === void 0) throw new RemoteError("subagent/parent-unavailable", `parent session "${parentSessionId}" is not live`, { parentSessionId });
3209
3179
  const principal = principalOf(this.ctx.invocation);
3210
3180
  const source = {
3211
3181
  kind: "user",
@@ -3224,38 +3194,29 @@ let SubagentRuntime = (() => {
3224
3194
  if (attachments === void 0) throw new Error("subagent image prompt requires an attachment store");
3225
3195
  content = await attachments.admitPromptContent(request.content);
3226
3196
  }
3227
- return { messageId: await this[deliverSubagentPrompt](parent, childSessionId, content, source, signal, delivery) };
3197
+ return { messageId: await this.requireManager().deliverPrompt(childSessionId, content, {
3198
+ source,
3199
+ signal,
3200
+ delivery
3201
+ }) };
3228
3202
  } catch (error) {
3229
3203
  return rejectPrompt(error, childSessionId, signal);
3230
3204
  }
3231
3205
  }
3232
3206
  /**
3233
- * Remote face of {@link interrupt} under one durable parent address. No
3234
- * catalog, history, persistence, or parent Agent lookup runs: the core
3235
- * primitive alone authorizes the address against the live Activation, which
3236
- * is what keeps a live child interruptible while its parent Agent is offline.
3207
+ * Remote face of {@link interrupt}, authorized on the target Session by the Gateway.
3208
+ * No catalog, history, persistence, or parent Agent lookup runs.
3237
3209
  * Absent, idle, and already-completed targets are accepted no-ops there.
3238
3210
  * @param childSessionId - durable child session id to interrupt.
3239
- * @param parentSessionId - durable direct parent whose authority is claimed.
3240
- * @param mode - required continuable-address discriminator.
3241
3211
  * @returns acknowledgement that the cancel signal was admitted, not that the target is quiescent.
3242
3212
  * @throws {RemoteError} `gateway/bad-request` for an empty id,
3243
- * `subagent/unauthorized` when the address does not own the live target,
3244
3213
  * otherwise `gateway/internal`.
3245
3214
  */
3246
- interruptByParent(childSessionId, parentSessionId, mode) {
3247
- validateControlRequest("subagent.interrupt", {
3248
- childSessionId,
3249
- parentSessionId,
3250
- mode
3251
- });
3215
+ interruptByUser(childSessionId) {
3216
+ validateControlRequest("subagent.interrupt", { childSessionId });
3252
3217
  try {
3253
- this.interrupt(childSessionId, {
3254
- kind: "user",
3255
- parentSessionId
3256
- });
3218
+ this.interrupt(childSessionId, { kind: "user" });
3257
3219
  } catch (error) {
3258
- if (error instanceof SubagentError && error.code === "UNAUTHORIZED") throw new RemoteError("subagent/unauthorized", "subagent does not belong to this parent", { childSessionId }, { cause: error });
3259
3220
  throw new RemoteError("gateway/internal", "subagent interrupt failed", {}, { cause: error });
3260
3221
  }
3261
3222
  return { accepted: true };
@@ -3289,20 +3250,9 @@ let SubagentRuntime = (() => {
3289
3250
  getProvider(name) {
3290
3251
  return this.providers.get(name);
3291
3252
  }
3292
- /**
3293
- * List registered provider names in insertion order.
3294
- * @returns the registered names.
3295
- */
3296
- list() {
3297
- return [...this.providers.keys()];
3298
- }
3299
- /**
3300
- * Resolve one provider's detached continuable-creation contribution. Method
3301
- * presence on the provider IS the capability, so a provider without it is
3302
- * rejected before the manager reserves any child resources.
3303
- */
3304
- async prepareContinuable(name, request) {
3305
- return this.expectProvider(name).prepareContinuable(request);
3253
+ /** A pending start must use the exact provider whose capabilities were checked. */
3254
+ assertProviderCurrent(provider) {
3255
+ if (this.providers.get(provider.name) !== provider) throw new SubagentError(`subagent provider "${provider.name}" changed during startup; retry the delegation`, "PROVIDER_CHANGED");
3306
3256
  }
3307
3257
  /** Look up a provider for dispatch or fail loud. */
3308
3258
  expectProvider(name) {
@@ -3315,13 +3265,6 @@ let SubagentRuntime = (() => {
3315
3265
  if (this.manager === void 0) throw new SubagentError("continuable subagents require the agents service", "CONTINUATION_UNAVAILABLE");
3316
3266
  return this.manager;
3317
3267
  }
3318
- /**
3319
- * Build the lifecycle observer for one continuable Activation's residency
3320
- * epoch, so the manager publishes its edges without owning event dispatch.
3321
- */
3322
- observeActivation(provider, childId, parent) {
3323
- return createActivationObserver(this.emitLifecycle, provider, childId, parent);
3324
- }
3325
3268
  /** Reject the first requested capability that the provider lacks. */
3326
3269
  assertCapabilities(provider, request) {
3327
3270
  if (request.agentPreset !== void 0 && (!provider.capabilities.agentPreset || provider.inheritsParentContext)) throw new SubagentError(`subagent provider "${provider.name}" does not support independent agent preset selection`, "UNSUPPORTED_CAPABILITY");
@@ -3344,4 +3287,4 @@ let SubagentRuntime = (() => {
3344
3287
  };
3345
3288
  })();
3346
3289
  //#endregion
3347
- export { AssistantOutputFold, NO_START_CAPABILITIES, STRUCTURED_OUTPUT_TOOL, SUBAGENT_DESCRIPTOR_VERSION, SubagentDepthError, SubagentError, SubagentRunId, SubagentRuntime, SubagentRuntime as default, appendDelegatedPolicyOverrides, applyChildComposition, assertPositiveFinite, assertSubagentMaxDepth, assertUsableCwd, captureDelegatedPolicyOverrides, childSessionMeta, delegationDepthOf, finalAssistantOutput, foldSubagentDescriptor, parentAgentOptionsForDelegation, resolveChildAgentOptions, resolveChildDepth, settleRunResult, snapshotSubagentDescriptor, subprocessRunHandle };
3290
+ export { AssistantOutputFold, NO_START_CAPABILITIES, ROOT_AGENT_NAME, STRUCTURED_OUTPUT_TOOL, SUBAGENT_DESCRIPTOR_VERSION, SubagentDepthError, SubagentError, SubagentRunId, SubagentRuntime, SubagentRuntime as default, appendDelegatedPolicyOverrides, applyChildComposition, assertPositiveFinite, assertSubagentMaxDepth, assertUsableCwd, captureDelegatedPolicyOverrides, childSessionMeta, delegationDepthOf, finalAssistantOutput, foldSubagentDescriptor, parentAgentOptionsForDelegation, resolveChildAgentOptions, resolveChildDepth, settleRunResult, snapshotSubagentDescriptor, subprocessRunHandle };