@deepseek-ai/dsh-subagent 0.2.2-alpha.3 → 0.2.2-rc.2

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 +59 -59
  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/src/manager.ts ADDED
@@ -0,0 +1,1359 @@
1
+ /**
2
+ * Owns subagent startup, message admission, cold resume, and execution lifetimes.
3
+ * One child lock orders input acceptance and closure; one activation map owns
4
+ * capacity, runtime ownership, and resource release across all providers.
5
+ *
6
+ * @module @deepseek-ai/dsh-subagent/manager
7
+ */
8
+
9
+ import { randomUUID } from 'node:crypto'
10
+ import { isAbsolute, resolve } from 'node:path'
11
+ import type {} from '@deepseek-ai/dsh-working-directory'
12
+ import { FiberState, type Context } from '@deepseek-ai/cordis'
13
+ import type { Agent, AgentOptions, CreateAgentOptions } from '@deepseek-ai/dsh-agent'
14
+ import { brandString } from '@deepseek-ai/dsh-brand'
15
+ import { ReasoningEffortId, contentHasImage, createUserMessage, errorChain } from '@deepseek-ai/dsh-llm'
16
+ import type { ContentBlock, MessageId, MessageSource } from '@deepseek-ai/dsh-llm'
17
+ import { SessionLogOffset } from '@deepseek-ai/dsh-session'
18
+ import type { Session, SessionId, SessionEvent, UserMessage } from '@deepseek-ai/dsh-session'
19
+ import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence'
20
+ import type { SessionObservation, SessionQueryEngine } from '@deepseek-ai/dsh-session-query'
21
+ import type { ObjectJsonSchema } from '@deepseek-ai/dsh-tools'
22
+ import {
23
+ appendDelegatedPolicyOverrides, applyChildComposition, captureDelegatedPolicyOverrides,
24
+ childSessionMeta, resolveChildAgentOptions, resolveChildDepth,
25
+ } from './child-agent.ts'
26
+ import type { ChildComposition, DelegatedPolicyOverrides } from './child-agent.ts'
27
+ import {
28
+ createAgentMessage, createSettlementMessage, withResultDeliveryGuidance,
29
+ } from './continuation-messages.ts'
30
+ import { installSubagentArchiveAdmission } from './archive-admission.ts'
31
+ import { foldSubagentDescriptor, snapshotSubagentDescriptor } from './descriptor.ts'
32
+ import type { SubagentDescriptorData } from './descriptor.ts'
33
+ import { catalogNames, establishCatalogChild, establishExternalCatalogChild } from './catalog.ts'
34
+ import { SubagentError } from './error.ts'
35
+ import type { LifecycleEmitter } from './lifecycle.ts'
36
+ import { ROOT_AGENT_NAME, SiblingNameReservations, agentAddress, joinAgentPath, parentAgentPath } from './names.ts'
37
+ import type { SiblingNameReservation } from './names.ts'
38
+ import type { SubagentCatalogEntry, SubagentIdentityProjection } from './projection-types.ts'
39
+ import { SubagentRunId } from './types.ts'
40
+ import type {
41
+ ContinuableCreateRequest, ContinuableCreateSpec, SubagentInterruptAuthority,
42
+ SubagentActivationSpec, SubagentActivation, SubagentMemberNames, SubagentStartRequest, SubagentRun,
43
+ SubagentSendMessageOptions, SubagentResult, SubagentRunInfo, ResolvedSubagentStartRequest,
44
+ } from './types.ts'
45
+ import { attachStructuredRuntime } from './structured.ts'
46
+ import type { StructuredAttachment } from './structured.ts'
47
+ import type { SubagentDelivery } from './control-types.ts'
48
+ import { ActivationPool, ChildLock, activationAgent, captureLocalResult, observeLocalFailure, requireLocalActivation } from './activation.ts'
49
+ import type { Activation, ActivationResource, LocalActivation } from './activation.ts'
50
+
51
+ /** Inputs shared by model steering and human prompt delivery. */
52
+ type ChildDeliveryOptions = {
53
+ readonly delivery: SubagentDelivery
54
+ readonly source: MessageSource
55
+ readonly signal: AbortSignal
56
+ /** Recheck the original model caller at final inbox admission. */
57
+ readonly authorize?: () => void
58
+ /** Record successful inbox admission before another asynchronous operation can intervene. */
59
+ readonly onAccepted?: () => void
60
+ }
61
+
62
+ /** Package-private hooks supplied by the owning service. */
63
+ interface SubagentHost {
64
+ /** Read the current descriptor identity through the service-owned projection. */
65
+ identityOf(session: Session): SubagentIdentityProjection | undefined
66
+ /** Read a live Session's direct-child catalog through the service-owned projection. */
67
+ catalogOf(session: Session): readonly SubagentCatalogEntry[]
68
+ /** Publish lifecycle events through the owning service's scoped dispatcher. */
69
+ readonly emitLifecycle: LifecycleEmitter
70
+ }
71
+
72
+ /** Inputs shared by fresh and resumed Activation materialization. */
73
+ interface MaterializeBase {
74
+ provider: string
75
+ root: Agent
76
+ ancestors: readonly SessionId[]
77
+ /** Slash-separated names from the root, undefined when any link is unnamed. */
78
+ path: string | undefined
79
+ signal: AbortSignal
80
+ delivery?: 'parent' | 'caller' | undefined
81
+ }
82
+
83
+ /** Creation inputs for a local residency or one external backend execution. */
84
+ type MaterializeInputs = MaterializeBase & (
85
+ | {
86
+ kind: 'local'
87
+ childId: SessionId
88
+ /**
89
+ * Creation inputs; absent for a cold resume, which loads the persisted
90
+ * session — including the delegation policy events a fresh creation seeded,
91
+ * so a resume never re-captures the parent's policy.
92
+ */
93
+ create?: {
94
+ /** Live creator used only while establishing the child. */
95
+ parent: Agent
96
+ /** Absolute initial directory captured before provider preparation. */
97
+ cwd: string
98
+ seed: readonly SessionEvent[] | undefined
99
+ meta: NonNullable<CreateAgentOptions['meta']>
100
+ /** Exact parent-log prefix length inside {@link seed}. */
101
+ inheritedEventCount: SessionLogOffset
102
+ /** Policy captured at delegation: the parent's sandbox override plus the approval pin. */
103
+ delegatedPolicies: DelegatedPolicyOverrides
104
+ /** Child-owned composition record appended after the inherited marker. */
105
+ descriptor: SubagentDescriptorData
106
+ }
107
+ agentOptions: AgentOptions
108
+ composition: ChildComposition
109
+ outputSchema?: ObjectJsonSchema | undefined
110
+ }
111
+ | { kind: 'external'; start: (signal: AbortSignal) => Promise<SubagentRun> }
112
+ )
113
+
114
+ /**
115
+ * One admitted materialization and the exact live ancestry observed at its
116
+ * synchronous admission point. Retaining identities lets a scoped teardown
117
+ * keep waiting even if an intermediate Agent leaves the registry meanwhile.
118
+ */
119
+ interface Materialization {
120
+ readonly root: Agent
121
+ readonly settled: Promise<void>
122
+ readonly controller: AbortController
123
+ }
124
+
125
+ /** Residency state observed by the natural-settlement watcher. */
126
+ type SettlementState = 'closed' | 'retry' | 'wait' | 'ready'
127
+
128
+ /** Result of the final child-lock settlement decision. */
129
+ type SettlementAttempt =
130
+ | Exclude<SettlementState, 'ready'>
131
+ | { readonly done: Promise<void> }
132
+
133
+ /** Render only the safe outer message from execution or teardown failures. */
134
+ function failureMessage(error: unknown): string {
135
+ return error instanceof Error ? error.message : 'unknown teardown failure'
136
+ }
137
+
138
+ /** Own subagent requests and the resources of every live activation. */
139
+ export class SubagentManager {
140
+ /** Child session id → its live Activation. Process-local, never durable. */
141
+ private readonly resident = new Map<SessionId, Activation>()
142
+ /** Root identities retain their pool across child settlement without retaining dead roots. */
143
+ private readonly rootPools = new WeakMap<Agent, ActivationPool>()
144
+ /** Materializations admitted before drain, tracked through publication or rollback. */
145
+ private readonly materializations = new Set<Materialization>()
146
+ /** Per-child serializer shared by delivery, release, and disposal. */
147
+ private readonly locks = new ChildLock()
148
+ /** Structural Cordis owner of every Activation handle. */
149
+ private readonly ownerCtx: Context
150
+ /** Exact subagent tree roots whose host teardown has closed admission. */
151
+ private readonly closingRoots = new Set<Agent>()
152
+ /** Sibling names held by creations that have not committed their catalog entry. */
153
+ private readonly names = new SiblingNameReservations()
154
+ private draining = false
155
+
156
+ /**
157
+ * Build one manager inside the service's Agent-injected context.
158
+ * @param ctx - context providing Agents, Sessions, and teardown ownership.
159
+ * @param host - descriptor reads and lifecycle publication owned by the service.
160
+ * @param maxActiveSubagents - the current configured child capacity.
161
+ */
162
+ constructor(
163
+ private readonly ctx: Context,
164
+ private readonly host: SubagentHost,
165
+ private readonly maxActiveSubagents: () => number,
166
+ ) {
167
+ // Drain managed instances before Cordis releases their owning scope.
168
+ const scope = ctx.plugin(function activationOwner() {})
169
+ this.ownerCtx = scope.ctx
170
+ installSubagentArchiveAdmission(ctx, (agent) => {
171
+ const activation = this.resident.get(agent.id)
172
+ return activation !== undefined && activationAgent(activation) === agent ? activation.ancestors : undefined
173
+ }, session => host.identityOf(session))
174
+ ctx.on('agent/disposed', ({ agent }) => {
175
+ this.closingRoots.delete(agent)
176
+ const activation = this.resident.get(agent.id)
177
+ if (activation?.kind === 'local' && activation.handle.agent === agent) {
178
+ void this.close(activation, () => this.finishDisposal(activation, false)).catch((error: unknown) => {
179
+ this.reportTeardownFailure(activation, error)
180
+ })
181
+ }
182
+ })
183
+ ctx.effect(function* (this: SubagentManager) {
184
+ yield scope.dispose
185
+ yield () => this.drain()
186
+ }.bind(this), 'subagents.manager()')
187
+ }
188
+
189
+ /**
190
+ * Interrupt one live continuable child's current turn under the supplied authority.
191
+ * @param targetSessionId - the durable child session id to interrupt.
192
+ * @param authority - a trusted user operation or exact live ancestor Agent.
193
+ */
194
+ interrupt(
195
+ targetSessionId: SessionId,
196
+ authority: SubagentInterruptAuthority,
197
+ ): void {
198
+ if (authority.kind === 'ancestor') {
199
+ const caller = authority.agent
200
+ if (this.ctx.agents.get(caller.id) !== caller) {
201
+ throw new SubagentError(
202
+ `interrupting "${targetSessionId}" requires the exact live ancestor agent`,
203
+ 'UNAUTHORIZED',
204
+ )
205
+ }
206
+ if (caller.id === targetSessionId) {
207
+ throw new SubagentError(
208
+ `agent "${caller.id}" cannot interrupt itself`,
209
+ 'UNAUTHORIZED',
210
+ )
211
+ }
212
+ }
213
+ const activation = this.resident.get(targetSessionId)
214
+ if (activation === undefined) return
215
+ if (authority.kind === 'ancestor'
216
+ && (this.rootOf(authority.agent) !== activation.root || !activation.ancestors.includes(authority.agent.id))) {
217
+ throw new SubagentError(
218
+ `subagent "${targetSessionId}" is not a live descendant of agent "${authority.agent.id}"`,
219
+ 'UNAUTHORIZED',
220
+ )
221
+ }
222
+ // Disposal already stopped the target with a whole-Activation teardown;
223
+ // a second cancel would be a redundant signal on a closing handle.
224
+ if (activation.closing !== undefined) return
225
+ const kind = authority.kind === 'user' ? 'user' : 'parent'
226
+ if (activation.kind === 'local') {
227
+ activation.handle.agent.cancel({ kind }, { keepInbox: true })
228
+ } else {
229
+ activation.controller.abort({ kind })
230
+ // The settlement observer reports teardown failures.
231
+ void this.dispose(activation).catch(() => undefined)
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Close admission, await every already-admitted materialization through
237
+ * publication or rollback, then dispose every agent in the subagent tree.
238
+ */
239
+ async drain(): Promise<void> {
240
+ this.draining = true
241
+ for (const pending of this.materializations) pending.controller.abort()
242
+ await Promise.all([...this.materializations].map(materialization => materialization.settled))
243
+ await this.disposeRoots([...this.resident.values()], 'activation(s)')
244
+ }
245
+
246
+ /**
247
+ * Join progressing subagent tree work for its root, leaving idle parked inboxes resident.
248
+ * @param root - exact live subagent tree root; ordinary members return false.
249
+ * @returns whether work was joined and the host must recheck root completion.
250
+ */
251
+ async waitForTreeWork(root: Agent): Promise<boolean> {
252
+ if (this.rootOf(root) !== root) return false
253
+ let observed = false
254
+ while (true) {
255
+ const pending = [...this.materializations].filter(item => item.root === root)
256
+ const children = [...this.resident.values()].filter(item => item.root === root)
257
+ observed ||= children.some(item => item.kind === 'local' && item.handle.agent.status !== 'idle')
258
+ await Promise.all(children.flatMap(item => item.kind === 'local' ? [item.handle.agent.whenIdle()] : []))
259
+ const waits: Promise<unknown>[] = pending.map(item => item.settled)
260
+ for (const item of children) {
261
+ if (item.kind === 'external' || item.closing !== undefined) {
262
+ waits.push(item.result.promise.catch(() => undefined))
263
+ continue
264
+ }
265
+ if (item.handle.agent.status !== 'idle') {
266
+ waits.push(item.handle.agent.whenIdle())
267
+ continue
268
+ }
269
+ const inbox = item.handle.agent.inbox
270
+ if (item.failureAt === undefined && (inbox.nextTurn.length > 0 || inbox.nextStep.length > 0)) continue
271
+ waits.push(Promise.race([item.result.promise.catch(() => undefined), item.poke.promise]))
272
+ }
273
+ if (waits.length > 0) {
274
+ observed = true
275
+ await Promise.all(waits)
276
+ continue
277
+ }
278
+ // A descendant can be published while whenIdle follows another child.
279
+ if ([...this.materializations].some(item => item.root === root && !pending.includes(item))
280
+ || [...this.resident.values()].some(item => item.root === root && !children.includes(item))) continue
281
+ return observed
282
+ }
283
+ }
284
+
285
+ /**
286
+ * Stop every member of the selected subagent trees; ordinary members do not close a subagent tree.
287
+ * @param parents - exact live subagent tree roots whose instances must stop.
288
+ */
289
+ async drainDescendants(parents: readonly Agent[]): Promise<void> {
290
+ const roots = new Set(parents.filter(root => this.ctx.agents.get(root.id) === root && this.rootOf(root) === root))
291
+ for (const root of roots) this.closingRoots.add(root)
292
+ const pending = [...this.materializations].filter(item => roots.has(item.root))
293
+ for (const item of pending) item.controller.abort()
294
+ const targets = [...this.resident.values()].filter(item => roots.has(item.root))
295
+ const disposal = this.disposeRoots(targets, 'scoped activation(s)')
296
+ const [disposed] = await Promise.allSettled([disposal, ...pending.map(item => item.settled)])
297
+ if (disposed.status === 'rejected') throw disposed.reason
298
+ }
299
+
300
+ /**
301
+ * Start one continuable background child and resolve at initial inbox acceptance.
302
+ * Every earlier failure disposes any created handle and rolls back Activation
303
+ * and its capacity slot without returning either id.
304
+ * @param spec - provider, delegation request, and caller cancellation.
305
+ * @param prepare - creation contribution bound to the checked provider.
306
+ * @returns the durable child id and accepted initial prompt message id.
307
+ */
308
+ async startLocal(
309
+ spec: SubagentActivationSpec,
310
+ prepare: (request: ContinuableCreateRequest) => Promise<ContinuableCreateSpec>,
311
+ ): Promise<SubagentActivation & { messageId: MessageId }> {
312
+ const parent = spec.parent
313
+ this.assertAdmitting(parent)
314
+ const ancestry = this.ancestryForChild(parent)
315
+ const reservation = this.reserveName(parent, spec.name)
316
+ const path = joinAgentPath(this.pathOf(parent, ancestry.root), reservation.name)
317
+ try {
318
+ return await this.startLocalNamed(spec, prepare, ancestry, reservation, path)
319
+ } finally {
320
+ reservation.release()
321
+ }
322
+ }
323
+
324
+ /** Create one local child under a name reserved before any await. */
325
+ private startLocalNamed(
326
+ spec: SubagentActivationSpec,
327
+ prepare: (request: ContinuableCreateRequest) => Promise<ContinuableCreateSpec>,
328
+ ancestry: Pick<MaterializeBase, 'root' | 'ancestors'>,
329
+ reservation: SiblingNameReservation,
330
+ path: string | undefined,
331
+ ): Promise<SubagentActivation & { messageId: MessageId }> {
332
+ const parent = spec.parent
333
+ return this.trackStartup(ancestry.root, spec.signal, async (signal) => {
334
+ const persistence = spec.delivery === 'caller' ? this.ctx.get('sessionPersistence') : this.requirePersistence()
335
+ const childId = spec.childId ?? brandString<SessionId>(randomUUID())
336
+ this.assertChildIdAvailable(childId)
337
+ const childDepth = resolveChildDepth(parent, spec.maxDepth)
338
+ // Snapshot before any await: invalid descriptor JSON rejects the call
339
+ // before a child exists, and the detached value is what reaches the log.
340
+ const agentOptions = resolveChildAgentOptions(parent, spec.agentOptions, childDepth)
341
+ const agentProvider = agentOptions.provider
342
+ const agentModel = agentOptions.model
343
+ const agentReasoningEffort = agentOptions.reasoningEffort
344
+ const descriptor = snapshotSubagentDescriptor({
345
+ mode: 'continuable',
346
+ provider: spec.provider,
347
+ label: spec.label,
348
+ ...agentProvider !== undefined ? { agentProvider } : {},
349
+ ...agentModel !== undefined ? { agentModel } : {},
350
+ ...agentReasoningEffort !== undefined ? { agentReasoningEffort } : {},
351
+ })
352
+ // Capture before the first await: a later parent switch belongs to the
353
+ // parent's future, not to this child.
354
+ const delegatedPolicies = captureDelegatedPolicyOverrides(parent)
355
+
356
+ const cwd = await this.resolveDirectory(spec, signal)
357
+ const prepared = await prepare({
358
+ sessionId: childId,
359
+ cwd,
360
+ parent,
361
+ signal,
362
+ })
363
+ signal.throwIfAborted()
364
+ this.assertAdmitting(parent)
365
+
366
+ const inheritedEventCount = SessionLogOffset(prepared.seed?.length ?? 0)
367
+ const seed = prepared.seed
368
+ let established!: Activation
369
+ const messageId = await this.locks.run(childId, async () => {
370
+ signal.throwIfAborted()
371
+ this.assertAdmitting(parent)
372
+ this.assertChildIdAvailable(childId)
373
+ if (spec.childId !== undefined) {
374
+ const persisted = await persistence?.stat(childId, { signal: signal })
375
+ signal.throwIfAborted()
376
+ this.assertAdmitting(parent)
377
+ this.assertChildIdAvailable(childId)
378
+ if (persisted !== undefined) {
379
+ throw new SubagentError(`subagent "${childId}" already exists`, 'DUPLICATE_CHILD')
380
+ }
381
+ }
382
+ const activation = await this.materialize({
383
+ kind: 'local',
384
+ childId,
385
+ provider: spec.provider,
386
+ ...ancestry,
387
+ path,
388
+ create: {
389
+ parent,
390
+ cwd,
391
+ seed,
392
+ meta: childSessionMeta(parent, childDepth, prepared.seed !== undefined, spec.agentPreset),
393
+ inheritedEventCount,
394
+ delegatedPolicies,
395
+ descriptor,
396
+ },
397
+ agentOptions,
398
+ composition: { agentPreset: spec.agentPreset },
399
+ signal,
400
+ delivery: spec.delivery,
401
+ outputSchema: spec.outputSchema,
402
+ })
403
+ established = activation
404
+ const child = requireLocalActivation(activation).handle.agent
405
+ const childHeader = child.session.header
406
+ return await this.submitMaterialized(
407
+ activation,
408
+ spec.delivery !== 'caller'
409
+ ? withResultDeliveryGuidance(spec.prompt)
410
+ : spec.prompt,
411
+ { source: { kind: 'user' }, signal, delivery: 'queue', authorize: () => { this.assertAdmitting(parent) } },
412
+ ancestry.root,
413
+ () => {
414
+ this.assertAdmitting(parent)
415
+ establishCatalogChild(parent.session, childHeader, descriptor, reservation.name)
416
+ },
417
+ )
418
+ })
419
+ return { ...this.receipt(established), childId, messageId }
420
+ })
421
+ }
422
+
423
+ /**
424
+ * Start an external backend under activation ownership.
425
+ * @param spec - task, provider, cancellation, and delivery policy.
426
+ * @param start - execution bound to the checked provider.
427
+ * @returns the accepted activation and its result/disposal capabilities.
428
+ */
429
+ async startExternal(
430
+ spec: SubagentActivationSpec,
431
+ start: (request: ResolvedSubagentStartRequest) => Promise<SubagentRun>,
432
+ ): Promise<SubagentActivation> {
433
+ const { delivery, name: requestedName, parent } = spec
434
+ this.assertAdmitting(parent)
435
+ const ancestry = this.ancestryForChild(parent)
436
+ if (delivery === 'caller' && requestedName !== undefined) {
437
+ throw new SubagentError('agent names require a cataloged child; caller-delivered external runs are not cataloged', 'UNSUPPORTED_CAPABILITY')
438
+ }
439
+ // Only parent-delivered external runs enter the catalog, so only they hold a name.
440
+ const reservation = delivery === 'parent' ? this.reserveName(parent, requestedName) : undefined
441
+ const path = joinAgentPath(this.pathOf(parent, ancestry.root), reservation?.name)
442
+ try {
443
+ return await this.startExternalNamed(spec, start, ancestry, reservation, path)
444
+ } finally {
445
+ reservation?.release()
446
+ }
447
+ }
448
+
449
+ /** Start one external execution, cataloging parent-delivered runs under their reserved name. */
450
+ private startExternalNamed(
451
+ spec: SubagentActivationSpec,
452
+ start: (request: ResolvedSubagentStartRequest) => Promise<SubagentRun>,
453
+ ancestry: Pick<MaterializeBase, 'root' | 'ancestors'>,
454
+ reservation: SiblingNameReservation | undefined,
455
+ path: string | undefined,
456
+ ): Promise<SubagentActivation> {
457
+ const { provider, delivery, childId: _childId, name: _name, ...request } = spec
458
+ const parent = request.parent
459
+ return this.trackStartup(ancestry.root, spec.signal, async (signal) => {
460
+ let activation: Activation | undefined
461
+ try {
462
+ const cwd = await this.resolveDirectory(spec, signal)
463
+ activation = await this.materialize({
464
+ kind: 'external',
465
+ provider,
466
+ ...ancestry,
467
+ path,
468
+ signal,
469
+ delivery,
470
+ start: signal => start({
471
+ ...request, cwd, signal,
472
+ }),
473
+ })
474
+ this.assertAdmitting(parent)
475
+ signal.throwIfAborted()
476
+ if (reservation !== undefined) {
477
+ establishExternalCatalogChild(parent.session, activation.childId, spec.label, reservation.name)
478
+ }
479
+ this.accept(activation)
480
+ return this.receipt(activation)
481
+ } catch (error: unknown) {
482
+ if (activation !== undefined) {
483
+ try {
484
+ await this.dispose(activation)
485
+ } catch (cleanupError: unknown) {
486
+ this.ctx.logger.warn(`subagent "${activation.childId}" admission rollback failed: ${failureMessage(cleanupError)}`)
487
+ }
488
+ }
489
+ throw error
490
+ }
491
+ })
492
+ }
493
+
494
+ /** Capture the explicit or inherited directory while the parent still owns startup. */
495
+ private async resolveDirectory(request: Pick<SubagentStartRequest, 'parent' | 'cwd'>, signal: AbortSignal): Promise<string> {
496
+ const cwd = request.cwd !== undefined && isAbsolute(request.cwd)
497
+ ? request.cwd
498
+ : resolve(await this.ctx.workingDirectory.ensure(request.parent, signal), request.cwd ?? '.')
499
+ signal.throwIfAborted()
500
+ return cwd
501
+ }
502
+
503
+ /**
504
+ * Resolve the live subagent tree root from runtime ownership, independent of creator residency.
505
+ * @param caller - exact live Agent selecting the subagent tree.
506
+ * @returns the live subagent tree root.
507
+ * @throws when the caller has no active runtime owner.
508
+ */
509
+ rootOf(caller: Agent): Agent {
510
+ if (this.ctx.agents.get(caller.id) !== caller) {
511
+ throw new SubagentError('subagent tree access requires the exact live caller', 'UNAUTHORIZED')
512
+ }
513
+ const identity = this.host.identityOf(caller.session)
514
+ const delegated = caller.session.header.origin === 'subagent' || identity != null && caller.session.isOwnSeq(identity.seq)
515
+ const activation = this.resident.get(caller.id)
516
+ if (activation !== undefined && activationAgent(activation) === caller
517
+ && this.ctx.agents.get(activation.root.id) === activation.root) return activation.root
518
+ if (delegated || activation !== undefined) {
519
+ throw new SubagentError('agent has no active runtime owner', 'UNAUTHORIZED')
520
+ }
521
+ return caller
522
+ }
523
+
524
+ /** Capture creation ancestry separately from the root that owns the new instance. */
525
+ private ancestryForChild(creator: Agent): Pick<MaterializeBase, 'root' | 'ancestors'> {
526
+ const root = this.rootOf(creator)
527
+ const ancestors = this.resident.get(creator.id)?.ancestors ?? []
528
+ return { root, ancestors: [...ancestors, creator.id] }
529
+ }
530
+
531
+ /** Claim a sibling name against the creator's committed catalog and in-flight siblings. */
532
+ private reserveName(parent: Agent, requested: string | undefined): SiblingNameReservation {
533
+ return this.names.reserve(parent, catalogNames(this.host.catalogOf(parent.session)), requested)
534
+ }
535
+
536
+ /** Path of an exact live tree member: `''` for the root, undefined for unnamed history. */
537
+ private pathOf(member: Agent, root: Agent): string | undefined {
538
+ return member === root ? '' : this.resident.get(member.id)?.path
539
+ }
540
+
541
+ /**
542
+ * Report the model-facing names of a live member and its direct creator.
543
+ * @param agent - exact live root or resident tree member.
544
+ * @returns `lead` for the root, otherwise the member's and creator's names or Session ids.
545
+ * @throws when the caller has no active runtime owner.
546
+ */
547
+ namesOf(agent: Agent): SubagentMemberNames {
548
+ const root = this.rootOf(agent)
549
+ if (root === agent) return { self: ROOT_AGENT_NAME }
550
+ // rootOf returns another root only for the caller's own resident Activation.
551
+ const activation = this.resident.get(agent.id) as Activation
552
+ const parentId = activation.ancestors.at(-1) as SessionId
553
+ const parentPath = activation.path === undefined
554
+ ? parentId === root.id ? '' : this.resident.get(parentId)?.path
555
+ : parentAgentPath(activation.path)
556
+ return { self: agentAddress(activation.path, agent.id), parent: agentAddress(parentPath, parentId) }
557
+ }
558
+
559
+ /**
560
+ * Deliver to another agent in the subagent tree, restoring only the target when absent.
561
+ * @param sender - exact live root or resident continuable Agent.
562
+ * @param targetId - another member's durable Session id.
563
+ * @param content - model-authored message blocks.
564
+ * @param options - cancellation before inbox acceptance.
565
+ * @returns the accepted inbox message id.
566
+ */
567
+ async sendMessage(sender: Agent, targetId: SessionId, content: ContentBlock[], options: SubagentSendMessageOptions): Promise<MessageId> {
568
+ options.signal.throwIfAborted()
569
+ const root = this.rootOf(sender)
570
+ if (sender.id === targetId) throw new SubagentError('send_message requires another agent in the subagent tree', 'UNAUTHORIZED')
571
+ this.assertAdmitting(sender)
572
+ const message = createAgentMessage(sender, agentAddress(this.pathOf(sender, root), sender.id), content)
573
+ const activation = this.resident.get(sender.id)
574
+ return this.deliverToMember(root, targetId, [...message.content], {
575
+ signal: options.signal, delivery: 'steer', source: message.source,
576
+ authorize: () => { this.assertAdmitting(sender) },
577
+ onAccepted: () => {
578
+ if (activation?.kind === 'local' && activation.ancestors.at(-1) === targetId) {
579
+ activation.omitClosingText = true
580
+ }
581
+ },
582
+ })
583
+ }
584
+
585
+ /** Resolve the live owner through verified creation edges without activating ancestors. */
586
+ private async resolveCreationAncestry(
587
+ source: SessionObservation, signal: AbortSignal, root?: Agent,
588
+ ): Promise<Pick<MaterializeBase, 'root' | 'ancestors' | 'path'>> {
589
+ const ancestors: SessionId[] = []
590
+ const names: (string | undefined)[] = []
591
+ const seen = new Set<SessionId>([source.header.id])
592
+ let { header, projections, inheritedEventCount } = source
593
+ const pathFromRoot = (): string | undefined => names.reduce<string | undefined>(joinAgentPath, '')
594
+ while (true) {
595
+ signal.throwIfAborted()
596
+ const parentId = header.parentSession
597
+ const identity = projections?.values.subagent
598
+ if (parentId === undefined || identity == null || identity.seq < inheritedEventCount) break
599
+ if (seen.has(parentId)) throw new SubagentError('cyclic subagent creation ancestry', 'UNAUTHORIZED')
600
+ seen.add(parentId)
601
+ using parent = await this.observeContinuation(parentId, signal)
602
+ const entry = parent.projections?.values.subagentCatalog?.find(entry => entry.id === header.id)
603
+ if (entry === undefined) {
604
+ throw new SubagentError('subagent is absent from its creator catalog', 'UNAUTHORIZED')
605
+ }
606
+ ancestors.unshift(parentId)
607
+ names.unshift('name' in entry ? entry.name : undefined)
608
+ if (parentId === root?.id) return { root, ancestors, path: pathFromRoot() }
609
+ ;({ header, projections, inheritedEventCount } = parent)
610
+ }
611
+ if (root === undefined && ancestors.length > 0 && header.origin !== 'subagent') {
612
+ const owner = this.ctx.agents.get(header.id)
613
+ if (owner === undefined || this.rootOf(owner) !== owner) {
614
+ throw new SubagentError('subagent tree root is not live', 'CONTINUATION_UNAVAILABLE')
615
+ }
616
+ return { root: owner, ancestors, path: pathFromRoot() }
617
+ }
618
+ throw new SubagentError(`agent "${source.header.id}" is not a member of this subagent tree`, 'UNAUTHORIZED')
619
+ }
620
+
621
+ /**
622
+ * Deliver one host-authored prompt through the target's live subagent tree root.
623
+ * Remote callers must be authorized for the target Session before invoking this operation.
624
+ * @param childId - durable continuable subagent session id.
625
+ * @param content - model-visible prompt blocks.
626
+ * @param options - inbox destination, durable attribution, and cancellation before acceptance.
627
+ * @returns the accepted durable message id.
628
+ */
629
+ async deliverPrompt(
630
+ childId: SessionId,
631
+ content: ContentBlock[],
632
+ options: Pick<ChildDeliveryOptions, 'delivery' | 'source' | 'signal'>,
633
+ ): Promise<MessageId> {
634
+ options.signal.throwIfAborted()
635
+ let root = this.resident.get(childId)?.root
636
+ if (root === undefined) {
637
+ using source = await this.observeContinuation(childId, options.signal)
638
+ ;({ root } = await this.resolveCreationAncestry(source, options.signal))
639
+ }
640
+ return this.deliverToMember(root, childId, content, options)
641
+ }
642
+
643
+ /** Admit local input synchronously before any teardown can begin. */
644
+ private deliver(activation: Activation, message: UserMessage, delivery: SubagentDelivery): void {
645
+ if (activation.closing !== undefined) {
646
+ throw new SubagentError(
647
+ 'subagent activation is being disposed; the message was not accepted',
648
+ 'ACTIVATION_CLOSING',
649
+ )
650
+ }
651
+ const local = requireLocalActivation(activation)
652
+ if (local.structured?.acceptsInput() === false) {
653
+ throw new SubagentError('subagent is submitting or has submitted its structured result; the message was not accepted', 'INPUT_CLOSED')
654
+ }
655
+ if (delivery === 'steer') local.handle.agent.steer(message)
656
+ else local.handle.agent.followup(message)
657
+ }
658
+
659
+ /**
660
+ * Reject one child identity already owned by a live Agent or Session.
661
+ * @param childId - proposed durable child session id.
662
+ */
663
+ private assertChildIdAvailable(childId: SessionId): void {
664
+ if (this.resident.has(childId) || this.ctx.agents.get(childId) !== undefined || this.ctx.get('sessions')?.get(childId) !== undefined) {
665
+ throw new SubagentError(`subagent "${childId}" already exists`, 'DUPLICATE_CHILD')
666
+ }
667
+ }
668
+
669
+ /**
670
+ * Apply activation admission to a resident parent before delivering input.
671
+ * @param parent - exact live Agent receiving the message.
672
+ * @param message - durable user message to deliver.
673
+ * @param delivery - receiving inbox destination.
674
+ */
675
+ private sendWaking(parent: Agent, message: UserMessage, delivery: SubagentDelivery): void {
676
+ const parentActivation = this.resident.get(parent.id)
677
+ if (parentActivation !== undefined && activationAgent(parentActivation) === parent) {
678
+ try {
679
+ this.deliver(parentActivation, message, delivery)
680
+ } finally {
681
+ this.wake(parentActivation)
682
+ }
683
+ return
684
+ }
685
+ if (delivery === 'steer') parent.steer(message)
686
+ else parent.followup(message)
687
+ }
688
+
689
+ /**
690
+ * Reject new work from closing members or subagent trees.
691
+ * @param agent - exact live caller whose instance and subagent tree must admit work.
692
+ */
693
+ private assertAdmitting(agent: Agent): void {
694
+ const closing = this.closingTeardownFor(agent)
695
+ if (closing === undefined) {
696
+ if (this.resident.get(agent.id)?.closing !== undefined) {
697
+ throw new SubagentError(`subagent "${agent.id}" is closing`, 'ACTIVATION_CLOSING')
698
+ }
699
+ return
700
+ }
701
+ throw new SubagentError(
702
+ closing === 'manager'
703
+ ? 'subagents are draining; the operation was not admitted'
704
+ : `subagent tree "${closing.id}" is draining; the operation was not admitted`,
705
+ 'DRAINING',
706
+ )
707
+ }
708
+
709
+ /**
710
+ * Create or resume one child Agent and publish its Activation.
711
+ * @param inputs - reconstruction and admission inputs for the residency epoch.
712
+ * @returns the published process-local Activation.
713
+ */
714
+ private materialize(inputs: MaterializeInputs): Promise<Activation> {
715
+ this.assertAdmitting(inputs.root)
716
+ inputs.signal.throwIfAborted()
717
+ const pool = this.rootPool(inputs.root)
718
+ const releaseSlot = pool.reserve(this.maxActiveSubagents())
719
+ return this.materializeTracked(inputs, releaseSlot).catch((error: unknown) => {
720
+ releaseSlot()
721
+ throw error
722
+ })
723
+ }
724
+
725
+ /** Keep subagent tree shutdown and host waits joined to preparation, publication, and rollback. */
726
+ private trackStartup<T>(root: Agent, signal: AbortSignal, start: (signal: AbortSignal) => Promise<T>): Promise<T> {
727
+ this.assertAdmitting(root)
728
+ signal.throwIfAborted()
729
+ const settled = Promise.withResolvers<void>()
730
+ const controller = new AbortController()
731
+ const materialization: Materialization = { root, settled: settled.promise, controller }
732
+ this.materializations.add(materialization)
733
+ return start(AbortSignal.any([signal, controller.signal])).catch((error: unknown) => {
734
+ if (error instanceof Error && error.name === 'AbortError') this.assertAdmitting(root)
735
+ throw error
736
+ }).finally(() => {
737
+ this.materializations.delete(materialization)
738
+ settled.resolve()
739
+ })
740
+ }
741
+
742
+ /**
743
+ * Stop and release one Activation through its memoized close transaction.
744
+ * @param activation - exact residency epoch to close.
745
+ * @returns the shared close transaction.
746
+ */
747
+ private dispose(activation: Activation): Promise<void> {
748
+ return this.close(activation, () => this.finishDisposal(activation, true))
749
+ }
750
+
751
+ /** Close admission synchronously and share one release, including startup rollback. */
752
+ private close(activation: Activation, release: () => Promise<void>): Promise<void> {
753
+ if (activation.closing !== undefined) return activation.closing
754
+ const completion = Promise.withResolvers<void>()
755
+ activation.closing = completion.promise
756
+ void release().then(completion.resolve, completion.reject)
757
+ return completion.promise
758
+ }
759
+
760
+ /** Dispose independent roots and report every branch failure after all settle. */
761
+ private async disposeRoots(
762
+ roots: readonly Activation[],
763
+ failureSubject: 'activation(s)' | 'scoped activation(s)',
764
+ ): Promise<void> {
765
+ const failures = await Promise.all(roots.map(async (activation) => {
766
+ try {
767
+ await this.dispose(activation)
768
+ return undefined
769
+ } catch (error: unknown) {
770
+ return error
771
+ }
772
+ }))
773
+ const reasons = failures.filter(failure => failure !== undefined)
774
+ if (reasons.length > 0) {
775
+ throw new SubagentError(
776
+ `subagent teardown failed for ${reasons.length} ${failureSubject}: `
777
+ + reasons.map(reason => failureMessage(reason)).join('; '),
778
+ 'ACTIVATION_TEARDOWN_FAILED',
779
+ )
780
+ }
781
+ }
782
+
783
+ /** Return the subagent tree teardown that closed admission for this exact Agent. */
784
+ private closingTeardownFor(agent: Agent): Agent | 'manager' | undefined {
785
+ if (this.draining) return 'manager'
786
+ const root = this.rootOf(agent)
787
+ return this.closingRoots.has(root) ? root : undefined
788
+ }
789
+
790
+ /** Share one capacity pool across every instance in a subagent tree. */
791
+ private rootPool(parent: Agent): ActivationPool {
792
+ let pool = this.rootPools.get(parent)
793
+ if (pool === undefined) {
794
+ pool = new ActivationPool()
795
+ this.rootPools.set(parent, pool)
796
+ }
797
+ return pool
798
+ }
799
+
800
+ /** Perform one tracked materialization through publication or rollback. */
801
+ private async materializeTracked(
802
+ inputs: MaterializeInputs,
803
+ releaseSlot: () => void,
804
+ ): Promise<Activation> {
805
+ const { provider, root } = inputs
806
+ inputs.signal.throwIfAborted()
807
+ let resource: ActivationResource
808
+ if (inputs.kind === 'external') {
809
+ const controller = new AbortController()
810
+ const cancelStartup = (): void => { controller.abort(inputs.signal.reason) }
811
+ inputs.signal.addEventListener('abort', cancelStartup, { once: true })
812
+ try {
813
+ const run = await inputs.start(controller.signal)
814
+ resource = { kind: 'external', run, controller }
815
+ void run.result.catch(() => undefined)
816
+ try { this.assertChildIdAvailable(run.id) } catch (error: unknown) {
817
+ await run.dispose()
818
+ throw error
819
+ }
820
+ } finally {
821
+ inputs.signal.removeEventListener('abort', cancelStartup)
822
+ }
823
+ } else {
824
+ const { create, childId } = inputs
825
+ let structured: StructuredAttachment | undefined
826
+ const setup = async (childCtx: Context, child: Agent): Promise<void> => {
827
+ // Only fresh creation appends the descriptor and delegated policy after
828
+ // the inherited marker; a cold resume replays those persisted events.
829
+ if (inputs.composition.agentPreset !== undefined) {
830
+ await applyChildComposition(childCtx, create?.parent, inputs.composition)
831
+ }
832
+ if (create !== undefined) {
833
+ if (inputs.composition.agentPreset !== undefined) {
834
+ child.session.append('agent-preset/selected', { agentPreset: inputs.composition.agentPreset })
835
+ }
836
+ child.session.append('subagent/descriptor', create.descriptor)
837
+ appendDelegatedPolicyOverrides(child.session, create.delegatedPolicies)
838
+ const workingDirectory = childCtx.get('workingDirectory')
839
+ if (workingDirectory === undefined) throw new Error('local subagents require the working-directory service')
840
+ await workingDirectory.set(child, create.cwd, inputs.signal)
841
+ }
842
+ if (inputs.composition.agentPreset === undefined) await applyChildComposition(childCtx, create?.parent, inputs.composition)
843
+ if (inputs.outputSchema !== undefined) {
844
+ structured = attachStructuredRuntime(childCtx, inputs.outputSchema, () =>
845
+ child.inbox.nextStep.length === 0
846
+ && child.inbox.nextTurn.length === 0,
847
+ )
848
+ }
849
+ }
850
+ const handle = create === undefined
851
+ ? await this.ownerCtx.agents.resume({
852
+ resumeSessionId: childId,
853
+ agentOptions: inputs.agentOptions,
854
+ signal: inputs.signal,
855
+ setup,
856
+ })
857
+ : await this.ownerCtx.agents.create({
858
+ sessionId: childId,
859
+ meta: create.meta,
860
+ ...(create.seed === undefined ? {} : { seed: create.seed }),
861
+ inheritedEventCount: create.inheritedEventCount,
862
+ agentOptions: inputs.agentOptions,
863
+ signal: inputs.signal,
864
+ setup,
865
+ })
866
+
867
+ resource = {
868
+ kind: 'local',
869
+ handle,
870
+ outputStart: handle.agent.session.seq,
871
+ structured,
872
+ failureAt: undefined,
873
+ poke: Promise.withResolvers<void>(),
874
+ omitClosingText: false,
875
+ }
876
+ }
877
+ const childId = resource.kind === 'local' ? resource.handle.agent.id : resource.run.id
878
+ const activation: Activation = {
879
+ releaseSlot,
880
+ childId,
881
+ runId: SubagentRunId(randomUUID()),
882
+ provider,
883
+ ...resource,
884
+ root,
885
+ ancestors: inputs.ancestors,
886
+ path: inputs.path,
887
+ delivery: inputs.delivery ?? 'parent',
888
+ result: Promise.withResolvers<SubagentResult>(),
889
+ closing: undefined,
890
+ accepted: false,
891
+ }
892
+ void activation.result.promise.catch(() => undefined)
893
+ this.resident.set(childId, activation)
894
+ try {
895
+ this.assertAdmitting(root)
896
+ inputs.signal.throwIfAborted()
897
+ const wakeSettlement = (): void => { this.wake(activation) }
898
+ if (activation.kind === 'local') {
899
+ observeLocalFailure(activation, wakeSettlement)
900
+ activation.handle.agent.ctx.on('agent/inbox/inserted', wakeSettlement)
901
+ activation.handle.agent.ctx.on('agent/inbox/claimed', () => {
902
+ // Claimed input means the closing text may report work the child's
903
+ // last message to its parent did not.
904
+ activation.omitClosingText = false
905
+ wakeSettlement()
906
+ })
907
+ activation.handle.agent.ctx.on('agent/inbox/discarded', wakeSettlement)
908
+ // A tool call logged after the message also voids it; logged calls
909
+ // cannot be skipped by tool policy. `send_message` is not concurrency
910
+ // safe, so a later call in its step is logged after it executes.
911
+ activation.handle.agent.ctx.on('session/event', (_session, event) => {
912
+ if (event.type === 'tool/call') activation.omitClosingText = false
913
+ })
914
+ }
915
+ // Listeners may read the resident Agent or drain it immediately. Publish
916
+ // after residency and inbox listeners, as the last rollback-protected step.
917
+ this.host.emitLifecycle('subagent/start', this.runInfo(activation), root)
918
+ } catch (error: unknown) {
919
+ /* v8 ignore next -- rollback failure must not mask the admission failure
920
+ * that prevented this operation from returning an accepted message id. */
921
+ await this.rollbackUnpublished(activation, error).catch(() => undefined)
922
+ throw error
923
+ }
924
+ return activation
925
+ }
926
+
927
+ /** Identity shared by one residency epoch's start/end pair, including cold resumes. */
928
+ private runInfo(activation: Activation): SubagentRunInfo {
929
+ return {
930
+ runId: activation.runId,
931
+ provider: activation.provider,
932
+ parentSessionId: activation.ancestors.at(-1) as SessionId,
933
+ id: activation.childId,
934
+ local: activation.kind === 'local',
935
+ }
936
+ }
937
+
938
+ /** Record acceptance and begin settlement observation before returning the receipt. */
939
+ private accept(activation: Activation): void {
940
+ activation.accepted = true
941
+ if (activation.kind === 'local') {
942
+ this.watchLocalSettlement(activation)
943
+ } else {
944
+ const finish = (): Promise<void> => this.close(activation, () => this.finishDisposal(activation, false))
945
+ void activation.run.result.then(finish, finish).catch((error: unknown) => { this.reportTeardownFailure(activation, error) })
946
+ }
947
+ }
948
+
949
+ /** Release an Activation whose start edge was not published. */
950
+ private rollbackUnpublished(activation: Activation, error: unknown): Promise<void> {
951
+ return this.close(activation, async () => {
952
+ try {
953
+ await (activation.kind === 'local' ? activation.handle.dispose() : activation.run.dispose())
954
+ } finally {
955
+ this.resident.delete(activation.childId)
956
+ activation.releaseSlot()
957
+ activation.result.reject(error)
958
+ }
959
+ })
960
+ }
961
+
962
+ /** Let a settlement watcher re-check residency after relevant state changes. */
963
+ private wake(activation: Activation): void {
964
+ if (activation.kind === 'external') return
965
+ activation.poke.resolve()
966
+ activation.poke = Promise.withResolvers<void>()
967
+ }
968
+
969
+ /** Follow one Activation to natural settlement. */
970
+ private watchLocalSettlement(activation: LocalActivation): void {
971
+ void (async () => {
972
+ while (true) {
973
+ const idleObservation = activation.poke
974
+ await activation.handle.agent.whenIdle()
975
+ if (activation.closing !== undefined) return
976
+ const readiness = await this.locks.run(activation.childId, () => Promise.resolve(
977
+ this.settlementState(activation, idleObservation),
978
+ ))
979
+ if (readiness === 'closed') return
980
+ if (readiness === 'retry') continue
981
+ if (readiness === 'wait') {
982
+ await idleObservation.promise
983
+ continue
984
+ }
985
+
986
+ const finalSeq = activation.handle.agent.session.seq
987
+ await this.flushFinalState(activation)
988
+ const attempt = await this.locks.run<SettlementAttempt>(activation.childId, () => {
989
+ const state = this.settlementState(activation, idleObservation)
990
+ if (state !== 'ready') return Promise.resolve(state)
991
+ if (activation.handle.agent.session.seq !== finalSeq) {
992
+ return Promise.resolve('retry')
993
+ }
994
+ let done!: Promise<void>
995
+ try {
996
+ void activation.handle.agent.runMaintenance(() => {
997
+ done = this.close(activation, () => this.finishDisposal(activation, false))
998
+ return Promise.resolve()
999
+ })
1000
+ } catch (_error: unknown) {
1001
+ // Another activity already owns the Agent's idle phase.
1002
+ return Promise.resolve('retry')
1003
+ }
1004
+ return Promise.resolve({ done })
1005
+ })
1006
+
1007
+ if (typeof attempt === 'string') {
1008
+ if (attempt === 'closed') return
1009
+ continue
1010
+ }
1011
+ try {
1012
+ await attempt.done
1013
+ } catch (error: unknown) {
1014
+ this.reportTeardownFailure(activation, error)
1015
+ }
1016
+ return
1017
+ }
1018
+ })()
1019
+ }
1020
+
1021
+ /** Report disposal failure once after the natural settlement observer finishes. */
1022
+ private reportTeardownFailure(activation: Activation, error: unknown): void {
1023
+ this.ctx.logger.warn(`subagent "${activation.childId}" activation teardown failed: ${failureMessage(error)}`)
1024
+ }
1025
+
1026
+ /** Check pending input before closing admission. */
1027
+ private settlementState(
1028
+ activation: LocalActivation,
1029
+ observation: PromiseWithResolvers<void>,
1030
+ ): SettlementState {
1031
+ if (activation.closing !== undefined) return 'closed'
1032
+ if (activation.poke !== observation) return 'retry'
1033
+ const inbox = activation.handle.agent.inbox
1034
+ if (activation.failureAt === undefined && (inbox.nextTurn.length > 0 || inbox.nextStep.length > 0)) return 'wait'
1035
+ return 'ready'
1036
+ }
1037
+
1038
+ /** Stop and release one instance without affecting its creation descendants. */
1039
+ private async finishDisposal(activation: Activation, stop: boolean): Promise<void> {
1040
+ this.wake(activation)
1041
+ const { childId } = activation
1042
+ const failures: SubagentError[] = []
1043
+ let result: SubagentResult = { output: [], stopReason: 'error' }
1044
+ let resultFailure: { error: unknown } | undefined
1045
+ let externalDisposal: Promise<void> | undefined
1046
+ const child = activationAgent(activation)
1047
+ const detail = (error: unknown): string => child === undefined
1048
+ ? failureMessage(error)
1049
+ : errorChain(error)
1050
+ try {
1051
+ if (activation.kind === 'external') {
1052
+ if (stop) {
1053
+ activation.controller.abort({ kind: 'parent' })
1054
+ // Some backends settle their result only when disposal begins.
1055
+ externalDisposal = Promise.resolve().then(() => activation.run.dispose())
1056
+ void externalDisposal.catch(() => undefined)
1057
+ }
1058
+ result = await activation.run.result
1059
+ } else {
1060
+ if (stop) {
1061
+ activation.handle.agent.cancel({ kind: 'parent' })
1062
+ const idle = activation.handle.agent.whenIdle()
1063
+ await idle
1064
+ await this.flushFinalState(activation)
1065
+ }
1066
+ result = captureLocalResult(activation)
1067
+ }
1068
+ } catch (error: unknown) {
1069
+ resultFailure = { error }
1070
+ failures.push(new SubagentError(
1071
+ `subagent "${childId}" activation teardown failed: ${detail(error)}`,
1072
+ 'ACTIVATION_TEARDOWN_FAILED',
1073
+ { cause: error },
1074
+ ))
1075
+ }
1076
+ try {
1077
+ if (activation.kind === 'local') await activation.handle.dispose()
1078
+ else await (externalDisposal ?? activation.run.dispose())
1079
+ } catch (error: unknown) {
1080
+ failures.push(new SubagentError(
1081
+ `subagent "${childId}" activation handle disposal failed: ${detail(error)}`,
1082
+ 'ACTIVATION_TEARDOWN_FAILED',
1083
+ { cause: error },
1084
+ ))
1085
+ }
1086
+
1087
+ let failure: SubagentError | undefined
1088
+ if (failures.length === 1) {
1089
+ failure = failures[0]
1090
+ } else if (failures.length > 1) {
1091
+ failure = new SubagentError(
1092
+ `subagent "${childId}" activation teardown failed at ${failures.length} boundaries: `
1093
+ + failures.map(item => detail(item)).join('; '),
1094
+ 'ACTIVATION_TEARDOWN_FAILED',
1095
+ { cause: new AggregateError(failures) },
1096
+ )
1097
+ }
1098
+ if (failure !== undefined && result.stopReason === 'completed' && child !== undefined
1099
+ && (child.inbox.nextStep.length > 0 || child.inbox.nextTurn.length > 0)) {
1100
+ result = { ...result, stopReason: 'error' }
1101
+ }
1102
+ this.resident.delete(childId)
1103
+ activation.releaseSlot()
1104
+ const terminal: SubagentResult = failure === undefined ? result : { output: [], stopReason: 'error' }
1105
+ this.notifySettlement(activation, result)
1106
+ // The sole end publication follows resource release and parent notification,
1107
+ // before result delivery.
1108
+ this.host.emitLifecycle('subagent/end', {
1109
+ ...this.runInfo(activation),
1110
+ stopReason: terminal.stopReason,
1111
+ ...terminal.output.length === 0 ? {} : { lastAssistantMessage: terminal.output },
1112
+ }, activation.root)
1113
+ if (resultFailure === undefined) activation.result.resolve(result)
1114
+ else activation.result.reject(resultFailure.error)
1115
+ if (failure !== undefined) throw failure
1116
+ }
1117
+
1118
+ /** Deliver the captured execution result to the durable direct parent after cleanup. */
1119
+ private notifySettlement(activation: Activation, terminal: SubagentResult): void {
1120
+ if (!activation.accepted || activation.delivery === 'caller') return
1121
+ try {
1122
+ const parentId = activation.ancestors.at(-1) as SessionId
1123
+ const parent = this.ctx.agents.get(parentId)
1124
+ if (parent === undefined || parent.ctx.fiber.state !== FiberState.ACTIVE
1125
+ || this.rootOf(parent) !== activation.root) return
1126
+ const message = createSettlementMessage(
1127
+ activation.childId, agentAddress(activation.path, activation.childId), terminal,
1128
+ activation.kind === 'local', activation.kind === 'local' && activation.omitClosingText,
1129
+ )
1130
+ if (this.closingTeardownFor(parent) !== undefined) {
1131
+ parent.inject(message)
1132
+ return
1133
+ }
1134
+ this.sendWaking(parent, message, parent.status === 'idle' ? 'queue' : 'steer')
1135
+ } catch (error: unknown) {
1136
+ this.ctx.logger.warn(
1137
+ `subagent "${activation.childId}" settlement notice was not delivered to its parent: `
1138
+ + errorChain(error),
1139
+ )
1140
+ }
1141
+ }
1142
+
1143
+ /** Request a best-effort final session flush before closing natural-settlement admission. */
1144
+ private async flushFinalState(activation: LocalActivation): Promise<void> {
1145
+ try {
1146
+ await activation.handle.agent.ctx.sessions.flush(activation.handle.agent.session)
1147
+ } catch (error: unknown) {
1148
+ this.ctx.logger.warn(
1149
+ `subagent "${activation.childId}" best-effort final session flush failed; `
1150
+ + `the persisted state may be unavailable or stale on resume: ${errorChain(error)}`,
1151
+ )
1152
+ }
1153
+ }
1154
+
1155
+ /** Return capabilities bound to an exact activation instead of a future same-id instance. */
1156
+ private receipt(activation: Activation): SubagentActivation {
1157
+ return {
1158
+ childId: activation.childId,
1159
+ name: agentAddress(activation.path, activation.childId),
1160
+ result: activation.result.promise,
1161
+ dispose: () => this.dispose(activation),
1162
+ }
1163
+ }
1164
+
1165
+ /** Serialize target restoration and inbox admission; closure is awaited outside the lock. */
1166
+ private async deliverToMember(
1167
+ root: Agent, childId: SessionId, content: ContentBlock[], options: ChildDeliveryOptions,
1168
+ ): Promise<MessageId> {
1169
+ while (true) {
1170
+ this.assertAdmitting(root)
1171
+ options.signal.throwIfAborted()
1172
+ const result = await this.locks.run(childId, async () => {
1173
+ if (childId === root.id) {
1174
+ if (contentHasImage(content)) await this.assertImageCapable(root, options.signal)
1175
+ options.signal.throwIfAborted()
1176
+ options.authorize?.()
1177
+ this.assertAdmitting(root)
1178
+ const message = createUserMessage({ content, source: options.source })
1179
+ this.sendWaking(root, message, options.delivery)
1180
+ options.onAccepted?.()
1181
+ return { messageId: message.id }
1182
+ }
1183
+ const activation = this.resident.get(childId)
1184
+ if (activation === undefined) {
1185
+ const restored = await this.restoreTarget(root, childId, options.signal)
1186
+ return { messageId: await this.submitMaterialized(restored, content, options, root) }
1187
+ }
1188
+ if (activation.root !== root) throw new SubagentError('target belongs to another subagent tree', 'UNAUTHORIZED')
1189
+ requireLocalActivation(activation)
1190
+ if (activation.closing === undefined && contentHasImage(content)) {
1191
+ await this.assertImageCapable(requireLocalActivation(activation).handle.agent, options.signal)
1192
+ }
1193
+ if (activation.closing !== undefined) return { closing: activation.closing }
1194
+ const messageId = this.submitAdmitted(activation, content, options, root)
1195
+ return { messageId }
1196
+ })
1197
+ if ('messageId' in result) return result.messageId
1198
+ await Promise.allSettled([result.closing])
1199
+ }
1200
+ }
1201
+
1202
+ /** Read continuation history, preserving cancellation and reporting unavailable storage. */
1203
+ private async observeContinuation(childId: SessionId, signal: AbortSignal): Promise<SessionObservation> {
1204
+ const query = this.requireSessionQuery()
1205
+ try {
1206
+ return await query.observeSession(childId, { signal })
1207
+ } catch (error: unknown) {
1208
+ signal.throwIfAborted()
1209
+ throw new SubagentError(`subagent "${childId}" is unavailable`, 'NOT_RESUMABLE', { cause: error })
1210
+ }
1211
+ }
1212
+
1213
+ /** Reconstruct only the target under its subagent tree root; the caller owns acceptance or rollback. */
1214
+ private async restoreTarget(root: Agent, childId: SessionId, signal: AbortSignal): Promise<Activation> {
1215
+ return this.trackStartup(root, signal, async (signal) => {
1216
+ using source = await this.observeContinuation(childId, signal)
1217
+ this.assertAdmitting(root)
1218
+ const ownEvents = source.events.slice(source.inheritedEventCount)
1219
+ const descriptor = foldSubagentDescriptor(ownEvents)
1220
+ if (descriptor === undefined || descriptor.mode !== 'continuable') {
1221
+ throw new SubagentError(
1222
+ `subagent "${childId}" has no supported continuation state and cannot be resumed; choose a different target`,
1223
+ 'NOT_RESUMABLE',
1224
+ )
1225
+ }
1226
+ const { ancestors, path } = await this.resolveCreationAncestry(source, signal, root)
1227
+ let activation: Activation
1228
+ try {
1229
+ const projectedPreset = source.projections?.values.agentPreset
1230
+ if (projectedPreset === undefined && source.events.some(event => event.type === 'agent-preset/selected')) {
1231
+ throw new SubagentError(`subagent "${childId}" has no agent preset projection for restoration`, 'NOT_RESUMABLE')
1232
+ }
1233
+ const agentPreset = projectedPreset ?? source.header.agentPreset
1234
+ activation = await this.materialize({
1235
+ kind: 'local',
1236
+ childId,
1237
+ provider: descriptor.provider,
1238
+ root,
1239
+ ancestors,
1240
+ path,
1241
+ agentOptions: {
1242
+ ...descriptor.agentProvider !== undefined ? { provider: descriptor.agentProvider } : {},
1243
+ ...descriptor.agentModel !== undefined ? { model: descriptor.agentModel } : {},
1244
+ ...descriptor.agentReasoningEffort !== undefined
1245
+ ? { reasoningEffort: ReasoningEffortId(descriptor.agentReasoningEffort) }
1246
+ : {},
1247
+ },
1248
+ composition: {
1249
+ agentPreset: agentPreset ?? undefined,
1250
+ persona: descriptor.persona,
1251
+ toolFilter: descriptor.toolFilter,
1252
+ },
1253
+ signal,
1254
+ })
1255
+ } catch (error: unknown) {
1256
+ signal.throwIfAborted()
1257
+ if (error instanceof SubagentError) throw error
1258
+ throw new SubagentError(`subagent "${childId}" is unavailable`, 'NOT_RESUMABLE', { cause: error })
1259
+ }
1260
+ return activation
1261
+ })
1262
+ }
1263
+
1264
+ /** Admit a materialized child, commit its creation fact, and release it on failure. */
1265
+ private async submitMaterialized(
1266
+ activation: Activation,
1267
+ content: ContentBlock[],
1268
+ options: ChildDeliveryOptions,
1269
+ parent: Agent,
1270
+ commit?: () => void,
1271
+ ): Promise<MessageId> {
1272
+ try {
1273
+ if (contentHasImage(content)) {
1274
+ await this.assertImageCapable(requireLocalActivation(activation).handle.agent, options.signal)
1275
+ if (activation.closing !== undefined) {
1276
+ throw new SubagentError(`subagent "${activation.childId}" is closing`, 'ACTIVATION_CLOSING')
1277
+ }
1278
+ }
1279
+ const messageId = this.submitAdmitted(activation, content, options, parent)
1280
+ commit?.()
1281
+ this.accept(activation)
1282
+ return messageId
1283
+ } catch (error: unknown) {
1284
+ try {
1285
+ await this.dispose(activation)
1286
+ } catch (cleanupError: unknown) {
1287
+ this.ctx.logger.warn(
1288
+ `subagent continuation: disposal after admission or catalog append failure also failed: ${String(cleanupError)}`,
1289
+ )
1290
+ }
1291
+ throw error
1292
+ }
1293
+ }
1294
+
1295
+ /** Build and submit one message across the final synchronous admission cutoff. */
1296
+ private submitAdmitted(
1297
+ activation: Activation,
1298
+ content: ContentBlock[],
1299
+ options: ChildDeliveryOptions,
1300
+ parent: Agent,
1301
+ ): MessageId {
1302
+ const message = createUserMessage({ content, source: options.source })
1303
+ options.signal.throwIfAborted()
1304
+ options.authorize?.()
1305
+ this.assertAdmitting(parent)
1306
+ try {
1307
+ this.deliver(activation, message, options.delivery)
1308
+ } finally {
1309
+ this.wake(activation)
1310
+ }
1311
+ options.onAccepted?.()
1312
+ return message.id
1313
+ }
1314
+
1315
+ /** Refuse image content for a child whose fixed model accepts text only. */
1316
+ private async assertImageCapable(
1317
+ agent: Agent,
1318
+ signal: AbortSignal,
1319
+ ): Promise<void> {
1320
+ const { provider, model } = agent.options
1321
+ if (provider === undefined || model === undefined) return
1322
+ const llm = this.ctx.get('llm')
1323
+ /* v8 ignore next -- without an LLM registry, delivery defers to projection. */
1324
+ if (llm === undefined) return
1325
+ const info = await llm.resolveModelInfo(provider, model, signal)
1326
+ if (info.inputModalities !== undefined && !info.inputModalities.includes('image')) {
1327
+ throw new SubagentError(
1328
+ `Model "${model}" does not support image input.`,
1329
+ 'MODEL_DOES_NOT_SUPPORT_IMAGES',
1330
+ )
1331
+ }
1332
+ }
1333
+
1334
+ /** Resolve the persistence service continuable children require, or fail loud. */
1335
+ private requirePersistence(): SessionPersistence {
1336
+ const persistence = this.ctx.get('sessionPersistence')
1337
+ if (persistence === undefined) {
1338
+ throw new SubagentError(
1339
+ 'continuable subagents require session persistence (load a dsh-session-persistence backend)',
1340
+ 'PERSISTENCE_UNAVAILABLE',
1341
+ )
1342
+ }
1343
+ return persistence
1344
+ }
1345
+
1346
+ /** Resolve the Session query service used for cold child observations. */
1347
+ private requireSessionQuery(): SessionQueryEngine {
1348
+ const query = this.ctx.get('sessionQuery')
1349
+ if (query === undefined) {
1350
+ throw new SubagentError(
1351
+ 'continuable subagents require session query (load @deepseek-ai/dsh-session-query)',
1352
+ 'CONTINUATION_UNAVAILABLE',
1353
+ )
1354
+ }
1355
+ return query
1356
+ }
1357
+ }
1358
+
1359
+ export default SubagentManager