@deepseek-ai/dsh-subagent 0.0.1-rc.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/LICENSE +28 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +132 -0
  4. package/README.zh.md +132 -0
  5. package/lib/index.js +2392 -0
  6. package/lib/invariant.js +76 -0
  7. package/lib/types/activation-setup-registry.d.ts +57 -0
  8. package/lib/types/activation-setup-registry.js +148 -0
  9. package/lib/types/child-agent.d.ts +139 -0
  10. package/lib/types/child-agent.js +169 -0
  11. package/lib/types/client.d.ts +7 -0
  12. package/lib/types/client.js +7 -0
  13. package/lib/types/continuation.d.ts +375 -0
  14. package/lib/types/continuation.js +951 -0
  15. package/lib/types/depth.d.ts +31 -0
  16. package/lib/types/depth.js +39 -0
  17. package/lib/types/descriptor-seed.d.ts +21 -0
  18. package/lib/types/descriptor-seed.js +24 -0
  19. package/lib/types/descriptor.d.ts +139 -0
  20. package/lib/types/descriptor.js +189 -0
  21. package/lib/types/error.d.ts +11 -0
  22. package/lib/types/error.js +14 -0
  23. package/lib/types/index.d.ts +278 -0
  24. package/lib/types/index.js +338 -0
  25. package/lib/types/invariant.d.ts +13 -0
  26. package/lib/types/invariant.js +91 -0
  27. package/lib/types/lifecycle.d.ts +93 -0
  28. package/lib/types/lifecycle.js +169 -0
  29. package/lib/types/list-children.d.ts +112 -0
  30. package/lib/types/list-children.js +316 -0
  31. package/lib/types/out-of-process.d.ts +115 -0
  32. package/lib/types/out-of-process.js +181 -0
  33. package/lib/types/projection-types.d.ts +60 -0
  34. package/lib/types/projection-types.js +7 -0
  35. package/lib/types/projection.d.ts +48 -0
  36. package/lib/types/projection.js +135 -0
  37. package/lib/types/run-settlement.d.ts +17 -0
  38. package/lib/types/run-settlement.js +59 -0
  39. package/lib/types/types.d.ts +293 -0
  40. package/lib/types/types.js +19 -0
  41. package/package.json +106 -0
