@xneog/dsh-subagent 0.1.0 → 0.1.3-alpha.1

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 (41) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +108 -76
  3. package/README.zh.md +112 -80
  4. package/lib/index.js +1258 -718
  5. package/lib/typert.host.d.ts +3 -0
  6. package/lib/typert.host.js +923 -0
  7. package/lib/typert.remote-client.d.ts +27 -0
  8. package/lib/typert.remote-client.js +159 -0
  9. package/lib/types/assistant-output.d.ts +3 -3
  10. package/lib/types/assistant-output.js +8 -4
  11. package/lib/types/child-agent.d.ts +16 -5
  12. package/lib/types/child-agent.js +51 -13
  13. package/lib/types/client.d.ts +2 -1
  14. package/lib/types/client.js +1 -1
  15. package/lib/types/continuation.d.ts +100 -72
  16. package/lib/types/continuation.js +439 -169
  17. package/lib/types/control-types.d.ts +144 -0
  18. package/lib/types/control-types.js +9 -0
  19. package/lib/types/control.d.ts +67 -0
  20. package/lib/types/control.js +115 -0
  21. package/lib/types/descriptor-seed.d.ts +1 -1
  22. package/lib/types/descriptor-seed.js +1 -1
  23. package/lib/types/descriptor.d.ts +6 -1
  24. package/lib/types/descriptor.js +6 -2
  25. package/lib/types/index.d.ts +103 -69
  26. package/lib/types/index.js +436 -287
  27. package/lib/types/internal.d.ts +59 -0
  28. package/lib/types/internal.js +58 -0
  29. package/lib/types/lifecycle.js +4 -3
  30. package/lib/types/list-children.d.ts +12 -59
  31. package/lib/types/list-children.js +166 -101
  32. package/lib/types/out-of-process.d.ts +5 -2
  33. package/lib/types/out-of-process.js +42 -4
  34. package/lib/types/projection-types.d.ts +4 -3
  35. package/lib/types/projection.d.ts +55 -8
  36. package/lib/types/projection.js +33 -17
  37. package/lib/types/run-settlement.js +17 -6
  38. package/lib/types/types.d.ts +25 -0
  39. package/package.json +67 -37
  40. package/lib/types/activation-setup-registry.d.ts +0 -57
  41. package/lib/types/activation-setup-registry.js +0 -148
@@ -4,10 +4,8 @@
4
4
  * child before returning its run, so fulfillment is the single publication and
5
5
  * ownership-transfer boundary.
6
6
  *
7
- * Unlike the bash seam (one executor per context, second load throws), MULTIPLE
8
- * providers coexist here: each registers under a unique name and a caller picks
9
- * one by name. The shape mirrors the LLM adapter registry
10
- * (`LlmRuntime.registerAdapter`), not the single-service bash executor.
7
+ * Multiple providers coexist: each registers under a unique name and callers
8
+ * select one by name.
11
9
  *
12
10
  * This package owns the Service Definition role of the capability seam. Service Providers
13
11
  * (`@xneog/dsh-subagent-spawn-in-process`, `-fork`, `-acp`) and the model-facing
@@ -15,8 +13,8 @@
15
13
  *
16
14
  * Public operations express caller intent: `start` returns one published owned
17
15
  * one-shot run, `startContinuable` establishes a durable continuable child, and
18
- * `followup` delivers later content without exposing whether the child is
19
- * resident. Continuable children never become a {@link SubagentRun}: the
16
+ * `sendMessage` steers between adjacent Agents without exposing whether a child
17
+ * is resident. Continuable children never become a {@link SubagentRun}: the
20
18
  * continuation manager holds their `AgentHandle` directly and orders every turn
21
19
  * through the child's own inbox, so providers contribute only the detached
22
20
  * creation spec and see no handle, turn, or teardown. Child and descendant
@@ -30,310 +28,461 @@
30
28
  *
31
29
  * @module @xneog/dsh-subagent
32
30
  */
33
- import { Service } from '@xneog/cordis';
31
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
32
+ var useValue = arguments.length > 2;
33
+ for (var i = 0; i < initializers.length; i++) {
34
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
35
+ }
36
+ return useValue ? value : void 0;
37
+ };
38
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
39
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
40
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
41
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
42
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
43
+ var _, done = false;
44
+ for (var i = decorators.length - 1; i >= 0; i--) {
45
+ var context = {};
46
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
47
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
48
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
49
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
50
+ if (kind === "accessor") {
51
+ if (result === void 0) continue;
52
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
53
+ if (_ = accept(result.get)) descriptor.get = _;
54
+ if (_ = accept(result.set)) descriptor.set = _;
55
+ if (_ = accept(result.init)) initializers.unshift(_);
56
+ }
57
+ else if (_ = accept(result)) {
58
+ if (kind === "field") initializers.unshift(_);
59
+ else descriptor[key] = _;
60
+ }
61
+ }
62
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
63
+ done = true;
64
+ };
34
65
  import { scopeTarget } from '@xneog/dsh-scope';
35
66
  import { assertObjectJsonSchema } from '@xneog/dsh-tools';
67
+ import { canonicalClientTimeZone } from '@xneog/dsh-util-time';
68
+ import { Remote, RemoteError, TypertRemoteService } from '@xneog/dsh-typert-protocol';
69
+ import { catalogView, rejectCatalogRead, rejectPrompt, validateControlRequest, } from "./control.js";
36
70
  import { SubagentError } from "./error.js";
