@deepseek-ai/dsh-subagent 0.2.0-rc.2 → 0.2.1-alpha.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 (44) hide show
  1. package/README.i18n.yaml +36 -36
  2. package/README.md +33 -27
  3. package/README.zh.md +33 -27
  4. package/lib/index.js +1436 -1304
  5. package/lib/typert.host.js +73 -60
  6. package/lib/typert.remote-client.js +2 -2
  7. package/lib/types/activation.d.ts +114 -0
  8. package/lib/types/activation.js +112 -0
  9. package/lib/types/catalog.d.ts +14 -6
  10. package/lib/types/catalog.js +34 -30
  11. package/lib/types/child-agent.d.ts +1 -3
  12. package/lib/types/child-agent.js +1 -3
  13. package/lib/types/continuation-messages.d.ts +4 -3
  14. package/lib/types/continuation-messages.js +13 -5
  15. package/lib/types/control-types.d.ts +7 -0
  16. package/lib/types/descriptor.d.ts +7 -46
  17. package/lib/types/descriptor.js +20 -21
  18. package/lib/types/index.d.ts +52 -53
  19. package/lib/types/index.js +75 -95
  20. package/lib/types/internal.d.ts +1 -1
  21. package/lib/types/lifecycle.d.ts +28 -58
  22. package/lib/types/lifecycle.js +9 -74
  23. package/lib/types/list-children.js +1 -1
  24. package/lib/types/manager.d.ts +247 -0
  25. package/lib/types/manager.js +1294 -0
  26. package/lib/types/out-of-process.d.ts +2 -28
  27. package/lib/types/out-of-process.js +3 -44
  28. package/lib/types/projection-types.d.ts +3 -0
  29. package/lib/types/structured.d.ts +49 -0
  30. package/lib/types/structured.js +130 -0
  31. package/lib/types/types.d.ts +57 -81
  32. package/lib/types/types.js +1 -1
  33. package/package.json +53 -63
  34. package/lib/invariant.js +0 -76
  35. package/lib/types/continuation-activation.d.ts +0 -267
  36. package/lib/types/continuation-activation.js +0 -700
  37. package/lib/types/continuation.d.ts +0 -124
  38. package/lib/types/continuation.js +0 -455
  39. package/lib/types/inbox.d.ts +0 -43
  40. package/lib/types/inbox.js +0 -61
  41. package/lib/types/invariant.d.ts +0 -13
  42. package/lib/types/invariant.js +0 -91
  43. package/lib/types/run-settlement.d.ts +0 -17
  44. package/lib/types/run-settlement.js +0 -70
@@ -83,7 +83,7 @@ export const TYPERT = {
83
83
  typeSymbol: '@deepseek-ai/dsh-subagent/client#SubagentInterruptReceipt',
84
84
  create: _deepseek_ai_dsh_subagent_subagents_interruptByParent_result$schema,
85
85
  },
86
- sourceLocation: {"file":"packages/subagent/subagent/src/index.ts","line":483,"column":3},
86
+ sourceLocation: {"file":"packages/subagent/subagent/src/index.ts","line":513,"column":3},
87
87
  },
88
88
  {
89
89
  id: '@deepseek-ai/dsh-subagent#subagents/prompt',
@@ -109,16 +109,16 @@ export const TYPERT = {
109
109
  typeSymbol: '@deepseek-ai/dsh-subagent/client#SubagentPromptReceipt',
110
110
  create: _deepseek_ai_dsh_subagent_subagents_prompt_result$schema,
111
111
  },
112
- sourceLocation: {"file":"packages/subagent/subagent/src/index.ts","line":416,"column":9},
112
+ sourceLocation: {"file":"packages/subagent/subagent/src/index.ts","line":446,"column":9},
113
113
  },
114
114
  ],
