@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/index.ts ADDED
@@ -0,0 +1,604 @@
1
+ /**
2
+ * Service Definition for the subagent capability seam (`ctx.subagents`): a named-provider registry plus a
3
+ * capability-validating asynchronous start API. Providers establish a
4
+ * child before returning its run, so fulfillment is the single publication and
5
+ * ownership-transfer boundary.
6
+ *
7
+ * Multiple providers coexist: each registers under a unique name and callers
8
+ * select one by name.
9
+ *
10
+ * This package owns the Service Definition role of the capability seam. Service Providers
11
+ * (`@deepseek-ai/dsh-subagent-spawn-in-process`, `-fork`, `-acp`) and the model-facing
12
+ * consumer (`@deepseek-ai/dsh-tool-subagent`) are separate packages.
13
+ *
14
+ * `startActivation` establishes every child under the activation manager, which
15
+ * owns execution, result delivery, and resource release. Local providers seed
16
+ * resumable Agents; external providers return a single execution handle.
17
+ * `sendMessage` steers between local Agents in one subagent tree without exposing
18
+ * whether a child is resident. Discovery combines real child Sessions with
19
+ * parent-owned records for external executions.
20
+ * Direct discovery reads parent catalogs; descendants recursively read reachable
21
+ * child catalogs. External entries are leaves without local Sessions.
22
+ *
23
+ * Same-process providers are trusted typed collaborators. Requests, provider
24
+ * descriptors, results, and lifecycle payloads are borrowed immutable values;
25
+ * serialization and hostile-input validation belong at real process, worker,
26
+ * persistence, and model boundaries.
27
+ *
28
+ * @module @deepseek-ai/dsh-subagent
29
+ */
30
+ import type { Volatile } from '@deepseek-ai/cordis'
31
+
32
+ import { Context, Service } from '@deepseek-ai/cordis'
33
+ import z from '@deepseek-ai/schemastery'
34
+ import type {} from '@deepseek-ai/dsh-working-directory'
35
+ import type {} from '@deepseek-ai/dsh-attachment'
36
+ import { brandString } from '@deepseek-ai/dsh-brand'
37
+ import { scopeTarget } from '@deepseek-ai/dsh-scope'
38
+ import type { Scoped } from '@deepseek-ai/dsh-scope'
39
+ import { assertObjectJsonSchema } from '@deepseek-ai/dsh-tools'
40
+ import type { ContentBlock, MessageId } from '@deepseek-ai/dsh-llm'
41
+ import type { Agent } from '@deepseek-ai/dsh-agent'
42
+ import type { SessionId } from '@deepseek-ai/dsh-session'
43
+ import { canonicalClientTimeZone } from '@deepseek-ai/dsh-util-time'
44
+ import { Remote, RemoteError, TypertRemoteService, principalOf, type Principal } from '@deepseek-ai/dsh-typert-protocol'
45
+ import {
46
+ rejectPrompt, validateControlRequest,
47
+ } from './control.ts'
48
+ import type {
49
+ SubagentInterruptReceipt,
50
+ SubagentPromptReceipt,
51
+ SubagentPromptRequest,
52
+ SubagentPromptRequestId,
53
+ } from './control-types.ts'
54
+ import type {
55
+ SubagentCapabilities,
56
+ SubagentActivation,
57
+ SubagentActivationSpec,
58
+ SubagentInterruptAuthority,
59
+ SubagentMemberNames,
60
+ SubagentProvider,
61
+ SubagentRunEndInfo,
62
+ SubagentRunInfo,
63
+ SubagentSendMessageOptions,
64
+ SubagentStartRequest,
65
+ } from './types.ts'
66
+ import { SubagentError } from './error.ts'
67
+ import { assertSubagentMaxDepth } from './depth.ts'
68
+ import { createLifecycleEmitter } from './lifecycle.ts'
69
+ import type { LifecycleEmitter } from './lifecycle.ts'
70
+ import SubagentManager from './manager.ts'
71
+ import { listDescendants as listSubagentDescendants, resolveAgentPath } from './list-children.ts'
72
+ import type { SubagentDescendantListEntry } from './list-children.ts'
73
+ import { subagentIdentityProjectionDefinition, subagentTimingProjectionDefinition } from './projection.ts'
74
+ import { subagentCatalogProjectionDefinition } from './catalog.ts'
75
+ import { ROOT_AGENT_NAME } from './names.ts'
76
+
77
+ export type {} from './catalog.ts'
78
+ export type {} from './projection.ts'
79
+ export * from './out-of-process.ts'
80
+ export { AssistantOutputFold, finalAssistantOutput } from './assistant-output.ts'
81
+ export { SubagentRunId } from './types.ts'
82
+ export { ROOT_AGENT_NAME } from './names.ts'
83
+ export type {
84
+ ContinuableCreateRequest,
85
+ ContinuableCreateSpec,
86
+ SubagentCapabilities,
87
+ SubagentActivation,
88
+ SubagentActivationSpec,
89
+ SubagentInterruptAuthority,
90
+ SubagentMemberNames,
91
+ SubagentProvider,
92
+ SubagentResult,
93
+ SubagentRun,
94
+ SubagentSendMessageOptions,
95
+ SubagentStartRequest,
96
+ ResolvedSubagentStartRequest,
97
+ SubagentStopReason,
98
+ SubagentStopReasonMap,
99
+ } from './types.ts'
100
+ export {
101
+ foldSubagentDescriptor,
102
+ snapshotSubagentDescriptor,
103
+ SUBAGENT_DESCRIPTOR_VERSION,
104
+ } from './descriptor.ts'
105
+ export type {
106
+ ContinuableSubagentDescriptorData,
107
+ ContinuableSubagentDescriptorInput,
108
+ OneShotSubagentDescriptorData,
109
+ SubagentDescriptorData,
110
+ } from './descriptor.ts'
111
+ export { STRUCTURED_OUTPUT_TOOL } from './structured.ts'
112
+ export { SubagentError } from './error.ts'
113
+ export { assertSubagentMaxDepth, delegationDepthOf } from './depth.ts'
114
+ export {
115
+ appendDelegatedPolicyOverrides,
116
+ applyChildComposition,
117
+ captureDelegatedPolicyOverrides,
118
+ childSessionMeta,
119
+ parentAgentOptionsForDelegation,
120
+ resolveChildAgentOptions,
121
+ resolveChildDepth,
122
+ SubagentDepthError,
123
+ } from './child-agent.ts'
124
+ export type { ChildComposition, DelegatedPolicyOverrides } from './child-agent.ts'
125
+ export type { AgentMessageSource, SubagentSettledMessageSource } from './continuation-messages.ts'
126
+ export type * from './control-types.ts'
127
+ export type { SubagentDescendantListEntry } from './list-children.ts'
128
+ export type { SubagentRunEndInfo, SubagentRunInfo } from './types.ts'
129
+ export type { SubagentCatalogEntry, SubagentIdentityProjection, SubagentTimingProjection } from './projection-types.ts'
130
+
131
+ declare module '@deepseek-ai/cordis' {
132
+ interface Context {
133
+ subagents: SubagentRuntime
134
+ }
135
+
136
+ interface Events {
137
+ /**
138
+ * A provider became resolvable in the registry.
139
+ * @param provider - the registered provider.
140
+ * @mode emit
141
+ */
142
+ 'subagent/provider-added'(provider: SubagentProvider): void
143
+ /**
144
+ * A provider left the registry. Accepted runs remain holder-owned.
145
+ * @param name - the provider name that no longer resolves.
146
+ * @mode emit
147
+ */
148
+ 'subagent/provider-removed'(name: string): void
149
+ /**
150
+ * A provider established a published child. For in-process providers,
151
+ * `ctx.agents.get(info.id)` resolves during this notification.
152
+ * Scope-filtered dispatch keys the carrier by the subagent tree root, so a
153
+ * root-scoped listener observes all subagent tree activations. Paired with
154
+ * `subagent/end`.
155
+ * @param info - provider, child identity, and durable direct creator `parentSessionId`.
156
+ * @mode emit
157
+ */
158
+ 'subagent/start'(this: Scoped<SubagentRuntime>, info: SubagentRunInfo): void
159
+ /**
160
+ * A published child settled. Scope-filtered dispatch uses the same subagent tree-root
161
+ * carrier as `subagent/start`, so the lifecycle pair reaches the
162
+ * same scoped audience.
163
+ * @param info - run identity, durable direct creator `parentSessionId`, and terminal outcome.
164
+ * @mode emit
165
+ */
166
+ 'subagent/end'(this: Scoped<SubagentRuntime>, info: SubagentRunEndInfo): void
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Durable attribution of one browser-authored follow-up. The Session
172
+ * Controller declares this `user-rpc` message source and depends on this
173
+ * package, so the fields are spelled here: `MessageSource`'s `user` member
174
+ * accepts the record and the correlation id rides the durable message the
175
+ * Client reconciles its optimistic prompt against.
176
+ */
177
+ interface BrowserPromptSource {
178
+ readonly kind: 'user'
179
+ readonly rpcId: SubagentPromptRequestId
180
+ readonly clientTimeZone?: string
181
+ /** Caller that submitted this follow-up, written only when it is not the owner; absent means the owner. */
182
+ readonly principal?: Principal
183
+ }
184
+
185
+ /** Host configuration for continuable subagent capacity. */
186
+ export interface Config {
187
+ /** Maximum live children sharing uninterrupted continuable parent links; defaults to 8. */
188
+ maxActiveSubagents: Volatile<number>
189
+ /** Default delegation depth for tools without an explicit limit; defaults to 1. */
190
+ maxDepth: Volatile<number>
191
+ }
192
+
193
+ /** Named provider registry with managed activations, durable discovery, and local child messaging. */
194
+ export class SubagentRuntime extends TypertRemoteService {
195
+ static Config = z.object({
196
+ maxDepth: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(1).volatile(),
197
+ maxActiveSubagents: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(8).volatile(),
198
+ })
199
+ static inject = ['workingDirectory', 'sessionProjections']
200
+ private providers = new Map<string, SubagentProvider>()
201
+ private manager: SubagentManager | undefined
202
+ /**
203
+ * The contained lifecycle-edge publisher. Built here because scoped dispatch
204
+ * keys its carrier by this exact service instance, whose own context filter
205
+ * composes into the carrier.
206
+ */
207
+ private readonly emitLifecycle: LifecycleEmitter
208
+
209
+ constructor(ctx: Context, private config: Config) {
210
+ super(ctx, 'subagents')
211
+ this.emitLifecycle = createLifecycleEmitter(this.ctx, parent => scopeTarget(this, parent))
212
+ }
213
+
214
+ protected async [Service.init](): Promise<void> {
215
+ const ctx = this.ctx
216
+ const catalogProjection = await ctx.sessionProjections.register(subagentCatalogProjectionDefinition)
217
+ await ctx.sessionProjections.register(subagentTimingProjectionDefinition)
218
+ const identityProjection = await ctx.sessionProjections.register(subagentIdentityProjectionDefinition)
219
+ if (ctx.fiber.uid === null) return
220
+ ctx.inject(['agents'], (childCtx: Context) => {
221
+ const manager = new SubagentManager(childCtx, {
222
+ identityOf: session => identityProjection.stateOf(session).identity,
223
+ catalogOf: session => subagentCatalogProjectionDefinition.wire.view(catalogProjection.stateOf(session)),
224
+ emitLifecycle: this.emitLifecycle,
225
+ }, () => this.config.maxActiveSubagents.get())
226
+ this.manager = manager
227
+ childCtx.effect(() => () => {
228
+ /* v8 ignore else -- one injected binding owns the slot until its fiber disposes. */
229
+ if (this.manager === manager) this.manager = undefined
230
+ }, 'subagents.managerBinding()')
231
+ })
232
+ }
233
+
234
+ /**
235
+ * Resolve a delegation tool's depth policy against the current user setting.
236
+ * @param configured - Explicit tool limit, or provider-managed for external delegation.
237
+ * @returns The numeric limit, or undefined when the provider owns depth enforcement.
238
+ */
239
+ resolveMaxDepth(configured?: number | 'provider-managed'): number | undefined {
240
+ if (configured === 'provider-managed') return undefined
241
+ if (configured !== undefined) return configured
242
+ const depth = this.config.maxDepth.get()
243
+ assertSubagentMaxDepth(depth)
244
+ return depth
245
+ }
246
+
247
+ /**
248
+ * Start a local child under its reserved identity.
249
+ * @param spec - local task, reserved child id, and result recipient.
250
+ * @returns activation with its accepted initial message id.
251
+ */
252
+ startActivation(spec: SubagentActivationSpec & { readonly childId: SessionId }):
253
+ Promise<SubagentActivation & { readonly messageId: MessageId }>
254
+ /**
255
+ * Start a local or external child.
256
+ * @param spec - task, backend, and result recipient.
257
+ * @returns activation with a message id only for local children.
258
+ */
259
+ startActivation(spec: SubagentActivationSpec): Promise<SubagentActivation>
260
+ /**
261
+ * Establish a managed child with backend-specific execution capabilities.
262
+ * @param spec - task, backend, and result recipient.
263
+ * @returns identities, execution result, and exact-activation disposal. A reserved
264
+ * childId requires a local backend and guarantees an accepted messageId.
265
+ * @throws PROVIDER_CHANGED if the selected provider is removed or replaced before dispatch.
266
+ */
267
+ async startActivation(spec: SubagentActivationSpec): Promise<SubagentActivation> {
268
+ const provider = this.expectProvider(spec.provider)
269
+ if (spec.childId !== undefined && provider.prepareContinuable === undefined) {
270
+ throw new SubagentError('reserved child ids require a local backend', 'UNSUPPORTED_CAPABILITY')
271
+ }
272
+ assertSubagentMaxDepth(spec.maxDepth)
273
+ this.assertCapabilities(provider, spec)
274
+ const manager = this.requireManager()
275
+ if (this.ctx.get('agents')?.get(spec.parent.id) !== spec.parent) {
276
+ throw new SubagentError('subagent creation requires the exact live parent agent', 'UNAUTHORIZED')
277
+ }
278
+ if (spec.outputSchema !== undefined) assertObjectJsonSchema(spec.outputSchema)
279
+ const prepare = provider.prepareContinuable?.bind(provider)
280
+ if (prepare !== undefined) {
281
+ return manager.startLocal(spec, (request) => {
282
+ this.assertProviderCurrent(provider)
283
+ return prepare(request)
284
+ })
285
+ }
286
+ // oxlint-disable-next-line typescript/no-non-null-assertion -- registerProvider requires start when prepareContinuable is absent.
287
+ const start = provider.start!.bind(provider)
288
+ return manager.startExternal(spec, (request) => {
289
+ this.assertProviderCurrent(provider)
290
+ return start(request)
291
+ })
292
+ }
293
+
294
+ /**
295
+ * Resolve the root shared by an Agent and its other agents in its subagent tree.
296
+ * @param caller - exact live Agent whose subagent ancestry selects the tree.
297
+ * @returns the live root; ordinary Session forks lead independent trees.
298
+ * @throws when the caller or its runtime owner is unavailable.
299
+ */
300
+ rootOf(caller: Agent): Agent {
301
+ return this.requireManager().rootOf(caller)
302
+ }
303
+
304
+ /**
305
+ * Report the model-facing names of a live tree member and its direct creator.
306
+ * The root is `lead`; a descendant is the slash-separated path of names from
307
+ * the root, or its Session id when it or a creator below the root has no name.
308
+ * @param agent - exact live root or resident tree member.
309
+ * @returns the member's name and, for a descendant, its creator's name.
310
+ * @throws when the caller or its runtime owner is unavailable.
311
+ */
312
+ namesOf(agent: Agent): SubagentMemberNames {
313
+ return this.requireManager().namesOf(agent)
314
+ }
315
+
316
+ /**
317
+ * Resolve a model-supplied agent reference within the caller's tree. `lead`
318
+ * selects the root and a slash-separated path is looked up through the
319
+ * catalogs along it. Any other text that is not a name in the tree is
320
+ * returned as a Session id, because a single token can be one; a
321
+ * slash-separated address never is, so an unmatched path fails instead of
322
+ * reaching a member lookup as an unknown id. Resolution grants no authority:
323
+ * messaging, interruption, and assignment authorize the result.
324
+ * @param caller - exact live Agent whose tree root anchors the lookup.
325
+ * @param name - `lead`, a full name from the root, or a Session id.
326
+ * @param signal - cancellation forwarded to each catalog read.
327
+ * @returns the referenced Session id.
328
+ * @throws {@link SubagentError} `AGENT_NAME_NOT_FOUND` when a path names no member;
329
+ * when the caller's root is unavailable; or when a catalog along the path cannot be read.
330
+ */
331
+ async resolveName(caller: Agent, name: string, signal: AbortSignal): Promise<SessionId> {
332
+ const root = this.rootOf(caller)
333
+ if (name === ROOT_AGENT_NAME) return root.id
334
+ const resolved = await resolveAgentPath(this.ctx, root.id, name, signal)
335
+ if (resolved !== undefined) return resolved
336
+ if (name.includes('/')) {
337
+ throw new SubagentError(
338
+ `agent name ${JSON.stringify(name)} was not found in this subagent tree; use list_agents to see the names`,
339
+ 'AGENT_NAME_NOT_FOUND',
340
+ )
341
+ }
342
+ return brandString<SessionId>(name)
343
+ }
344
+
345
+ /**
346
+ * Join progressing subagent tree work for its root. Idle members with parked input
347
+ * stay resident without delaying host completion. Ordinary members return false.
348
+ * @param root - exact live subagent tree root whose member work is awaited.
349
+ * @returns whether work was joined; hosts recheck root idle after true.
350
+ */
351
+ async waitForTreeWork(root: Agent): Promise<boolean> {
352
+ return this.manager?.waitForTreeWork(root) ?? false
353
+ }
354
+
355
+ /**
356
+ * Steer one model-authored message to another member of the same subagent tree.
357
+ * A running target receives it at its next step; an idle target starts a turn.
358
+ * A cold target resumes under its runtime subagent tree root without restoring
359
+ * its creation ancestors. Sender identity is rechecked before inbox acceptance; cancellation
360
+ * stops only pre-acceptance work and never retracts an accepted message.
361
+ * @param sender - exact live root or resident continuable Agent originating the message.
362
+ * @param targetId - another root or continuable member's durable Session id.
363
+ * @param content - model-authored content to deliver.
364
+ * @param options - caller cancellation before inbox acceptance.
365
+ * @returns the accepted message's inbox id.
366
+ * @throws when the target is outside the tree, cannot resume, or rejects input.
367
+ */
368
+ async sendMessage(
369
+ sender: Agent,
370
+ targetId: SessionId,
371
+ content: ContentBlock[],
372
+ options: SubagentSendMessageOptions,
373
+ ): Promise<MessageId> {
374
+ return this.requireManager().sendMessage(sender, targetId, content, options)
375
+ }
376
+
377
+ /**
378
+ * Interrupt one live child's current execution under a trusted user
379
+ * operation or an exact live ancestor Agent. Fire-and-return: the cancel
380
+ * signal is issued before this returns, but the target may keep running
381
+ * until it observes the signal. Unclaimed pending inbox work, the Activation,
382
+ * and published descendants are preserved; claimed work is not requeued.
383
+ * Once the interrupted Agent is idle, a waking send resumes the parked FIFO
384
+ * queue. External backends stop their single execution. An absent target
385
+ * is an accepted no-op, as is a manager-less composition, which cannot own a
386
+ * live Activation.
387
+ * @param targetSessionId - the durable child session id to interrupt.
388
+ * @param authority - a trusted user operation or exact live ancestor Agent.
389
+ * @throws {SubagentError} `UNAUTHORIZED` when the authority does not own the
390
+ * live target.
391
+ */
392
+ interrupt(targetSessionId: SessionId, authority: SubagentInterruptAuthority): void {
393
+ this.manager?.interrupt(targetSessionId, authority)
394
+ }
395
+
396
+ /**
397
+ * Close admission and stop all instances in the selected subagent trees, then await
398
+ * pending startup and cleanup. Ordinary members are ignored. The cutoff lasts
399
+ * until each exact root leaves the registry; unrelated subagent trees remain live.
400
+ * @param parents - exact live subagent tree roots entering teardown.
401
+ * @returns once all admitted startup and member cleanup have settled.
402
+ * @throws an aggregate error after all branches settle when any failed.
403
+ */
404
+ async drainDescendants(parents: readonly Agent[]): Promise<void> {
405
+ const manager = this.manager
406
+ // An absent activation manager cannot own materialized children.
407
+ if (manager === undefined) return
408
+ await manager.drainDescendants(parents)
409
+ }
410
+
411
+ /**
412
+ * Recursively list reachable parent catalogs in stable pre-order, preserving
413
+ * each catalog's event order. Each row carries its catalog parent and depth;
414
+ * external children are leaves; one-shot and unknown-mode children remain
415
+ * traversal nodes. Unknown modes
416
+ * produce unsupported diagnostics. Unreadable child catalogs produce corrupt
417
+ * or unavailable diagnostics and stop only that branch. Root read failures,
418
+ * missing services or projections, and cancellation reject the whole listing.
419
+ * Each catalog is observed once and released before the next read. No Agent
420
+ * is loaded or resumed; Sessions absent from reachable catalogs are omitted.
421
+ * @param rootSessionId - session whose catalog starts descendant discovery.
422
+ * @param signal - cancellation forwarded to and checked around each catalog read.
423
+ * @returns children and branch diagnostics in parent-catalog pre-order.
424
+ * @throws {@link SubagentError} when listing dependencies are unavailable or the caller cancels.
425
+ * @throws SessionQueryError when the root catalog cannot be read.
426
+ */
427
+ listDescendants(rootSessionId: SessionId, signal?: AbortSignal): Promise<SubagentDescendantListEntry[]> {
428
+ return listSubagentDescendants(this.ctx, rootSessionId, signal)
429
+ }
430
+
431
+ /**
432
+ * Deliver one browser-authored message to a continuable child through its
433
+ * live subagent tree root, retaining the caller-minted request identity and
434
+ * validated browser zone on the accepted message. Success identifies the
435
+ * message the child's inbox accepted; later execution is independent of this
436
+ * call. Queue delivery targets a later turn; steer delivery targets the
437
+ * nearest step and retains the Agent loop's best-effort fallback semantics.
438
+ * Image parts are admitted and persisted through the attachment store
439
+ * before delivery, and the child's model must accept image input.
440
+ * Cold resume at capacity rejects with `subagent/delivery-unavailable`.
441
+ * Access is checked on the target Session before attachment admission or restoration.
442
+ * @param request - target id, delivery, minted identity, content, and optional browser zone.
443
+ * @param signal - carrier cancellation, owning the call until inbox acceptance.
444
+ * @returns the accepted message's inbox identity.
445
+ * @throws {RemoteError} `gateway/bad-request`, `subagent/attachment-invalid`,
446
+ * `subagent/invalid-time-zone`,
447
+ * `subagent/not-resumable`, `subagent/unauthorized`,
448
+ * `subagent/delivery-unavailable`, `gateway/cancelled`, or `gateway/internal`.
449
+ */
450
+ @Remote({ name: 'prompt', resources: { session: request => request.childSessionId } })
451
+ async prompt(request: SubagentPromptRequest, signal: AbortSignal): Promise<SubagentPromptReceipt> {
452
+ const { childSessionId, clientTimeZone, delivery } = request
453
+ validateControlRequest('subagent.prompt', request)
454
+ const canonicalTimeZone = clientTimeZone === undefined
455
+ ? undefined
456
+ : canonicalClientTimeZone(clientTimeZone)
457
+ if (clientTimeZone !== undefined && canonicalTimeZone === undefined) {
458
+ throw new RemoteError(
459
+ 'subagent/invalid-time-zone',
460
+ 'clientTimeZone must be UTC or a valid IANA Area/Location name',
461
+ { value: clientTimeZone },
462
+ )
463
+ }
464
+ const principal = principalOf(this.ctx.invocation)
465
+ const source: BrowserPromptSource = {
466
+ kind: 'user',
467
+ rpcId: request.requestId,
468
+ ...(canonicalTimeZone === undefined ? {} : { clientTimeZone: canonicalTimeZone }),
469
+ ...(principal === undefined ? {} : { principal }),
470
+ }
471
+ try {
472
+ // Admission precedes delivery: image parts become durable references
473
+ // here, so the child inbox only ever accepts Host-persisted attachments.
474
+ let content: ContentBlock[]
475
+ if (request.content.every((part): part is { readonly type: 'text'; readonly text: string } => part.type === 'text')) {
476
+ content = request.content.map(part => ({ type: 'text', text: part.text }))
477
+ } else {
478
+ const attachments = this.ctx.get('attachments')
479
+ if (attachments === undefined) throw new Error('subagent image prompt requires an attachment store')
480
+ content = await attachments.admitPromptContent(request.content)
481
+ }
482
+ return {
483
+ messageId: await this.requireManager().deliverPrompt(
484
+ childSessionId,
485
+ content,
486
+ { source, signal, delivery },
487
+ ),
488
+ }
489
+ } catch (error: unknown) {
490
+ return rejectPrompt(error, childSessionId, signal)
491
+ }
492
+ }
493
+
494
+ /**
495
+ * Remote face of {@link interrupt}, authorized on the target Session by the Gateway.
496
+ * No catalog, history, persistence, or parent Agent lookup runs.
497
+ * Absent, idle, and already-completed targets are accepted no-ops there.
498
+ * @param childSessionId - durable child session id to interrupt.
499
+ * @returns acknowledgement that the cancel signal was admitted, not that the target is quiescent.
500
+ * @throws {RemoteError} `gateway/bad-request` for an empty id,
501
+ * otherwise `gateway/internal`.
502
+ */
503
+ @Remote({ name: 'interruptByUser', resources: { session: childSessionId => childSessionId } })
504
+ interruptByUser(childSessionId: SessionId): SubagentInterruptReceipt {
505
+ validateControlRequest('subagent.interrupt', { childSessionId })
506
+ try {
507
+ this.interrupt(childSessionId, { kind: 'user' })
508
+ } catch (error: unknown) {
509
+ throw new RemoteError('gateway/internal', 'subagent interrupt failed', {}, { cause: error })
510
+ }
511
+ return { accepted: true }
512
+ }
513
+
514
+ /**
515
+ * Register a provider under its name. Registration is effect-scoped and HMR
516
+ * safe; removing a provider blocks new starts but does not revoke runs that
517
+ * were already returned to their holders. Providers without either execution
518
+ * method are rejected with UNSUPPORTED_CAPABILITY before registration.
519
+ * @param provider - the trusted provider implementation.
520
+ * @returns the exact Cordis effect disposer.
521
+ */
522
+ registerProvider(provider: SubagentProvider): () => void {
523
+ const name = provider.name
524
+ if (provider.start === undefined && provider.prepareContinuable === undefined) {
525
+ throw new SubagentError(`subagent provider "${name}" must implement start or prepareContinuable`, 'UNSUPPORTED_CAPABILITY')
526
+ }
527
+ // oxlint-disable-next-line typescript/no-misused-promises -- synchronous disposer
528
+ return this.ctx.effect(function* (this: SubagentRuntime) {
529
+ if (this.providers.has(name)) {
530
+ throw new SubagentError(`a subagent provider named "${name}" is already registered`, 'DUPLICATE_PROVIDER')
531
+ }
532
+ this.providers.set(name, provider)
533
+ yield () => {
534
+ this.providers.delete(name)
535
+ this.emitLifecycle('subagent/provider-removed', name)
536
+ }
537
+ // A throwing added-listener unwinds the yielded rollback, matching the
538
+ // repository's fail-loud registration semantics.
539
+ this.ctx.emit('subagent/provider-added', provider)
540
+ }.bind(this), 'subagents.registerProvider()')
541
+ }
542
+
543
+ /**
544
+ * Look up a provider by name.
545
+ * @param name - the provider name.
546
+ * @returns the provider, or undefined when absent.
547
+ */
548
+ getProvider(name: string): SubagentProvider | undefined {
549
+ return this.providers.get(name)
550
+ }
551
+
552
+ /** A pending start must use the exact provider whose capabilities were checked. */
553
+ private assertProviderCurrent(provider: SubagentProvider): void {
554
+ if (this.providers.get(provider.name) !== provider) {
555
+ throw new SubagentError(`subagent provider "${provider.name}" changed during startup; retry the delegation`, 'PROVIDER_CHANGED')
556
+ }
557
+ }
558
+
559
+ /** Look up a provider for dispatch or fail loud. */
560
+ private expectProvider(name: string): SubagentProvider {
561
+ const provider = this.providers.get(name)
562
+ if (provider === undefined) {
563
+ throw new SubagentError(`no subagent provider registered for "${name}"`, 'NO_PROVIDER')
564
+ }
565
+ return provider
566
+ }
567
+
568
+ /** Resolve the subagent manager or fail loud. */
569
+ private requireManager(): SubagentManager {
570
+ if (this.manager === undefined) {
571
+ throw new SubagentError(
572
+ 'continuable subagents require the agents service',
573
+ 'CONTINUATION_UNAVAILABLE',
574
+ )
575
+ }
576
+ return this.manager
577
+ }
578
+
579
+ /** Reject the first requested capability that the provider lacks. */
580
+ private assertCapabilities(provider: SubagentProvider, request: SubagentStartRequest): void {
581
+ if (request.agentPreset !== undefined && (!provider.capabilities.agentPreset || provider.inheritsParentContext)) {
582
+ throw new SubagentError(
583
+ `subagent provider "${provider.name}" does not support independent agent preset selection`,
584
+ 'UNSUPPORTED_CAPABILITY',
585
+ )
586
+ }
587
+ const needs: { when: boolean; cap: keyof SubagentCapabilities }[] = [
588
+ { when: request.agentOptions !== undefined, cap: 'agentOptions' },
589
+ { when: request.outputSchema !== undefined, cap: 'outputSchema' },
590
+ { when: request.maxDepth !== undefined, cap: 'depthLimit' },
591
+ ]
592
+ for (const { when, cap } of needs) {
593
+ if (when && !provider.capabilities[cap]) {
594
+ throw new SubagentError(
595
+ `subagent provider "${provider.name}" does not support the "${cap}" capability`,
596
+ 'UNSUPPORTED_CAPABILITY',
597
+ )
598
+ }
599
+ }
600
+ }
601
+
602
+ }
603
+
604
+ export default SubagentRuntime