@@ -0,0 +1,278 @@
1
+ /**
2
+ * Service Definition for the subagent capability seam (`ctx.subagents`): a named-provider registry plus a
3
+ * capability-validating asynchronous start surface. Providers establish a
4
+ * child before returning its run, so fulfillment is the single publication and
5
+ * ownership-transfer boundary.
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
+ * (`LlmService.registerAdapter`), not the single-service bash executor.
11
+ *
12
+ * This package owns the Service Definition role of the capability seam. Service providers
13
+ * (`@deepseek-ai/dsh-subagent-spawn`, `-fork`, `-acp`) and the model-facing
14
+ * consumer (`@deepseek-ai/dsh-tool-subagent`) are separate packages.
15
+ *
16
+ * Public operations express caller intent: `start` returns one published owned
17
+ * 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
20
+ * continuation manager holds their `AgentHandle` directly and orders every turn
21
+ * through the child's own inbox, so providers contribute only the detached
22
+ * creation spec and see no handle, turn, or teardown. Child and descendant
23
+ * discovery read the live session store and optional session persistence
24
+ * directly and do not require that continuation runtime.
25
+ *
26
+ * Same-process providers are trusted typed collaborators. Requests, provider
27
+ * descriptors, results, and lifecycle payloads are borrowed immutable values;
28
+ * serialization and hostile-input validation belong at real process, worker,
29
+ * persistence, and model boundaries.
30
+ *
31
+ * @module @deepseek-ai/dsh-subagent
32
+ */
33
+ import { Context, Service } from '@deepseek-ai/cordis';
34
+ import type { Scoped } from '@deepseek-ai/dsh-scope';
35
+ import type { ContentBlock, MessageId } from '@deepseek-ai/dsh-llm';
36
+ import type { Agent } from '@deepseek-ai/dsh-agent';
37
+ import type { SessionId } from '@deepseek-ai/dsh-session';
38
+ import type { SubagentProvider, SubagentRun, SubagentRunEndInfo, SubagentRunInfo, SubagentStartRequest } from './types.ts';
39
+ import type { ContinuableStart, ContinuableStartSpec, SubagentFollowupOptions, SubagentInterruptAuthority, SubagentReportOptions } from './continuation.ts';
40
+ import type { ContinuableSetupContribution } from './activation-setup-registry.ts';
41
+ import type { SubagentDescendantListEntry, SubagentListEntry } from './list-children.ts';
42
+ export * from './out-of-process.ts';
43
+ export { SubagentRunId } from './types.ts';
44
+ export type { ContinuableCreateRequest, ContinuableCreateSpec, ResolvedSubagentStartRequest, SubagentCapabilities, SubagentProvider, SubagentResult, SubagentRun, SubagentStartRequest, SubagentStopReason, SubagentStopReasonMap, } from './types.ts';
45
+ export { foldSubagentDescriptor, snapshotSubagentDescriptor, SUBAGENT_DESCRIPTOR_VERSION, } from './descriptor.ts';
46
+ export type { ContinuableSubagentDescriptorData, ContinuableSubagentDescriptorInput, OneShotSubagentDescriptorData, OneShotSubagentDescriptorInput, SubagentDescriptorData, SubagentDescriptorInput, } from './descriptor.ts';
47
+ export { seedDescriptorTurn } from './descriptor-seed.ts';
48
+ export { SubagentError } from './error.ts';
49
+ export { settleRun } from './run-settlement.ts';
50
+ export { assertSubagentMaxDepth, delegationDepthOf } from './depth.ts';
51
+ export { appendDelegatedPolicyOverrides, applyChildComposition, captureDelegatedPolicyOverrides, childSessionMeta, resolveChildAgentOptions, resolveChildDepth, SubagentDepthError, } from './child-agent.ts';
52
+ export type { ChildComposition, DelegatedPolicyOverrides } from './child-agent.ts';
53
+ export type { ContinuableStart, ContinuableStartSpec, CoordinatorMessageSource, SubagentFollowupOptions, SubagentInterruptAuthority, SubagentReportDelivery, SubagentReportMessageSource, SubagentReportOptions, } from './continuation.ts';
54
+ export type { ContinuableSetupContribution } from './activation-setup-registry.ts';
55
+ export type { SubagentDescendantListEntry, SubagentListEntry } from './list-children.ts';
56
+ export type { SubagentRunEndInfo, SubagentRunInfo } from './types.ts';
57
+ export type { SubagentIdentityProjection, SubagentTimingProjection } from './projection-types.ts';
58
+ declare module '@deepseek-ai/cordis' {
59
+ interface Context {
60
+ subagents: SubagentService;
61
+ }
62
+ interface Events {
63
+ /**
64
+ * A provider became resolvable in the registry.
65
+ * @param provider - the registered provider.
66
+ * @mode emit
67
+ */
68
+ 'subagent/provider-added'(provider: SubagentProvider): void;
69
+ /**
70
+ * A provider left the registry. Accepted runs remain holder-owned.
71
+ * @param name - the provider name that no longer resolves.
72
+ * @mode emit
73
+ */
74
+ 'subagent/provider-removed'(name: string): void;
75
+ /**
76
+ * A provider established a published child. For in-process providers,
77
+ * `ctx.agents.get(info.id)` resolves during this notification.
78
+ * Scope-filtered dispatch keys the carrier by the delegating parent, so a
79
+ * parent-scoped listener observes only its own delegations. Paired with
80
+ * `subagent/end`.
81
+ * @param info - the provider and published child identity.
82
+ * @dshScopeScan unsupported
83
+ * @mode emit
84
+ */
85
+ 'subagent/start'(this: Scoped<SubagentService>, info: SubagentRunInfo): void;
86
+ /**
87
+ * A published child settled. Scope-filtered dispatch uses the same delegating
88
+ * parent carrier as `subagent/start`, so the lifecycle pair reaches the
89
+ * same scoped audience.
90
+ * @param info - the run identity and terminal outcome.
91
+ * @dshScopeScan unsupported
92
+ * @mode emit
93
+ */
94
+ 'subagent/end'(this: Scoped<SubagentService>, info: SubagentRunEndInfo): void;
95
+ }
96
+ }
97
+ /** Named provider registry with one-shot runs, durable discovery, and continuable-child operations. */
98
+ export declare class SubagentService extends Service {
99
+ private providers;
100
+ private continuations;
101
+ /** Deployment contributions composed into unpublished continuable children. */
102
+ private readonly setupRegistry;
103
+ /**
104
+ * The contained lifecycle-edge publisher. Built here because scoped dispatch
105
+ * keys its carrier by this exact service instance, whose own context filter
106
+ * composes into the carrier.
107
+ */
108
+ private readonly emitLifecycle;
109
+ constructor(ctx: Context);
110
+ /**
111
+ * Establish one durable continuable child and deliver its initial prompt.
112
+ * Resolves when the child's inbox accepts that prompt, without waiting for the
113
+ * turn to start or for the message to reach the Session log; any earlier
114
+ * failure rejects with no ids and rolls back the child entirely.
115
+ * @param spec - provider, delegation request, and caller cancellation.
116
+ * @returns the durable child id and the accepted prompt's message id.
117
+ * @throws when continuation services are unavailable or materialization fails.
118
+ */
119
+ startContinuable(spec: ContinuableStartSpec): Promise<ContinuableStart>;
120
+ /**
121
+ * Deliver one later message to a continuable child as its next FIFO turn. A
122
+ * resident child's Agent inbox accepts it directly (waking a `waiting`
123
+ * Activation), while an absent one is cold-resumed from its persisted
124
+ * Session. The Agent inbox is the only queue, so every accepted message has
125
+ * one observable order.
126
+ * @param parent - the exact live direct parent authorizing this delivery.
127
+ * @param childId - durable child session id.
128
+ * @param content - user-role content to deliver.
129
+ * @param options - the message source fields and caller cancellation, which stops the
130
+ * operation only before inbox acceptance.
131
+ * @returns the accepted message's inbox id.
132
+ * @throws when continuation services are unavailable, parent authority is
133
+ * rejected, or the message was not admitted.
134
+ */
135
+ followup(parent: Agent, childId: SessionId, content: ContentBlock[], options: SubagentFollowupOptions): Promise<MessageId>;
136
+ /**
137
+ * Interrupt one live continuable child's current turn under a human parent
138
+ * address or an exact live ancestor Agent. Fire-and-return: the cancel
139
+ * signal is issued before this returns, but the target may keep running
140
+ * until it observes the signal. Unclaimed pending inbox work, the Activation,
141
+ * and published descendants are preserved; claimed work is not requeued.
142
+ * Once the interrupted driver is idle, a waking send resumes the parked FIFO
143
+ * queue. An absent target — including a one-shot or unknown id —
144
+ * is an accepted no-op, as is a manager-less composition, which cannot own a
145
+ * live Activation.
146
+ * @param targetSessionId - the durable child session id to interrupt.
147
+ * @param authority - the human parent address or exact live ancestor Agent.
148
+ * @throws {SubagentError} `UNAUTHORIZED` when the authority does not own the
149
+ * live target.
150
+ */
151
+ interrupt(targetSessionId: SessionId, authority: SubagentInterruptAuthority): void;
152
+ /**
153
+ * Deliver selected content from one live continuable child to its durable
154
+ * direct parent. The child is the authority credential; callers cannot name a
155
+ * recipient. Reporting does not conclude the child's turn or Activation.
156
+ * @param child - exact live reporting child.
157
+ * @param content - selected model-facing content.
158
+ * @param options - parent scheduling and pre-acceptance cancellation.
159
+ * @returns the stable identity of the parent-accepted message.
160
+ * @throws when continuation services are unavailable, sender authorization
161
+ * fails, or the direct parent is not live.
162
+ */
163
+ reportFrom(child: Agent, content: ContentBlock[], options: SubagentReportOptions): Promise<MessageId>;
164
+ /**
165
+ * Compose one deployment capability into every continuable child's
166
+ * unpublished creation context on fresh creation and cold resume. Grants wait
167
+ * for the next Activation; removing the contribution revokes every resident
168
+ * installation immediately.
169
+ * @param contribution - synchronous child-scope installer.
170
+ * @returns the exact Cordis effect disposer.
171
+ */
172
+ registerContinuableSetup(contribution: ContinuableSetupContribution): () => void;
173
+ /**
174
+ * Close continuable admission below exact live parent Agents, stop only their
175
+ * visible descendant Activations synchronously, then await admitted scoped
176
+ * materializations and release those forests child-first. The scoped cutoff
177
+ * lasts until each exact parent leaves the registry; unrelated parent trees
178
+ * remain live.
179
+ * @param parents - exact host-owned parent Agents entering teardown.
180
+ * @returns once every retained descendant Activation released its `AgentHandle`.
181
+ * @throws an aggregate error after all branches settle when any failed.
182
+ */
183
+ drainContinuableDescendants(parents: readonly Agent[]): Promise<void>;
184
+ /**
185
+ * Enumerate the parent's direct session-backed subagents without loading or
186
+ * resuming an Agent and without any query service: the listing merges the live
187
+ * session store with optional session persistence (live-preferred) and
188
+ * serves each child's durable mode/label from the registered `subagent`
189
+ * projection unit down a three-rung ladder — the registry's watermark
190
+ * snapshot for a live child; for a cold one, a durable projection-cache
191
+ * row when the optional cache serves an own-suffix identity (its `seq`
192
+ * gate proves the value postdates the fork seed, where a child's own
193
+ * descriptor is immutable once appended), else one persistence inspection
194
+ * folded through the registry. The
195
+ * projection fold is the single classification authority; per-child
196
+ * diagnostics relay a fold that served no identity or a failed inspection,
197
+ * never a list-time descriptor parse. Absent persistence, enumeration is
198
+ * live-only (a cold child cannot be resumed then either, so its absence is
199
+ * capability absence, not an error). This service consults no Agent
200
+ * registrations, Activations, or providers.
201
+ *
202
+ * Every persistence read receives `signal`, and the listing rechecks
203
+ * cancellation around each of those awaits. Read rejections that settle
204
+ * after an abort become a stable `SubagentError` with code `CANCELLED`.
205
+ * @param parentSessionId - parent session whose direct children are listed.
206
+ * @param signal - caller-owned cancellation forwarded to persistence reads
207
+ * and observed around every read await.
208
+ * @returns children and per-child diagnostics ordered by `createdAt`, then id.
209
+ * @throws {@link SubagentError} when the projection registry or the session
210
+ * store is not mounted, or the caller cancels the listing.
211
+ */
212
+ listChildren(parentSessionId: SessionId, signal?: AbortSignal): Promise<SubagentListEntry[]>;
213
+ /**
214
+ * Enumerate the root's complete session-backed subagent tree in stable
215
+ * pre-order from one live-preferred corpus, without loading or resuming an
216
+ * Agent. Ordinary sessions and one-shot children remain traversal nodes so
217
+ * continuable descendants below them are discovered; each returned entry
218
+ * adds its durable `parentId` and root-relative `depth`. Identity resolution,
219
+ * diagnostics, optional persistence, and cancellation follow the same
220
+ * projection-backed contract as {@link listChildren}.
221
+ * @param rootSessionId - session whose complete descendant tree is listed.
222
+ * @param signal - caller-owned cancellation forwarded to persistence reads
223
+ * and observed around every read await.
224
+ * @returns children and per-candidate diagnostics with tree position, in
225
+ * stable pre-order.
226
+ * @throws {@link SubagentError} under the same conditions as {@link listChildren}.
227
+ */
228
+ listDescendants(rootSessionId: SessionId, signal?: AbortSignal): Promise<SubagentDescendantListEntry[]>;
229
+ /**
230
+ * Register a provider under its name. Registration is effect-scoped and HMR
231
+ * safe; removing a provider blocks new starts but does not revoke runs that
232
+ * were already returned to their holders.
233
+ * @param provider - the trusted provider implementation.
234
+ * @returns the exact Cordis effect disposer.
235
+ */
236
+ registerProvider(provider: SubagentProvider): () => void;
237
+ /**
238
+ * Look up a provider by name.
239
+ * @param name - the provider name.
240
+ * @returns the provider, or undefined when absent.
241
+ */
242
+ getProvider(name: string): SubagentProvider | undefined;
243
+ /**
244
+ * List registered provider names in insertion order.
245
+ * @returns the registered names.
246
+ */
247
+ list(): string[];
248
+ /**
249
+ * Establish a published child on the named provider. Capability and semantic
250
+ * checks run before delegation. Provider ownership lasts until its promise
251
+ * fulfills; a rejection therefore has no run for the caller to dispose and
252
+ * emits no run lifecycle events. Post-publication turn and infrastructure
253
+ * failures settle through the returned run.
254
+ * @param name - the provider to use.
255
+ * @param request - child label, prompt, parent, signal, and optional capabilities.
256
+ * @returns the published holder-owned run.
257
+ */
258
+ start(name: string, request: SubagentStartRequest): Promise<SubagentRun>;
259
+ /**
260
+ * Resolve one provider's detached continuable-creation contribution. Method
261
+ * presence on the provider IS the capability, so a provider without it is
262
+ * rejected before the manager reserves any child resources.
263
+ */
264
+ private prepareContinuable;
265
+ /** Look up a provider for dispatch or fail loud. */
266
+ private expectProvider;
267
+ /** Resolve the optional continuable-subagent manager or fail loud. */
268
+ private requireContinuations;
269
+ /**
270
+ * Build the lifecycle observer for one continuable Activation's residency
271
+ * epoch, so the manager publishes its edges without owning event dispatch.
272
+ */
273
+ private observeActivation;
274
+ /** Reject the first requested capability that the provider lacks. */
275
+ private assertCapabilities;
276
+ }
277
+ export default SubagentService;
278
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,338 @@
1
+ /**
2
+ * Service Definition for the subagent capability seam (`ctx.subagents`): a named-provider registry plus a
3
+ * capability-validating asynchronous start surface. Providers establish a
4
+ * child before returning its run, so fulfillment is the single publication and
5
+ * ownership-transfer boundary.
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
+ * (`LlmService.registerAdapter`), not the single-service bash executor.
11
+ *
12
+ * This package owns the Service Definition role of the capability seam. Service providers
13
+ * (`@deepseek-ai/dsh-subagent-spawn`, `-fork`, `-acp`) and the model-facing
14
+ * consumer (`@deepseek-ai/dsh-tool-subagent`) are separate packages.
15
+ *
16
+ * Public operations express caller intent: `start` returns one published owned
17
+ * 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
20
+ * continuation manager holds their `AgentHandle` directly and orders every turn
21
+ * through the child's own inbox, so providers contribute only the detached
22
+ * creation spec and see no handle, turn, or teardown. Child and descendant
23
+ * discovery read the live session store and optional session persistence
24
+ * directly and do not require that continuation runtime.
25
+ *
26
+ * Same-process providers are trusted typed collaborators. Requests, provider
27
+ * descriptors, results, and lifecycle payloads are borrowed immutable values;
28
+ * serialization and hostile-input validation belong at real process, worker,
29
+ * persistence, and model boundaries.
30
+ *
31
+ * @module @deepseek-ai/dsh-subagent
32
+ */
33
+ import { Service } from '@deepseek-ai/cordis';
34
+ import { scopeTarget } from '@deepseek-ai/dsh-scope';
35
+ import { assertObjectJsonSchema } from '@deepseek-ai/dsh-tools';
36
+ import { SubagentError } from "./error.js";
37
+ import { assertSubagentMaxDepth } from "./depth.js";
38
+ import { createActivationObserver, createLifecycleEmitter, observeRun } from "./lifecycle.js";
39
+ import SubagentContinuationManager from "./continuation.js";
40
+ import SubagentActivationSetupRegistry from "./activation-setup-registry.js";
41
+ import { listChildren as listSubagentChildren, listDescendants as listSubagentDescendants } from "./list-children.js";
42
+ import { snapshotSubagentDescriptor } from "./descriptor.js";
43
+ import { subagentIdentityProjectionDefinition, subagentTimingProjectionDefinition } from "./projection.js";
44
+ export * from "./out-of-process.js";
45
+ export { SubagentRunId } from "./types.js";
46
+ export { foldSubagentDescriptor, snapshotSubagentDescriptor, SUBAGENT_DESCRIPTOR_VERSION, } from "./descriptor.js";
47
+ export { seedDescriptorTurn } from "./descriptor-seed.js";
48
+ export { SubagentError } from "./error.js";
49
+ export { settleRun } from "./run-settlement.js";
50
+ export { assertSubagentMaxDepth, delegationDepthOf } from "./depth.js";
51
+ export { appendDelegatedPolicyOverrides, applyChildComposition, captureDelegatedPolicyOverrides, childSessionMeta, resolveChildAgentOptions, resolveChildDepth, SubagentDepthError, } from "./child-agent.js";
52
+ /** Named provider registry with one-shot runs, durable discovery, and continuable-child operations. */
53
+ export class SubagentService extends Service {
54
+ providers = new Map();
55
+ continuations;
56
+ /** Deployment contributions composed into unpublished continuable children. */
57
+ setupRegistry = new SubagentActivationSetupRegistry();
58
+ /**
59
+ * The contained lifecycle-edge publisher. Built here because scoped dispatch
60
+ * keys its carrier by this exact service instance, whose own context filter
61
+ * composes into the carrier.
62
+ */
63
+ emitLifecycle;
64
+ constructor(ctx) {
65
+ super(ctx, 'subagents');
66
+ this.emitLifecycle = createLifecycleEmitter(this.ctx, parent => scopeTarget(this, parent));
67
+ ctx.inject(['agents'], (childCtx) => {
68
+ const manager = new SubagentContinuationManager(childCtx, {
69
+ prepareContinuable: (name, request) => this.prepareContinuable(name, request),
70
+ observeActivation: (provider, childId, parent) => this.observeActivation(provider, childId, parent),
71
+ }, this.setupRegistry);
72
+ this.continuations = manager;
73
+ childCtx.effect(() => () => {
74
+ /* v8 ignore else -- one injected binding owns the slot until its fiber disposes. */
75
+ if (this.continuations === manager)
76
+ this.continuations = undefined;
77
+ }, 'subagents.continuationBinding()');
78
+ });
79
+ ctx.inject(['sessionProjections'], (projectionCtx) => {
80
+ projectionCtx.sessionProjections.register(subagentTimingProjectionDefinition);
81
+ projectionCtx.sessionProjections.register(subagentIdentityProjectionDefinition);
82
+ });
83
+ }
84
+ /**
85
+ * Establish one durable continuable child and deliver its initial prompt.
86
+ * Resolves when the child's inbox accepts that prompt, without waiting for the
87
+ * turn to start or for the message to reach the Session log; any earlier
88
+ * failure rejects with no ids and rolls back the child entirely.
89
+ * @param spec - provider, delegation request, and caller cancellation.
90
+ * @returns the durable child id and the accepted prompt's message id.
91
+ * @throws when continuation services are unavailable or materialization fails.
92
+ */
93
+ async startContinuable(spec) {
94
+ return this.requireContinuations().startContinuable(spec);
95
+ }
96
+ /**
97
+ * Deliver one later message to a continuable child as its next FIFO turn. A
98
+ * resident child's Agent inbox accepts it directly (waking a `waiting`
99
+ * Activation), while an absent one is cold-resumed from its persisted
100
+ * Session. The Agent inbox is the only queue, so every accepted message has
101
+ * one observable order.
102
+ * @param parent - the exact live direct parent authorizing this delivery.
103
+ * @param childId - durable child session id.
104
+ * @param content - user-role content to deliver.
105
+ * @param options - the message source fields and caller cancellation, which stops the
106
+ * operation only before inbox acceptance.
107
+ * @returns the accepted message's inbox id.
108
+ * @throws when continuation services are unavailable, parent authority is
109
+ * rejected, or the message was not admitted.
110
+ */
111
+ async followup(parent, childId, content, options) {
112
+ return this.requireContinuations().followup(parent, childId, content, options);
113
+ }
114
+ /**
115
+ * Interrupt one live continuable child's current turn under a human parent
116
+ * address or an exact live ancestor Agent. Fire-and-return: the cancel
117
+ * signal is issued before this returns, but the target may keep running
118
+ * until it observes the signal. Unclaimed pending inbox work, the Activation,
119
+ * and published descendants are preserved; claimed work is not requeued.
120
+ * Once the interrupted driver is idle, a waking send resumes the parked FIFO
121
+ * queue. An absent target — including a one-shot or unknown id —
122
+ * is an accepted no-op, as is a manager-less composition, which cannot own a
123
+ * live Activation.
124
+ * @param targetSessionId - the durable child session id to interrupt.
125
+ * @param authority - the human parent address or exact live ancestor Agent.
126
+ * @throws {SubagentError} `UNAUTHORIZED` when the authority does not own the
127
+ * live target.
128
+ */
129
+ interrupt(targetSessionId, authority) {
130
+ this.continuations?.interrupt(targetSessionId, authority);
131
+ }
132
+ /**
133
+ * Deliver selected content from one live continuable child to its durable
134
+ * direct parent. The child is the authority credential; callers cannot name a
135
+ * recipient. Reporting does not conclude the child's turn or Activation.
136
+ * @param child - exact live reporting child.
137
+ * @param content - selected model-facing content.
138
+ * @param options - parent scheduling and pre-acceptance cancellation.
139
+ * @returns the stable identity of the parent-accepted message.
140
+ * @throws when continuation services are unavailable, sender authorization
141
+ * fails, or the direct parent is not live.
142
+ */
143
+ async reportFrom(child, content, options) {
144
+ return this.requireContinuations().reportFrom(child, content, options);
145
+ }
146
+ /**
147
+ * Compose one deployment capability into every continuable child's
148
+ * unpublished creation context on fresh creation and cold resume. Grants wait
149
+ * for the next Activation; removing the contribution revokes every resident
150
+ * installation immediately.
151
+ * @param contribution - synchronous child-scope installer.
152
+ * @returns the exact Cordis effect disposer.
153
+ */
154
+ registerContinuableSetup(contribution) {
155
+ // oxlint-disable-next-line typescript/no-misused-promises -- synchronous cleanup; direct return preserves disposer identity
156
+ return this.ctx.effect(() => this.setupRegistry.register(contribution), 'subagents.registerContinuableSetup()');
157
+ }
158
+ /**
159
+ * Close continuable admission below exact live parent Agents, stop only their
160
+ * visible descendant Activations synchronously, then await admitted scoped
161
+ * materializations and release those forests child-first. The scoped cutoff
162
+ * lasts until each exact parent leaves the registry; unrelated parent trees
163
+ * remain live.
164
+ * @param parents - exact host-owned parent Agents entering teardown.
165
+ * @returns once every retained descendant Activation released its `AgentHandle`.
166
+ * @throws an aggregate error after all branches settle when any failed.
167
+ */
168
+ async drainContinuableDescendants(parents) {
169
+ const manager = this.continuations;
170
+ // Absent continuation services means nothing was ever materialized.
171
+ if (manager === undefined)
172
+ return;
173
+ await manager.drainDescendants(parents);
174
+ }
175
+ /**
176
+ * Enumerate the parent's direct session-backed subagents without loading or
177
+ * resuming an Agent and without any query service: the listing merges the live
178
+ * session store with optional session persistence (live-preferred) and
179
+ * serves each child's durable mode/label from the registered `subagent`
180
+ * projection unit down a three-rung ladder — the registry's watermark
181
+ * snapshot for a live child; for a cold one, a durable projection-cache
182
+ * row when the optional cache serves an own-suffix identity (its `seq`
183
+ * gate proves the value postdates the fork seed, where a child's own
184
+ * descriptor is immutable once appended), else one persistence inspection
185
+ * folded through the registry. The
186
+ * projection fold is the single classification authority; per-child
187
+ * diagnostics relay a fold that served no identity or a failed inspection,
188
+ * never a list-time descriptor parse. Absent persistence, enumeration is
189
+ * live-only (a cold child cannot be resumed then either, so its absence is
190
+ * capability absence, not an error). This service consults no Agent
191
+ * registrations, Activations, or providers.
192
+ *
193
+ * Every persistence read receives `signal`, and the listing rechecks
194
+ * cancellation around each of those awaits. Read rejections that settle
195
+ * after an abort become a stable `SubagentError` with code `CANCELLED`.
196
+ * @param parentSessionId - parent session whose direct children are listed.
197
+ * @param signal - caller-owned cancellation forwarded to persistence reads
198
+ * and observed around every read await.
199
+ * @returns children and per-child diagnostics ordered by `createdAt`, then id.
200
+ * @throws {@link SubagentError} when the projection registry or the session
201
+ * store is not mounted, or the caller cancels the listing.
202
+ */
203
+ listChildren(parentSessionId, signal) {
204
+ return listSubagentChildren(this.ctx, parentSessionId, signal);
205
+ }
206
+ /**
207
+ * Enumerate the root's complete session-backed subagent tree in stable
208
+ * pre-order from one live-preferred corpus, without loading or resuming an
209
+ * Agent. Ordinary sessions and one-shot children remain traversal nodes so
210
+ * continuable descendants below them are discovered; each returned entry
211
+ * adds its durable `parentId` and root-relative `depth`. Identity resolution,
212
+ * diagnostics, optional persistence, and cancellation follow the same
213
+ * projection-backed contract as {@link listChildren}.
214
+ * @param rootSessionId - session whose complete descendant tree is listed.
215
+ * @param signal - caller-owned cancellation forwarded to persistence reads
216
+ * and observed around every read await.
217
+ * @returns children and per-candidate diagnostics with tree position, in
218
+ * stable pre-order.
219
+ * @throws {@link SubagentError} under the same conditions as {@link listChildren}.
220
+ */
221
+ listDescendants(rootSessionId, signal) {
222
+ return listSubagentDescendants(this.ctx, rootSessionId, signal);
223
+ }
224
+ /**
225
+ * Register a provider under its name. Registration is effect-scoped and HMR
226
+ * safe; removing a provider blocks new starts but does not revoke runs that
227
+ * were already returned to their holders.
228
+ * @param provider - the trusted provider implementation.
229
+ * @returns the exact Cordis effect disposer.
230
+ */
231
+ registerProvider(provider) {
232
+ const name = provider.name;
233
+ // oxlint-disable-next-line typescript/no-misused-promises -- synchronous cleanup; direct return preserves disposer identity
234
+ return this.ctx.effect(function* () {
235
+ if (this.providers.has(name)) {
236
+ throw new SubagentError(`a subagent provider named "${name}" is already registered`, 'DUPLICATE_PROVIDER');
237
+ }
238
+ this.providers.set(name, provider);
239
+ yield () => {
240
+ this.providers.delete(name);
241
+ this.emitLifecycle('subagent/provider-removed', name);
242
+ };
243
+ // A throwing added-listener unwinds the yielded rollback, matching the
244
+ // repository's fail-loud registration semantics.
245
+ this.ctx.emit('subagent/provider-added', provider);
246
+ }.bind(this), 'subagents.registerProvider()');
247
+ }
248
+ /**
249
+ * Look up a provider by name.
250
+ * @param name - the provider name.
251
+ * @returns the provider, or undefined when absent.
252
+ */
253
+ getProvider(name) {
254
+ return this.providers.get(name);
255
+ }
256
+ /**
257
+ * List registered provider names in insertion order.
258
+ * @returns the registered names.
259
+ */
260
+ list() {
261
+ return [...this.providers.keys()];
262
+ }
263
+ /**
264
+ * Establish a published child on the named provider. Capability and semantic
265
+ * checks run before delegation. Provider ownership lasts until its promise
266
+ * fulfills; a rejection therefore has no run for the caller to dispose and
267
+ * emits no run lifecycle events. Post-publication turn and infrastructure
268
+ * failures settle through the returned run.
269
+ * @param name - the provider to use.
270
+ * @param request - child label, prompt, parent, signal, and optional capabilities.
271
+ * @returns the published holder-owned run.
272
+ */
273
+ async start(name, request) {
274
+ const provider = this.expectProvider(name);
275
+ this.assertCapabilities(provider, request);
276
+ assertSubagentMaxDepth(request.maxDepth);
277
+ if (request.outputSchema !== undefined)
278
+ assertObjectJsonSchema(request.outputSchema);
279
+ const descriptor = snapshotSubagentDescriptor({
280
+ mode: 'one-shot',
281
+ provider: name,
282
+ ...request.label !== undefined ? { label: request.label } : {},
283
+ });
284
+ const resolved = { ...request, descriptor };
285
+ return observeRun(this.emitLifecycle, name, request.parent, await provider.start(resolved));
286
+ }
287
+ /**
288
+ * Resolve one provider's detached continuable-creation contribution. Method
289
+ * presence on the provider IS the capability, so a provider without it is
290
+ * rejected before the manager reserves any child resources.
291
+ */
292
+ async prepareContinuable(name, request) {
293
+ const provider = this.expectProvider(name);
294
+ if (provider.prepareContinuable === undefined) {
295
+ throw new SubagentError(`subagent provider "${provider.name}" does not support continuable children `
296
+ + '(no prepareContinuable capability)', 'UNSUPPORTED_CAPABILITY');
297
+ }
298
+ return provider.prepareContinuable(request);
299
+ }
300
+ /** Look up a provider for dispatch or fail loud. */
301
+ expectProvider(name) {
302
+ const provider = this.providers.get(name);
303
+ if (provider === undefined) {
304
+ throw new SubagentError(`no subagent provider registered for "${name}"`, 'NO_PROVIDER');
305
+ }
306
+ return provider;
307
+ }
308
+ /** Resolve the optional continuable-subagent manager or fail loud. */
309
+ requireContinuations() {
310
+ if (this.continuations === undefined) {
311
+ throw new SubagentError('continuable subagents require the agents service', 'CONTINUATION_UNAVAILABLE');
312
+ }
313
+ return this.continuations;
314
+ }
315
+ /**
316
+ * Build the lifecycle observer for one continuable Activation's residency
317
+ * epoch, so the manager publishes its edges without owning event dispatch.
318
+ */
319
+ observeActivation(provider, childId, parent) {
320
+ return createActivationObserver(this.emitLifecycle, provider, childId, parent);
321
+ }
322
+ /** Reject the first requested capability that the provider lacks. */
323
+ assertCapabilities(provider, request) {
324
+ const needs = [
325
+ { when: request.outputSchema !== undefined, cap: 'outputSchema' },
326
+ { when: request.maxDepth !== undefined, cap: 'depthLimit' },
327
+ { when: request.toolFilter !== undefined, cap: 'toolFilter' },
328
+ { when: request.persona !== undefined, cap: 'persona' },
329
+ ];
330
+ for (const { when, cap } of needs) {
331
+ if (when && !provider.capabilities[cap]) {
332
+ throw new SubagentError(`subagent provider "${provider.name}" does not support the "${cap}" capability`, 'UNSUPPORTED_CAPABILITY');
333
+ }
334
+ }
335
+ }
336
+ }
337
+ export default SubagentService;
338
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,13 @@
1
+ /** Package-owned subagent registry and lifecycle invariants. @module @deepseek-ai/dsh-subagent/invariant */
2
+ import type { Context } from '@deepseek-ai/cordis';
3
+ /** Cordis companion plugin name. */
4
+ export declare const name = "subagent-invariant";
5
+ /** Service required before the companion can reserve package ownership. */
6
+ export declare const inject: string[];
7
+ /**
8
+ * Register the subagent invariant companion.
9
+ * @param ctx - Cordis context carrying the invariant service.
10
+ * @returns the installed registration's disposer after setup succeeds.
11
+ */
12
+ export declare const apply: (ctx: Context) => Promise<() => void>;
13
+ //# sourceMappingURL=invariant.d.ts.map