@morlay/dsh-subagent 0.0.6 → 0.0.7

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.
@@ -0,0 +1,718 @@
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 adjacent local Agents 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 } 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 { scopeTarget } from "@deepseek-ai/dsh-scope";
37
+ import type { Scoped } from "@deepseek-ai/dsh-scope";
38
+ import { assertObjectJsonSchema } from "@deepseek-ai/dsh-tools";
39
+ import type { ContentBlock, MessageId, MessageSource } from "@deepseek-ai/dsh-llm";
40
+ import type { Agent } from "@deepseek-ai/dsh-agent";
41
+ import type { SessionId } from "@deepseek-ai/dsh-session";
42
+ import { canonicalClientTimeZone } from "@deepseek-ai/dsh-util-time";
43
+ import {
44
+ Remote,
45
+ RemoteError,
46
+ TypertRemoteService,
47
+ principalOf,
48
+ type Principal,
49
+ } from "@deepseek-ai/dsh-typert-protocol";
50
+ import { rejectPrompt, validateControlRequest } from "./control.ts";
51
+ import type {
52
+ SubagentDelivery,
53
+ SubagentInterruptReceipt,
54
+ SubagentPromptReceipt,
55
+ SubagentPromptRequest,
56
+ SubagentPromptRequestId,
57
+ } from "./control-types.ts";
58
+ import type {
59
+ ContinuableCreateRequest,
60
+ ContinuableCreateSpec,
61
+ SubagentCapabilities,
62
+ SubagentActivation,
63
+ SubagentActivationSpec,
64
+ SubagentInterruptAuthority,
65
+ SubagentProvider,
66
+ SubagentRunEndInfo,
67
+ SubagentRunInfo,
68
+ SubagentSendMessageOptions,
69
+ SubagentStartRequest,
70
+ } from "./types.ts";
71
+ import { SubagentError } from "./error.ts";
72
+ import { assertSubagentMaxDepth } from "./depth.ts";
73
+ import { createActivationObserver, createLifecycleEmitter } from "./lifecycle.ts";
74
+ import type { ActivationObserver, LifecycleEmitter } from "./lifecycle.ts";
75
+ import SubagentManager from "./manager.ts";
76
+ import {
77
+ listChildren as listSubagentChildren,
78
+ listDescendants as listSubagentDescendants,
79
+ } from "./list-children.ts";
80
+ import type { SubagentDescendantListEntry } from "./list-children.ts";
81
+ import { installSubagentArchiveAdmission } from "./archive-admission.ts";
82
+ import type { SubagentCatalogEntry } from "./projection-types.ts";
83
+ import {
84
+ subagentIdentityProjectionDefinition,
85
+ subagentTimingProjectionDefinition,
86
+ } from "./projection.ts";
87
+ import { subagentCatalogProjectionDefinition } from "./catalog.ts";
88
+ import { deliverSubagentPrompt } from "./internal.ts";
89
+
90
+ export type {} from "./catalog.ts";
91
+ export * from "./out-of-process.ts";
92
+ export { AssistantOutputFold, finalAssistantOutput } from "./assistant-output.ts";
93
+ export { SubagentRunId } from "./types.ts";
94
+ export type {
95
+ ContinuableCreateRequest,
96
+ ContinuableCreateSpec,
97
+ SubagentCapabilities,
98
+ SubagentActivation,
99
+ SubagentActivationSpec,
100
+ SubagentInterruptAuthority,
101
+ SubagentProvider,
102
+ SubagentResult,
103
+ SubagentRun,
104
+ SubagentSendMessageOptions,
105
+ SubagentStartRequest,
106
+ ResolvedSubagentStartRequest,
107
+ SubagentStopReason,
108
+ SubagentStopReasonMap,
109
+ } from "./types.ts";
110
+ export {
111
+ foldSubagentDescriptor,
112
+ snapshotSubagentDescriptor,
113
+ SUBAGENT_DESCRIPTOR_VERSION,
114
+ } from "./descriptor.ts";
115
+ export type {
116
+ ContinuableSubagentDescriptorData,
117
+ ContinuableSubagentDescriptorInput,
118
+ OneShotSubagentDescriptorData,
119
+ SubagentDescriptorData,
120
+ } from "./descriptor.ts";
121
+ export { STRUCTURED_OUTPUT_TOOL } from "./structured.ts";
122
+ export { SubagentError } from "./error.ts";
123
+ export { assertSubagentMaxDepth, delegationDepthOf } from "./depth.ts";
124
+ export {
125
+ appendDelegatedPolicyOverrides,
126
+ applyChildComposition,
127
+ captureDelegatedPolicyOverrides,
128
+ childSessionMeta,
129
+ parentAgentOptionsForDelegation,
130
+ resolveChildAgentOptions,
131
+ resolveChildDepth,
132
+ SubagentDepthError,
133
+ } from "./child-agent.ts";
134
+ export type { ChildComposition, DelegatedPolicyOverrides } from "./child-agent.ts";
135
+ export type { AgentMessageSource, SubagentSettledMessageSource } from "./continuation-messages.ts";
136
+ export type * from "./control-types.ts";
137
+ export type { SubagentDescendantListEntry } from "./list-children.ts";
138
+ export type { SubagentRunEndInfo, SubagentRunInfo } from "./types.ts";
139
+ export type {
140
+ SubagentCatalogEntry,
141
+ SubagentIdentityProjection,
142
+ SubagentTimingProjection,
143
+ } from "./projection-types.ts";
144
+
145
+ declare module "@deepseek-ai/cordis" {
146
+ interface Context {
147
+ subagents: SubagentRuntime;
148
+ }
149
+
150
+ interface Events {
151
+ /**
152
+ * A provider became resolvable in the registry.
153
+ * @param provider - the registered provider.
154
+ * @mode emit
155
+ */
156
+ "subagent/provider-added"(provider: SubagentProvider): void;
157
+ /**
158
+ * A provider left the registry. Accepted runs remain holder-owned.
159
+ * @param name - the provider name that no longer resolves.
160
+ * @mode emit
161
+ */
162
+ "subagent/provider-removed"(name: string): void;
163
+ /**
164
+ * A provider established a published child. For in-process providers,
165
+ * `ctx.agents.get(info.id)` resolves during this notification.
166
+ * Scope-filtered dispatch keys the carrier by the delegating parent, so a
167
+ * parent-scoped listener observes only its own delegations. Paired with
168
+ * `subagent/end`.
169
+ * @param info - the provider and published child identity.
170
+ * @mode emit
171
+ */
172
+ "subagent/start"(this: Scoped<SubagentRuntime>, info: SubagentRunInfo): void;
173
+ /**
174
+ * A published child settled. Scope-filtered dispatch uses the same delegating
175
+ * parent carrier as `subagent/start`, so the lifecycle pair reaches the
176
+ * same scoped audience.
177
+ * @param info - the run identity and terminal outcome.
178
+ * @mode emit
179
+ */
180
+ "subagent/end"(this: Scoped<SubagentRuntime>, info: SubagentRunEndInfo): void;
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Durable attribution of one browser-authored follow-up. The Session
186
+ * Controller declares this `user-rpc` message source and depends on this
187
+ * package, so the fields are spelled here: `MessageSource`'s `user` member
188
+ * accepts the record and the correlation id rides the durable message the
189
+ * Client reconciles its optimistic prompt against.
190
+ */
191
+ interface BrowserPromptSource {
192
+ readonly kind: "user";
193
+ readonly rpcId: SubagentPromptRequestId;
194
+ readonly clientTimeZone?: string;
195
+ /** Caller that submitted this follow-up, written only when it is not the owner; absent means the owner. */
196
+ readonly principal?: Principal;
197
+ }
198
+
199
+ /** Host configuration for continuable subagent capacity. */
200
+ export interface Config {
201
+ /** Maximum live children sharing uninterrupted continuable parent links; defaults to 8. */
202
+ maxActiveSubagents: Volatile<number>;
203
+ /** Default delegation depth for tools without an explicit limit; defaults to 1. */
204
+ maxDepth: Volatile<number>;
205
+ }
206
+
207
+ /** Named provider registry with managed activations, durable discovery, and local child messaging. */
208
+ export class SubagentRuntime extends TypertRemoteService {
209
+ static Config = z.object({
210
+ maxDepth: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(1).volatile(),
211
+ maxActiveSubagents: z
212
+ .number()
213
+ .step(1)
214
+ .min(1)
215
+ .max(Number.MAX_SAFE_INTEGER)
216
+ .default(8)
217
+ .volatile(),
218
+ });
219
+ static inject = ["workingDirectory"];
220
+ private providers = new Map<string, SubagentProvider>();
221
+ private manager: SubagentManager | undefined;
222
+ /**
223
+ * The contained lifecycle-edge publisher. Built here because scoped dispatch
224
+ * keys its carrier by this exact service instance, whose own context filter
225
+ * composes into the carrier.
226
+ */
227
+ private readonly emitLifecycle: LifecycleEmitter;
228
+
229
+ constructor(
230
+ ctx: Context,
231
+ private config: Config,
232
+ ) {
233
+ super(ctx, "subagents");
234
+ this.emitLifecycle = createLifecycleEmitter(this.ctx, (parent) => scopeTarget(this, parent));
235
+ ctx.inject(["agents"], (childCtx: Context) => {
236
+ const manager = new SubagentManager(
237
+ childCtx,
238
+ {
239
+ startExternal: (name, request) => {
240
+ const provider = this.expectProvider(name) as SubagentProvider &
241
+ Required<Pick<SubagentProvider, "start">>;
242
+ return provider.start(request);
243
+ },
244
+ prepareContinuable: (name, request) => this.prepareContinuable(name, request),
245
+ observeActivation: (provider, childId, parent) =>
246
+ this.observeActivation(provider, childId, parent),
247
+ },
248
+ () => this.config.maxActiveSubagents.get(),
249
+ );
250
+ this.manager = manager;
251
+ childCtx.effect(
252
+ () => () => {
253
+ /* v8 ignore else -- one injected binding owns the slot until its fiber disposes. */
254
+ if (this.manager === manager) this.manager = undefined;
255
+ },
256
+ "subagents.managerBinding()",
257
+ );
258
+ });
259
+ ctx.inject(["sessionProjections"], (projectionCtx) => {
260
+ projectionCtx.sessionProjections.register(subagentCatalogProjectionDefinition);
261
+ projectionCtx.sessionProjections.register(subagentTimingProjectionDefinition);
262
+ projectionCtx.sessionProjections.register(subagentIdentityProjectionDefinition);
263
+ });
264
+ // Archive admission: this runtime is the owner that knows which live
265
+ // children descend from a Session and how a parent stops them.
266
+ ctx.inject(["agents"], (agentsCtx: Context) => {
267
+ installSubagentArchiveAdmission(agentsCtx);
268
+ });
269
+ }
270
+
271
+ /**
272
+ * Resolve a delegation tool's depth policy against the current user setting.
273
+ * @param configured - Explicit tool limit, or provider-managed for external delegation.
274
+ * @returns The numeric limit, or undefined when the provider owns depth enforcement.
275
+ */
276
+ resolveMaxDepth(configured?: number | "provider-managed"): number | undefined {
277
+ if (configured === "provider-managed") return undefined;
278
+ if (configured !== undefined) return configured;
279
+ const depth = this.config.maxDepth.get();
280
+ assertSubagentMaxDepth(depth);
281
+ return depth;
282
+ }
283
+
284
+ /**
285
+ * Start a local child under its reserved identity.
286
+ * @param spec - local task, reserved child id, and result recipient.
287
+ * @returns activation with its accepted initial message id.
288
+ */
289
+ startActivation(
290
+ spec: SubagentActivationSpec & { readonly childId: SessionId },
291
+ ): Promise<SubagentActivation & { readonly messageId: MessageId }>;
292
+ /**
293
+ * Start a local or external child.
294
+ * @param spec - task, backend, and result recipient.
295
+ * @returns activation with a message id only for local children.
296
+ */
297
+ startActivation(spec: SubagentActivationSpec): Promise<SubagentActivation>;
298
+ /**
299
+ * Establish a managed child with backend-specific execution capabilities.
300
+ * @param spec - task, backend, and result recipient.
301
+ * @returns identities, execution result, and exact-activation disposal. A reserved
302
+ * childId requires a local backend and guarantees an accepted messageId.
303
+ */
304
+ async startActivation(spec: SubagentActivationSpec): Promise<SubagentActivation> {
305
+ const provider = this.expectProvider(spec.provider);
306
+ if (spec.childId !== undefined && provider.prepareContinuable === undefined) {
307
+ throw new SubagentError(
308
+ "reserved child ids require a local backend",
309
+ "UNSUPPORTED_CAPABILITY",
310
+ );
311
+ }
312
+ assertSubagentMaxDepth(spec.request.maxDepth);
313
+ this.assertCapabilities(provider, { ...spec.request, signal: spec.signal });
314
+ const manager = this.requireManager();
315
+ if (this.ctx.get("agents")?.get(spec.request.parent.id) !== spec.request.parent) {
316
+ throw new SubagentError(
317
+ "subagent creation requires the exact live parent agent",
318
+ "UNAUTHORIZED",
319
+ );
320
+ }
321
+ if (spec.request.outputSchema !== undefined) assertObjectJsonSchema(spec.request.outputSchema);
322
+ return provider.prepareContinuable === undefined
323
+ ? manager.startExternal(spec)
324
+ : manager.startLocal(spec);
325
+ }
326
+
327
+ /**
328
+ * Join progressing descendants without cancelling them. Idle descendants whose
329
+ * inboxes require a later wake stay resident and do not delay host completion.
330
+ * @param parent - the exact parent whose descendant work is observed.
331
+ * @returns whether work was joined; hosts recheck parent idle after true.
332
+ */
333
+ async waitForChildren(parent: Agent): Promise<boolean> {
334
+ return this.manager?.waitForChildren(parent) ?? false;
335
+ }
336
+
337
+ /**
338
+ * Steer one model-authored message to the sender's direct parent or direct
339
+ * continuable child. A running target admits it at the nearest step boundary;
340
+ * an idle target starts a turn, and an absent direct child cold-resumes from
341
+ * persistence. The service derives durable sender attribution from the exact
342
+ * live sender. Caller cancellation stops only pre-acceptance work.
343
+ * @param sender - exact live Agent authorizing and originating the message.
344
+ * @param targetId - durable direct-parent or direct-child session id.
345
+ * @param content - model-authored content to deliver.
346
+ * @param options - caller cancellation before inbox acceptance.
347
+ * @returns the accepted message's inbox id.
348
+ * @throws when continuation services are unavailable, adjacency is rejected,
349
+ * or the message was not admitted.
350
+ */
351
+ async sendMessage(
352
+ sender: Agent,
353
+ targetId: SessionId,
354
+ content: ContentBlock[],
355
+ options: SubagentSendMessageOptions,
356
+ ): Promise<MessageId> {
357
+ return this.requireManager().sendMessage(sender, targetId, content, options);
358
+ }
359
+
360
+ /**
361
+ * Deliver one host-protocol message to a direct continuable child.
362
+ * Symbol-keyed so host adapters can preserve their own source descriptors without
363
+ * widening the public Service Definition or impersonating an Agent sender.
364
+ * @param parent - exact live direct parent authorizing delivery.
365
+ * @param childId - durable direct-child session id.
366
+ * @param content - host-authored content to deliver.
367
+ * @param source - durable host-protocol source descriptor.
368
+ * @param signal - caller cancellation before inbox acceptance.
369
+ * @param delivery - Queue as a distinct turn or Steer at the nearest step.
370
+ * @returns the accepted message's inbox id.
371
+ */
372
+ private [deliverSubagentPrompt](
373
+ parent: Agent,
374
+ childId: SessionId,
375
+ content: ContentBlock[],
376
+ source: MessageSource,
377
+ signal: AbortSignal,
378
+ delivery: SubagentDelivery,
379
+ ): Promise<MessageId> {
380
+ return delivery === "steer"
381
+ ? this.requireManager().steerPrompt(parent, childId, content, source, signal)
382
+ : this.requireManager().queuePrompt(parent, childId, content, source, signal);
383
+ }
384
+
385
+ /**
386
+ * Interrupt one live child's current execution under a human parent
387
+ * address or an exact live ancestor Agent. Fire-and-return: the cancel
388
+ * signal is issued before this returns, but the target may keep running
389
+ * until it observes the signal. Unclaimed pending inbox work, the Activation,
390
+ * and published descendants are preserved; claimed work is not requeued.
391
+ * Once the interrupted Agent is idle, a waking send resumes the parked FIFO
392
+ * queue. External backends stop their single execution. An absent target
393
+ * is an accepted no-op, as is a manager-less composition, which cannot own a
394
+ * live Activation.
395
+ * @param targetSessionId - the durable child session id to interrupt.
396
+ * @param authority - the human parent address or exact live ancestor Agent.
397
+ * @throws {SubagentError} `UNAUTHORIZED` when the authority does not own the
398
+ * live target.
399
+ */
400
+ interrupt(targetSessionId: SessionId, authority: SubagentInterruptAuthority): void {
401
+ this.manager?.interrupt(targetSessionId, authority);
402
+ }
403
+
404
+ /**
405
+ * Close subagent admission below exact live parent Agents, stop only their
406
+ * visible descendant Activations synchronously, then await admitted scoped
407
+ * materializations and release those forests child-first. The scoped cutoff
408
+ * lasts until each exact parent leaves the registry; unrelated parent trees
409
+ * remain live.
410
+ * @param parents - exact host-owned parent Agents entering teardown.
411
+ * @returns once every retained descendant activation released its execution handle.
412
+ * @throws an aggregate error after all branches settle when any failed.
413
+ */
414
+ async drainDescendants(parents: readonly Agent[]): Promise<void> {
415
+ const manager = this.manager;
416
+ // An absent activation manager cannot own materialized children.
417
+ if (manager === undefined) return;
418
+ await manager.drainDescendants(parents);
419
+ }
420
+
421
+ /**
422
+ * Release selected resident direct children of one exact live
423
+ * parent. Other children of the same parent remain admitted and resident.
424
+ * Absent targets and a manager-less composition are accepted no-ops.
425
+ * @param parent - exact live direct parent authorizing the selected release.
426
+ * @param childIds - durable direct-child ids to release when resident.
427
+ * @returns once every selected activation released its execution handle.
428
+ * @throws {SubagentError} `UNAUTHORIZED` when a resident target belongs to a
429
+ * different parent or the supplied parent identity is stale.
430
+ */
431
+ async drainChildren(parent: Agent, childIds: readonly SessionId[]): Promise<void> {
432
+ const manager = this.manager;
433
+ if (manager === undefined) return;
434
+ await manager.drainChildren(parent, childIds);
435
+ }
436
+
437
+ /**
438
+ * Read the parent's durable direct-child catalog without loading or resuming an Agent.
439
+ * The service owns and releases the live-preferred Session observation.
440
+ * @param parentSessionId - parent whose direct children are requested.
441
+ * @param signal - cancellation forwarded to the Session query.
442
+ * @returns catalog children in parent event order.
443
+ * @throws {@link SubagentError} when query or catalog projection is unavailable.
444
+ * @throws SessionQueryError when the parent cannot be read or the query is cancelled.
445
+ */
446
+ listChildren(parentSessionId: SessionId, signal?: AbortSignal): Promise<SubagentCatalogEntry[]> {
447
+ return listSubagentChildren(this.ctx, parentSessionId, signal);
448
+ }
449
+
450
+ /**
451
+ * Recursively list reachable parent catalogs in stable pre-order, preserving
452
+ * each catalog's event order. Each row carries its catalog parent and depth;
453
+ * external children are leaves; one-shot and unknown-mode children remain
454
+ * traversal nodes. Unknown modes
455
+ * produce unsupported diagnostics. Unreadable child catalogs produce corrupt
456
+ * or unavailable diagnostics and stop only that branch. Root read failures,
457
+ * missing services or projections, and cancellation reject the whole listing.
458
+ * Each catalog is observed once and released before the next read. No Agent
459
+ * is loaded or resumed; Sessions absent from reachable catalogs are omitted.
460
+ * @param rootSessionId - session whose catalog starts descendant discovery.
461
+ * @param signal - cancellation forwarded to and checked around each catalog read.
462
+ * @returns children and branch diagnostics in parent-catalog pre-order.
463
+ * @throws {@link SubagentError} when listing dependencies are unavailable or the caller cancels.
464
+ * @throws SessionQueryError when the root catalog cannot be read.
465
+ */
466
+ listDescendants(
467
+ rootSessionId: SessionId,
468
+ signal?: AbortSignal,
469
+ ): Promise<SubagentDescendantListEntry[]> {
470
+ return listSubagentDescendants(this.ctx, rootSessionId, signal);
471
+ }
472
+
473
+ /**
474
+ * Deliver one browser-authored message to a continuable child through the
475
+ * exact live direct parent, retaining the caller-minted request identity and
476
+ * validated browser zone on the accepted message. Success identifies the
477
+ * message the child's inbox accepted; later execution is independent of this
478
+ * call. Queue delivery targets a later turn; steer delivery targets the
479
+ * nearest step and retains the Agent loop's best-effort fallback semantics.
480
+ * Image parts are admitted and persisted through the attachment store
481
+ * before delivery, and the child's model must accept image input.
482
+ * Cold resume at capacity rejects with `subagent/delivery-unavailable`.
483
+ * @param request - durable address, delivery, minted identity, content, and optional browser zone.
484
+ * @param signal - carrier cancellation, owning the call until inbox acceptance.
485
+ * @returns the accepted message's inbox identity.
486
+ * @throws {RemoteError} `gateway/bad-request`, `subagent/attachment-invalid`,
487
+ * `subagent/invalid-time-zone`, `subagent/parent-unavailable`,
488
+ * `subagent/not-resumable`, `subagent/unauthorized`,
489
+ * `subagent/delivery-unavailable`, `gateway/cancelled`, or `gateway/internal`.
490
+ */
491
+ @Remote("prompt")
492
+ async prompt(
493
+ request: SubagentPromptRequest,
494
+ signal: AbortSignal,
495
+ ): Promise<SubagentPromptReceipt> {
496
+ const { parentSessionId, childSessionId, clientTimeZone, delivery } = request;
497
+ validateControlRequest("subagent.prompt", request);
498
+ const canonicalTimeZone =
499
+ clientTimeZone === undefined ? undefined : canonicalClientTimeZone(clientTimeZone);
500
+ if (clientTimeZone !== undefined && canonicalTimeZone === undefined) {
501
+ throw new RemoteError(
502
+ "subagent/invalid-time-zone",
503
+ "clientTimeZone must be UTC or a valid IANA Area/Location name",
504
+ { value: clientTimeZone },
505
+ );
506
+ }
507
+ const parent = this.ctx.get("agents")?.get(parentSessionId);
508
+ if (parent === undefined) {
509
+ throw new RemoteError(
510
+ "subagent/parent-unavailable",
511
+ `parent session "${parentSessionId}" is not live`,
512
+ { parentSessionId },
513
+ );
514
+ }
515
+ const principal = principalOf(this.ctx.invocation);
516
+ const source: BrowserPromptSource = {
517
+ kind: "user",
518
+ rpcId: request.requestId,
519
+ ...(canonicalTimeZone === undefined ? {} : { clientTimeZone: canonicalTimeZone }),
520
+ ...(principal === undefined ? {} : { principal }),
521
+ };
522
+ try {
523
+ // Admission precedes delivery: image parts become durable references
524
+ // here, so the child inbox only ever accepts Host-persisted attachments.
525
+ let content: ContentBlock[];
526
+ if (
527
+ request.content.every(
528
+ (part): part is { readonly type: "text"; readonly text: string } => part.type === "text",
529
+ )
530
+ ) {
531
+ content = request.content.map((part) => ({ type: "text", text: part.text }));
532
+ } else {
533
+ const attachments = this.ctx.get("attachments");
534
+ if (attachments === undefined)
535
+ throw new Error("subagent image prompt requires an attachment store");
536
+ content = await attachments.admitPromptContent(request.content);
537
+ }
538
+ return {
539
+ messageId: await this[deliverSubagentPrompt](
540
+ parent,
541
+ childSessionId,
542
+ content,
543
+ source,
544
+ signal,
545
+ delivery,
546
+ ),
547
+ };
548
+ } catch (error: unknown) {
549
+ return rejectPrompt(error, childSessionId, signal);
550
+ }
551
+ }
552
+
553
+ /**
554
+ * Remote face of {@link interrupt} under one durable parent address. No
555
+ * catalog, history, persistence, or parent Agent lookup runs: the core
556
+ * primitive alone authorizes the address against the live Activation, which
557
+ * is what keeps a live child interruptible while its parent Agent is offline.
558
+ * Absent, idle, and already-completed targets are accepted no-ops there.
559
+ * @param childSessionId - durable child session id to interrupt.
560
+ * @param parentSessionId - durable direct parent whose authority is claimed.
561
+ * @param mode - required continuable-address discriminator.
562
+ * @returns acknowledgement that the cancel signal was admitted, not that the target is quiescent.
563
+ * @throws {RemoteError} `gateway/bad-request` for an empty id,
564
+ * `subagent/unauthorized` when the address does not own the live target,
565
+ * otherwise `gateway/internal`.
566
+ */
567
+ @Remote("interruptByParent")
568
+ interruptByParent(
569
+ childSessionId: SessionId,
570
+ parentSessionId: SessionId,
571
+ mode: "continuable",
572
+ ): SubagentInterruptReceipt {
573
+ validateControlRequest("subagent.interrupt", { childSessionId, parentSessionId, mode });
574
+ try {
575
+ this.interrupt(childSessionId, { kind: "user", parentSessionId });
576
+ } catch (error: unknown) {
577
+ if (error instanceof SubagentError && error.code === "UNAUTHORIZED") {
578
+ throw new RemoteError(
579
+ "subagent/unauthorized",
580
+ "subagent does not belong to this parent",
581
+ { childSessionId },
582
+ { cause: error },
583
+ );
584
+ }
585
+ throw new RemoteError("gateway/internal", "subagent interrupt failed", {}, { cause: error });
586
+ }
587
+ return { accepted: true };
588
+ }
589
+
590
+ /**
591
+ * Register a provider under its name. Registration is effect-scoped and HMR
592
+ * safe; removing a provider blocks new starts but does not revoke runs that
593
+ * were already returned to their holders. Providers without either execution
594
+ * method are rejected with UNSUPPORTED_CAPABILITY before registration.
595
+ * @param provider - the trusted provider implementation.
596
+ * @returns the exact Cordis effect disposer.
597
+ */
598
+ registerProvider(provider: SubagentProvider): () => void {
599
+ const name = provider.name;
600
+ if (provider.start === undefined && provider.prepareContinuable === undefined) {
601
+ throw new SubagentError(
602
+ `subagent provider "${name}" must implement start or prepareContinuable`,
603
+ "UNSUPPORTED_CAPABILITY",
604
+ );
605
+ }
606
+ // oxlint-disable-next-line typescript/no-misused-promises -- synchronous disposer
607
+ return this.ctx.effect(
608
+ function* (this: SubagentRuntime) {
609
+ if (this.providers.has(name)) {
610
+ throw new SubagentError(
611
+ `a subagent provider named "${name}" is already registered`,
612
+ "DUPLICATE_PROVIDER",
613
+ );
614
+ }
615
+ this.providers.set(name, provider);
616
+ yield () => {
617
+ this.providers.delete(name);
618
+ this.emitLifecycle("subagent/provider-removed", name);
619
+ };
620
+ // A throwing added-listener unwinds the yielded rollback, matching the
621
+ // repository's fail-loud registration semantics.
622
+ this.ctx.emit("subagent/provider-added", provider);
623
+ }.bind(this),
624
+ "subagents.registerProvider()",
625
+ );
626
+ }
627
+
628
+ /**
629
+ * Look up a provider by name.
630
+ * @param name - the provider name.
631
+ * @returns the provider, or undefined when absent.
632
+ */
633
+ getProvider(name: string): SubagentProvider | undefined {
634
+ return this.providers.get(name);
635
+ }
636
+
637
+ /**
638
+ * List registered provider names in insertion order.
639
+ * @returns the registered names.
640
+ */
641
+ list(): string[] {
642
+ return [...this.providers.keys()];
643
+ }
644
+
645
+ /**
646
+ * Resolve one provider's detached continuable-creation contribution. Method
647
+ * presence on the provider IS the capability, so a provider without it is
648
+ * rejected before the manager reserves any child resources.
649
+ */
650
+ private async prepareContinuable(
651
+ name: string,
652
+ request: ContinuableCreateRequest,
653
+ ): Promise<ContinuableCreateSpec> {
654
+ const provider = this.expectProvider(name) as SubagentProvider &
655
+ Required<Pick<SubagentProvider, "prepareContinuable">>;
656
+ return provider.prepareContinuable(request);
657
+ }
658
+
659
+ /** Look up a provider for dispatch or fail loud. */
660
+ private expectProvider(name: string): SubagentProvider {
661
+ const provider = this.providers.get(name);
662
+ if (provider === undefined) {
663
+ throw new SubagentError(`no subagent provider registered for "${name}"`, "NO_PROVIDER");
664
+ }
665
+ return provider;
666
+ }
667
+
668
+ /** Resolve the subagent manager or fail loud. */
669
+ private requireManager(): SubagentManager {
670
+ if (this.manager === undefined) {
671
+ throw new SubagentError(
672
+ "continuable subagents require the agents service",
673
+ "CONTINUATION_UNAVAILABLE",
674
+ );
675
+ }
676
+ return this.manager;
677
+ }
678
+
679
+ /**
680
+ * Build the lifecycle observer for one continuable Activation's residency
681
+ * epoch, so the manager publishes its edges without owning event dispatch.
682
+ */
683
+ private observeActivation(
684
+ provider: string,
685
+ childId: SessionId,
686
+ parent: Agent,
687
+ ): ActivationObserver {
688
+ return createActivationObserver(this.emitLifecycle, provider, childId, parent);
689
+ }
690
+
691
+ /** Reject the first requested capability that the provider lacks. */
692
+ private assertCapabilities(provider: SubagentProvider, request: SubagentStartRequest): void {
693
+ if (
694
+ request.agentPreset !== undefined &&
695
+ (!provider.capabilities.agentPreset || provider.inheritsParentContext)
696
+ ) {
697
+ throw new SubagentError(
698
+ `subagent provider "${provider.name}" does not support independent agent preset selection`,
699
+ "UNSUPPORTED_CAPABILITY",
700
+ );
701
+ }
702
+ const needs: { when: boolean; cap: keyof SubagentCapabilities }[] = [
703
+ { when: request.agentOptions !== undefined, cap: "agentOptions" },
704
+ { when: request.outputSchema !== undefined, cap: "outputSchema" },
705
+ { when: request.maxDepth !== undefined, cap: "depthLimit" },
706
+ ];
707
+ for (const { when, cap } of needs) {
708
+ if (when && !provider.capabilities[cap]) {
709
+ throw new SubagentError(
710
+ `subagent provider "${provider.name}" does not support the "${cap}" capability`,
711
+ "UNSUPPORTED_CAPABILITY",
712
+ );
713
+ }
714
+ }
715
+ }
716
+ }
717
+
718
+ export default SubagentRuntime;