115
115
  model: {
116
116
  "services": [
117
117
  {
118
- "description": "Named provider registry with one-shot runs, durable discovery, and continuable-child operations.",
119
- "summary": "Named provider registry with one-shot runs, durable discovery, and continuable-child operations.",
118
+ "description": "Named provider registry with managed activations, durable discovery, and local child messaging.",
119
+ "summary": "Named provider registry with managed activations, durable discovery, and local child messaging.",
120
120
  "tags": [],
121
- "jsDoc": "/** Named provider registry with one-shot runs, durable discovery, and continuable-child operations. */",
121
+ "jsDoc": "/** Named provider registry with managed activations, durable discovery, and local child messaging. */",
122
122
  "key": "subagents",
123
123
  "exportName": "SubagentRuntime",
124
124
  "members": [
@@ -131,10 +131,24 @@ export const TYPERT = {
131
131
  },
132
132
  {
133
133
  "kind": "method",
134
- "name": "startContinuable",
135
- "signature": "async startContinuable(spec: ContinuableStartSpec): Promise<ContinuableStart>",
136
- "summary": "Establish one durable continuable child and deliver its initial prompt.",
137
- "jsDoc": "/**\n * Establish one durable continuable child and deliver its initial prompt.\n * Resolves when the child's inbox accepts that prompt, without waiting for the\n * turn to start or for the message to reach the Session log; any earlier\n * failure rejects with no ids and rolls back the child entirely.\n * @param spec - provider, delegation request, and caller cancellation.\n * @returns the durable child id and the accepted prompt's message id.\n * @throws when continuation services are unavailable or materialization fails.\n */"
134
+ "name": "startActivation",
135
+ "signature": "startActivation(spec: SubagentActivationSpec & { readonly childId: SessionId }): Promise<SubagentActivation & { readonly messageId: MessageId }>",
136
+ "summary": "Start a local child under its reserved identity.",
137
+ "jsDoc": "/**\n * Start a local child under its reserved identity.\n * @param spec - local task, reserved child id, and result recipient.\n * @returns activation with its accepted initial message id.\n */"
138
+ },
139
+ {
140
+ "kind": "method",
141
+ "name": "startActivation",
142
+ "signature": "startActivation(spec: SubagentActivationSpec): Promise<SubagentActivation>",
143
+ "summary": "Start a local or external child.",
144
+ "jsDoc": "/**\n * Start a local or external child.\n * @param spec - task, backend, and result recipient.\n * @returns activation with a message id only for local children.\n */"
145
+ },
146
+ {
147
+ "kind": "method",
148
+ "name": "waitForChildren",
149
+ "signature": "async waitForChildren(parent: Agent): Promise<boolean>",
150
+ "summary": "Join progressing descendants without cancelling them.",
151
+ "jsDoc": "/**\n * Join progressing descendants without cancelling them. Idle descendants whose\n * inboxes require a later wake stay resident and do not delay host completion.\n * @param parent - the exact parent whose descendant work is observed.\n * @returns whether work was joined; hosts recheck parent idle after true.\n */"
138
152
  },
139
153
  {
140
154
  "kind": "method",
@@ -147,22 +161,22 @@ export const TYPERT = {
147
161
  "kind": "method",
148
162
  "name": "interrupt",
149
163
  "signature": "interrupt(targetSessionId: SessionId, authority: SubagentInterruptAuthority): void",
150
- "summary": "Interrupt one live continuable child's current turn under a human parent address or an exact live ancestor Agent.",
151
- "jsDoc": "/**\n * Interrupt one live continuable child's current turn under a human parent\n * address or an exact live ancestor Agent. Fire-and-return: the cancel\n * signal is issued before this returns, but the target may keep running\n * until it observes the signal. Unclaimed pending inbox work, the Activation,\n * and published descendants are preserved; claimed work is not requeued.\n * Once the interrupted driver is idle, a waking send resumes the parked FIFO\n * queue. An absent target — including a one-shot or unknown id —\n * is an accepted no-op, as is a manager-less composition, which cannot own a\n * live Activation.\n * @param targetSessionId - the durable child session id to interrupt.\n * @param authority - the human parent address or exact live ancestor Agent.\n * @throws {SubagentError} `UNAUTHORIZED` when the authority does not own the\n * live target.\n */"
164
+ "summary": "Interrupt one live child's current execution under a human parent address or an exact live ancestor Agent.",
165
+ "jsDoc": "/**\n * Interrupt one live child's current execution under a human parent\n * address or an exact live ancestor Agent. Fire-and-return: the cancel\n * signal is issued before this returns, but the target may keep running\n * until it observes the signal. Unclaimed pending inbox work, the Activation,\n * and published descendants are preserved; claimed work is not requeued.\n * Once the interrupted Agent is idle, a waking send resumes the parked FIFO\n * queue. External backends stop their single execution. An absent target\n * is an accepted no-op, as is a manager-less composition, which cannot own a\n * live Activation.\n * @param targetSessionId - the durable child session id to interrupt.\n * @param authority - the human parent address or exact live ancestor Agent.\n * @throws {SubagentError} `UNAUTHORIZED` when the authority does not own the\n * live target.\n */"
152
166
  },
153
167
  {
154
168
  "kind": "method",
155
- "name": "drainContinuableDescendants",
156
- "signature": "async drainContinuableDescendants(parents: readonly Agent[]): Promise<void>",
157
- "summary": "Close continuable admission below exact live parent Agents, stop only their visible descendant Activations synchronously, then await admitted scoped materializations and release those forests child-first.",
158
- "jsDoc": "/**\n * Close continuable admission below exact live parent Agents, stop only their\n * visible descendant Activations synchronously, then await admitted scoped\n * materializations and release those forests child-first. The scoped cutoff\n * lasts until each exact parent leaves the registry; unrelated parent trees\n * remain live.\n * @param parents - exact host-owned parent Agents entering teardown.\n * @returns once every retained descendant Activation released its `AgentHandle`.\n * @throws an aggregate error after all branches settle when any failed.\n */"
169
+ "name": "drainDescendants",
170
+ "signature": "async drainDescendants(parents: readonly Agent[]): Promise<void>",
171
+ "summary": "Close subagent admission below exact live parent Agents, stop only their visible descendant Activations synchronously, then await admitted scoped materializations and release those forests child-first.",
172
+ "jsDoc": "/**\n * Close subagent admission below exact live parent Agents, stop only their\n * visible descendant Activations synchronously, then await admitted scoped\n * materializations and release those forests child-first. The scoped cutoff\n * lasts until each exact parent leaves the registry; unrelated parent trees\n * remain live.\n * @param parents - exact host-owned parent Agents entering teardown.\n * @returns once every retained descendant activation released its execution handle.\n * @throws an aggregate error after all branches settle when any failed.\n */"
159
173
  },
160
174
  {
161
175
  "kind": "method",
162
- "name": "drainContinuableChildren",
163
- "signature": "async drainContinuableChildren(parent: Agent, childIds: readonly SessionId[]): Promise<void>",
164
- "summary": "Release selected resident continuable direct children of one exact live parent.",
165
- "jsDoc": "/**\n * Release selected resident continuable direct children of one exact live\n * parent. Other children of the same parent remain admitted and resident.\n * Absent targets and a manager-less composition are accepted no-ops.\n * @param parent - exact live direct parent authorizing the selected release.\n * @param childIds - durable direct-child ids to release when resident.\n * @returns once every selected Activation released its `AgentHandle`.\n * @throws {SubagentError} `UNAUTHORIZED` when a resident target belongs to a\n * different parent or the supplied parent identity is stale.\n */"
176
+ "name": "drainChildren",
177
+ "signature": "async drainChildren(parent: Agent, childIds: readonly SessionId[]): Promise<void>",
178
+ "summary": "Release selected resident direct children of one exact live parent.",
179
+ "jsDoc": "/**\n * Release selected resident direct children of one exact live\n * parent. Other children of the same parent remain admitted and resident.\n * Absent targets and a manager-less composition are accepted no-ops.\n * @param parent - exact live direct parent authorizing the selected release.\n * @param childIds - durable direct-child ids to release when resident.\n * @returns once every selected activation released its execution handle.\n * @throws {SubagentError} `UNAUTHORIZED` when a resident target belongs to a\n * different parent or the supplied parent identity is stale.\n */"
166
180
  },
167
181
  {
168
182
  "kind": "method",
@@ -176,7 +190,7 @@ export const TYPERT = {
176
190
  "name": "listDescendants",
177
191
  "signature": "listDescendants(rootSessionId: SessionId, signal?: AbortSignal): Promise<SubagentDescendantListEntry[]>",
178
192
  "summary": "Recursively list reachable parent catalogs in stable pre-order, preserving each catalog's event order.",
179
- "jsDoc": "/**\n * Recursively list reachable parent catalogs in stable pre-order, preserving\n * each catalog's event order. Each row carries its catalog parent and depth;\n * one-shot and unknown-mode children remain traversal nodes. Unknown modes\n * produce unsupported diagnostics. Unreadable child catalogs produce corrupt\n * or unavailable diagnostics and stop only that branch. Root read failures,\n * missing services or projections, and cancellation reject the whole listing.\n * Each catalog is observed once and released before the next read. No Agent\n * is loaded or resumed; Sessions absent from reachable catalogs are omitted.\n * @param rootSessionId - session whose catalog starts descendant discovery.\n * @param signal - cancellation forwarded to and checked around each catalog read.\n * @returns children and branch diagnostics in parent-catalog pre-order.\n * @throws {@link SubagentError} when listing dependencies are unavailable or the caller cancels.\n * @throws SessionQueryError when the root catalog cannot be read.\n */"
193
+ "jsDoc": "/**\n * Recursively list reachable parent catalogs in stable pre-order, preserving\n * each catalog's event order. Each row carries its catalog parent and depth;\n * external children are leaves; one-shot and unknown-mode children remain\n * traversal nodes. Unknown modes\n * produce unsupported diagnostics. Unreadable child catalogs produce corrupt\n * or unavailable diagnostics and stop only that branch. Root read failures,\n * missing services or projections, and cancellation reject the whole listing.\n * Each catalog is observed once and released before the next read. No Agent\n * is loaded or resumed; Sessions absent from reachable catalogs are omitted.\n * @param rootSessionId - session whose catalog starts descendant discovery.\n * @param signal - cancellation forwarded to and checked around each catalog read.\n * @returns children and branch diagnostics in parent-catalog pre-order.\n * @throws {@link SubagentError} when listing dependencies are unavailable or the caller cancels.\n * @throws SessionQueryError when the root catalog cannot be read.\n */"
180
194
  },
181
195
  {
182
196
  "kind": "method",
@@ -197,7 +211,7 @@ export const TYPERT = {
197
211
  "name": "registerProvider",
198
212
  "signature": "registerProvider(provider: SubagentProvider): () => void",
199
213
  "summary": "Register a provider under its name.",
200
- "jsDoc": "/**\n * Register a provider under its name. Registration is effect-scoped and HMR\n * safe; removing a provider blocks new starts but does not revoke runs that\n * were already returned to their holders.\n * @param provider - the trusted provider implementation.\n * @returns the exact Cordis effect disposer.\n */"
214
+ "jsDoc": "/**\n * Register a provider under its name. Registration is effect-scoped and HMR\n * safe; removing a provider blocks new starts but does not revoke runs that\n * were already returned to their holders. Providers without either execution\n * method are rejected with UNSUPPORTED_CAPABILITY before registration.\n * @param provider - the trusted provider implementation.\n * @returns the exact Cordis effect disposer.\n */"
201
215
  },
202
216
  {
203
217
  "kind": "method",
@@ -212,13 +226,6 @@ export const TYPERT = {
212
226
  "signature": "list(): string[]",
213
227
  "summary": "List registered provider names in insertion order.",
214
228
  "jsDoc": "/**\n * List registered provider names in insertion order.\n * @returns the registered names.\n */"
215
- },
216
- {
217
- "kind": "method",
218
- "name": "start",
219
- "signature": "async start(name: string, request: SubagentStartRequest): Promise<SubagentRun>",
220
- "summary": "Establish a published child on the named provider.",
221
- "jsDoc": "/**\n * Establish a published child on the named provider. Capability and semantic\n * checks run before delegation. Provider ownership lasts until its promise\n * fulfills; a rejection therefore has no run for the caller to dispose and\n * emits no run lifecycle events. Post-publication turn and infrastructure\n * failures settle through the returned run.\n * A catalog append failure disposes the run and handles its result rejection;\n * the caller receives the catalog error even if disposal also fails.\n * @param name - the provider to use.\n * @param request - child label, prompt, parent, signal, and optional capabilities.\n * @returns the published holder-owned run.\n */"
222
229
  }
223
230
  ],
224
231
  "types": [
@@ -332,20 +339,12 @@ export const TYPERT = {
332
339
  },
333
340
  {
334
341
  "name": "ContinuableCreateRequest",
335
- "declaration": "export interface ContinuableCreateRequest {\n readonly sessionId: SessionId;\n readonly parent: Agent;\n readonly signal: AbortSignal;\n}"
342
+ "declaration": "export interface ContinuableCreateRequest {\n readonly cwd: string;\n readonly sessionId: SessionId;\n readonly parent: Agent;\n readonly signal: AbortSignal;\n}"
336
343
  },
337
344
  {
338
345
  "name": "ContinuableCreateSpec",
339
346
  "declaration": "export interface ContinuableCreateSpec {\n readonly seed?: readonly SessionEvent[];\n}"
340
347
  },
341
- {
342
- "name": "ContinuableStart",
343
- "declaration": "export interface ContinuableStart {\n readonly childId: SessionId;\n readonly messageId: MessageId;\n}"
344
- },
345
- {
346
- "name": "ContinuableStartSpec",
347
- "declaration": "export interface ContinuableStartSpec {\n readonly provider: string;\n readonly label: string;\n readonly childId?: SessionId;\n readonly request: Omit<SubagentStartRequest, 'label' | 'signal' | 'outputSchema'>;\n readonly signal: AbortSignal;\n}"
348
- },
349
348
  {
350
349
  "name": "ContinuableSubagentDescriptorData",
351
350
  "declaration": "export interface ContinuableSubagentDescriptorData extends SubagentDescriptorBase {\n readonly mode: 'continuable';\n readonly label: string;\n readonly agentProvider?: string;\n readonly agentModel?: string;\n readonly agentReasoningEffort?: ReasoningEffortId;\n readonly persona?: string;\n readonly toolFilter?: ToolRestriction;\n}"
@@ -492,16 +491,28 @@ export const TYPERT = {
492
491
  },
493
492
  {
494
493
  "name": "LlmCallConfig",
495
- "declaration": "export interface LlmCallConfig {\n provider: string;\n model: string;\n reasoningEffort?: ReasoningEffortId;\n temperature?: number;\n maxTokens?: number;\n stop?: string[];\n}"
494
+ "declaration": "export interface LlmCallConfig extends LlmCallControls {\n provider: string;\n model: string;\n}"
496
495
  },
497
496
  {
498
497
  "name": "LlmCallConfigAdapterDefaults",
499
498
  "declaration": "export interface LlmCallConfigAdapterDefaults {\n reasoningEffort?: true;\n maxTokens?: true;\n}"
500
499
  },
500
+ {
501
+ "name": "LlmCallControls",
502
+ "declaration": "export interface LlmCallControls {\n reasoningEffort?: ReasoningEffortId;\n temperature?: number;\n maxTokens?: number;\n stop?: string[];\n}"
503
+ },
501
504
  {
502
505
  "name": "LlmFailure",
503
506
  "declaration": "export interface LlmFailure {\n readonly message: string;\n readonly code: string;\n readonly status?: number;\n readonly providerRetryAfterMs?: number;\n readonly requestId?: ProviderRequestId;\n readonly offloadImages?: number;\n}"
504
507
  },
508
+ {
509
+ "name": "LlmRetryEventData",
510
+ "declaration": "export type LlmRetryEventData = { retryId: RetryId; turn: number; step: number; provider: string; mode: 'normal'; policyKey: string; retry: number; maxRetries: number; delayMs: number; failure: LlmFailure; } | { retryId: RetryId; turn: number; step: number; provider: string; mode: 'always'; policyKey: string; retry: number; delayMs: number; failure: LlmFailure; };"
511
+ },
512
+ {
513
+ "name": "LlmRetryStartedEventData",
514
+ "declaration": "export interface LlmRetryStartedEventData {\n retryId: RetryId;\n turn: number;\n step: number;\n retry: number;\n}"
515
+ },
505
516
  {
506
517
  "name": "Message",
507
518
  "declaration": "export type Message = MessageRoleMap[keyof MessageRoleMap];"
@@ -544,7 +555,7 @@ export const TYPERT = {
544
555
  },
545
556
  {
546
557
  "name": "MessageSourceMap",
547
- "declaration": "export interface MessageSourceMap {\n user: { kind: 'user'; };\n model: ModelMessageSource;\n tool: ToolMessageSource;\n 'system-prompt': SystemPromptMessageSource;\n 'model-selection': { kind: 'model-selection'; } & ContextFormed;\n 'user-approval': { kind: 'user-approval'; } & ContextFormed;\n 'ptc-mode': { kind: 'ptc-mode'; };\n 'tool-registry': { kind: 'tool-registry'; };\n 'user-rpc': { kind: 'user'; rpcId: SessionRequestId; clientTimeZone?: string; };\n 'agent-message': AgentMessageSource;\n 'subagent-settled': SubagentSettledMessageSource;\n 'skill-invocation': SkillInvocationSource;\n 'cordis-host-runner': { kind: 'cordis-host-runner'; };\n goal: GoalMessageSource;\n schedule: { kind: 'schedule'; } & ContextFormed;\n 'compact-checkpoint': CompactionCheckpointSource;\n 'session-reference': SessionReferenceSource;\n 'user-question-reply': { kind: 'user-question-reply'; callId: ToolCallId; outcome: 'answered'; };\n}"
558
+ "declaration": "export interface MessageSourceMap {\n user: { kind: 'user'; };\n model: ModelMessageSource;\n tool: ToolMessageSource;\n 'system-prompt': SystemPromptMessageSource;\n 'model-selection': { kind: 'model-selection'; } & ContextFormed;\n 'working-directory': { kind: 'working-directory'; };\n 'user-approval': { kind: 'user-approval'; } & ContextFormed;\n 'ptc-mode': { kind: 'ptc-mode'; };\n 'tool-registry': { kind: 'tool-registry'; };\n 'user-rpc': { kind: 'user'; rpcId: SessionRequestId; clientTimeZone?: string; };\n 'agent-message': AgentMessageSource;\n 'subagent-settled': SubagentSettledMessageSource;\n 'skill-invocation': SkillInvocationSource;\n 'cordis-host-runner': { kind: 'cordis-host-runner'; };\n 'compact-checkpoint': CompactionCheckpointSource;\n 'user-question-reply': { kind: 'user-question-reply'; callId: ToolCallId; outcome: 'answered'; };\n goal: GoalMessageSource;\n schedule: { kind: 'schedule'; } & ContextFormed;\n 'session-reference': SessionReferenceSource;\n}"
548
559
  },
549
560
  {
550
561
  "name": "ModelMessageSource",
@@ -580,7 +591,7 @@ export const TYPERT = {
580
591
  },
581
592
  {
582
593
  "name": "PtcDispatchEventData",
583
- "declaration": "export interface PtcDispatchEventData extends PtcDispatchStartEventData {\n isError: boolean;\n content: ContentBlock[];\n error?: { name: string; code: string; reason?: string; };\n}"
594
+ "declaration": "export interface PtcDispatchEventData extends PtcDispatchStartEventData {\n isError: boolean;\n content: ContentBlock[];\n meta?: JsonValue;\n error?: { name: string; code: string; reason?: string; };\n}"
584
595
  },
585
596
  {
586
597
  "name": "PtcDispatchStartEventData",
@@ -608,7 +619,11 @@ export const TYPERT = {
608
619
  },
609
620
  {
610
621
  "name": "ResolvedSubagentStartRequest",
611
- "declaration": "export interface ResolvedSubagentStartRequest extends SubagentStartRequest {\n readonly descriptor: SubagentDescriptorData;\n}"
622
+ "declaration": "export interface ResolvedSubagentStartRequest extends SubagentStartRequest {\n readonly cwd: string;\n}"
623
+ },
624
+ {
625
+ "name": "RetryId",
626
+ "declaration": "export type RetryId = Branded<'RetryId'>;"
612
627
  },
613
628
  {
614
629
  "name": "SandboxMode",
@@ -644,7 +659,7 @@ export const TYPERT = {
644
659
  },
645
660
  {
646
661
  "name": "SessionEventMap",
647
- "declaration": "export interface SessionEventMap {\n 'turn/start': { turn: number; };\n 'turn/end': { turn: number; reason: TurnEndReason; };\n 'step/start': { turn: number; step: number; };\n 'step/end': { turn: number; step: number; };\n 'user/message': UserMessage;\n 'developer/message': { turn: number; step: number; message: DeveloperMessage; headerSeq?: SessionSeq; };\n 'system/message': { turn: number; step: number; message: SystemMessage; };\n 'assistant/message': { turn: number; step: number; message: AssistantMessage; stream: AssistantStreamRecord[]; usage?: TokenUsage; interrupted?: true; };\n 'assistant/attempt': { turn: number; step: number; stream: AssistantStreamRecord[]; };\n 'tool/call': { turn: number; step: number; callId: ToolCallId; name: string; arguments: string; };\n 'tool/result': { turn: number; step: number; message: ToolResultMessage; error?: { name: string; code: string; reason?: string; }; meta?: JsonValue; };\n 'request/header': { header: EpochHeader; reason: RequestHeaderReason; startsSeries?: true; };\n 'request/context': RequestContext;\n 'session/end-seed': { inherited?: true; };\n 'agent/inbox/spliced': { target: InboxTarget; start: number; removedCount?: number; inserted: UserMessage[]; outcome?: 'canceled'; };\n 'sandbox/mode': { mode: SandboxMode; source?: 'delegation'; };\n 'approval/asked': { id: ApprovalRequestId; toolName: string; callId?: ToolCallId; reason?: string; };\n 'approval/decided': { id: ApprovalRequestId; outcome: ApprovalOutcome; };\n 'approval/policy': { policy: ApprovalPolicy; source?: 'delegation'; };\n 'tool/ptc-dispatch-start': PtcDispatchStartEventData;\n 'tool/ptc-dispatch': PtcDispatchEventData;\n 'agent-preset/selected': { agentPreset: string; };\n 'command/run': { commandId: CommandId; name: string; args?: string; source: CommandSource; };\n 'command/done': { commandId: CommandId; kind: 'success' | 'error'; text?: string; sourceEventSeq?: import('@deepseek-ai/dsh-session/types').SessionSeq; };\n 'image/offload': { targets: ImageOffloadTarget[]; };\n 'session/title': SessionTitleEventData;\n 'todo/write': { todos: TodoItem[]; };\n 'model/selection': ModelSelection;\n 'subagent/descriptor': SubagentDescriptorData;\n 'permission/preset': { preset: string; };\n 'subagent/catalog': SubagentCatalogEvent;\n 'compaction/start': { compactionId: CompactionId; sourceCommandId?: CommandId; turn: number | null; };\n 'compaction/summary': { compactionId: CompactionId; sourceCommandId?: CommandId; summary: ContentBlock[]; shadowedRange: { start: SessionSeq; end: SessionSeq; }; shadowedSeqs: SessionSeq[]; shadowedTokenCount: number; provider: string; model: string; maxTokens?: number; usage?: TokenUsage; } & ({ rawOutput: ContentBlock[]; llmStreamCall: true; } | { rawOutput?: ContentBlock[]; llmStreamCall?: never; });\n 'compaction/end': { compactionId: CompactionId; sourceCommandId?: CommandId; turn: number | null; error?: string; };\n 'compaction/prune': { shadowedRange: { start: SessionSeq; end: SessionSeq; }; shadowedSeqs: SessionSeq[]; shadowedTokenCount: number; };\n 'feedback/record': FeedbackRecord;\n 'goal/change': GoalChangeMeta;\n 'feedback/message-put': MessageFeedbackPut;\n 'feedback/message-delete': MessageFeedbackDelete;\n 'schedule/change': ScheduleChange;\n}"
662
+ "declaration": "export interface SessionEventMap {\n 'turn/start': { turn: number; };\n 'turn/end': { turn: number; reason: TurnEndReason; };\n 'step/start': { turn: number; step: number; };\n 'step/end': { turn: number; step: number; };\n 'user/message': UserMessage;\n 'developer/message': { turn: number; step: number; message: DeveloperMessage; headerSeq?: SessionSeq; };\n 'system/message': { turn: number; step: number; message: SystemMessage; };\n 'assistant/message': { turn: number; step: number; message: AssistantMessage; stream: AssistantStreamRecord[]; usage?: TokenUsage; interrupted?: true; };\n 'assistant/attempt': { turn: number; step: number; stream: AssistantStreamRecord[]; };\n 'tool/call': { turn: number; step: number; callId: ToolCallId; name: string; arguments: string; };\n 'tool/result': { turn: number; step: number; message: ToolResultMessage; error?: { name: string; code: string; reason?: string; }; meta?: JsonValue; };\n 'request/header': { header: EpochHeader; reason: RequestHeaderReason; startsSeries?: true; };\n 'request/context': RequestContext;\n 'session/end-seed': { inherited?: true; };\n 'agent/inbox/spliced': { target: InboxTarget; start: number; removedCount?: number; inserted: UserMessage[]; outcome?: 'canceled'; };\n 'working-directory/change': { cwd: string; };\n 'sandbox/mode': { mode: SandboxMode; source?: 'delegation'; };\n 'approval/asked': { id: ApprovalRequestId; toolName: string; callId?: ToolCallId; reason?: string; };\n 'approval/decided': { id: ApprovalRequestId; outcome: ApprovalOutcome; };\n 'approval/policy': { policy: ApprovalPolicy; source?: 'delegation'; };\n 'tool/ptc-dispatch-start': PtcDispatchStartEventData;\n 'tool/ptc-dispatch': PtcDispatchEventData;\n 'agent-preset/selected': { agentPreset: string; };\n 'command/run': { commandId: CommandId; name: string; args?: string; source: CommandSource; };\n 'command/done': { commandId: CommandId; kind: 'success' | 'error'; text?: string; sourceEventSeq?: import('@deepseek-ai/dsh-session/types').SessionSeq; };\n 'image/offload': { targets: ImageOffloadTarget[]; };\n 'session/title': SessionTitleEventData;\n 'todo/write': { todos: TodoItem[]; };\n 'model/selection': ModelSelection;\n 'permission/preset': { preset: string; };\n 'subagent/descriptor': SubagentDescriptorData;\n 'subagent/catalog': SubagentCatalogEvent;\n 'compaction/start': { compactionId: CompactionId; sourceCommandId?: CommandId; turn: number | null; };\n 'compaction/summary': { compactionId: CompactionId; sourceCommandId?: CommandId; summary: ContentBlock[]; shadowedRange: { start: SessionSeq; end: SessionSeq; }; shadowedSeqs: SessionSeq[]; shadowedTokenCount: number; provider: string; model: string; maxTokens?: number; usage?: TokenUsage; } & ({ rawOutput: ContentBlock[]; llmStreamCall: true; } | { rawOutput?: ContentBlock[]; llmStreamCall?: never; });\n 'compaction/end': { compactionId: CompactionId; sourceCommandId?: CommandId; turn: number | null; error?: string; };\n 'compaction/prune': { shadowedRange: { start: SessionSeq; end: SessionSeq; }; shadowedSeqs: SessionSeq[]; shadowedTokenCount: number; };\n 'feedback/record': FeedbackRecord;\n 'llm/retry': LlmRetryEventData;\n 'llm/retry-started': LlmRetryStartedEventData;\n 'goal/change': GoalChangeMeta;\n 'feedback/message-put': MessageFeedbackPut;\n 'feedback/message-delete': MessageFeedbackDelete;\n 'schedule/change': ScheduleChange;\n}"
648
663
  },
649
664
  {
650
665
  "name": "SessionEventType",
@@ -702,21 +717,29 @@ export const TYPERT = {
702
717
  "name": "StreamChunk",
703
718
  "declaration": "export type StreamChunk = { type: 'block-start'; index: number; blockType: ContentBlockType; } | { type: 'text-delta'; index: number; text: string; } | { type: 'reasoning-delta'; index: number; text: string; } | { type: 'tool-call-delta'; index: number; id: ToolCallId; name?: string; argumentsDelta: string; } | { type: 'block-end'; index: number; block: ContentBlock; } | { type: 'usage'; usage: TokenUsage; } | { type: 'finish'; reason: FinishReason; replayState?: ReplayEnvelope; };"
704
719
  },
720
+ {
721
+ "name": "SubagentActivation",
722
+ "declaration": "export interface SubagentActivation {\n readonly childId: SessionId;\n readonly messageId?: MessageId;\n readonly result: Promise<SubagentResult>;\n dispose(): Promise<void>;\n}"
723
+ },
724
+ {
725
+ "name": "SubagentActivationSpec",
726
+ "declaration": "export interface SubagentActivationSpec {\n readonly provider: string;\n readonly label: string;\n readonly childId?: SessionId;\n readonly request: Omit<SubagentStartRequest, 'label' | 'signal'>;\n readonly signal: AbortSignal;\n readonly delivery: 'parent' | 'caller';\n}"
727
+ },
705
728
  {
706
729
  "name": "SubagentCapabilities",
707
730
  "declaration": "export interface SubagentCapabilities {\n readonly agentOptions: boolean;\n readonly outputSchema: boolean;\n readonly depthLimit: boolean;\n readonly toolFilter: boolean;\n readonly persona: boolean;\n}"
708
731
  },
709
732
  {
710
733
  "name": "SubagentCatalogEntry",
711
- "declaration": "export type SubagentCatalogEntry = { readonly id: SessionId; readonly createdAt: number; } & ({ readonly mode: 'one-shot'; readonly label?: string; } | { readonly mode: 'continuable'; readonly label: string; } | { readonly mode: 'unknown'; readonly label?: string; });"
734
+ "declaration": "export type SubagentCatalogEntry = { readonly id: SessionId; readonly createdAt: number; } & ({ readonly mode: 'one-shot'; readonly label?: string; } | { readonly mode: 'external'; readonly label?: string; } | { readonly mode: 'continuable'; readonly label: string; } | { readonly mode: 'unknown'; readonly label?: string; });"
712
735
  },
713
736
  {
714
737
  "name": "SubagentCatalogEvent",
715
- "declaration": "export type SubagentCatalogEvent = { readonly childId: SessionId; readonly childCreatedAt: number; } & (({ readonly version: 0; } & KnownCatalogMode) | ({ readonly version: 1; } & (KnownCatalogMode | { readonly mode: 'unknown'; readonly label?: string; })));"
738
+ "declaration": "export type SubagentCatalogEvent = { readonly childId: SessionId; readonly childCreatedAt: number; } & (({ readonly version: 0; } & KnownCatalogMode) | ({ readonly version: 1; } & (KnownCatalogMode | { readonly mode: 'unknown'; readonly label?: string; })) | { readonly version: 2; readonly mode: 'external'; readonly label?: string; });"
716
739
  },
717
740
  {
718
741
  "name": "SubagentCatalogRow",
719
- "declaration": "export type SubagentCatalogRow = { readonly id: SessionId; readonly activity: 'running' | 'inactive'; } & ({ readonly mode: 'one-shot'; readonly label?: string; } | { readonly mode: 'continuable'; readonly label: string; });"
742
+ "declaration": "export type SubagentCatalogRow = { readonly id: SessionId; readonly activity: 'running' | 'inactive'; } & ({ readonly mode: 'one-shot'; readonly label?: string; } | { readonly mode: 'external'; readonly label?: string; } | { readonly mode: 'continuable'; readonly label: string; });"
720
743
  },
721
744
  {
722
745
  "name": "SubagentDescendantListEntry",
@@ -756,7 +779,7 @@ export const TYPERT = {
756
779
  },
757
780
  {
758
781
  "name": "SubagentProvider",
759
- "declaration": "export interface SubagentProvider {\n readonly name: string;\n readonly capabilities: SubagentCapabilities;\n readonly inheritsParentContext: boolean;\n readonly agentRouteDefaults?: Readonly<{ provider: string; model: string; }>;\n start(request: ResolvedSubagentStartRequest): Promise<SubagentRun>;\n prepareContinuable?(request: ContinuableCreateRequest): Promise<ContinuableCreateSpec>;\n}"
782
+ "declaration": "export interface SubagentProvider {\n readonly name: string;\n readonly capabilities: SubagentCapabilities;\n readonly inheritsParentContext: boolean;\n readonly agentRouteDefaults?: Readonly<{ provider: string; model: string; }>;\n start?(request: ResolvedSubagentStartRequest): Promise<SubagentRun>;\n prepareContinuable?(request: ContinuableCreateRequest): Promise<ContinuableCreateSpec>;\n}"
760
783
  },
761
784
  {
762
785
  "name": "SubagentResult",
@@ -764,7 +787,7 @@ export const TYPERT = {
764
787
  },
765
788
  {
766
789
  "name": "SubagentRun",
767
- "declaration": "export interface SubagentRun {\n readonly id: SessionId;\n readonly localAgent: Agent | undefined;\n readonly result: Promise<SubagentResult>;\n dispose(): Promise<void>;\n}"
790
+ "declaration": "export interface SubagentRun {\n readonly id: SessionId;\n readonly result: Promise<SubagentResult>;\n dispose(): Promise<void>;\n}"
768
791
  },
769
792
  {
770
793
  "name": "SubagentSendMessageOptions",
@@ -776,7 +799,7 @@ export const TYPERT = {
776
799
  },
777
800
  {
778
801
  "name": "SubagentStartRequest",
779
- "declaration": "export interface SubagentStartRequest {\n readonly label?: string;\n readonly prompt: ContentBlock[];\n readonly parent: Agent;\n readonly signal: AbortSignal;\n readonly agentOptions?: AgentOptions;\n readonly outputSchema?: ObjectJsonSchema;\n readonly maxDepth?: number;\n readonly toolFilter?: ToolRestriction;\n readonly persona?: string;\n}"
802
+ "declaration": "export interface SubagentStartRequest {\n readonly cwd?: string;\n readonly label?: string;\n readonly prompt: ContentBlock[];\n readonly parent: Agent;\n readonly signal: AbortSignal;\n readonly agentOptions?: AgentOptions;\n readonly outputSchema?: ObjectJsonSchema;\n readonly maxDepth?: number;\n readonly toolFilter?: ToolRestriction;\n readonly persona?: string;\n}"
780
803
  },
781
804
  {
782
805
  "name": "SubagentStopReason",
@@ -888,18 +911,13 @@ export const TYPERT = {
888
911
  "comment": "- the run identity and terminal outcome.",
889
912
  "text": "@param info - the run identity and terminal outcome.\n *"
890
913
  },
891
- {
892
- "name": "dshScopeScan",
893
- "comment": "unsupported",
894
- "text": "@dshScopeScan unsupported\n *"
895
- },
896
914
  {
897
915
  "name": "mode",
898
916
  "comment": "emit",
899
917
  "text": "@mode emit"
900
918
  }
901
919
  ],
902
- "jsDoc": "/**\n * A published child settled. Scope-filtered dispatch uses the same delegating\n * parent carrier as `subagent/start`, so the lifecycle pair reaches the\n * same scoped audience.\n * @param info - the run identity and terminal outcome.\n * @dshScopeScan unsupported\n * @mode emit\n */",
920
+ "jsDoc": "/**\n * A published child settled. Scope-filtered dispatch uses the same delegating\n * parent carrier as `subagent/start`, so the lifecycle pair reaches the\n * same scoped audience.\n * @param info - the run identity and terminal outcome.\n * @mode emit\n */",
903
921
  "name": "subagent/end",
904
922
  "mode": "emit",
905
923
  "signature": "'subagent/end'(this: Scoped<SubagentRuntime>, info: SubagentRunEndInfo): void"
@@ -956,18 +974,13 @@ export const TYPERT = {
956
974
  "comment": "- the provider and published child identity.",
957
975
  "text": "@param info - the provider and published child identity.\n *"
958
976
  },
959
- {
960
- "name": "dshScopeScan",
961
- "comment": "unsupported",
962
- "text": "@dshScopeScan unsupported\n *"
963
- },
964
977
  {
965
978
  "name": "mode",
966
979
  "comment": "emit",
967
980
  "text": "@mode emit"
968
981
  }
969
982
  ],
970
- "jsDoc": "/**\n * A provider established a published child. For in-process providers,\n * `ctx.agents.get(info.id)` resolves during this notification.\n * Scope-filtered dispatch keys the carrier by the delegating parent, so a\n * parent-scoped listener observes only its own delegations. Paired with\n * `subagent/end`.\n * @param info - the provider and published child identity.\n * @dshScopeScan unsupported\n * @mode emit\n */",
983
+ "jsDoc": "/**\n * A provider established a published child. For in-process providers,\n * `ctx.agents.get(info.id)` resolves during this notification.\n * Scope-filtered dispatch keys the carrier by the delegating parent, so a\n * parent-scoped listener observes only its own delegations. Paired with\n * `subagent/end`.\n * @param info - the provider and published child identity.\n * @mode emit\n */",
971
984
  "name": "subagent/start",
972
985
  "mode": "emit",
973
986
  "signature": "'subagent/start'(this: Scoped<SubagentRuntime>, info: SubagentRunInfo): void"
@@ -80,7 +80,7 @@ export const TYPERT_REMOTE = {
80
80
  typeSymbol: '@deepseek-ai/dsh-subagent/client#SubagentInterruptReceipt',
81
81
  create: _deepseek_ai_dsh_subagent_subagents_interruptByParent_result$schema,
82
82
  },
83
- sourceLocation: {"file":"packages/subagent/subagent/src/index.ts","line":483,"column":3},
83
+ sourceLocation: {"file":"packages/subagent/subagent/src/index.ts","line":513,"column":3},
84
84
  },
85
85
  {
86
86
  id: '@deepseek-ai/dsh-subagent#subagents/prompt',
@@ -106,7 +106,7 @@ export const TYPERT_REMOTE = {
106
106
  typeSymbol: '@deepseek-ai/dsh-subagent/client#SubagentPromptReceipt',
107
107
  create: _deepseek_ai_dsh_subagent_subagents_prompt_result$schema,
108
108
  },
109
- sourceLocation: {"file":"packages/subagent/subagent/src/index.ts","line":416,"column":9},
109
+ sourceLocation: {"file":"packages/subagent/subagent/src/index.ts","line":446,"column":9},
110
110
  },
111
111
  ],
112
112
  }
@@ -0,0 +1,114 @@
1
+ /** Execution-period records, capacity slots, child serialization, and local output capture.
2
+ * @module @deepseek-ai/dsh-subagent/activation
3
+ */
4
+ import type { Agent, AgentHandle } from '@deepseek-ai/dsh-agent';
5
+ import type { SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session';
6
+ import type { ActivationObserver } from './lifecycle.ts';
7
+ import type { StructuredAttachment } from './structured.ts';
8
+ import type { SubagentResult, SubagentRun } from './types.ts';
9
+ /** Process-local slots shared through uninterrupted continuable parent links. */
10
+ export declare class ActivationPool {
11
+ private readonly slots;
12
+ /**
13
+ * Reserve before reconstruction; release also tolerates unpublished rollback.
14
+ * @param capacity - the maximum simultaneous activations in this pool.
15
+ * @returns an idempotent slot release.
16
+ */
17
+ reserve(capacity: number): () => void;
18
+ }
19
+ /**
20
+ * One residency epoch for a local child or an external execution.
21
+ * The manager owns admission, execution handles, and resource release.
22
+ */
23
+ interface ActivationBase {
24
+ /** Shared capacity for this Activation and all its managed descendants. */
25
+ readonly pool: ActivationPool;
26
+ /** Return this epoch's slot after its handle has finished disposal. */
27
+ readonly releaseSlot: () => void;
28
+ /** The durable child this Activation is an epoch of. */
29
+ readonly childId: SessionId;
30
+ readonly parent: Agent;
31
+ readonly delivery: 'parent' | 'caller';
32
+ readonly result: PromiseWithResolvers<SubagentResult>;
33
+ /** Published synchronously before teardown; subsequent callers share this transaction. */
34
+ closing: Promise<void> | undefined;
35
+ /**
36
+ * Exact live Agent ancestry observed when this Activation materialized.
37
+ * Weak membership preserves host-scope identity across an intermediate
38
+ * ancestor leaving the registry without retaining that ancestor's runtime.
39
+ */
40
+ readonly ancestry: WeakSet<Agent>;
41
+ /**
42
+ * Session ids of the child Activations this one owns. Because one Session has
43
+ * at most one live Activation, the id identifies the live child without
44
+ * another runtime-incarnation reference. Non-empty blocks settlement.
45
+ */
46
+ readonly ownedChildren: Set<SessionId>;
47
+ /** The lifecycle observer that emits this epoch's start and terminal edges. */
48
+ readonly observer: ActivationObserver;
49
+ /**
50
+ * Whether any delivery to this child was ever accepted. A materialization
51
+ * rolled back before its first acceptance is a child the caller was told does
52
+ * not exist, so its teardown owes the parent no settlement account.
53
+ */
54
+ announced: boolean;
55
+ }
56
+ /** Resources retained only for the selected execution kind. */
57
+ export type ActivationResource = {
58
+ readonly kind: 'local';
59
+ readonly handle: AgentHandle;
60
+ readonly outputStart: SessionLogOffset;
61
+ readonly structured: StructuredAttachment | undefined;
62
+ /** Latest live failure not superseded by a later committed turn ending. */
63
+ failureAt: SessionLogOffset | undefined;
64
+ /** Renewed when local settlement must recheck input or owned children. */
65
+ poke: PromiseWithResolvers<void>;
66
+ } | {
67
+ readonly kind: 'external';
68
+ readonly run: SubagentRun;
69
+ readonly controller: AbortController;
70
+ };
71
+ /** One managed execution period with its provider-specific resources. */
72
+ export type Activation = ActivationBase & ActivationResource;
73
+ /** Local residency with input admission and Session-backed result capture. */
74
+ export type LocalActivation = Extract<Activation, {
75
+ kind: 'local';
76
+ }>;
77
+ /**
78
+ * Read the live Agent retained by local execution.
79
+ * @param activation - the managed local or external execution.
80
+ * @returns the local Agent, absent for an external run.
81
+ */
82
+ export declare function activationAgent(activation: Activation): Agent | undefined;
83
+ /**
84
+ * Require local residency before accepting further input.
85
+ * @param activation - execution targeted by message delivery.
86
+ * @returns the local activation.
87
+ * @throws when the external backend cannot accept another message.
88
+ */
89
+ export declare function requireLocalActivation(activation: Activation): LocalActivation;
90
+ /**
91
+ * Retain local failures whose turn ending could not be committed.
92
+ * @param activation - exact local Agent and epoch receiving the scoped observers.
93
+ * @param wake - notify its settlement watcher when failure changes readiness.
94
+ */
95
+ export declare function observeLocalFailure(activation: LocalActivation, wake: () => void): void;
96
+ /**
97
+ * Capture local output and retain failures without a later committed turn ending.
98
+ * @param activation - the settled local execution and any structured result.
99
+ * @returns final output, stop reason, and committed structured value.
100
+ */
101
+ export declare function captureLocalResult(activation: LocalActivation): SubagentResult;
102
+ /** Serialize each durable child's delivery, release, and disposal. */
103
+ export declare class ChildLock {
104
+ private tails;
105
+ /**
106
+ * Run `operation` after every previously queued operation for `childId`.
107
+ * @param childId - the durable child whose operations are linearized.
108
+ * @param operation - the critical section to run in order.
109
+ * @returns the operation's own settlement.
110
+ */
111
+ run<T>(childId: SessionId, operation: () => Promise<T>): Promise<T>;
112
+ }
113
+ export {};
114
+ //# sourceMappingURL=activation.d.ts.map
@@ -0,0 +1,112 @@
1
+ /** Execution-period records, capacity slots, child serialization, and local output capture.
2
+ * @module @deepseek-ai/dsh-subagent/activation
3
+ */
4
+ import { assertNever } from '@deepseek-ai/dsh-util-values';
5
+ import { finalAssistantOutput } from "./assistant-output.js";
6
+ import { epochStopReason } from "./lifecycle.js";
7
+ import { SubagentError } from "./error.js";
8
+ /** Process-local slots shared through uninterrupted continuable parent links. */
9
+ export class ActivationPool {
10
+ slots = new Set();
11
+ /**
12
+ * Reserve before reconstruction; release also tolerates unpublished rollback.
13
+ * @param capacity - the maximum simultaneous activations in this pool.
14
+ * @returns an idempotent slot release.
15
+ */
16
+ reserve(capacity) {
17
+ if (this.slots.size >= capacity) {
18
+ throw new SubagentError(`subagent limit reached (active child limit: ${capacity}); wait for an existing child to finish `
19
+ + 'or complete this work with the current agents', 'ACTIVATION_LIMIT_REACHED');
20
+ }
21
+ const slot = Symbol();
22
+ this.slots.add(slot);
23
+ return () => { this.slots.delete(slot); };
24
+ }
25
+ }
26
+ /**
27
+ * Read the live Agent retained by local execution.
28
+ * @param activation - the managed local or external execution.
29
+ * @returns the local Agent, absent for an external run.
30
+ */
31
+ export function activationAgent(activation) {
32
+ return activation.kind === 'local' ? activation.handle.agent : undefined;
33
+ }
34
+ /**
35
+ * Require local residency before accepting further input.
36
+ * @param activation - execution targeted by message delivery.
37
+ * @returns the local activation.
38
+ * @throws when the external backend cannot accept another message.
39
+ */
40
+ export function requireLocalActivation(activation) {
41
+ switch (activation.kind) {
42
+ case 'local': return activation;
43
+ case 'external':
44
+ throw new SubagentError(`subagent "${activation.childId}" does not accept follow-up input`, 'NOT_CONTINUABLE');
45
+ /* v8 ignore next 2 -- Both execution kinds are handled above. */
46
+ default: return assertNever(activation);
47
+ }
48
+ }
49
+ /**
50
+ * Retain local failures whose turn ending could not be committed.
51
+ * @param activation - exact local Agent and epoch receiving the scoped observers.
52
+ * @param wake - notify its settlement watcher when failure changes readiness.
53
+ */
54
+ export function observeLocalFailure(activation, wake) {
55
+ const child = activation.handle.agent;
56
+ child.ctx.on('agent/error', ({ agent }) => {
57
+ if (agent !== child)
58
+ return;
59
+ activation.failureAt = child.session.seq;
60
+ wake();
61
+ });
62
+ child.ctx.on('session/event', (session, event) => {
63
+ if (session === child.session && event.type === 'turn/end'
64
+ && activation.failureAt !== undefined && event.seq >= activation.failureAt) {
65
+ activation.failureAt = undefined;
66
+ }
67
+ });
68
+ }
69
+ /**
70
+ * Capture local output and retain failures without a later committed turn ending.
71
+ * @param activation - the settled local execution and any structured result.
72
+ * @returns final output, stop reason, and committed structured value.
73
+ */
74
+ export function captureLocalResult(activation) {
75
+ // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
76
+ const events = activation.handle.agent.session.snapshotEvents(activation.outputStart);
77
+ const output = finalAssistantOutput(events) ?? [];
78
+ const stopReason = activation.failureAt === undefined ? epochStopReason(events) : 'error';
79
+ const structured = activation.structured;
80
+ if (structured !== undefined) {
81
+ const captured = structured.captured();
82
+ if (captured !== undefined)
83
+ return { output, stopReason, structured: captured.value };
84
+ if (stopReason === 'completed')
85
+ return { output, stopReason: 'error' };
86
+ }
87
+ return { output, stopReason };
88
+ }
89
+ /** Serialize each durable child's delivery, release, and disposal. */
90
+ export class ChildLock {
91
+ tails = new Map();
92
+ /**
93
+ * Run `operation` after every previously queued operation for `childId`.
94
+ * @param childId - the durable child whose operations are linearized.
95
+ * @param operation - the critical section to run in order.
96
+ * @returns the operation's own settlement.
97
+ */
98
+ run(childId, operation) {
99
+ const previous = this.tails.get(childId) ?? Promise.resolve();
100
+ const result = previous.then(operation, operation);
101
+ // Absorb rejections in the chaining tail so one failed critical section
102
+ // cannot reject an unrelated later caller.
103
+ const tail = result.then(() => undefined, () => undefined);
104
+ this.tails.set(childId, tail);
105
+ void tail.then(() => {
106
+ if (this.tails.get(childId) === tail)
107
+ this.tails.delete(childId);
108
+ });
109
+ return result;
110
+ }
111
+ }
112
+ //# sourceMappingURL=activation.js.map