37
71
  import { assertSubagentMaxDepth } from "./depth.js";
38
72
  import { createActivationObserver, createLifecycleEmitter, observeRun } from "./lifecycle.js";
39
73
  import SubagentContinuationManager from "./continuation.js";
40
- import SubagentActivationSetupRegistry from "./activation-setup-registry.js";
41
74
  import { listChildren as listSubagentChildren, listDescendants as listSubagentDescendants } from "./list-children.js";
42
75
  import { snapshotSubagentDescriptor } from "./descriptor.js";
43
76
  import { subagentIdentityProjectionDefinition, subagentTimingProjectionDefinition } from "./projection.js";
77
+ import { deliverSubagentPrompt } from "./internal.js";
44
78
  export * from "./out-of-process.js";
45
79
  export { AssistantOutputFold, finalAssistantOutput } from "./assistant-output.js";
46
80
  export { SubagentRunId } from "./types.js";
47
81
  export { foldSubagentDescriptor, snapshotSubagentDescriptor, SUBAGENT_DESCRIPTOR_VERSION, } from "./descriptor.js";
48
- export { seedDescriptorTurn } from "./descriptor-seed.js";
49
82
  export { SubagentError } from "./error.js";
50
83
  export { settleRun } from "./run-settlement.js";
51
84
  export { assertSubagentMaxDepth, delegationDepthOf } from "./depth.js";
52
- export { appendDelegatedPolicyOverrides, applyChildComposition, captureDelegatedPolicyOverrides, childSessionMeta, resolveChildAgentOptions, resolveChildDepth, SubagentDepthError, } from "./child-agent.js";
85
+ export { appendDelegatedPolicyOverrides, applyChildComposition, captureDelegatedPolicyOverrides, childSessionMeta, parentAgentOptionsForDelegation, resolveChildAgentOptions, resolveChildDepth, SubagentDepthError, } from "./child-agent.js";
53
86
  /** Named provider registry with one-shot runs, durable discovery, and continuable-child operations. */
