@morlay/dsh-subagent 0.0.5 → 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,356 @@
1
+ /**
2
+ * The seam's consumer-facing contracts: request, result, and capability types
3
+ * for {@link SubagentProvider}, plus the `subagent/start` and `subagent/end`
4
+ * payloads that plugins and hosts observe. Internal control interfaces belong
5
+ * with their implementation — the lifecycle observer in `./lifecycle.ts`, the
6
+ * manager host in `./manager.ts` — so this module stays the published
7
+ * surface rather than a bag of everything type-shaped.
8
+ *
9
+ * @module @deepseek-ai/dsh-subagent/types
10
+ */
11
+
12
+ import type { Agent, AgentOptions } from "@deepseek-ai/dsh-agent";
13
+ import type { Branded } from "@deepseek-ai/dsh-brand";
14
+ import type { ContentBlock, MessageId } from "@deepseek-ai/dsh-llm";
15
+ import type { SessionEvent, SessionId } from "@deepseek-ai/dsh-session";
16
+ import type { ObjectJsonSchema } from "@deepseek-ai/dsh-tools";
17
+
18
+ /** Identifies one accepted subagent run across its lifecycle event pair. */
19
+ export type SubagentRunId = Branded<"SubagentRunId">;
20
+
21
+ /**
22
+ * Brand a string as a {@link SubagentRunId}.
23
+ * @param id - the raw run id.
24
+ * @returns the same string, branded.
25
+ */
26
+ export function SubagentRunId(id: string): SubagentRunId {
27
+ return id as SubagentRunId;
28
+ }
29
+
30
+ /** One managed child execution and its result delivery policy. */
31
+ export interface SubagentActivationSpec {
32
+ /** Registered backend to use. */
33
+ readonly provider: string;
34
+ /** Short task label retained in cataloged child membership. */
35
+ readonly label: string;
36
+ /** Optional reserved identity for a local child; external backends allocate their own ids. */
37
+ readonly childId?: SessionId;
38
+ /** Task, parent, and backend-supported execution options. */
39
+ readonly request: Omit<SubagentStartRequest, "label" | "signal">;
40
+ /** Cancellation before publication; callers own later cancellation through dispose. */
41
+ readonly signal: AbortSignal;
42
+ /** Parent delivery notifies the model; caller delivery only returns the result. Local children always enter the parent catalog. */
43
+ readonly delivery: "parent" | "caller";
44
+ }
45
+
46
+ /** A managed execution; disposal addresses this exact activation, never a later resume. */
47
+ export interface SubagentActivation {
48
+ /** Stable identity of the child. */
49
+ readonly childId: SessionId;
50
+ /** Accepted inbox message, when the backend has a local inbox. */
51
+ readonly messageId?: MessageId;
52
+ /**
53
+ * Execution result after teardown settles and notifications are sent; capture failures reject.
54
+ * Teardown failures are reported by dispose() without replacing a captured result.
55
+ */
56
+ readonly result: Promise<SubagentResult>;
57
+ /** Stop and release this activation and its owned descendants; rejects on teardown failure. */
58
+ dispose(): Promise<void>;
59
+ }
60
+
61
+ /**
62
+ * Authority under which one interrupt request is admitted. `user` carries the
63
+ * durable direct-parent address a human client presented; `ancestor` carries
64
+ * the exact live Agent object whose recorded lineage must contain the caller.
65
+ */
66
+ export type SubagentInterruptAuthority =
67
+ | { readonly kind: "user"; readonly parentSessionId: SessionId }
68
+ | { readonly kind: "ancestor"; readonly agent: Agent };
69
+
70
+ /** Options for one model-authored message between adjacent Agents. */
71
+ export interface SubagentSendMessageOptions {
72
+ /** Caller cancellation, owning the operation only until inbox acceptance. */
73
+ readonly signal: AbortSignal;
74
+ }
75
+
76
+ /**
77
+ * Observe-only identifying detail for a published subagent run, carried by
78
+ * `subagent/start`. Local and external activations share this payload.
79
+ */
80
+ export interface SubagentRunInfo {
81
+ /** Unique identity shared with the paired terminal event. */
82
+ readonly runId: SubagentRunId;
83
+ /**
84
+ * Provider name recorded when the child was first created, retained even
85
+ * after that provider is unregistered.
86
+ */
87
+ readonly provider: string;
88
+ /** The child agent's id. */
89
+ readonly id: SessionId;
90
+ /** Whether this activation owns a local Agent, fixed at publication. */
91
+ readonly local: boolean;
92
+ }
93
+
94
+ /**
95
+ * Observe-only outcome detail for a settled subagent run, carried by
96
+ * `subagent/end` and paired with one {@link SubagentRunInfo} by `runId`.
97
+ */
98
+ export interface SubagentRunEndInfo {
99
+ /** Unique identity shared with the paired start event. */
100
+ readonly runId: SubagentRunId;
101
+ /** The same provider name carried by the paired start event. */
102
+ readonly provider: string;
103
+ /** The child agent's id. */
104
+ readonly id: SessionId;
105
+ /** Whether this activation owns a local Agent, fixed at publication. */
106
+ readonly local: boolean;
107
+ /** The terminal stop reason. */
108
+ readonly stopReason: SubagentResult["stopReason"];
109
+ /**
110
+ * The child's final assistant output, selected by the same rule as
111
+ * {@link SubagentResult.output}; absent on infrastructure rejection or when
112
+ * the child produced none.
113
+ */
114
+ readonly lastAssistantMessage?: readonly ContentBlock[];
115
+ }
116
+
117
+ /**
118
+ * Start-time options supported by a registered backend. The manager checks
119
+ * every requested option before preparing a local child or starting an external
120
+ * execution. depthLimit controls maxDepth; the remaining flag names match
121
+ * SubagentStartRequest fields.
122
+ */
123
+ export interface SubagentCapabilities {
124
+ readonly agentOptions: boolean;
125
+ /** Supports selecting a preset independently of the parent's composition. */
126
+ readonly agentPreset: boolean;
127
+ readonly outputSchema: boolean;
128
+ readonly depthLimit: boolean;
129
+ }
130
+
131
+ /**
132
+ * Task and optional capabilities supplied to a backend. startActivation carries
133
+ * these fields in request while owning its label, cancellation, and delivery
134
+ * policy separately.
135
+ */
136
+ export interface SubagentStartRequest {
137
+ /** Initial child directory; relative paths resolve against the parent's current directory. Omitted inherits that directory at start. */
138
+ readonly cwd?: string;
139
+ /**
140
+ * Independent preset id; omission joins the parent's current generation.
141
+ * Requires a provider with `capabilities.agentPreset` that does not inherit
142
+ * parent context.
143
+ */
144
+ readonly agentPreset?: string;
145
+ /** Optional short display label persisted with a session-backed child. */
146
+ readonly label?: string;
147
+ /** Content delivered as the child's user message. */
148
+ readonly prompt: ContentBlock[];
149
+ /**
150
+ * The spawning agent. Its effective directory supplies the default cwd;
151
+ * in-process children retain its origin, lineage, and delegation depth.
152
+ */
153
+ readonly parent: Agent;
154
+ /**
155
+ * Cancellation signal from the spawning context (the tool's `exec.signal`).
156
+ * This is the canonical cancellation channel both before and after startup:
157
+ * a provider rejects `start()` after cleaning partial resources when it
158
+ * fires before the run is published, and cancels the published run's
159
+ * remaining turn work when it fires afterward.
160
+ */
161
+ readonly signal: AbortSignal;
162
+ /**
163
+ * Optional host-Agent provider, model, reasoning-effort, and output-token
164
+ * overrides. Requires {@link SubagentCapabilities.agentOptions}; in-process
165
+ * providers merge them over the parent Agent's options when they create the
166
+ * child, while the DSH SDK provider merges them over its instance defaults
167
+ * before initializing the separate child runtime.
168
+ */
169
+ readonly agentOptions?: AgentOptions;
170
+ /**
171
+ * Object-rooted JSON Schema within `assertObjectJsonSchema`'s enforced subset. Start rejects
172
+ * unsupported schemas or providers without the capability. Data must be plain host-realm JSON;
173
+ * a successful child returns the matching value as {@link SubagentResult.structured}.
174
+ */
175
+ readonly outputSchema?: ObjectJsonSchema;
176
+ /**
177
+ * Optional absolute delegation-depth cap for the child being started: its
178
+ * computed depth must be less than or equal to this non-negative safe
179
+ * integer. Requires {@link SubagentCapabilities.depthLimit}; rejected at
180
+ * start otherwise.
181
+ */
182
+ readonly maxDepth?: number;
183
+ }
184
+
185
+ /** Provider-facing request with an absolute directory selected before startup. */
186
+ export interface ResolvedSubagentStartRequest extends SubagentStartRequest {
187
+ /** Absolute child directory captured from the parent or explicit request. */
188
+ readonly cwd: string;
189
+ }
190
+
191
+ /**
192
+ * What the continuation manager asks a provider for while materializing one
193
+ * continuable child's FIRST activation. The manager has already reserved the
194
+ * durable child identity and owns every later operation, so this request
195
+ * carries only what distinguishes a fresh child from one seeded with parent
196
+ * history.
197
+ */
198
+ export interface ContinuableCreateRequest {
199
+ /** Absolute initial directory captured before provider preparation. */
200
+ readonly cwd: string;
201
+ /** The reserved durable child session id, for provider diagnostics. */
202
+ readonly sessionId: SessionId;
203
+ /** The delegating parent agent whose history a seeding provider reads. */
204
+ readonly parent: Agent;
205
+ /**
206
+ * Caller cancellation, which owns preparation only until the manager accepts
207
+ * the initial prompt into the child's inbox.
208
+ */
209
+ readonly signal: AbortSignal;
210
+ }
211
+
212
+ /**
213
+ * A provider's detached contribution to one continuable child's creation. This
214
+ * is DATA, never a capability: it carries no Agent, `AgentHandle`, prompt
215
+ * delivery, result, disposal, or resume operation, because the continuation
216
+ * manager owns the child's whole lifecycle after preparation.
217
+ */
218
+ export interface ContinuableCreateSpec {
219
+ /**
220
+ * Completed-turn prefix of the parent's log to seed the child session with,
221
+ * or absent for a fresh child. Same durable contract as
222
+ * `CreateAgentOptions.seed`: contiguous from seq 0, lossless JSON, balanced.
223
+ */
224
+ readonly seed?: readonly SessionEvent[];
225
+ }
226
+
227
+ /**
228
+ * Why a subagent run ended. Merge-extensible (a backend may add variants);
229
+ * consumers branch on the known cases and fall through `default`. The known
230
+ * cases mirror the harness turn-end vocabulary so the tool layer can map a
231
+ * non-`completed` result to an `isError` tool result.
232
+ */
233
+ export interface SubagentStopReasonMap {
234
+ /** The child finished its turn normally. */
235
+ completed: "completed";
236
+ /** Cancelled through the request signal or disposal. */
237
+ aborted: "aborted";
238
+ /** Model or transport failure. */
239
+ error: "error";
240
+ /** The child hit its token ceiling before finishing. */
241
+ "max-tokens": "max-tokens";
242
+ /** The child declined the task. */
243
+ refusal: "refusal";
244
+ }
245
+
246
+ /** The union over {@link SubagentStopReasonMap} — widens automatically as backends merge in variants. */
247
+ export type SubagentStopReason = SubagentStopReasonMap[keyof SubagentStopReasonMap];
248
+
249
+ /**
250
+ * The terminal outcome of a subagent run, resolved by {@link SubagentRun.result}.
251
+ */
252
+ export interface SubagentResult {
253
+ /**
254
+ * The child's final assistant output is the content of its last non-empty
255
+ * assistant message. Empty-content messages, including usage-only messages,
256
+ * are skipped. Without a non-empty message, the output is its accumulated
257
+ * assistant text stream, or `[]` when the child produced neither.
258
+ */
259
+ readonly output: readonly ContentBlock[];
260
+ /**
261
+ * The structured result after a requested `outputSchema` was successfully
262
+ * satisfied. Requesting a schema does not guarantee presence: a provider can
263
+ * end with `stopReason: 'error'` when the child fails or finishes without a
264
+ * valid capture. The structured value is validated against the requested
265
+ * output schema by the provider; `unknown` here because the seam is
266
+ * schema-agnostic.
267
+ */
268
+ readonly structured?: unknown;
269
+ /**
270
+ * Provider-authored, non-assistant failure detail for a non-`completed`
271
+ * result. Providers keep this text free of tool inputs, file contents,
272
+ * environment values, credentials, and raw protocol payloads, and limit it
273
+ * to 4096 UTF-8 bytes. Consumers present it separately from {@link output}.
274
+ */
275
+ readonly diagnostic?: string;
276
+ /** Why the run ended. A non-`completed` reason means `output` may be partial. */
277
+ readonly stopReason: SubagentStopReason;
278
+ }
279
+
280
+ /**
281
+ * Backend execution handle owned directly by the activation registry.
282
+ * A result may become available before resource release; the manager always
283
+ * disposes the handle and awaits cleanup. Backend startup failures clean up
284
+ * partial resources before rejecting, while accepted execution failures settle
285
+ * through result.
286
+ */
287
+ export interface SubagentRun {
288
+ /** Provider-minted id, unique across all parents, providers, and local Sessions in this runtime. */
289
+ readonly id: SessionId;
290
+ /**
291
+ * Resolves with the child's terminal {@link SubagentResult} when the run
292
+ * settles. Does NOT reject on a child-level failure — a model/transport
293
+ * failure resolves with `stopReason: 'error'` so the consumer maps it to an
294
+ * `isError` tool result. Rejects on an infrastructure fault the seam cannot
295
+ * represent as a stop reason.
296
+ */
297
+ readonly result: Promise<SubagentResult>;
298
+ /**
299
+ * Cancel remaining work, reach child quiescence, and release resources.
300
+ * Idempotent.
301
+ */
302
+ dispose(): Promise<void>;
303
+ }
304
+
305
+ /**
306
+ * One registered transport for running child agents. Providers are trusted
307
+ * same-process implementations; callers treat descriptors and returned values
308
+ * as borrowed immutable data. The service may call one provider concurrently
309
+ * for distinct children. Providers isolate operation-local mutable state; a
310
+ * shared capacity controller may delay an operation but must not couple its
311
+ * settlement or cleanup to a sibling.
312
+ */
313
+ export interface SubagentProvider {
314
+ /** Unique registry name (e.g. `spawn`, `fork`, `acp`). */
315
+ readonly name: string;
316
+ /** The start-time features this provider supports (see {@link SubagentCapabilities}). */
317
+ readonly capabilities: SubagentCapabilities;
318
+ /**
319
+ * Whether the child sees the parent's completed-turn prefix. This is descriptive, not a
320
+ * service-validated start capability: the model-facing tool derives truthful wording from it.
321
+ * It says nothing about tool registration, injected services, or authority inheritance.
322
+ */
323
+ readonly inheritsParentContext: boolean;
324
+ /**
325
+ * Optional static provider-owned provider/model route for child Agent
326
+ * options. Consumers merge tool/model overrides over these values before
327
+ * preflight; providers whose route derives from the parent omit it. The value
328
+ * is detached immutable data and requires `agentOptions` support.
329
+ */
330
+ readonly agentRouteDefaults?: Readonly<{ provider: string; model: string }>;
331
+ /**
332
+ * Establish one external execution and return its owned handle.
333
+ * The service has already validated that every requested start-time
334
+ * capability is supported. Before fulfillment, the provider owns setup and
335
+ * cleans any unpublished partial resources before rejecting. Ownership transfers on
336
+ * fulfillment; subsequent turn or infrastructure failure settles through
337
+ * the returned run. Distinct starts may overlap; cancellation, failure,
338
+ * result settlement, and disposal remain independent for each run.
339
+ */
340
+ start?(request: ResolvedSubagentStartRequest): Promise<SubagentRun>;
341
+ /**
342
+ * OPTIONAL (continuable-creation capability): contribute the detached
343
+ * creation inputs that distinguish this provider's continuable children —
344
+ * only whether the child session is seeded with parent history. Method
345
+ * presence selects local activation execution. Providers without it execute
346
+ * through start and do not accept subsequent messages.
347
+ *
348
+ * This is the provider's ONLY participation in a continuable child. The
349
+ * continuation manager owns identity reservation, composition, Agent
350
+ * creation, prompt delivery, cold resume, ownership, and disposal, so a
351
+ * provider never sees the child's Agent, handle, turns, or teardown.
352
+ * Distinct preparations may overlap; each follows its own signal and returns
353
+ * data belonging only to `request.sessionId`.
354
+ */
355
+ prepareContinuable?(request: ContinuableCreateRequest): Promise<ContinuableCreateSpec>;
356
+ }