@toddzheng024/dscode-bundle 0.4.0 → 0.6.0

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 (93) hide show
  1. package/THIRD_PARTY_NOTICES.md +15 -0
  2. package/cordis.patch.yml +3 -3
  3. package/package.json +7 -1
  4. package/plugins/clipboard-image/clipboard-image.swift +56 -0
  5. package/plugins/clipboard-image/index.mjs +70 -0
  6. package/plugins/code-review/git.mjs +95 -0
  7. package/plugins/code-review/index.mjs +88 -0
  8. package/plugins/dscode/index.mjs +57 -5
  9. package/plugins/email-tools/index.mjs +2 -2
  10. package/plugins/exec/index.mjs +107 -0
  11. package/plugins/session-metrics/index.mjs +6 -2
  12. package/plugins/session-metrics/rate.mjs +62 -0
  13. package/plugins/session-metrics/view.mjs +15 -9
  14. package/plugins/tui-tools/doctor-cli.mjs +22 -0
  15. package/plugins/tui-tools/doctor.mjs +141 -0
  16. package/plugins/tui-tools/index.mjs +14 -6
  17. package/plugins/ultra/policy.mjs +13 -2
  18. package/plugins/worktree-subagent/worktree.mjs +50 -0
  19. package/presets/dscode/agent.cordis.yml +14 -3
  20. package/vendor/deepseek/index.js +12 -2
  21. package/vendor/subagent/index.js +39 -12
  22. package/vendor/subagent-core/LICENSE +21 -0
  23. package/vendor/subagent-core/index.js +3232 -0
  24. package/vendor/subagent-core/invariant.js +76 -0
  25. package/vendor/subagent-core/typert.host.d.ts +3 -0
  26. package/vendor/subagent-core/typert.host.js +964 -0
  27. package/vendor/subagent-core/typert.remote-client.d.ts +27 -0
  28. package/vendor/subagent-core/typert.remote-client.js +160 -0
  29. package/vendor/subagent-core/types/assistant-output.d.ts +48 -0
  30. package/vendor/subagent-core/types/assistant-output.js +73 -0
  31. package/vendor/subagent-core/types/catalog.d.ts +77 -0
  32. package/vendor/subagent-core/types/catalog.js +103 -0
  33. package/vendor/subagent-core/types/child-agent.d.ts +150 -0
  34. package/vendor/subagent-core/types/child-agent.js +207 -0
  35. package/vendor/subagent-core/types/client.d.ts +8 -0
  36. package/vendor/subagent-core/types/client.js +7 -0
  37. package/vendor/subagent-core/types/continuation-activation.d.ts +251 -0
  38. package/vendor/subagent-core/types/continuation-activation.js +663 -0
  39. package/vendor/subagent-core/types/continuation-messages.d.ts +62 -0
  40. package/vendor/subagent-core/types/continuation-messages.js +102 -0
  41. package/vendor/subagent-core/types/continuation.d.ts +124 -0
  42. package/vendor/subagent-core/types/continuation.js +455 -0
  43. package/vendor/subagent-core/types/control-types.d.ts +146 -0
  44. package/vendor/subagent-core/types/control-types.js +9 -0
  45. package/vendor/subagent-core/types/control.d.ts +71 -0
  46. package/vendor/subagent-core/types/control.js +116 -0
  47. package/vendor/subagent-core/types/depth.d.ts +31 -0
  48. package/vendor/subagent-core/types/depth.js +39 -0
  49. package/vendor/subagent-core/types/descriptor.d.ts +144 -0
  50. package/vendor/subagent-core/types/descriptor.js +193 -0
  51. package/vendor/subagent-core/types/error.d.ts +11 -0
  52. package/vendor/subagent-core/types/error.js +14 -0
  53. package/vendor/subagent-core/types/inbox.d.ts +43 -0
  54. package/vendor/subagent-core/types/inbox.js +61 -0
  55. package/vendor/subagent-core/types/index.d.ts +316 -0
  56. package/vendor/subagent-core/types/index.js +511 -0
  57. package/vendor/subagent-core/types/internal.d.ts +58 -0
  58. package/vendor/subagent-core/types/internal.js +58 -0
  59. package/vendor/subagent-core/types/invariant.d.ts +13 -0
  60. package/vendor/subagent-core/types/invariant.js +91 -0
  61. package/vendor/subagent-core/types/lifecycle.d.ts +113 -0
  62. package/vendor/subagent-core/types/lifecycle.js +178 -0
  63. package/vendor/subagent-core/types/list-children.d.ts +65 -0
  64. package/vendor/subagent-core/types/list-children.js +381 -0
  65. package/vendor/subagent-core/types/out-of-process.d.ts +118 -0
  66. package/vendor/subagent-core/types/out-of-process.js +219 -0
  67. package/vendor/subagent-core/types/projection-types.d.ts +74 -0
  68. package/vendor/subagent-core/types/projection-types.js +7 -0
  69. package/vendor/subagent-core/types/projection.d.ts +95 -0
  70. package/vendor/subagent-core/types/projection.js +151 -0
  71. package/vendor/subagent-core/types/run-settlement.d.ts +17 -0
  72. package/vendor/subagent-core/types/run-settlement.js +70 -0
  73. package/vendor/subagent-core/types/types.d.ts +377 -0
  74. package/vendor/subagent-core/types/types.js +19 -0
  75. package/vendor/subagent-driver/LICENSE +21 -0
  76. package/vendor/subagent-driver/index.js +255 -0
  77. package/vendor/subagent-driver/types/index.d.ts +33 -0
  78. package/vendor/subagent-driver/types/structured.d.ts +42 -0
  79. package/vendor/subagent-fork/LICENSE +21 -0
  80. package/vendor/subagent-fork/index.js +61 -0
  81. package/vendor/subagent-fork/types/index.d.ts +20 -0
  82. package/vendor/subagent-spawn/LICENSE +21 -0
  83. package/vendor/subagent-spawn/index.js +45 -0
  84. package/vendor/subagent-spawn/types/index.d.ts +19 -0
  85. package/vendor/terminal/LICENSE +21 -0
  86. package/vendor/terminal/index.js +1013 -0
  87. package/vendor/terminal/types/config.d.ts +71 -0
  88. package/vendor/terminal/types/index.d.ts +36 -0
  89. package/vendor/terminal/types/sanitize.d.ts +47 -0
  90. package/vendor/terminal/types/session.d.ts +87 -0
  91. package/vendor/tui/dscode-clipboard-image/clipboard-image.swift +56 -0
  92. package/vendor/tui/dscode-clipboard-image/index.mjs +70 -0
  93. package/vendor/tui/index.mjs +341 -93