54
- export class SubagentRuntime extends Service {
55
- providers = new Map();
56
- continuations;
57
- /** Deployment contributions composed into unpublished continuable children. */
58
- setupRegistry = new SubagentActivationSetupRegistry();
59
- /**
60
- * The contained lifecycle-edge publisher. Built here because scoped dispatch
61
- * keys its carrier by this exact service instance, whose own context filter
62
- * composes into the carrier.
63
- */
64
- emitLifecycle;
65
- constructor(ctx) {
66
- super(ctx, 'subagents');
67
- this.emitLifecycle = createLifecycleEmitter(this.ctx, parent => scopeTarget(this, parent));
68
- ctx.inject(['agents'], (childCtx) => {
69
- const manager = new SubagentContinuationManager(childCtx, {
70
- prepareContinuable: (name, request) => this.prepareContinuable(name, request),
71
- observeActivation: (provider, childId, parent) => this.observeActivation(provider, childId, parent),
72
- }, this.setupRegistry);
73
- this.continuations = manager;
74
- childCtx.effect(() => () => {
75
- /* v8 ignore else -- one injected binding owns the slot until its fiber disposes. */
76
- if (this.continuations === manager)
77
- this.continuations = undefined;
78
- }, 'subagents.continuationBinding()');
79
- });
80
- ctx.inject(['sessionProjections'], (projectionCtx) => {
81
- projectionCtx.sessionProjections.register(subagentTimingProjectionDefinition);
82
- projectionCtx.sessionProjections.register(subagentIdentityProjectionDefinition);
83
- });
84
- }
85
- /**
86
- * Establish one durable continuable child and deliver its initial prompt.
87
- * Resolves when the child's inbox accepts that prompt, without waiting for the
88
- * turn to start or for the message to reach the Session log; any earlier
89
- * failure rejects with no ids and rolls back the child entirely.
90
- * @param spec - provider, delegation request, and caller cancellation.
91
- * @returns the durable child id and the accepted prompt's message id.
92
- * @throws when continuation services are unavailable or materialization fails.
93
- */
94
- async startContinuable(spec) {
95
- return this.requireContinuations().startContinuable(spec);
96
- }
97
- /**
98
- * Deliver one later message to a continuable child as its next FIFO turn. A
99
- * resident child's Agent inbox accepts it directly (waking a `waiting`
100
- * Activation), while an absent one is cold-resumed from its persisted
101
- * Session. The Agent inbox is the only queue, so every accepted message has
102
- * one observable order.
103
- * @param parent - the exact live direct parent authorizing this delivery.
104
- * @param childId - durable child session id.
105
- * @param content - user-role content to deliver.
106
- * @param options - the message source fields and caller cancellation, which stops the
107
- * operation only before inbox acceptance.
108
- * @returns the accepted message's inbox id.
109
- * @throws when continuation services are unavailable, parent authority is
110
- * rejected, or the message was not admitted.
111
- */
112
- async followup(parent, childId, content, options) {
113
- return this.requireContinuations().followup(parent, childId, content, options);
114
- }
115
- /**
116
- * Interrupt one live continuable child's current turn under a human parent
117
- * address or an exact live ancestor Agent. Fire-and-return: the cancel
118
- * signal is issued before this returns, but the target may keep running
119
- * until it observes the signal. Unclaimed pending inbox work, the Activation,
120
- * and published descendants are preserved; claimed work is not requeued.
121
- * Once the interrupted driver is idle, a waking send resumes the parked FIFO
122
- * queue. An absent target — including a one-shot or unknown id —
123
- * is an accepted no-op, as is a manager-less composition, which cannot own a
124
- * live Activation.
125
- * @param targetSessionId - the durable child session id to interrupt.
126
- * @param authority - the human parent address or exact live ancestor Agent.
127
- * @throws {SubagentError} `UNAUTHORIZED` when the authority does not own the
128
- * live target.
129
- */
130
- interrupt(targetSessionId, authority) {
131
- this.continuations?.interrupt(targetSessionId, authority);
132
- }
133
- /**
134
- * Deliver selected content from one live continuable child to its durable
135
- * direct parent. The child is the authority credential; callers cannot name a
136
- * recipient. Reporting does not conclude the child's turn or Activation.
137
- * @param child - exact live reporting child.
138
- * @param content - selected model-facing content.
139
- * @param options - parent scheduling and pre-acceptance cancellation.
140
- * @returns the stable identity of the parent-accepted message.
141
- * @throws when continuation services are unavailable, sender authorization
142
- * fails, or the direct parent is not live.
143
- */
144
- async reportFrom(child, content, options) {
145
- return this.requireContinuations().reportFrom(child, content, options);
146
- }
147
- /**
148
- * Compose one deployment capability into every continuable child's
149
- * unpublished creation context on fresh creation and cold resume. Grants wait
150
- * for the next Activation; removing the contribution revokes every resident
151
- * installation immediately.
152
- * @param contribution - synchronous child-scope installer.
153
- * @returns the exact Cordis effect disposer.
154
- */
155
- registerContinuableSetup(contribution) {
156
- // oxlint-disable-next-line typescript/no-misused-promises -- synchronous cleanup; direct return preserves disposer identity
157
- return this.ctx.effect(() => this.setupRegistry.register(contribution), 'subagents.registerContinuableSetup()');
158
- }
159
- /**
160
- * Close continuable admission below exact live parent Agents, stop only their
161
- * visible descendant Activations synchronously, then await admitted scoped
162
- * materializations and release those forests child-first. The scoped cutoff
163
- * lasts until each exact parent leaves the registry; unrelated parent trees
164
- * remain live.
165
- * @param parents - exact host-owned parent Agents entering teardown.
166
- * @returns once every retained descendant Activation released its `AgentHandle`.
167
- * @throws an aggregate error after all branches settle when any failed.
168
- */
169
- async drainContinuableDescendants(parents) {
170
- const manager = this.continuations;
171
- // Absent continuation services means nothing was ever materialized.
172
- if (manager === undefined)
173
- return;
174
- await manager.drainDescendants(parents);
175
- }
176
- /**
177
- * Enumerate the parent's direct session-backed subagents without loading or
178
- * resuming an Agent and without any query service: the listing merges the live
179
- * session store with optional session persistence (live-preferred) and
180
- * serves each child's durable mode/label from the registered `subagent`
181
- * projection unit down a three-rung ladder — the registry's watermark
182
- * snapshot for a live child; for a cold one, a durable projection-cache
183
- * row when the optional cache serves an own-suffix identity (its `seq`
184
- * gate proves the value postdates the fork seed, where a child's own
185
- * descriptor is immutable once appended), else one persistence inspection
186
- * folded through the registry. The
187
- * projection fold is the single classification authority; per-child
188
- * diagnostics relay a fold that served no identity or a failed inspection,
189
- * never a list-time descriptor parse. Absent persistence, enumeration is
190
- * live-only (a cold child cannot be resumed then either, so its absence is
191
- * capability absence, not an error). This service consults no Agent
192
- * registrations, Activations, or providers.
193
- *
194
- * Every persistence read receives `signal`, and the listing rechecks
195
- * cancellation around each of those awaits. Read rejections that settle
196
- * after an abort become a stable `SubagentError` with code `CANCELLED`.
197
- * @param parentSessionId - parent session whose direct children are listed.
198
- * @param signal - caller-owned cancellation forwarded to persistence reads
199
- * and observed around every read await.
200
- * @returns children and per-child diagnostics ordered by `createdAt`, then id.
201
- * @throws {@link SubagentError} when the projection registry or the session
202
- * store is not mounted, or the caller cancels the listing.
203
- */
204
- listChildren(parentSessionId, signal) {
205
- return listSubagentChildren(this.ctx, parentSessionId, signal);
206
- }
207
- /**
208
- * Enumerate the root's complete session-backed subagent tree in stable
209
- * pre-order from one live-preferred corpus, without loading or resuming an
210
- * Agent. Ordinary sessions and one-shot children remain traversal nodes so
211
- * continuable descendants below them are discovered; each returned entry
212
- * adds its durable `parentId` and root-relative `depth`. Identity resolution,
213
- * diagnostics, optional persistence, and cancellation follow the same
214
- * projection-backed contract as {@link listChildren}.
215
- * @param rootSessionId - session whose complete descendant tree is listed.
216
- * @param signal - caller-owned cancellation forwarded to persistence reads
217
- * and observed around every read await.
218
- * @returns children and per-candidate diagnostics with tree position, in
219
- * stable pre-order.
220
- * @throws {@link SubagentError} under the same conditions as {@link listChildren}.
221
- */
222
- listDescendants(rootSessionId, signal) {
223
- return listSubagentDescendants(this.ctx, rootSessionId, signal);
224
- }
225
- /**
226
- * Register a provider under its name. Registration is effect-scoped and HMR
227
- * safe; removing a provider blocks new starts but does not revoke runs that
228
- * were already returned to their holders.
229
- * @param provider - the trusted provider implementation.
230
- * @returns the exact Cordis effect disposer.
231
- */
232
- registerProvider(provider) {
233
- const name = provider.name;
234
- // oxlint-disable-next-line typescript/no-misused-promises -- synchronous cleanup; direct return preserves disposer identity
235
- return this.ctx.effect(function* () {
236
- if (this.providers.has(name)) {
237
- throw new SubagentError(`a subagent provider named "${name}" is already registered`, 'DUPLICATE_PROVIDER');
87
+ let SubagentRuntime = (() => {
88
+ let _classSuper = TypertRemoteService;
89
+ let _instanceExtraInitializers = [];
90
+ let _remoteExportList_decorators;
91
+ let _prompt_decorators;
92
+ let _interruptByParent_decorators;
93
+ return class SubagentRuntime extends _classSuper {
94
+ static {
95
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
96
+ _remoteExportList_decorators = [Remote('list')];
97
+ _prompt_decorators = [Remote('prompt')];
98
+ _interruptByParent_decorators = [Remote('interruptByParent')];
99
+ __esDecorate(this, null, _remoteExportList_decorators, { kind: "method", name: "remoteExportList", static: false, private: false, access: { has: obj => "remoteExportList" in obj, get: obj => obj.remoteExportList }, metadata: _metadata }, null, _instanceExtraInitializers);
100
+ __esDecorate(this, null, _prompt_decorators, { kind: "method", name: "prompt", static: false, private: false, access: { has: obj => "prompt" in obj, get: obj => obj.prompt }, metadata: _metadata }, null, _instanceExtraInitializers);
101
+ __esDecorate(this, null, _interruptByParent_decorators, { kind: "method", name: "interruptByParent", static: false, private: false, access: { has: obj => "interruptByParent" in obj, get: obj => obj.interruptByParent }, metadata: _metadata }, null, _instanceExtraInitializers);
102
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
103
+ }
104
+ providers = (__runInitializers(this, _instanceExtraInitializers), new Map());
105
+ continuations;
106
+ /**
107
+ * The contained lifecycle-edge publisher. Built here because scoped dispatch
108
+ * keys its carrier by this exact service instance, whose own context filter
109
+ * composes into the carrier.
110
+ */
111
+ emitLifecycle;
112
+ constructor(ctx) {
113
+ super(ctx, 'subagents');
114
+ this.emitLifecycle = createLifecycleEmitter(this.ctx, parent => scopeTarget(this, parent));
115
+ ctx.inject(['agents'], (childCtx) => {
116
+ const manager = new SubagentContinuationManager(childCtx, {
117
+ prepareContinuable: (name, request) => this.prepareContinuable(name, request),
118
+ observeActivation: (provider, childId, parent) => this.observeActivation(provider, childId, parent),
119
+ });
120
+ this.continuations = manager;
121
+ childCtx.effect(() => () => {
122
+ /* v8 ignore else -- one injected binding owns the slot until its fiber disposes. */
123
+ if (this.continuations === manager)
124
+ this.continuations = undefined;
125
+ }, 'subagents.continuationBinding()');
126
+ });
127
+ ctx.inject(['sessionProjections'], (projectionCtx) => {
128
+ projectionCtx.sessionProjections.register(subagentTimingProjectionDefinition);
129
+ projectionCtx.sessionProjections.register(subagentIdentityProjectionDefinition);
130
+ });
131
+ }
132
+ /**
133
+ * Establish one durable continuable child and deliver its initial prompt.
134
+ * Resolves when the child's inbox accepts that prompt, without waiting for the
135
+ * turn to start or for the message to reach the Session log; any earlier
136
+ * failure rejects with no ids and rolls back the child entirely.
137
+ * @param spec - provider, delegation request, and caller cancellation.
138
+ * @returns the durable child id and the accepted prompt's message id.
139
+ * @throws when continuation services are unavailable or materialization fails.
140
+ */
141
+ async startContinuable(spec) {
142
+ return this.requireContinuations().startContinuable(spec);
143
+ }
144
+ /**
145
+ * Steer one model-authored message to the sender's direct parent or direct
146
+ * continuable child. A running target admits it at the nearest step boundary;
147
+ * an idle target starts a turn, and an absent direct child cold-resumes from
148
+ * persistence. The service derives durable sender attribution from the exact
149
+ * live sender. Caller cancellation stops only pre-acceptance work.
150
+ * @param sender - exact live Agent authorizing and originating the message.
151
+ * @param targetId - durable direct-parent or direct-child session id.
152
+ * @param content - model-authored content to deliver.
153
+ * @param options - caller cancellation before inbox acceptance.
154
+ * @returns the accepted message's inbox id.
155
+ * @throws when continuation services are unavailable, adjacency is rejected,
156
+ * or the message was not admitted.
157
+ */
158
+ async sendMessage(sender, targetId, content, options) {
159
+ return this.requireContinuations().sendMessage(sender, targetId, content, options);
160
+ }
161
+ /**
162
+ * Deliver one host-protocol message to a direct continuable child.
163
+ * Symbol-keyed so host adapters can preserve their own provenance without
164
+ * widening the public Service Definition or impersonating an Agent sender.
165
+ * @param parent - exact live direct parent authorizing delivery.
166
+ * @param childId - durable direct-child session id.
167
+ * @param content - host-authored content to deliver.
168
+ * @param source - durable host-protocol provenance.
169
+ * @param signal - caller cancellation before inbox acceptance.
170
+ * @param delivery - Queue as a distinct turn or Steer at the nearest step.
171
+ * @returns the accepted message's inbox id.
172
+ */
173
+ [deliverSubagentPrompt](parent, childId, content, source, signal, delivery) {
174
+ return delivery === 'steer'
175
+ ? this.requireContinuations().steerPrompt(parent, childId, content, source, signal)
176
+ : this.requireContinuations().queuePrompt(parent, childId, content, source, signal);
177
+ }
178
+ /**
179
+ * Interrupt one live continuable child's current turn under a human parent
180
+ * address or an exact live ancestor Agent. Fire-and-return: the cancel
181
+ * signal is issued before this returns, but the target may keep running
182
+ * until it observes the signal. Unclaimed pending inbox work, the Activation,
183
+ * and published descendants are preserved; claimed work is not requeued.
184
+ * Once the interrupted driver is idle, a waking send resumes the parked FIFO
185
+ * queue. An absent target — including a one-shot or unknown id —
186
+ * is an accepted no-op, as is a manager-less composition, which cannot own a
187
+ * live Activation.
188
+ * @param targetSessionId - the durable child session id to interrupt.
189
+ * @param authority - the human parent address or exact live ancestor Agent.
190
+ * @throws {SubagentError} `UNAUTHORIZED` when the authority does not own the
191
+ * live target.
192
+ */
193
+ interrupt(targetSessionId, authority) {
194
+ this.continuations?.interrupt(targetSessionId, authority);
195
+ }
196
+ /**
197
+ * Close continuable admission below exact live parent Agents, stop only their
198
+ * visible descendant Activations synchronously, then await admitted scoped
199
+ * materializations and release those forests child-first. The scoped cutoff
200
+ * lasts until each exact parent leaves the registry; unrelated parent trees
201
+ * remain live.
202
+ * @param parents - exact host-owned parent Agents entering teardown.
203
+ * @returns once every retained descendant Activation released its `AgentHandle`.
204
+ * @throws an aggregate error after all branches settle when any failed.
205
+ */
206
+ async drainContinuableDescendants(parents) {
207
+ const manager = this.continuations;
208
+ // Absent continuation services means nothing was ever materialized.
209
+ if (manager === undefined)
210
+ return;
211
+ await manager.drainDescendants(parents);
212
+ }
213
+ /**
214
+ * Release selected resident continuable direct children of one exact live
215
+ * parent. Other children of the same parent remain admitted and resident.
216
+ * Absent targets and a manager-less composition are accepted no-ops.
217
+ * @param parent - exact live direct parent authorizing the selected release.
218
+ * @param childIds - durable direct-child ids to release when resident.
219
+ * @returns once every selected Activation released its `AgentHandle`.
220
+ * @throws {SubagentError} `UNAUTHORIZED` when a resident target belongs to a
221
+ * different parent or the supplied parent identity is stale.
222
+ */
223
+ async drainContinuableChildren(parent, childIds) {
224
+ const manager = this.continuations;
225
+ if (manager === undefined)
226
+ return;
227
+ await manager.drainChildren(parent, childIds);
228
+ }
229
+ /**
230
+ * Enumerate the parent's direct session-backed subagents without loading or
231
+ * resuming an Agent. The Session query service supplies one live-preferred
232
+ * corpus and shared point observations; the projection cache supplies
233
+ * immutable descriptor hits without opening cold logs. The registered
234
+ * `subagent` projection remains the sole mode/label classifier.
235
+ *
236
+ * Every query receives `signal`, and the listing rechecks cancellation
237
+ * around each await. Read rejections that settle
238
+ * after an abort become a stable `SubagentError` with code `CANCELLED`.
239
+ * @param parentSessionId - parent session whose direct children are listed.
240
+ * @param signal - caller-owned cancellation forwarded to Session queries
241
+ * and observed around every read await.
242
+ * @returns children and per-child diagnostics ordered by `createdAt`, then id.
243
+ * @throws {@link SubagentError} when the projection registry or the session
244
+ * store is not mounted, or the caller cancels the listing.
245
+ */
246
+ listChildren(parentSessionId, signal) {
247
+ return listSubagentChildren(this.ctx, parentSessionId, signal);
248
+ }
249
+ /**
250
+ * Enumerate the root's complete session-backed subagent tree in stable
251
+ * pre-order from one live-preferred corpus, without loading or resuming an
252
+ * Agent. Ordinary sessions and one-shot children remain traversal nodes so
253
+ * continuable descendants below them are discovered; each returned entry
254
+ * adds its durable `parentId` and root-relative `depth`. Identity resolution,
255
+ * diagnostics, optional persistence, and cancellation follow the same
256
+ * projection-backed contract as {@link listChildren}.
257
+ * @param rootSessionId - session whose complete descendant tree is listed.
258
+ * @param signal - caller-owned cancellation forwarded to persistence reads
259
+ * and observed around every read await.
260
+ * @returns children and per-candidate diagnostics with tree position, in
261
+ * stable pre-order.
262
+ * @throws {@link SubagentError} under the same conditions as {@link listChildren}.
263
+ */
264
+ listDescendants(rootSessionId, signal) {
265
+ return listSubagentDescendants(this.ctx, rootSessionId, signal);
266
+ }
267
+ /**
268
+ * Remote face of {@link listChildren} for one browser: the durable listing
269
+ * plus live Agent activity and the delivery-time parent availability hint.
270
+ * Parent availability is a hint; {@link prompt} performs the authoritative
271
+ * check. Named apart from the provider-name {@link list}, which owns the
272
+ * member.
273
+ * @param parentSessionId - parent session whose direct children are listed.
274
+ * @param signal - carrier cancellation forwarded to Session queries.
275
+ * @returns the catalog view for that parent.
276
+ * @throws {RemoteError} `gateway/bad-request` for an empty parent id,
277
+ * `gateway/cancelled` for an aborted read, `subagent/projections-unavailable` when
278
+ * the deployment has no projection registry, otherwise `gateway/internal`.
279
+ */
280
+ async remoteExportList(parentSessionId, signal) {
281
+ validateControlRequest('subagent.list', { parentSessionId });
282
+ try {
283
+ return catalogView(this.ctx, parentSessionId, await this.listChildren(parentSessionId, signal));
284
+ }
285
+ catch (error) {
286
+ return rejectCatalogRead(error, signal);
287
+ }
288
+ }
289
+ /**
290
+ * Deliver one browser-authored message to a continuable child through the
291
+ * exact live direct parent, retaining the caller-minted request identity and
292
+ * validated browser zone on the accepted message. Success identifies the
293
+ * message the child's FIFO inbox accepted; later execution is independent of
294
+ * this call.
295
+ * Image parts are admitted and persisted through the attachment store
296
+ * before delivery, and the child's model must accept image input.
297
+ * @param request - durable address, minted identity, content, and optional browser zone.
298
+ * @param signal - carrier cancellation, owning the call until inbox acceptance.
299
+ * @returns the accepted message's inbox identity.
300
+ * @throws {RemoteError} `gateway/bad-request`, `subagent/attachment-invalid`,
301
+ * `subagent/invalid-time-zone`, `subagent/parent-unavailable`,
302
+ * `subagent/not-resumable`, `subagent/unauthorized`,
303
+ * `subagent/delivery-unavailable`, `gateway/cancelled`, or `gateway/internal`.
304
+ */
305
+ async prompt(request, signal) {
306
+ const { parentSessionId, childSessionId, clientTimeZone } = request;
307
+ validateControlRequest('subagent.prompt', request);
308
+ const canonicalTimeZone = clientTimeZone === undefined
309
+ ? undefined
310
+ : canonicalClientTimeZone(clientTimeZone);
311
+ if (clientTimeZone !== undefined && canonicalTimeZone === undefined) {
312
+ throw new RemoteError('subagent/invalid-time-zone', 'clientTimeZone must be UTC or a valid IANA Area/Location name', { value: clientTimeZone });
313
+ }
314
+ const parent = this.ctx.get('agents')?.get(parentSessionId);
315
+ if (parent === undefined) {
316
+ throw new RemoteError('subagent/parent-unavailable', `parent session "${parentSessionId}" is not live`, { parentSessionId });
238
317
  }
239
- this.providers.set(name, provider);
240
- yield () => {
241
- this.providers.delete(name);
242
- this.emitLifecycle('subagent/provider-removed', name);
318
+ const source = {
319
+ kind: 'user',
320
+ rpcId: request.requestId,
321
+ ...(canonicalTimeZone === undefined ? {} : { clientTimeZone: canonicalTimeZone }),
243
322
  };
244
- // A throwing added-listener unwinds the yielded rollback, matching the
245
- // repository's fail-loud registration semantics.
246
- this.ctx.emit('subagent/provider-added', provider);
247
- }.bind(this), 'subagents.registerProvider()');
248
- }
249
- /**
250
- * Look up a provider by name.
251
- * @param name - the provider name.
252
- * @returns the provider, or undefined when absent.
253
- */
254
- getProvider(name) {
255
- return this.providers.get(name);
256
- }
257
- /**
258
- * List registered provider names in insertion order.
259
- * @returns the registered names.
260
- */
261
- list() {
262
- return [...this.providers.keys()];
263
- }
264
- /**
265
- * Establish a published child on the named provider. Capability and semantic
266
- * checks run before delegation. Provider ownership lasts until its promise
267
- * fulfills; a rejection therefore has no run for the caller to dispose and
268
- * emits no run lifecycle events. Post-publication turn and infrastructure
269
- * failures settle through the returned run.
270
- * @param name - the provider to use.
271
- * @param request - child label, prompt, parent, signal, and optional capabilities.
272
- * @returns the published holder-owned run.
273
- */
274
- async start(name, request) {
275
- const provider = this.expectProvider(name);
276
- this.assertCapabilities(provider, request);
277
- assertSubagentMaxDepth(request.maxDepth);
278
- if (request.outputSchema !== undefined)
279
- assertObjectJsonSchema(request.outputSchema);
280
- const descriptor = snapshotSubagentDescriptor({
281
- mode: 'one-shot',
282
- provider: name,
283
- ...request.label !== undefined ? { label: request.label } : {},
284
- });
285
- const resolved = { ...request, descriptor };
286
- return observeRun(this.emitLifecycle, name, request.parent, await provider.start(resolved));
287
- }
288
- /**
289
- * Resolve one provider's detached continuable-creation contribution. Method
290
- * presence on the provider IS the capability, so a provider without it is
291
- * rejected before the manager reserves any child resources.
292
- */
293
- async prepareContinuable(name, request) {
294
- const provider = this.expectProvider(name);
295
- if (provider.prepareContinuable === undefined) {
296
- throw new SubagentError(`subagent provider "${provider.name}" does not support continuable children `
297
- + '(no prepareContinuable capability)', 'UNSUPPORTED_CAPABILITY');
323
+ try {
324
+ // Admission precedes delivery: image parts become durable references
325
+ // here, so the child inbox only ever accepts Host-persisted attachments.
326
+ let content;
327
+ if (request.content.every((part) => part.type === 'text')) {
328
+ content = request.content.map(part => ({ type: 'text', text: part.text }));
329
+ }
330
+ else {
331
+ const attachments = this.ctx.get('attachments');
332
+ if (attachments === undefined)
333
+ throw new Error('subagent image prompt requires an attachment store');
334
+ content = await attachments.admitPromptContent(request.content);
335
+ }
336
+ return {
337
+ messageId: await this[deliverSubagentPrompt](parent, childSessionId, content, source, signal, 'queue'),
338
+ };
339
+ }
340
+ catch (error) {
341
+ return rejectPrompt(error, childSessionId, signal);
342
+ }
298
343
  }
299
- return provider.prepareContinuable(request);
300
- }
301
- /** Look up a provider for dispatch or fail loud. */
302
- expectProvider(name) {
303
- const provider = this.providers.get(name);
304
- if (provider === undefined) {
305
- throw new SubagentError(`no subagent provider registered for "${name}"`, 'NO_PROVIDER');
344
+ /**
345
+ * Remote face of {@link interrupt} under one durable parent address. No
346
+ * catalog, history, persistence, or parent Agent lookup runs: the core
347
+ * primitive alone authorizes the address against the live Activation, which
348
+ * is what keeps a live child interruptible while its parent Agent is offline.
349
+ * Absent, idle, and already-completed targets are accepted no-ops there.
350
+ * @param childSessionId - durable child session id to interrupt.
351
+ * @param parentSessionId - durable direct parent whose authority is claimed.
352
+ * @param mode - required continuable-address discriminator.
353
+ * @returns acknowledgement that the cancel signal was admitted, not that the target is quiescent.
354
+ * @throws {RemoteError} `gateway/bad-request` for an empty id,
355
+ * `subagent/unauthorized` when the address does not own the live target,
356
+ * otherwise `gateway/internal`.
357
+ */
358
+ interruptByParent(childSessionId, parentSessionId, mode) {
359
+ validateControlRequest('subagent.interrupt', { childSessionId, parentSessionId, mode });
360
+ try {
361
+ this.interrupt(childSessionId, { kind: 'user', parentSessionId });
362
+ }
363
+ catch (error) {
364
+ if (error instanceof SubagentError && error.code === 'UNAUTHORIZED') {
365
+ throw new RemoteError('subagent/unauthorized', 'subagent does not belong to this parent', { childSessionId }, { cause: error });
366
+ }
367
+ throw new RemoteError('gateway/internal', 'subagent interrupt failed', {}, { cause: error });
368
+ }
369
+ return { accepted: true };
306
370
  }
307
- return provider;
308
- }
309
- /** Resolve the optional continuable-subagent manager or fail loud. */
310
- requireContinuations() {
311
- if (this.continuations === undefined) {
312
- throw new SubagentError('continuable subagents require the agents service', 'CONTINUATION_UNAVAILABLE');
371
+ /**
372
+ * Register a provider under its name. Registration is effect-scoped and HMR
373
+ * safe; removing a provider blocks new starts but does not revoke runs that
374
+ * were already returned to their holders.
375
+ * @param provider - the trusted provider implementation.
376
+ * @returns the exact Cordis effect disposer.
377
+ */
378
+ registerProvider(provider) {
379
+ const name = provider.name;
380
+ // oxlint-disable-next-line typescript/no-misused-promises -- synchronous disposer
381
+ return this.ctx.effect(function* () {
382
+ if (this.providers.has(name)) {
383
+ throw new SubagentError(`a subagent provider named "${name}" is already registered`, 'DUPLICATE_PROVIDER');
384
+ }
385
+ this.providers.set(name, provider);
386
+ yield () => {
387
+ this.providers.delete(name);
388
+ this.emitLifecycle('subagent/provider-removed', name);
389
+ };
390
+ // A throwing added-listener unwinds the yielded rollback, matching the
391
+ // repository's fail-loud registration semantics.
392
+ this.ctx.emit('subagent/provider-added', provider);
393
+ }.bind(this), 'subagents.registerProvider()');
313
394
  }
314
- return this.continuations;
315
- }
316
- /**
317
- * Build the lifecycle observer for one continuable Activation's residency
318
- * epoch, so the manager publishes its edges without owning event dispatch.
319
- */
320
- observeActivation(provider, childId, parent) {
321
- return createActivationObserver(this.emitLifecycle, provider, childId, parent);
322
- }
323
- /** Reject the first requested capability that the provider lacks. */
324
- assertCapabilities(provider, request) {
325
- const needs = [
326
- { when: request.outputSchema !== undefined, cap: 'outputSchema' },
327
- { when: request.maxDepth !== undefined, cap: 'depthLimit' },
328
- { when: request.toolFilter !== undefined, cap: 'toolFilter' },
329
- { when: request.persona !== undefined, cap: 'persona' },
330
- ];
331
- for (const { when, cap } of needs) {
332
- if (when && !provider.capabilities[cap]) {
333
- throw new SubagentError(`subagent provider "${provider.name}" does not support the "${cap}" capability`, 'UNSUPPORTED_CAPABILITY');
395
+ /**
396
+ * Look up a provider by name.
397
+ * @param name - the provider name.
398
+ * @returns the provider, or undefined when absent.
399
+ */
400
+ getProvider(name) {
401
+ return this.providers.get(name);
402
+ }
403
+ /**
404
+ * List registered provider names in insertion order.
405
+ * @returns the registered names.
406
+ */
407
+ list() {
408
+ return [...this.providers.keys()];
409
+ }
410
+ /**
411
+ * Establish a published child on the named provider. Capability and semantic
412
+ * checks run before delegation. Provider ownership lasts until its promise
413
+ * fulfills; a rejection therefore has no run for the caller to dispose and
414
+ * emits no run lifecycle events. Post-publication turn and infrastructure
415
+ * failures settle through the returned run.
416
+ * @param name - the provider to use.
417
+ * @param request - child label, prompt, parent, signal, and optional capabilities.
418
+ * @returns the published holder-owned run.
419
+ */
420
+ async start(name, request) {
421
+ const provider = this.expectProvider(name);
422
+ this.assertCapabilities(provider, request);
423
+ assertSubagentMaxDepth(request.maxDepth);
424
+ if (request.outputSchema !== undefined)
425
+ assertObjectJsonSchema(request.outputSchema);
426
+ const descriptor = snapshotSubagentDescriptor({
427
+ mode: 'one-shot',
428
+ provider: name,
429
+ ...request.label !== undefined ? { label: request.label } : {},
430
+ });
431
+ const resolved = { ...request, descriptor };
432
+ return observeRun(this.emitLifecycle, name, request.parent, await provider.start(resolved));
433
+ }
434
+ /**
435
+ * Resolve one provider's detached continuable-creation contribution. Method
436
+ * presence on the provider IS the capability, so a provider without it is
437
+ * rejected before the manager reserves any child resources.
438
+ */
439
+ async prepareContinuable(name, request) {
440
+ const provider = this.expectProvider(name);
441
+ if (provider.prepareContinuable === undefined) {
442
+ throw new SubagentError(`subagent provider "${provider.name}" does not support continuable children `
443
+ + '(no prepareContinuable capability)', 'UNSUPPORTED_CAPABILITY');
334
444
  }
445
+ return provider.prepareContinuable(request);
335
446
  }
336
- }
337
- }
447
+ /** Look up a provider for dispatch or fail loud. */
448
+ expectProvider(name) {
449
+ const provider = this.providers.get(name);
450
+ if (provider === undefined) {
451
+ throw new SubagentError(`no subagent provider registered for "${name}"`, 'NO_PROVIDER');
452
+ }
453
+ return provider;
454
+ }
455
+ /** Resolve the optional continuable-subagent manager or fail loud. */
456
+ requireContinuations() {
457
+ if (this.continuations === undefined) {
458
+ throw new SubagentError('continuable subagents require the agents service', 'CONTINUATION_UNAVAILABLE');
459
+ }
460
+ return this.continuations;
461
+ }
462
+ /**
463
+ * Build the lifecycle observer for one continuable Activation's residency
464
+ * epoch, so the manager publishes its edges without owning event dispatch.
465
+ */
466
+ observeActivation(provider, childId, parent) {
467
+ return createActivationObserver(this.emitLifecycle, provider, childId, parent);
468
+ }
469
+ /** Reject the first requested capability that the provider lacks. */
470
+ assertCapabilities(provider, request) {
471
+ const needs = [
472
+ { when: request.agentOptions !== undefined, cap: 'agentOptions' },
473
+ { when: request.outputSchema !== undefined, cap: 'outputSchema' },
474
+ { when: request.maxDepth !== undefined, cap: 'depthLimit' },
475
+ { when: request.toolFilter !== undefined, cap: 'toolFilter' },
476
+ { when: request.persona !== undefined, cap: 'persona' },
477
+ ];
478
+ for (const { when, cap } of needs) {
479
+ if (when && !provider.capabilities[cap]) {
480
+ throw new SubagentError(`subagent provider "${provider.name}" does not support the "${cap}" capability`, 'UNSUPPORTED_CAPABILITY');
481
+ }
482
+ }
483
+ }
484
+ };
485
+ })();
486
+ export { SubagentRuntime };
338
487
  export default SubagentRuntime;
339
488
  //# sourceMappingURL=index.js.map