@deepseek-ai/dsh-subagent 0.2.2-rc.1 → 0.2.2-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/README.i18n.yaml +46 -28
  2. package/README.md +52 -23
  3. package/README.zh.md +52 -23
  4. package/lib/index.js +845 -902
  5. package/lib/typert.host.js +91 -125
  6. package/lib/typert.remote-client.d.ts +3 -3
  7. package/lib/typert.remote-client.d.ts.map +1 -0
  8. package/lib/typert.remote-client.js +17 -63
  9. package/lib/types/activation.d.ts +17 -25
  10. package/lib/types/activation.d.ts.map +1 -0
  11. package/lib/types/activation.js +1 -1
  12. package/lib/types/activation.js.map +1 -0
  13. package/lib/types/archive-admission.d.ts +11 -4
  14. package/lib/types/archive-admission.d.ts.map +1 -0
  15. package/lib/types/archive-admission.js +39 -115
  16. package/lib/types/archive-admission.js.map +1 -0
  17. package/lib/types/assistant-output.d.ts.map +1 -0
  18. package/lib/types/assistant-output.js.map +1 -0
  19. package/lib/types/catalog.d.ts +27 -7
  20. package/lib/types/catalog.d.ts.map +1 -0
  21. package/lib/types/catalog.js +31 -8
  22. package/lib/types/catalog.js.map +1 -0
  23. package/lib/types/child-agent.d.ts +7 -17
  24. package/lib/types/child-agent.d.ts.map +1 -0
  25. package/lib/types/child-agent.js +6 -4
  26. package/lib/types/child-agent.js.map +1 -0
  27. package/lib/types/client.d.ts.map +1 -0
  28. package/lib/types/client.js.map +1 -0
  29. package/lib/types/continuation-messages.d.ts +13 -10
  30. package/lib/types/continuation-messages.d.ts.map +1 -0
  31. package/lib/types/continuation-messages.js +22 -22
  32. package/lib/types/continuation-messages.js.map +1 -0
  33. package/lib/types/control-types.d.ts +7 -28
  34. package/lib/types/control-types.d.ts.map +1 -0
  35. package/lib/types/control-types.js.map +1 -0
  36. package/lib/types/control.d.ts +0 -4
  37. package/lib/types/control.d.ts.map +1 -0
  38. package/lib/types/control.js +1 -5
  39. package/lib/types/control.js.map +1 -0
  40. package/lib/types/depth.d.ts.map +1 -0
  41. package/lib/types/depth.js.map +1 -0
  42. package/lib/types/descriptor.d.ts +1 -1
  43. package/lib/types/descriptor.d.ts.map +1 -0
  44. package/lib/types/descriptor.js +1 -1
  45. package/lib/types/descriptor.js.map +1 -0
  46. package/lib/types/error.d.ts.map +1 -0
  47. package/lib/types/error.js.map +1 -0
  48. package/lib/types/index.d.ts +74 -97
  49. package/lib/types/index.d.ts.map +1 -0
  50. package/lib/types/index.js +125 -146
  51. package/lib/types/index.js.map +1 -0
  52. package/lib/types/lifecycle.d.ts +9 -38
  53. package/lib/types/lifecycle.d.ts.map +1 -0
  54. package/lib/types/lifecycle.js +5 -31
  55. package/lib/types/lifecycle.js.map +1 -0
  56. package/lib/types/list-children.d.ts +12 -0
  57. package/lib/types/list-children.d.ts.map +1 -0
  58. package/lib/types/list-children.js +35 -6
  59. package/lib/types/list-children.js.map +1 -0
  60. package/lib/types/manager.d.ts +96 -112
  61. package/lib/types/manager.d.ts.map +1 -0
  62. package/lib/types/manager.js +471 -568
  63. package/lib/types/manager.js.map +1 -0
  64. package/lib/types/names.d.ts +56 -0
  65. package/lib/types/names.d.ts.map +1 -0
  66. package/lib/types/names.js +96 -0
  67. package/lib/types/names.js.map +1 -0
  68. package/lib/types/out-of-process.d.ts.map +1 -0
  69. package/lib/types/out-of-process.js.map +1 -0
  70. package/lib/types/projection-types.d.ts +18 -6
  71. package/lib/types/projection-types.d.ts.map +1 -0
  72. package/lib/types/projection-types.js.map +1 -0
  73. package/lib/types/projection.d.ts +2 -2
  74. package/lib/types/projection.d.ts.map +1 -0
  75. package/lib/types/projection.js.map +1 -0
  76. package/lib/types/structured.d.ts +1 -1
  77. package/lib/types/structured.d.ts.map +1 -0
  78. package/lib/types/structured.js +2 -2
  79. package/lib/types/structured.js.map +1 -0
  80. package/lib/types/types.d.ts +34 -28
  81. package/lib/types/types.d.ts.map +1 -0
  82. package/lib/types/types.js +2 -4
  83. package/lib/types/types.js.map +1 -0
  84. package/package.json +54 -54
  85. package/src/activation.ts +184 -0
  86. package/src/archive-admission.ts +84 -0
  87. package/src/assistant-output.ts +75 -0
  88. package/src/catalog.ts +194 -0
  89. package/src/child-agent.ts +280 -0
  90. package/src/client.ts +8 -0
  91. package/src/continuation-messages.ts +176 -0
  92. package/src/control-types.ts +127 -0
  93. package/src/control.ts +103 -0
  94. package/src/depth.ts +51 -0
  95. package/src/descriptor.ts +269 -0
  96. package/src/error.ts +15 -0
  97. package/src/index.ts +604 -0
  98. package/src/lifecycle.ts +116 -0
  99. package/src/list-children.ts +168 -0
  100. package/src/manager.ts +1359 -0
  101. package/src/names.ts +113 -0
  102. package/src/out-of-process.ts +217 -0
  103. package/src/projection-types.ts +109 -0
  104. package/src/projection.ts +184 -0
  105. package/src/structured.ts +155 -0
  106. package/src/types.ts +364 -0
  107. package/lib/types/internal.d.ts +0 -58
  108. package/lib/types/internal.js +0 -58
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Child-scoped structured-output tool, prompt instruction, terminal guard, and authoritative
3
+ * result capture for in-process subagents. Each child registers its real schema on its own
4
+ * scope, so concurrent runs do not interact and disposal leaves no global residue. The prompt
5
+ * contribution is ordinary reconstructed request state.
6
+ *
7
+ * Capture commits only after the authoritative `tools/result` succeeds; PTC mode capture also
8
+ * waits for the enclosing `run_code` result. The terminal result marker and monotonic tool
9
+ * guard prevent later calls from reopening a completed structured run.
10
+ * @module @deepseek-ai/dsh-subagent/structured
11
+ */
12
+
13
+ import type { Context } from '@deepseek-ai/cordis'
14
+ import type { ToolSchema } from '@deepseek-ai/dsh-llm'
15
+ import type { ToolExecution, ToolRunContext } from '@deepseek-ai/dsh-tools'
16
+ import { ToolArgsError, validateJsonSchemaValue, type ObjectJsonSchema } from '@deepseek-ai/dsh-tools'
17
+
18
+ /** The model-facing tool name a structured child must call to finish. */
19
+ export const STRUCTURED_OUTPUT_TOOL = 'structured_output'
20
+
21
+ /**
22
+ * The instruction registered as the child's trailing scoped prompt section:
23
+ * the demand travels with the
24
+ * tool, as ordinary prompt state of exactly one agent.
25
+ */
26
+ export const STRUCTURED_OUTPUT_INSTRUCTION
27
+ = 'When you have your final answer, you MUST report it by calling the '
28
+ + `\`${STRUCTURED_OUTPUT_TOOL}\` tool with arguments matching its parameter schema exactly. `
29
+ + 'Do not finish with a plain text answer: only the tool call counts as your result.'
30
+
31
+ /** One structured run's live handle: read the captured value once the child settles. */
32
+ export interface StructuredAttachment {
33
+ /**
34
+ * Input stays closed from capture staging through its final result, including
35
+ * an enclosing PTC execution. A failed result discards its capture and reopens input.
36
+ * @returns whether the activation can accept another message.
37
+ */
38
+ acceptsInput(): boolean
39
+ /**
40
+ * The captured value, once the child called the tool with valid arguments
41
+ * and the authoritative final tool result accepted that call.
42
+ * @returns the committed value, or undefined while none was accepted.
43
+ */
44
+ captured(): { value: unknown } | undefined
45
+ }
46
+
47
+ /**
48
+ * Attach the scoped capture tool, instruction, and enforcement to a child during
49
+ * its creation window. Child disposal removes every registration.
50
+ * @param childCtx - the child agent's scope context (`setup`'s argument).
51
+ * @param schema - the trusted, already-asserted schema subset to enforce (see
52
+ * `assertObjectJsonSchema` in dsh-tools).
53
+ * @param canComplete - whether accepted input has been processed.
54
+ * @returns the attachment handle (read `captured()` after the child settles).
55
+ */
56
+ export function attachStructuredRuntime(
57
+ childCtx: Context,
58
+ schema: ObjectJsonSchema,
59
+ canComplete: () => boolean,
60
+ ): StructuredAttachment {
61
+ /**
62
+ * Validated values staged by the capture tool body, awaiting THEIR OWN
63
+ * authoritative `tools/result` notification. The execution object's identity
64
+ * uniquely identifies a trip through the pipeline: adapter call ids may
65
+ * repeat across steps, but another execution can never reach this Map
66
+ * entry. This is distinct from the opaque `ToolExecutionToken` used to
67
+ * correlate nested transports. The final notification always deletes its own
68
+ * stage, whether the result succeeded or failed.
69
+ */
70
+ const staged = new Map<ToolExecution, { value: unknown }>()
71
+ /** Successful nested capture waiting for its enclosing transport to commit. */
72
+ let pending: { parent: ToolExecution['token']; value: unknown } | undefined
73
+ let captured: { value: unknown } | undefined
74
+
75
+ const schemaEntry: ToolSchema = {
76
+ name: STRUCTURED_OUTPUT_TOOL,
77
+ description:
78
+ 'Report your final structured result. Call this exactly once, when your answer is complete; '
79
+ + 'the arguments must match this tool\'s parameter schema exactly.',
80
+ parameters: { ...schema },
81
+ }
82
+
83
+ childCtx.tools.register({
84
+ ...schemaEntry,
85
+ output: {
86
+ schema: {
87
+ type: 'object',
88
+ properties: { recorded: { type: 'boolean', const: true } },
89
+ required: ['recorded'],
90
+ additionalProperties: false,
91
+ },
92
+ render: () => [{ type: 'text', text: 'Structured output recorded.' }],
93
+ },
94
+ execute(args: unknown, exec: ToolRunContext): Promise<{ recorded: true }> {
95
+ const violations = validateJsonSchemaValue(schema, args)
96
+ // ToolArgsError → isError result with INVALID_ARGS: the model retries
97
+ // within the same turn, exactly like a schema-validated defineTool call.
98
+ if (violations.length > 0) throw new ToolArgsError(violations)
99
+ if (!canComplete()) throw new Error('Process pending messages before submitting structured output.')
100
+ // Two-phase commit, keyed by THIS execution: later transformable
101
+ // waterfalls may still turn the success into an error. ToolRuntime has
102
+ // already frozen model-bound arguments at the actual input boundary.
103
+ staged.set(exec, { value: args })
104
+ exec.concludeTurn()
105
+ return Promise.resolve({ recorded: true })
106
+ },
107
+ })
108
+
109
+ childCtx.systemPrompt.section({
110
+ name: `tool:${STRUCTURED_OUTPUT_TOOL}`,
111
+ order: childCtx.systemPrompt.getSectionOrder('STRUCTURED_OUTPUT'),
112
+ text: STRUCTURED_OUTPUT_INSTRUCTION,
113
+ })
114
+
115
+ // Terminal WITHIN the step. Guards run after the whole pre-execute
116
+ // waterfall and compose monotonically (deny or abstain, never allow), so a
117
+ // later prepended listener cannot resurrect dispatch. Calls that precede
118
+ // capture in the same response remain untouched.
119
+ childCtx.tools.guard(exec => captured === undefined && pending === undefined
120
+ ? undefined
121
+ : `structured output already recorded: the run is complete, so \`${exec.name}\` is not executed`)
122
+
123
+ // The capture COMMIT observes the immutable, authoritative result after the
124
+ // complete pipeline and outer error normalization. This notification cannot
125
+ // transform the outcome, so there is no wrapper outside the commit verdict.
126
+ childCtx.on('tools/result', function (this: unknown, exec, result) {
127
+ if (exec.name === STRUCTURED_OUTPUT_TOOL) {
128
+ const entry = staged.get(exec)
129
+ if (entry === undefined) return
130
+ staged.delete(exec)
131
+ if (result.isError) return
132
+ if (exec.parent === undefined) {
133
+ /* v8 ignore else -- sequential agent-loop dispatch lets the guard block every later supported call */
134
+ if (captured === undefined) captured = { value: entry.value }
135
+ } else {
136
+ /* v8 ignore else -- PTC mode serializes sub-dispatches, so the guard blocks every later supported call */
137
+ if (captured === undefined && pending === undefined) {
138
+ pending = { parent: exec.parent, value: entry.value }
139
+ }
140
+ }
141
+ return
142
+ }
143
+ if (pending?.parent !== exec.token) return
144
+ const entry = pending
145
+ pending = undefined
146
+ if (result.isError) return
147
+ /* v8 ignore else -- PTC mode serializes outer executions, so the guard blocks every later supported call */
148
+ if (captured === undefined) captured = { value: entry.value }
149
+ })
150
+
151
+ return {
152
+ captured: () => captured,
153
+ acceptsInput: () => staged.size === 0 && pending === undefined && captured === undefined,
154
+ }
155
+ }
package/src/types.ts ADDED
@@ -0,0 +1,364 @@
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, such
5
+ * as the manager host, belong with their implementation.
6
+ *
7
+ * @module @deepseek-ai/dsh-subagent/types
8
+ */
9
+
10
+ import type { Agent, AgentOptions } from '@deepseek-ai/dsh-agent'
11
+ import type { Branded } from '@deepseek-ai/dsh-brand'
12
+ import type { ContentBlock, MessageId } from '@deepseek-ai/dsh-llm'
13
+ import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session'
14
+ import type { ObjectJsonSchema } from '@deepseek-ai/dsh-tools'
15
+
16
+ /** Identifies one subagent residency epoch across its lifecycle event pair. */
17
+ export type SubagentRunId = Branded<'SubagentRunId'>
18
+
19
+ /**
20
+ * Brand a string as a {@link SubagentRunId}.
21
+ * @param id - the raw run id.
22
+ * @returns the same string, branded.
23
+ */
24
+ export function SubagentRunId(id: string): SubagentRunId {
25
+ return id as SubagentRunId
26
+ }
27
+
28
+ /** One managed child execution and its result delivery policy. */
29
+ export interface SubagentActivationSpec extends Omit<SubagentStartRequest, 'label' | 'signal'> {
30
+ /** Registered backend to use. */
31
+ readonly provider: string
32
+ /** Short task label retained in cataloged child membership. */
33
+ readonly label: string
34
+ /**
35
+ * Requested name, unique among the parent's children: 1–32 lower-case
36
+ * letters, digits, or hyphens starting with a letter, other than `lead`.
37
+ * Omission selects the first free `agent-N`.
38
+ */
39
+ readonly name?: string
40
+ /** Optional reserved identity for a local child; external backends allocate their own ids. */
41
+ readonly childId?: SessionId
42
+ /** Cancellation before publication; callers own later cancellation through dispose. */
43
+ readonly signal: AbortSignal
44
+ /** Parent delivery notifies the model; caller delivery only returns the result. Local children always enter the parent catalog. */
45
+ readonly delivery: 'parent' | 'caller'
46
+ }
47
+
48
+ /** A managed execution; disposal addresses this exact activation, never a later resume. */
49
+ export interface SubagentActivation {
50
+ /** Stable identity of the child. */
51
+ readonly childId: SessionId
52
+ /**
53
+ * Model-facing name: slash-separated names from the root when every creator
54
+ * below the root is named, otherwise the child Session id.
55
+ */
56
+ readonly name: string
57
+ /** Accepted inbox message, when the backend has a local inbox. */
58
+ readonly messageId?: MessageId
59
+ /**
60
+ * Execution result after teardown settles and notifications are sent; capture failures reject.
61
+ * Teardown failures are reported by dispose() without replacing a captured result.
62
+ */
63
+ readonly result: Promise<SubagentResult>
64
+ /** Stop and release only this activation; rejects on teardown failure. */
65
+ dispose(): Promise<void>
66
+ }
67
+
68
+ /** Model-facing names of one live tree member and its direct creator. */
69
+ export interface SubagentMemberNames {
70
+ /** `lead` for the root, the slash-separated path for a named descendant, otherwise the Session id. */
71
+ readonly self: string
72
+ /** The direct creator's name by the same rule; absent for the root. */
73
+ readonly parent?: string
74
+ }
75
+
76
+ /**
77
+ * Authority under which one interrupt request is admitted. `user` is a trusted
78
+ * host operation; Remote callers need permission on the target Session before
79
+ * invoking it. `ancestor` carries an exact live Agent in the target's creation ancestry.
80
+ */
81
+ export type SubagentInterruptAuthority =
82
+ | { readonly kind: 'user' }
83
+ | { readonly kind: 'ancestor'; readonly agent: Agent }
84
+
85
+ /** Options for one model-authored message within a subagent tree. */
86
+ export interface SubagentSendMessageOptions {
87
+ /** Caller cancellation, owning the operation only until inbox acceptance. */
88
+ readonly signal: AbortSignal
89
+ }
90
+
91
+ /**
92
+ * Observe-only identifying detail for a published subagent run, carried by
93
+ * `subagent/start` and `subagent/end`. Local and external activations share it.
94
+ */
95
+ export interface SubagentRunInfo {
96
+ /** Unique identity shared by one residency epoch's start/end pair. */
97
+ readonly runId: SubagentRunId
98
+ /**
99
+ * Provider name recorded when the child was first created, retained even
100
+ * after that provider is unregistered.
101
+ */
102
+ readonly provider: string
103
+ /** Durable direct creator, independent of the live subagent tree root. */
104
+ readonly parentSessionId: SessionId
105
+ /** The child agent's id. */
106
+ readonly id: SessionId
107
+ /** Whether this activation owns a local Agent, fixed at publication. */
108
+ readonly local: boolean
109
+ }
110
+
111
+ /**
112
+ * Observe-only outcome detail for a settled subagent run, carried by
113
+ * `subagent/end` and paired with one {@link SubagentRunInfo} by `runId`.
114
+ */
115
+ export interface SubagentRunEndInfo extends SubagentRunInfo {
116
+ /** The terminal stop reason. */
117
+ readonly stopReason: SubagentResult['stopReason']
118
+ /**
119
+ * The child's final assistant output, selected by the same rule as
120
+ * {@link SubagentResult.output}; absent on infrastructure rejection or when
121
+ * the child produced none.
122
+ */
123
+ readonly lastAssistantMessage?: readonly ContentBlock[]
124
+ }
125
+
126
+ /**
127
+ * Start-time options supported by a registered backend. The manager checks
128
+ * every requested option before preparing a local child or starting an external
129
+ * execution. depthLimit controls maxDepth; the remaining flag names match
130
+ * SubagentStartRequest fields.
131
+ */
132
+ export interface SubagentCapabilities {
133
+ readonly agentOptions: boolean
134
+ /** Supports selecting a preset independently of the parent's composition. */
135
+ readonly agentPreset: boolean
136
+ readonly outputSchema: boolean
137
+ readonly depthLimit: boolean
138
+ }
139
+
140
+ /**
141
+ * Task and optional capabilities supplied to a backend. The activation spec
142
+ * shares these task options and defines its own label and cancellation policy.
143
+ */
144
+ export interface SubagentStartRequest {
145
+ /** Initial child directory; relative paths resolve against the parent's current directory. Omitted inherits that directory at start. */
146
+ readonly cwd?: string
147
+ /**
148
+ * Independent preset id; omission joins the parent's current generation.
149
+ * Requires a provider with `capabilities.agentPreset` that does not inherit
150
+ * parent context.
151
+ */
152
+ readonly agentPreset?: string
153
+ /** Optional short display label persisted with a session-backed child. */
154
+ readonly label?: string
155
+ /** Content delivered as the child's user message. */
156
+ readonly prompt: ContentBlock[]
157
+ /**
158
+ * The spawning agent. Its effective directory supplies the default cwd;
159
+ * in-process children retain its origin, lineage, and delegation depth.
160
+ */
161
+ readonly parent: Agent
162
+ /**
163
+ * Cancellation signal from the spawning context (the tool's `exec.signal`).
164
+ * This is the canonical cancellation channel both before and after startup:
165
+ * a provider rejects `start()` after cleaning partial resources when it
166
+ * fires before the run is published, and cancels the published run's
167
+ * remaining turn work when it fires afterward.
168
+ */
169
+ readonly signal: AbortSignal
170
+ /**
171
+ * Optional host-Agent provider, model, reasoning-effort, and output-token
172
+ * overrides. Requires {@link SubagentCapabilities.agentOptions}; in-process
173
+ * providers merge them over the parent Agent's options when they create the
174
+ * child, while the DSH SDK provider merges them over its instance defaults
175
+ * before initializing the separate child runtime.
176
+ */
177
+ readonly agentOptions?: AgentOptions
178
+ /**
179
+ * Object-rooted JSON Schema within `assertObjectJsonSchema`'s enforced subset. Start rejects
180
+ * unsupported schemas or providers without the capability. Data must be plain host-realm JSON;
181
+ * a successful child returns the matching value as {@link SubagentResult.structured}.
182
+ */
183
+ readonly outputSchema?: ObjectJsonSchema
184
+ /**
185
+ * Optional absolute delegation-depth cap for the child being started: its
186
+ * computed depth must be less than or equal to this non-negative safe
187
+ * integer. Requires {@link SubagentCapabilities.depthLimit}; rejected at
188
+ * start otherwise.
189
+ */
190
+ readonly maxDepth?: number
191
+ }
192
+
193
+ /** Provider-facing request with an absolute directory selected before startup. */
194
+ export interface ResolvedSubagentStartRequest extends SubagentStartRequest {
195
+ /** Absolute child directory captured from the parent or explicit request. */
196
+ readonly cwd: string
197
+ }
198
+
199
+ /**
200
+ * What the continuation manager asks a provider for while materializing one
201
+ * continuable child's FIRST activation. The manager has already reserved the
202
+ * durable child identity and owns every later operation, so this request
203
+ * carries only what distinguishes a fresh child from one seeded with parent
204
+ * history.
205
+ */
206
+ export interface ContinuableCreateRequest {
207
+ /** Absolute initial directory captured before provider preparation. */
208
+ readonly cwd: string
209
+ /** The reserved durable child session id, for provider diagnostics. */
210
+ readonly sessionId: SessionId
211
+ /** The delegating parent agent whose history a seeding provider reads. */
212
+ readonly parent: Agent
213
+ /**
214
+ * Caller cancellation, which owns preparation only until the manager accepts
215
+ * the initial prompt into the child's inbox.
216
+ */
217
+ readonly signal: AbortSignal
218
+ }
219
+
220
+ /**
221
+ * A provider's detached contribution to one continuable child's creation. This
222
+ * is DATA, never a capability: it carries no Agent, `AgentHandle`, prompt
223
+ * delivery, result, disposal, or resume operation, because the continuation
224
+ * manager owns the child's whole lifecycle after preparation.
225
+ */
226
+ export interface ContinuableCreateSpec {
227
+ /**
228
+ * Completed-turn prefix of the parent's log to seed the child session with,
229
+ * or absent for a fresh child. Same durable contract as
230
+ * `CreateAgentOptions.seed`: contiguous from seq 0, lossless JSON, balanced.
231
+ */
232
+ readonly seed?: readonly SessionEvent[]
233
+ }
234
+
235
+ /**
236
+ * Why a subagent run ended. Merge-extensible (a backend may add variants);
237
+ * consumers branch on the known cases and fall through `default`. The known
238
+ * cases mirror the harness turn-end vocabulary so the tool layer can map a
239
+ * non-`completed` result to an `isError` tool result.
240
+ */
241
+ export interface SubagentStopReasonMap {
242
+ /** The child finished its turn normally. */
243
+ completed: 'completed'
244
+ /** Cancelled through the request signal or disposal. */
245
+ aborted: 'aborted'
246
+ /** Model or transport failure. */
247
+ error: 'error'
248
+ /** The child hit its token ceiling before finishing. */
249
+ 'max-tokens': 'max-tokens'
250
+ /** The child declined the task. */
251
+ refusal: 'refusal'
252
+ }
253
+
254
+ /** The union over {@link SubagentStopReasonMap} — widens automatically as backends merge in variants. */
255
+ export type SubagentStopReason = SubagentStopReasonMap[keyof SubagentStopReasonMap]
256
+
257
+ /**
258
+ * The terminal outcome of a subagent run, resolved by {@link SubagentRun.result}.
259
+ */
260
+ export interface SubagentResult {
261
+ /**
262
+ * The child's final assistant output is the content of its last non-empty
263
+ * assistant message. Empty-content messages, including usage-only messages,
264
+ * are skipped. Without a non-empty message, the output is its accumulated
265
+ * assistant text stream, or `[]` when the child produced neither.
266
+ */
267
+ readonly output: readonly ContentBlock[]
268
+ /**
269
+ * The structured result after a requested `outputSchema` was successfully
270
+ * satisfied. Requesting a schema does not guarantee presence: a provider can
271
+ * end with `stopReason: 'error'` when the child fails or finishes without a
272
+ * valid capture. The structured value is validated against the requested
273
+ * output schema by the provider; `unknown` here because the seam is
274
+ * schema-agnostic.
275
+ */
276
+ readonly structured?: unknown
277
+ /**
278
+ * Provider-authored, non-assistant failure detail for a non-`completed`
279
+ * result. Providers keep this text free of tool inputs, file contents,
280
+ * environment values, credentials, and raw protocol payloads, and limit it
281
+ * to 4096 UTF-8 bytes. Consumers present it separately from {@link output}.
282
+ */
283
+ readonly diagnostic?: string
284
+ /** Why the run ended. A non-`completed` reason means `output` may be partial. */
285
+ readonly stopReason: SubagentStopReason
286
+ }
287
+
288
+ /**
289
+ * Backend execution handle owned directly by the activation registry.
290
+ * A result may become available before resource release; the manager always
291
+ * disposes the handle and awaits cleanup. Backend startup failures clean up
292
+ * partial resources before rejecting, while accepted execution failures settle
293
+ * through result.
294
+ */
295
+ export interface SubagentRun {
296
+ /** Provider-minted id, unique across all parents, providers, and local Sessions in this runtime. */
297
+ readonly id: SessionId
298
+ /**
299
+ * Resolves with the child's terminal {@link SubagentResult} when the run
300
+ * settles. Does NOT reject on a child-level failure — a model/transport
301
+ * failure resolves with `stopReason: 'error'` so the consumer maps it to an
302
+ * `isError` tool result. Rejects on an infrastructure fault the seam cannot
303
+ * represent as a stop reason.
304
+ */
305
+ readonly result: Promise<SubagentResult>
306
+ /**
307
+ * Cancel remaining work, reach child quiescence, and release resources.
308
+ * Idempotent.
309
+ */
310
+ dispose(): Promise<void>
311
+ }
312
+
313
+ /**
314
+ * One registered transport for running child agents. Providers are trusted
315
+ * same-process implementations; callers treat descriptors and returned values
316
+ * as borrowed immutable data. The service may call one provider concurrently
317
+ * for distinct children. Providers isolate operation-local mutable state; a
318
+ * shared capacity controller may delay an operation but must not couple its
319
+ * settlement or cleanup to a sibling.
320
+ */
321
+ export interface SubagentProvider {
322
+ /** Unique registry name (e.g. `spawn`, `fork`, `acp`). */
323
+ readonly name: string
324
+ /** The start-time features this provider supports (see {@link SubagentCapabilities}). */
325
+ readonly capabilities: SubagentCapabilities
326
+ /**
327
+ * Whether the child sees the parent's completed-turn prefix. This is descriptive, not a
328
+ * service-validated start capability: the model-facing tool derives truthful wording from it.
329
+ * It says nothing about tool registration, injected services, or authority inheritance.
330
+ */
331
+ readonly inheritsParentContext: boolean
332
+ /**
333
+ * Optional static provider-owned provider/model route for child Agent
334
+ * options. Consumers merge tool/model overrides over these values before
335
+ * preflight; providers whose route derives from the parent omit it. The value
336
+ * is detached immutable data and requires `agentOptions` support.
337
+ */
338
+ readonly agentRouteDefaults?: Readonly<{ provider: string; model: string }>
339
+ /**
340
+ * Establish one external execution and return its owned handle.
341
+ * The service has already validated that every requested start-time
342
+ * capability is supported. Before fulfillment, the provider owns setup and
343
+ * cleans any unpublished partial resources before rejecting. Ownership transfers on
344
+ * fulfillment; subsequent turn or infrastructure failure settles through
345
+ * the returned run. Distinct starts may overlap; cancellation, failure,
346
+ * result settlement, and disposal remain independent for each run.
347
+ */
348
+ start?(request: ResolvedSubagentStartRequest): Promise<SubagentRun>
349
+ /**
350
+ * OPTIONAL (continuable-creation capability): contribute the detached
351
+ * creation inputs that distinguish this provider's continuable children —
352
+ * only whether the child session is seeded with parent history. Method
353
+ * presence selects local activation execution. Providers without it execute
354
+ * through start and do not accept subsequent messages.
355
+ *
356
+ * This is the provider's ONLY participation in a continuable child. The
357
+ * continuation manager owns identity reservation, composition, Agent
358
+ * creation, prompt delivery, cold resume, ownership, and disposal, so a
359
+ * provider never sees the child's Agent, handle, turns, or teardown.
360
+ * Distinct preparations may overlap; each follows its own signal and returns
361
+ * data belonging only to `request.sessionId`.
362
+ */
363
+ prepareContinuable?(request: ContinuableCreateRequest): Promise<ContinuableCreateSpec>
364
+ }
@@ -1,58 +0,0 @@
1
- /**
2
- * Continuation integration markers and host adapters outside the public
3
- * Service Definition and model-facing Agent messaging contract.
4
- * @module @deepseek-ai/dsh-subagent/internal
5
- */
6
- import type { Agent } from '@deepseek-ai/dsh-agent';
7
- import type { ContentBlock, MessageId, MessageSource } from '@deepseek-ai/dsh-llm';
8
- import type { SessionId } from '@deepseek-ai/dsh-session';
9
- import type { ToolDefinition } from '@deepseek-ai/dsh-tools';
10
- import type SubagentRuntime from './index.ts';
11
- import type { SubagentDelivery } from './control-types.ts';
12
- /** Process-stable identity carried only by the standard adjacent-Agent messaging tool. */
13
- export declare const adjacentAgentSendMessageTool: unique symbol;
14
- /**
15
- * Mark the standard adjacent-Agent messaging tool without changing its model-visible schema.
16
- * @param definition - the standard `send_message` definition.
17
- * @returns the same definition with its internal identity installed.
18
- */
19
- export declare function markAdjacentAgentSendMessageTool(definition: ToolDefinition): ToolDefinition;
20
- /**
21
- * Test whether one visible definition is the standard adjacent-Agent messaging tool.
22
- * @param definition - the scope-resolved `send_message` candidate.
23
- * @returns whether the definition carries the internal standard-tool identity.
24
- */
25
- export declare function isAdjacentAgentSendMessageTool(definition: ToolDefinition | undefined): boolean;
26
- /**
27
- * Process-stable symbol-keyed host delivery shared by the bundled runtime
28
- * entry and this unbundled internal subpath.
29
- * @internal
30
- */
31
- export declare const deliverSubagentPrompt: unique symbol;
32
- /** Runtime face required by the host-only prompt adapters. */
33
- export interface HostPromptDeliverer {
34
- [deliverSubagentPrompt](parent: Agent, childId: SessionId, content: ContentBlock[], source: MessageSource, signal: AbortSignal, delivery: SubagentDelivery): Promise<MessageId>;
35
- }
36
- /**
37
- * Queue one host-protocol message without exposing another Service operation.
38
- * @param runtime - subagent runtime owning continuation residency.
39
- * @param parent - exact live direct parent authorizing delivery.
40
- * @param childId - durable direct-child session id.
41
- * @param content - host-authored content to deliver.
42
- * @param source - durable host-protocol source descriptor.
43
- * @param signal - caller cancellation before inbox acceptance.
44
- * @returns the accepted message's inbox id.
45
- */
46
- export declare function queueHostSubagentPrompt(runtime: SubagentRuntime, parent: Agent, childId: SessionId, content: ContentBlock[], source: MessageSource, signal: AbortSignal): Promise<MessageId>;
47
- /**
48
- * Steer one host-protocol message without exposing another Service operation.
49
- * @param runtime - subagent runtime owning continuation residency.
50
- * @param parent - exact live direct parent authorizing delivery.
51
- * @param childId - durable direct-child session id.
52
- * @param content - host-authored content to deliver.
53
- * @param source - durable host-protocol source descriptor.
54
- * @param signal - caller cancellation before inbox acceptance.
55
- * @returns the accepted message's inbox id.
56
- */
57
- export declare function steerHostSubagentPrompt(runtime: SubagentRuntime, parent: Agent, childId: SessionId, content: ContentBlock[], source: MessageSource, signal: AbortSignal): Promise<MessageId>;
58
- //# sourceMappingURL=internal.d.ts.map
@@ -1,58 +0,0 @@
1
- /**
2
- * Continuation integration markers and host adapters outside the public
3
- * Service Definition and model-facing Agent messaging contract.
4
- * @module @deepseek-ai/dsh-subagent/internal
5
- */
6
- /** Process-stable identity carried only by the standard adjacent-Agent messaging tool. */
7
- export const adjacentAgentSendMessageTool = Symbol.for('dsh.subagent.adjacentAgentSendMessageTool');
8
- /**
9
- * Mark the standard adjacent-Agent messaging tool without changing its model-visible schema.
10
- * @param definition - the standard `send_message` definition.
11
- * @returns the same definition with its internal identity installed.
12
- */
13
- export function markAdjacentAgentSendMessageTool(definition) {
14
- Object.defineProperty(definition, adjacentAgentSendMessageTool, { value: true });
15
- return definition;
16
- }
17
- /**
18
- * Test whether one visible definition is the standard adjacent-Agent messaging tool.
19
- * @param definition - the scope-resolved `send_message` candidate.
20
- * @returns whether the definition carries the internal standard-tool identity.
21
- */
22
- export function isAdjacentAgentSendMessageTool(definition) {
23
- return definition !== undefined
24
- && definition[adjacentAgentSendMessageTool] === true;
25
- }
26
- /**
27
- * Process-stable symbol-keyed host delivery shared by the bundled runtime
28
- * entry and this unbundled internal subpath.
29
- * @internal
30
- */
31
- export const deliverSubagentPrompt = Symbol.for('dsh.subagent.deliverPrompt');
32
- /**
33
- * Queue one host-protocol message without exposing another Service operation.
34
- * @param runtime - subagent runtime owning continuation residency.
35
- * @param parent - exact live direct parent authorizing delivery.
36
- * @param childId - durable direct-child session id.
37
- * @param content - host-authored content to deliver.
38
- * @param source - durable host-protocol source descriptor.
39
- * @param signal - caller cancellation before inbox acceptance.
40
- * @returns the accepted message's inbox id.
41
- */
42
- export function queueHostSubagentPrompt(runtime, parent, childId, content, source, signal) {
43
- return runtime[deliverSubagentPrompt](parent, childId, content, source, signal, 'queue');
44
- }
45
- /**
46
- * Steer one host-protocol message without exposing another Service operation.
47
- * @param runtime - subagent runtime owning continuation residency.
48
- * @param parent - exact live direct parent authorizing delivery.
49
- * @param childId - durable direct-child session id.
50
- * @param content - host-authored content to deliver.
51
- * @param source - durable host-protocol source descriptor.
52
- * @param signal - caller cancellation before inbox acceptance.
53
- * @returns the accepted message's inbox id.
54
- */
55
- export function steerHostSubagentPrompt(runtime, parent, childId, content, source, signal) {
56
- return runtime[deliverSubagentPrompt](parent, childId, content, source, signal, 'steer');
57
- }
58
- //# sourceMappingURL=internal.js.map