@@ -0,0 +1,377 @@
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
+ * continuation host in `./continuation.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
+ import type { Agent, AgentOptions } from '@deepseek-ai/dsh-agent';
12
+ import type { Branded } from '@deepseek-ai/dsh-brand';
13
+ import type { ContentBlock, MessageId } from '@deepseek-ai/dsh-llm';
14
+ import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session';
15
+ import type { ObjectJsonSchema, ToolRestriction } from '@deepseek-ai/dsh-tools';
16
+ import type { SubagentDescriptorData } from './descriptor.ts';
17
+ /** Identifies one accepted subagent run across its lifecycle event pair. */
18
+ export type SubagentRunId = Branded<'SubagentRunId'>;
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 declare function SubagentRunId(id: string): SubagentRunId;
25
+ /** What a caller asks for when starting a continuable background child. */
26
+ export interface ContinuableStartSpec {
27
+ /** The `ctx.subagents` provider whose continuable-creation capability establishes the child. */
28
+ readonly provider: string;
29
+ /** The initial delegation's short `description`, persisted as the child's creation label. */
30
+ readonly label: string;
31
+ /**
32
+ * Optional caller-reserved child identity. Omission preserves the manager's
33
+ * UUID allocation; supplying one lets a durable parent record provisioning
34
+ * before child materialization without a second identity handshake.
35
+ */
36
+ readonly childId?: SessionId;
37
+ /**
38
+ * The delegation request. The manager reserves the stable child id, resolves
39
+ * the durable descriptor, and composes the child itself.
40
+ */
41
+ readonly request: Omit<SubagentStartRequest, 'label' | 'signal' | 'outputSchema'>;
42
+ /** Caller cancellation, owning the operation only until inbox acceptance. */
43
+ readonly signal: AbortSignal;
44
+ }
45
+ /** Identities returned once a continuable child accepted its initial prompt. */
46
+ export interface ContinuableStart {
47
+ /** The durable child session id, stable across activations. */
48
+ readonly childId: SessionId;
49
+ /** The accepted initial prompt's inbox message id. */
50
+ readonly messageId: MessageId;
51
+ }
52
+ /**
53
+ * Authority under which one interrupt request is admitted. `user` carries the
54
+ * durable direct-parent address a human client presented; `ancestor` carries
55
+ * the exact live Agent object whose recorded lineage must contain the caller.
56
+ */
57
+ export type SubagentInterruptAuthority = {
58
+ readonly kind: 'user';
59
+ readonly parentSessionId: SessionId;
60
+ } | {
61
+ readonly kind: 'ancestor';
62
+ readonly agent: Agent;
63
+ };
64
+ /** Options for one model-authored message between adjacent Agents. */
65
+ export interface SubagentSendMessageOptions {
66
+ /** Caller cancellation, owning the operation only until inbox acceptance. */
67
+ readonly signal: AbortSignal;
68
+ }
69
+ /**
70
+ * Observe-only identifying detail for a published subagent run, carried by
71
+ * `subagent/start`. One-shot runs and continuable Activation epochs share this
72
+ * payload, so an observer sees the same vocabulary for both.
73
+ */
74
+ export interface SubagentRunInfo {
75
+ /** Unique identity shared with the paired terminal event. */
76
+ readonly runId: SubagentRunId;
77
+ /**
78
+ * Provider name recorded when the child was first created. The provider may
79
+ * be absent when an accepted one-shot run becomes ready or a persisted
80
+ * Activation cold-resumes, because neither lifecycle depends on continued
81
+ * registration.
82
+ */
83
+ readonly provider: string;
84
+ /** The child agent's id. */
85
+ readonly id: SessionId;
86
+ /** Snapshot of whether `SubagentRun.localAgent` was present when start fulfilled. */
87
+ readonly local: boolean;
88
+ }
89
+ /**
90
+ * Observe-only outcome detail for a settled subagent run, carried by
91
+ * `subagent/end` and paired with one {@link SubagentRunInfo} by `runId`.
92
+ */
93
+ export interface SubagentRunEndInfo {
94
+ /** Unique identity shared with the paired start event. */
95
+ readonly runId: SubagentRunId;
96
+ /** The same provider name carried by the paired start event. */
97
+ readonly provider: string;
98
+ /** The child agent's id. */
99
+ readonly id: SessionId;
100
+ /** Snapshot of whether `SubagentRun.localAgent` was present when start fulfilled. */
101
+ readonly local: boolean;
102
+ /** The terminal stop reason. */
103
+ readonly stopReason: SubagentResult['stopReason'];
104
+ /**
105
+ * The child's final assistant output, selected by the same rule as
106
+ * {@link SubagentResult.output}; absent on infrastructure rejection or when
107
+ * the child produced none.
108
+ */
109
+ readonly lastAssistantMessage?: ContentBlock[];
110
+ }
111
+ /**
112
+ * Which START-TIME features a provider supports. Checked by the service before delegating to
113
+ * {@link SubagentProvider.start}: a request that needs a capability the chosen provider lacks
114
+ * is rejected with a typed error rather than accepted-then-ignored (the "fail loud, no silent
115
+ * degradation" rule). These flags describe the ONE-SHOT
116
+ * {@link SubagentProvider.start} path, where the provider composes the child;
117
+ * continuable children are composed by the continuation manager itself and are
118
+ * gated by {@link SubagentProvider.prepareContinuable} instead. Each flag
119
+ * corresponds one-to-one to a {@link SubagentStartRequest} option: `depthLimit`
120
+ * to `maxDepth`; the other names match.
121
+ */
122
+ export interface SubagentCapabilities {
123
+ readonly agentOptions: boolean;
124
+ readonly outputSchema: boolean;
125
+ readonly depthLimit: boolean;
126
+ readonly toolFilter: boolean;
127
+ readonly persona: boolean;
128
+ }
129
+ /**
130
+ * What a caller asks for when starting a ONE-SHOT subagent. The tool layer
131
+ * builds this from the model's `{ description, prompt }` plus its own config;
132
+ * the service validates {@link SubagentCapabilities} against the named provider
133
+ * and resolves the durable descriptor before dispatching to
134
+ * {@link SubagentProvider.start}.
135
+ */
136
+ export interface SubagentStartRequest {
137
+ /** Optional short display label persisted with a session-backed child. */
138
+ readonly label?: string;
139
+ /** Content delivered as the child's user message. */
140
+ readonly prompt: ContentBlock[];
141
+ /**
142
+ * The spawning agent. In-process providers derive workspace, lineage, and
143
+ * delegation depth from its durable session state. ACP reads only its cwd,
144
+ * and only when no deployment `cwd` override is configured.
145
+ */
146
+ readonly parent: Agent;
147
+ /**
148
+ * Cancellation signal from the spawning context (the tool's `exec.signal`).
149
+ * This is the canonical cancellation channel both before and after startup:
150
+ * a provider rejects `start()` after cleaning partial resources when it
151
+ * fires before the run is published, and cancels the published run's
152
+ * remaining turn work when it fires afterward.
153
+ */
154
+ readonly signal: AbortSignal;
155
+ /**
156
+ * Optional host-Agent provider, model, reasoning-effort, and output-token
157
+ * overrides. Requires {@link SubagentCapabilities.agentOptions}; in-process
158
+ * providers merge them over the parent Agent's options when they create the
159
+ * child, while the DSH SDK provider merges them over its instance defaults
160
+ * before initializing the separate child runtime.
161
+ */
162
+ readonly agentOptions?: AgentOptions;
163
+ /**
164
+ * Object-rooted JSON Schema within `assertObjectJsonSchema`'s enforced subset. Start rejects
165
+ * unsupported schemas or providers without the capability. Data must be plain host-realm JSON;
166
+ * a successful child returns the matching value as {@link SubagentResult.structured}.
167
+ */
168
+ readonly outputSchema?: ObjectJsonSchema;
169
+ /**
170
+ * Optional absolute delegation-depth cap for the child being started: its
171
+ * computed depth must be less than or equal to this non-negative safe
172
+ * integer. Requires {@link SubagentCapabilities.depthLimit}; rejected at
173
+ * start otherwise.
174
+ */
175
+ readonly maxDepth?: number;
176
+ /**
177
+ * Optional child tool scoping. Requires {@link SubagentCapabilities.toolFilter};
178
+ * rejected at start otherwise. In-process backends apply it as a scoped
179
+ * `tools.restrict()` in the child's creation window: the named tools vanish
180
+ * from the child's prompt AND refuse to execute (one visibility), with loud
181
+ * unknown-name validation.
182
+ */
183
+ readonly toolFilter?: ToolRestriction;
184
+ /**
185
+ * Optional per-child persona. Requires {@link SubagentCapabilities.persona};
186
+ * rejected at start otherwise. In-process backends register it as a scoped
187
+ * `deployment:persona-prefix` section on the child, SHADOWING the deployment's
188
+ * persona for this child alone — same template semantics as the deployment
189
+ * persona (strict `{{…}}` interpolation against the registered variables).
190
+ */
191
+ readonly persona?: string;
192
+ }
193
+ /**
194
+ * Provider-facing one-shot request after {@link SubagentRuntime.start} resolves
195
+ * the durable child descriptor.
196
+ */
197
+ export interface ResolvedSubagentStartRequest extends SubagentStartRequest {
198
+ /** Detached descriptor a session-backed provider persists in the child log. */
199
+ readonly descriptor: SubagentDescriptorData;
200
+ }
201
+ /**
202
+ * What the continuation manager asks a provider for while materializing one
203
+ * continuable child's FIRST activation. The manager has already reserved the
204
+ * durable child identity and owns every later operation, so this request
205
+ * carries only what distinguishes a fresh child from one seeded with parent
206
+ * history.
207
+ */
208
+ export interface ContinuableCreateRequest {
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
+ * A provider's detached contribution to one continuable child's creation. This
221
+ * is DATA, never a capability: it carries no Agent, `AgentHandle`, prompt
222
+ * delivery, result, disposal, or resume operation, because the continuation
223
+ * manager owns the child's whole lifecycle after preparation.
224
+ */
225
+ export interface ContinuableCreateSpec {
226
+ /**
227
+ * Completed-turn prefix of the parent's log to seed the child session with,
228
+ * or absent for a fresh child. Same durable contract as
229
+ * `CreateAgentOptions.seed`: contiguous from seq 0, lossless JSON, balanced.
230
+ */
231
+ readonly seed?: readonly SessionEvent[];
232
+ }
233
+ /**
234
+ * Why a subagent run ended. Merge-extensible (a backend may add variants);
235
+ * consumers branch on the known cases and fall through `default`. The known
236
+ * cases mirror the harness turn-end vocabulary so the tool layer can map a
237
+ * non-`completed` result to an `isError` tool result.
238
+ */
239
+ export interface SubagentStopReasonMap {
240
+ /** The child finished its turn normally. */
241
+ completed: 'completed';
242
+ /** Cancelled through the request signal or disposal. */
243
+ aborted: 'aborted';
244
+ /** Model or transport failure. */
245
+ error: 'error';
246
+ /** The child hit its token ceiling before finishing. */
247
+ 'max-tokens': 'max-tokens';
248
+ /** The child declined the task. */
249
+ refusal: 'refusal';
250
+ }
251
+ /** The union over {@link SubagentStopReasonMap} — widens automatically as backends merge in variants. */
252
+ export type SubagentStopReason = SubagentStopReasonMap[keyof SubagentStopReasonMap];
253
+ /**
254
+ * The terminal outcome of a subagent run, resolved by {@link SubagentRun.result}.
255
+ */
256
+ export interface SubagentResult {
257
+ /**
258
+ * The child's final assistant output is the content of its last non-empty
259
+ * assistant message. Empty-content messages, including usage-only messages,
260
+ * are skipped. Without a non-empty message, the output is its accumulated
261
+ * assistant text stream, or `[]` when the child produced neither.
262
+ */
263
+ readonly output: ContentBlock[];
264
+ /**
265
+ * The structured result after a requested `outputSchema` was successfully
266
+ * satisfied. Requesting a schema does not guarantee presence: a provider can
267
+ * end with `stopReason: 'error'` when the child fails or finishes without a
268
+ * valid capture. The structured value is validated against the requested
269
+ * output schema by the provider; `unknown` here because the seam is
270
+ * schema-agnostic.
271
+ */
272
+ readonly structured?: unknown;
273
+ /**
274
+ * Provider-authored, non-assistant failure detail for a non-`completed`
275
+ * result. Providers keep this text free of tool inputs, file contents,
276
+ * environment values, credentials, and raw protocol payloads, and limit it
277
+ * to 4096 UTF-8 bytes. Consumers present it separately from {@link output}.
278
+ */
279
+ readonly diagnostic?: string;
280
+ /** Why the run ended. A non-`completed` reason means `output` may be partial. */
281
+ readonly stopReason: SubagentStopReason;
282
+ }
283
+ /**
284
+ * ONE-SHOT child handle returned after publication. Prompt submission, turn
285
+ * work, and infrastructure faults after that boundary belong to {@link result}.
286
+ * Consumers await that result and must always {@link dispose} to cancel
287
+ * remaining work and reach quiescence. A run is one disposable foreground
288
+ * delegation with one result; continuable conversations have no run — the
289
+ * continuation manager holds their `AgentHandle` directly and orders every
290
+ * turn through the child's own inbox.
291
+ */
292
+ export interface SubagentRun {
293
+ /**
294
+ * Parent-scoped run id. For a local run, this MUST equal the published child
295
+ * session id, whose `parentSession` records `request.parent.session.id`; a
296
+ * remote provider mints an id unique in the parent namespace.
297
+ */
298
+ readonly id: SessionId;
299
+ /**
300
+ * The exact published in-process child, or `undefined` for a remote run.
301
+ * When present, its id is {@link id}; the provider retains no ownership
302
+ * implication beyond the run's ordinary {@link dispose} contract.
303
+ */
304
+ readonly localAgent: Agent | undefined;
305
+ /**
306
+ * Resolves with the child's terminal {@link SubagentResult} when the run
307
+ * settles. Does NOT reject on a child-level failure — a model/transport
308
+ * failure resolves with `stopReason: 'error'` so the consumer maps it to an
309
+ * `isError` tool result. Rejects on an infrastructure fault the seam cannot
310
+ * represent as a stop reason.
311
+ */
312
+ readonly result: Promise<SubagentResult>;
313
+ /**
314
+ * Cancel remaining work, reach child quiescence, and release resources.
315
+ * Idempotent.
316
+ */
317
+ dispose(): Promise<void>;
318
+ }
319
+ /**
320
+ * One registered transport for running child agents. Providers are trusted
321
+ * same-process implementations; callers treat descriptors and returned values
322
+ * as borrowed immutable data. The service may call one provider concurrently
323
+ * for distinct children. Providers isolate operation-local mutable state; a
324
+ * shared capacity controller may delay an operation but must not couple its
325
+ * settlement or cleanup to a sibling.
326
+ */
327
+ export interface SubagentProvider {
328
+ /** Unique registry name (e.g. `spawn`, `fork`, `acp`). */
329
+ readonly name: string;
330
+ /** The start-time features this provider supports (see {@link SubagentCapabilities}). */
331
+ readonly capabilities: SubagentCapabilities;
332
+ /**
333
+ * Whether the child sees the parent's completed-turn prefix. This is descriptive, not a
334
+ * service-validated start capability: the model-facing tool derives truthful wording from it.
335
+ * It says nothing about tool registration, injected services, or authority inheritance.
336
+ */
337
+ readonly inheritsParentContext: boolean;
338
+ /**
339
+ * Optional static provider-owned provider/model route for one-shot Agent
340
+ * options. Consumers merge tool/model overrides over these values before
341
+ * preflight; providers whose route derives from the parent omit it. The value
342
+ * is detached immutable data and requires `agentOptions` support.
343
+ */
344
+ readonly agentRouteDefaults?: Readonly<{
345
+ provider: string;
346
+ model: string;
347
+ }>;
348
+ /**
349
+ * Establish a ONE-SHOT child and return its handle after publication.
350
+ * The service has already validated that every requested start-time
351
+ * capability is supported and resolved `request.descriptor`, so a
352
+ * session-backed implementation appends that descriptor inside the child's
353
+ * initial turn. Before fulfillment, the provider owns setup and cleans any
354
+ * unpublished partial resources before rejecting. Ownership transfers on
355
+ * fulfillment; subsequent turn or infrastructure failure settles through
356
+ * the returned run. Distinct starts may overlap; cancellation, failure,
357
+ * result settlement, and disposal remain independent for each run.
358
+ */
359
+ start(request: ResolvedSubagentStartRequest): Promise<SubagentRun>;
360
+ /**
361
+ * OPTIONAL (continuable-creation capability): contribute the detached
362
+ * creation inputs that distinguish this provider's continuable children —
363
+ * only whether the child session is seeded with parent history. Method
364
+ * presence IS the capability: the service rejects continuable starts on
365
+ * providers without it, while a provider that has it may still serve
366
+ * ordinary one-shot delegations.
367
+ *
368
+ * This is the provider's ONLY participation in a continuable child. The
369
+ * continuation manager owns identity reservation, composition, Agent
370
+ * creation, prompt delivery, cold resume, ownership, and disposal, so a
371
+ * provider never sees the child's Agent, handle, turns, or teardown.
372
+ * Distinct preparations may overlap; each follows its own signal and returns
373
+ * data belonging only to `request.sessionId`.
374
+ */
375
+ prepareContinuable?(request: ContinuableCreateRequest): Promise<ContinuableCreateSpec>;
376
+ }
377
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,19 @@
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
+ * continuation host in `./continuation.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
+ * Brand a string as a {@link SubagentRunId}.
13
+ * @param id - the raw run id.
14
+ * @returns the same string, branded.
15
+ */
16
+ export function SubagentRunId(id) {
17
+ return id;
18
+ }
19
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DeepSeek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,255 @@
1
+ // dscode-child-cwd-v1
2
+ import { randomUUID } from "node:crypto";
3
+ import { brandString } from "@deepseek-ai/dsh-brand";
4
+ import { foldConsumedWork } from "@deepseek-ai/dsh-agent";
5
+ import { SessionLogOffset } from "@deepseek-ai/dsh-session";
6
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
7
+ import { appendDelegatedPolicyOverrides, applyChildComposition, assertSubagentMaxDepth, captureDelegatedPolicyOverrides, childSessionMeta, finalAssistantOutput, resolveChildAgentOptions, resolveChildDepth } from "../subagent-core/index.js";
8
+ import { ToolArgsError, validateJsonSchemaValue } from "@deepseek-ai/dsh-tools";
9
+ //#region lib/types/structured.js
10
+ /**
11
+ * Child-scoped structured-output tool, prompt instruction, terminal guard, and authoritative
12
+ * result capture for in-process subagents. Each child registers its real schema on its own
13
+ * scope, so concurrent runs do not interact and disposal leaves no global residue. The prompt
14
+ * contribution is ordinary reconstructed request state.
15
+ *
16
+ * Capture commits only after the authoritative `tools/result` succeeds; PTC mode capture also
17
+ * waits for the enclosing `run_code` result. The terminal result marker and monotonic tool
18
+ * guard prevent later calls from reopening a completed structured run.
19
+ * @module @deepseek-ai/dsh-subagent-in-process-driver/structured
20
+ */
21
+ /** The model-facing tool name a structured child must call to finish. */
22
+ const STRUCTURED_OUTPUT_TOOL = "structured_output";
23
+ /**
24
+ * The instruction registered as the child's trailing scoped prompt section:
25
+ * the demand travels with the
26
+ * tool, as ordinary prompt state of exactly one agent.
27
+ */
28
+ const STRUCTURED_OUTPUT_INSTRUCTION = `When you have your final answer, you MUST report it by calling the \`${STRUCTURED_OUTPUT_TOOL}\` tool with arguments matching its parameter schema exactly. Do not finish with a plain text answer: only the tool call counts as your result.`;
29
+ /**
30
+ * Attach the scoped capture tool, instruction, and enforcement to a child during
31
+ * its creation window. Child disposal removes every registration.
32
+ * @param childCtx - the child agent's scope context (`setup`'s argument).
33
+ * @param schema - the trusted, already-asserted schema subset to enforce (see
34
+ * `assertObjectJsonSchema` in dsh-tools).
35
+ * @returns the attachment handle (read `captured()` after the child settles).
36
+ */
37
+ function attachStructuredRuntime(childCtx, schema) {
38
+ /**
39
+ * Validated values staged by the capture tool body, awaiting THEIR OWN
40
+ * authoritative `tools/result` notification. The execution object's identity
41
+ * uniquely identifies a trip through the pipeline: adapter call ids may
42
+ * repeat across steps, but another execution can never reach this WeakMap
43
+ * entry. This is distinct from the opaque `ToolExecutionToken` used to
44
+ * correlate nested transports. The final notification always deletes its own
45
+ * stage, whether the result succeeded or failed.
46
+ */
47
+ const staged = /* @__PURE__ */ new WeakMap();
48
+ /** Successful nested capture waiting for its enclosing transport to commit. */
49
+ let pending;
50
+ let captured;
51
+ const schemaEntry = {
52
+ name: STRUCTURED_OUTPUT_TOOL,
53
+ description: "Report your final structured result. Call this exactly once, when your answer is complete; the arguments must match this tool's parameter schema exactly.",
54
+ parameters: schema
55
+ };
56
+ childCtx.tools.register({
57
+ ...schemaEntry,
58
+ output: {
59
+ schema: {
60
+ type: "object",
61
+ properties: { recorded: {
62
+ type: "boolean",
63
+ const: true
64
+ } },
65
+ required: ["recorded"],
66
+ additionalProperties: false
67
+ },
68
+ render: () => [{
69
+ type: "text",
70
+ text: "Structured output recorded."
71
+ }]
72
+ },
73
+ execute(args, exec) {
74
+ const violations = validateJsonSchemaValue(schema, args);
75
+ if (violations.length > 0) throw new ToolArgsError(violations);
76
+ staged.set(exec, { value: args });
77
+ exec.concludeTurn();
78
+ return Promise.resolve({ recorded: true });
79
+ }
80
+ });
81
+ childCtx.systemPrompt.section({
82
+ name: `tool:${STRUCTURED_OUTPUT_TOOL}`,
83
+ order: childCtx.systemPrompt.getSectionOrder("STRUCTURED_OUTPUT"),
84
+ text: STRUCTURED_OUTPUT_INSTRUCTION
85
+ });
86
+ childCtx.tools.guard((exec) => captured === void 0 && pending === void 0 ? void 0 : `structured output already recorded: the run is complete, so \`${exec.name}\` is not executed`);
87
+ childCtx.on("tools/result", function(exec, result) {
88
+ if (exec.name === "structured_output") {
89
+ const entry = staged.get(exec);
90
+ if (entry === void 0) return;
91
+ staged.delete(exec);
92
+ if (result.isError) return;
93
+ if (exec.parent === void 0) {
94
+ /* v8 ignore else -- sequential agent-loop dispatch lets the guard block every later supported call */
95
+ if (captured === void 0) captured = { value: entry.value };
96
+ } else if (captured === void 0 && pending === void 0) pending = {
97
+ parent: exec.parent,
98
+ value: entry.value
99
+ };
100
+ return;
101
+ }
102
+ if (pending?.parent !== exec.token) return;
103
+ const entry = pending;
104
+ pending = void 0;
105
+ if (result.isError) return;
106
+ /* v8 ignore else -- PTC mode serializes outer executions, so the guard blocks every later supported call */
107
+ if (captured === void 0) captured = { value: entry.value };
108
+ });
109
+ return { captured: () => captured };
110
+ }
111
+ //#endregion
112
+ //#region lib/types/index.js
113
+ /**
114
+ * Shared driver for in-process ONE-SHOT subagent providers. The agent factory's
115
+ * creation transaction owns unpublished setup and rollback; after publication
116
+ * the returned AgentHandle is the one quiescent lifecycle owner held by the
117
+ * provider's caller.
118
+ *
119
+ * Continuable children never come through here: the continuation manager
120
+ * composes and drives them directly, so this driver owns exactly one turn with
121
+ * one result.
122
+ *
123
+ * @module @deepseek-ai/dsh-subagent-in-process-driver
124
+ */
125
+ /** Map a session turn outcome to the subagent seam's terminal vocabulary. */
126
+ function toStopReason(reason) {
127
+ switch (reason?.kind) {
128
+ case "completed": return "completed";
129
+ case "max-tokens": return "max-tokens";
130
+ case "aborted": return "aborted";
131
+ case "blocked": return "refusal";
132
+ default: return "error";
133
+ }
134
+ }
135
+ /** Error used when cancellation wins before the child publication boundary. */
136
+ function prePublicationAbort() {
137
+ return /* @__PURE__ */ new Error("subagent request was aborted before child publication");
138
+ }
139
+ /** Append one one-shot descriptor inside the child's initial turn before its first request. */
140
+ function attachDescriptorAppend(childCtx, descriptor) {
141
+ let appended = false;
142
+ childCtx.on("agent/pre-step", async ({ agent }, next) => {
143
+ const decision = await next();
144
+ if (!appended && decision.kind === "enter") {
145
+ appended = true;
146
+ agent.session.append("subagent/descriptor", descriptor);
147
+ }
148
+ return decision;
149
+ });
150
+ }
151
+ /**
152
+ * Establish and drive one in-process one-shot child. Fulfillment means the agent
153
+ * is already published in the registry and transfers its turn, cancellation,
154
+ * and disposal work through the returned run. Rejection means the agent
155
+ * factory's unpublished creation transaction reached quiescence without
156
+ * publishing a child. Every start appends its resolved descriptor inside the
157
+ * child's initial turn.
158
+ * @param request - the trusted typed start request, including its required signal.
159
+ * @param options - the optional fork seed.
160
+ * @returns a published holder-owned run.
161
+ */
162
+ async function startInProcessRun(request, options) {
163
+ assertSubagentMaxDepth(request.maxDepth);
164
+ if (request.signal.aborted) throw prePublicationAbort();
165
+ const parent = request.parent;
166
+ const childDepth = resolveChildDepth(parent, request.maxDepth);
167
+ const childId = brandString(randomUUID());
168
+ const seed = options.seed;
169
+ const activationBoundary = SessionLogOffset(seed?.length ?? 0);
170
+ const inherited = captureDelegatedPolicyOverrides(parent);
171
+ let structured;
172
+ const setup = (childCtx, child) => {
173
+ appendDelegatedPolicyOverrides(child.session, inherited);
174
+ applyChildComposition(childCtx, parent, {
175
+ persona: request.persona,
176
+ toolFilter: request.toolFilter
177
+ });
178
+ if (request.outputSchema !== void 0) structured = attachStructuredRuntime(childCtx, request.outputSchema);
179
+ attachDescriptorAppend(childCtx, request.descriptor);
180
+ };
181
+ return drivePublishedRun(await parent.ctx.agents.create({
182
+ sessionId: childId,
183
+ parentAgent: parent,
184
+ meta: childSessionMeta(parent, childDepth, seed !== void 0, request.workspaceCwd),
185
+ ...seed !== void 0 ? { seed } : {},
186
+ ...seed === void 0 ? {} : { inheritedEventCount: activationBoundary },
187
+ agentOptions: resolveChildAgentOptions(parent, request.agentOptions, childDepth),
188
+ signal: request.signal,
189
+ setup
190
+ }), request.signal, request.prompt, childId, activationBoundary, structured);
191
+ }
192
+ /**
193
+ * Wrap a published child in the single run lifecycle that owns signal handoff,
194
+ * one turn, result settlement, and quiescent disposal.
195
+ */
196
+ function drivePublishedRun(handle, signal, prompt, childId, boundary, structured) {
197
+ const child = handle.agent;
198
+ const flags = { cancelled: false };
199
+ const onAbort = () => {
200
+ flags.cancelled = true;
201
+ child.cancel({ kind: "parent" });
202
+ };
203
+ signal.addEventListener("abort", onAbort, { once: true });
204
+ if (signal.aborted) onAbort();
205
+ const result = (async () => {
206
+ try {
207
+ if (!flags.cancelled) {
208
+ child.followup(createUserMessage({
209
+ content: prompt,
210
+ source: { kind: "user" }
211
+ }));
212
+ await child.whenIdle();
213
+ }
214
+ return readResult(child, boundary, flags.cancelled, structured ? { captured: structured.captured() } : void 0);
215
+ } finally {
216
+ signal.removeEventListener("abort", onAbort);
217
+ }
218
+ })();
219
+ return {
220
+ id: childId,
221
+ localAgent: child,
222
+ result,
223
+ async dispose() {
224
+ signal.removeEventListener("abort", onAbort);
225
+ flags.cancelled = true;
226
+ const disposal = (await Promise.allSettled([handle.dispose(), result]))[0];
227
+ if (disposal.status === "rejected") throw disposal.reason;
228
+ }
229
+ };
230
+ }
231
+ /** Read one settled child's result from events after its activation boundary. */
232
+ function readResult(child, boundary, cancelled, structured) {
233
+ const own = child.session.snapshotEvents(boundary);
234
+ const lastEnd = foldConsumedWork(own).end;
235
+ const output = finalAssistantOutput(own) ?? [];
236
+ const recorded = toStopReason(lastEnd?.data.reason);
237
+ const stopReason = cancelled && recorded !== "completed" ? "aborted" : recorded;
238
+ if (structured !== void 0) {
239
+ if (structured.captured !== void 0) return {
240
+ output,
241
+ structured: structured.captured.value,
242
+ stopReason
243
+ };
244
+ if (stopReason === "completed") return {
245
+ output,
246
+ stopReason: cancelled ? "aborted" : "error"
247
+ };
248
+ }
249
+ return {
250
+ output,
251
+ stopReason
252
+ };
253
+ }
254
+ //#endregion
255
+ export { STRUCTURED_OUTPUT_INSTRUCTION, STRUCTURED_OUTPUT_TOOL, startInProcessRun };