@dsmm/dsmm 0.3.2 → 0.3.4

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 (190) hide show
  1. package/README.md +2 -2
  2. package/agent-presets/dsmm-builder/agent.cordis.yml +1 -1
  3. package/agent-presets/dsmm-clarifier/agent.cordis.yml +1 -1
  4. package/agent-presets/dsmm-code-search/agent.cordis.yml +1 -1
  5. package/agent-presets/dsmm-coding/agent.cordis.yml +3 -2
  6. package/agent-presets/dsmm-complex/agent.cordis.yml +2 -1
  7. package/agent-presets/dsmm-creative/agent.cordis.yml +1 -1
  8. package/agent-presets/dsmm-cross-cutting/agent.cordis.yml +1 -1
  9. package/agent-presets/dsmm-deep/agent.cordis.yml +2 -1
  10. package/agent-presets/dsmm-doc-search/agent.cordis.yml +1 -1
  11. package/agent-presets/dsmm-documenting/agent.cordis.yml +1 -1
  12. package/agent-presets/dsmm-frontend/agent.cordis.yml +4 -2
  13. package/agent-presets/dsmm-hard-reasoning/agent.cordis.yml +1 -1
  14. package/agent-presets/dsmm-media-reader/agent.cordis.yml +1 -1
  15. package/agent-presets/dsmm-normal-task/agent.cordis.yml +3 -2
  16. package/agent-presets/dsmm-oracle/agent.cordis.yml +1 -1
  17. package/agent-presets/dsmm-oracle-2nd/agent.cordis.yml +1 -1
  18. package/agent-presets/dsmm-orchestrator/agent.cordis.yml +11 -1
  19. package/agent-presets/dsmm-plan-critic/agent.cordis.yml +1 -1
  20. package/agent-presets/dsmm-planner/agent.cordis.yml +1 -1
  21. package/agent-presets/dsmm-quick/agent.cordis.yml +2 -1
  22. package/agent-presets/dsmm-research/agent.cordis.yml +1 -1
  23. package/agent-presets/dsmm-reviewer/agent.cordis.yml +1 -1
  24. package/cordis.patch.yml +0 -9
  25. package/docs/agent-presets.md +5 -5
  26. package/docs/compatibility.md +2 -6
  27. package/docs/migration-from-ocmm.md +1 -1
  28. package/docs/native-permissions.md +11 -3
  29. package/docs/roadmap.md +31 -11
  30. package/docs/runtime-recovery.md +30 -2
  31. package/docs/settings-status.md +7 -5
  32. package/docs/skill-sync.md +13 -14
  33. package/lib/client/ChildrenPanel.d.ts +1 -4
  34. package/lib/client/ChildrenPanel.js +3 -3
  35. package/lib/client/DeploymentFields.js +12 -1
  36. package/lib/client/DeploymentPage.d.ts +1 -3
  37. package/lib/client/DeploymentPage.js +30 -18
  38. package/lib/client/NativeCommandEntries.js +47 -37
  39. package/lib/client/PermissionRuleEntries.d.ts +17 -0
  40. package/lib/client/PermissionRuleEntries.js +70 -0
  41. package/lib/client/PermissionsPanel.d.ts +1 -3
  42. package/lib/client/PermissionsPanel.js +5 -4
  43. package/lib/client/children-locales.d.ts +4 -4
  44. package/lib/client/controller.js +4 -1
  45. package/lib/client/deployment-locales.d.ts +2 -2
  46. package/lib/client/deployment-locales.js +8 -9
  47. package/lib/client/deployment-modules.d.ts +5 -3
  48. package/lib/client/deployment-modules.js +4 -4
  49. package/lib/client/deployment-workspace.d.ts +4 -0
  50. package/lib/client/deployment-workspace.js +37 -11
  51. package/lib/client/index.js +2 -7
  52. package/lib/client/locales.js +131 -119
  53. package/lib/client/permission-controller.d.ts +13 -0
  54. package/lib/client/permission-controller.js +50 -23
  55. package/lib/client/permission-locales.d.ts +28 -30
  56. package/lib/client/permission-locales.js +38 -38
  57. package/lib/client/styles.d.ts +1 -1
  58. package/lib/client/styles.js +8 -8
  59. package/lib/client.js +2272 -3773
  60. package/lib/core-permission-authority.js +28 -16
  61. package/lib/index.d.ts +0 -2
  62. package/lib/index.js +11 -31
  63. package/lib/native-admission.d.ts +3 -3
  64. package/lib/native-admission.js +67 -66
  65. package/lib/permission-controller.js +1 -1
  66. package/lib/permission-fs-search.js +1 -2
  67. package/lib/permission-fs.js +1 -2
  68. package/lib/permission-native-command.js +6 -4
  69. package/lib/permission-settings.d.ts +21 -7
  70. package/lib/permission-settings.js +21 -9
  71. package/lib/permission-web.js +1 -2
  72. package/lib/preset-materializer.js +3 -3
  73. package/lib/preset-registry.d.ts +20 -2
  74. package/lib/preset-registry.js +46 -17
  75. package/lib/profile-diagnostics.js +1 -1
  76. package/lib/profile-remote.js +1 -3
  77. package/lib/role-identity.d.ts +1 -1
  78. package/lib/role-identity.js +16 -4
  79. package/lib/role-policy.d.ts +3 -0
  80. package/lib/role-policy.js +30 -6
  81. package/lib/role-subagents.js +6 -4
  82. package/lib/roles.d.ts +2 -0
  83. package/lib/roles.js +2 -0
  84. package/lib/runtime-integration.js +4 -4
  85. package/lib/settings.d.ts +1 -3
  86. package/lib/settings.js +8 -10
  87. package/lib/state.d.ts +4 -1
  88. package/lib/state.js +37 -6
  89. package/package.json +1 -5
  90. package/prompts/deepwork.md +13 -1
  91. package/prompts/source/agents/orchestrator.md +10 -0
  92. package/prompts/source/category/coding.md +2 -1
  93. package/prompts/source/category/complex.md +1 -0
  94. package/prompts/source/category/deep.md +1 -0
  95. package/prompts/source/category/frontend.md +3 -1
  96. package/prompts/source/category/normal-task.md +2 -1
  97. package/prompts/source/category/quick.md +1 -0
  98. package/prompts/source/deepwork/claude-opus-5.md +2 -0
  99. package/prompts/source/deepwork/default.md +12 -0
  100. package/prompts/source/deepwork/gemini.md +6 -1
  101. package/prompts/source/deepwork/glm.md +5 -1
  102. package/prompts/source/deepwork/gpt.md +22 -2
  103. package/prompts/source/deepwork/kimi-k27.md +2 -0
  104. package/prompts/source/deepwork/planner.md +3 -1
  105. package/prompts/source/deepwork/swe-2.md +2 -0
  106. package/prompts/source/manifest.json +3 -68
  107. package/prompts/source/shared/dsh-host-contract.md +1 -1
  108. package/skills/ast-grep/SKILL.md +1 -1
  109. package/skills/brainstorming/SKILL.md +1 -1
  110. package/skills/coding-agent-sessions/SKILL.md +1 -1
  111. package/skills/debugging/SKILL.md +1 -1
  112. package/skills/dispatching-parallel-agents/SKILL.md +1 -1
  113. package/skills/frontend/SKILL.md +1 -1
  114. package/skills/git-master/SKILL.md +1 -1
  115. package/skills/init-deep/SKILL.md +1 -1
  116. package/skills/receiving-code-review/SKILL.md +1 -1
  117. package/skills/remove-ai-slops/SKILL.md +1 -1
  118. package/skills/requesting-code-review/SKILL.md +1 -1
  119. package/skills/subagent-driven-development/SKILL.md +1 -1
  120. package/skills/using-git-worktrees/SKILL.md +1 -1
  121. package/skills/writing-plans/SKILL.md +1 -1
  122. package/lib/client/ChildPermissions.d.ts +0 -43
  123. package/lib/client/ChildPermissions.js +0 -100
  124. package/lib/client/HistoryContinuation.d.ts +0 -7
  125. package/lib/client/HistoryContinuation.js +0 -22
  126. package/lib/client/PermissionPanelEntry.d.ts +0 -8
  127. package/lib/client/PermissionPanelEntry.js +0 -11
  128. package/lib/client/TemporaryPermissions.d.ts +0 -21
  129. package/lib/client/TemporaryPermissions.js +0 -94
  130. package/lib/client/history-controller.d.ts +0 -29
  131. package/lib/client/history-controller.js +0 -111
  132. package/lib/client/history-entry.d.ts +0 -11
  133. package/lib/client/history-entry.js +0 -106
  134. package/lib/client/history-locales.d.ts +0 -95
  135. package/lib/client/history-locales.js +0 -41
  136. package/lib/client/temporary-permission-client.d.ts +0 -20
  137. package/lib/client/temporary-permission-client.js +0 -52
  138. package/lib/client/temporary-permission-entry.d.ts +0 -6
  139. package/lib/client/temporary-permission-entry.js +0 -56
  140. package/lib/history-candidates.d.ts +0 -30
  141. package/lib/history-candidates.js +0 -176
  142. package/lib/history-codec.d.ts +0 -11
  143. package/lib/history-codec.js +0 -102
  144. package/lib/history-contract.d.ts +0 -44
  145. package/lib/history-contract.js +0 -2
  146. package/lib/history-controller.d.ts +0 -42
  147. package/lib/history-controller.js +0 -329
  148. package/lib/history-policy.d.ts +0 -4
  149. package/lib/history-policy.js +0 -8
  150. package/lib/history-remote.d.ts +0 -28
  151. package/lib/history-remote.js +0 -17
  152. package/lib/history-rpc.d.ts +0 -24
  153. package/lib/history-rpc.js +0 -136
  154. package/lib/history-support.d.ts +0 -15
  155. package/lib/history-support.js +0 -21
  156. package/lib/history-types.d.ts +0 -67
  157. package/lib/history-types.js +0 -2
  158. package/lib/permission-child-control.d.ts +0 -36
  159. package/lib/permission-child-control.js +0 -164
  160. package/lib/permission-exec-argv.d.ts +0 -32
  161. package/lib/permission-exec-argv.js +0 -171
  162. package/lib/permission-temporary-files.d.ts +0 -19
  163. package/lib/permission-temporary-files.js +0 -248
  164. package/lib/permission-temporary-grants.d.ts +0 -106
  165. package/lib/permission-temporary-grants.js +0 -198
  166. package/lib/permission-temporary-install.d.ts +0 -25
  167. package/lib/permission-temporary-install.js +0 -86
  168. package/lib/permission-temporary-remote.d.ts +0 -19
  169. package/lib/permission-temporary-remote.js +0 -75
  170. package/lib/permission-temporary-rpc.d.ts +0 -37
  171. package/lib/permission-temporary-rpc.js +0 -154
  172. package/lib/permission-temporary-types.d.ts +0 -47
  173. package/lib/permission-temporary-types.js +0 -2
  174. package/lib/permission-temporary-web.d.ts +0 -11
  175. package/lib/permission-temporary-web.js +0 -154
  176. package/patches/dsh-approval-settlement/@deepseek-ai__dsh-api-gateway@0.2.1-rc.2.patch +0 -13291
  177. package/patches/dsh-approval-settlement/@deepseek-ai__dsh-api-remotes@0.2.1-rc.2.patch +0 -9133
  178. package/patches/dsh-approval-settlement/@deepseek-ai__dsh-client-ui-approval@0.2.1-rc.2.patch +0 -156
  179. package/patches/dsh-approval-settlement/@deepseek-ai__dsh-subagent@0.2.1-rc.2.patch +0 -3546
  180. package/patches/dsh-approval-settlement/@deepseek-ai__dsh-user-approval@0.2.1-rc.2.patch +0 -431
  181. package/patches/dsh-approval-settlement/@deepseek-ai__dsh-web@0.2.1-rc.2.patch +0 -119
  182. package/patches/dsh-approval-settlement/README.md +0 -41
  183. package/patches/dsh-approval-settlement/metadata.json +0 -10
  184. package/patches/dsh-session-activation/@deepseek-ai__dsh-agent-loop@0.2.1-rc.2.patch +0 -383
  185. package/patches/dsh-session-activation/@deepseek-ai__dsh-agent-preset-registry@0.2.1-rc.2.patch +0 -55
  186. package/patches/dsh-session-activation/@deepseek-ai__dsh-api-session-controller@0.2.1-rc.2.patch +0 -16673
  187. package/patches/dsh-session-activation/@deepseek-ai__dsh-client-ui-subagent@0.2.1-rc.2.patch +0 -29
  188. package/patches/dsh-session-activation/@deepseek-ai__dsh-client-ui-workspace@0.2.1-rc.2.patch +0 -196
  189. package/patches/dsh-session-activation/@deepseek-ai__dsh-session-persistence-jsonl@0.2.1-rc.2.patch +0 -35
  190. package/patches/dsh-session-activation/@deepseek-ai__dsh-session-persistence@0.2.1-rc.2.patch +0 -40
@@ -1,3546 +0,0 @@
1
- diff --git a/lib/index.js b/lib/index.js
2
- index 5f8a4a91bdc321121b5ac02b9662147785b77215..5c491dcb0230e8e80c884c569c6ea9d40cf1307c 100644
3
- --- a/lib/index.js
4
- +++ b/lib/index.js
5
- @@ -1,3332 +1 @@
6
- -import z from "@deepseek-ai/schemastery";
7
- -import { scopeTarget } from "@deepseek-ai/dsh-scope";
8
- -import { ToolArgsError, assertObjectJsonSchema, validateJsonSchemaValue } from "@deepseek-ai/dsh-tools";
9
- -import { canonicalClientTimeZone } from "@deepseek-ai/dsh-util-time";
10
- -import { Remote, RemoteError, TypertRemoteService, principalOf } from "@deepseek-ai/dsh-typert-protocol";
11
- -import { AttachmentError } from "@deepseek-ai/dsh-attachment";
12
- -import { z as z$1 } from "zod";
13
- -import { HarnessError, ReasoningEffortId, boundContextSummary, contentHasImage, createUserMessage, errorChain, joinAssistantStreamText } from "@deepseek-ai/dsh-llm";
14
- -import { randomUUID } from "node:crypto";
15
- -import { foldConsumedWork } from "@deepseek-ai/dsh-agent";
16
- -import { isAbsolute, resolve } from "node:path";
17
- -import { brandString } from "@deepseek-ai/dsh-brand";
18
- -import { SessionLogOffset, SessionSeq } from "@deepseek-ai/dsh-session";
19
- -import { assertNever, snapshotJsonValue } from "@deepseek-ai/dsh-util-values";
20
- -import { appendChunkedList, chunkedListSchema, iterateChunkedList } from "@deepseek-ai/dsh-chunked-list";
21
- -import { accessSync, constants, statSync } from "node:fs";
22
- -//#region lib/types/error.js
23
- -/**
24
- -* Typed failures shared by subagent service and provider operations.
25
- -*
26
- -* @module @deepseek-ai/dsh-subagent
27
- -*/
28
- -/** Typed failure for the subagent seam. */
29
- -var SubagentError = class extends HarnessError {
30
- - constructor(message, code, options) {
31
- - super(message, code, options);
32
- - this.name = "SubagentError";
33
- - }
34
- -};
35
- -//#endregion
36
- -//#region lib/types/control.js
37
- -/**
38
- -* Browser-facing subagent prompt and interrupt request validation plus the
39
- -* stable prompt failure codes returned by the Remote surface.
40
- -*
41
- -* @module @deepseek-ai/dsh-subagent
42
- -*/
43
- -const SESSION_ID_SCHEMA = z$1.string().min(1);
44
- -const CONTROL_ID_SCHEMAS = {
45
- - "subagent.prompt": z$1.object({
46
- - parentSessionId: SESSION_ID_SCHEMA,
47
- - childSessionId: SESSION_ID_SCHEMA,
48
- - mode: z$1.literal("continuable"),
49
- - delivery: z$1.enum(["queue", "steer"])
50
- - }),
51
- - "subagent.interrupt": z$1.object({
52
- - parentSessionId: SESSION_ID_SCHEMA,
53
- - childSessionId: SESSION_ID_SCHEMA,
54
- - mode: z$1.literal("continuable")
55
- - })
56
- -};
57
- -/**
58
- -* Apply the subagent payload checks that are stricter than generated
59
- -* branded-string codecs.
60
- -* @param method - method name carried in the failure message.
61
- -* @param payload - decoded control fields to validate.
62
- -* @throws {RemoteError} `gateway/bad-request` with the original Zod issues.
63
- -*/
64
- -function validateControlRequest(method, payload) {
65
- - const parsed = CONTROL_ID_SCHEMAS[method].safeParse(payload);
66
- - if (!parsed.success) throw new RemoteError("gateway/bad-request", `invalid payload for ${method}`, { issues: parsed.error.issues });
67
- -}
68
- -/**
69
- -* Refuse one continuation prompt without exposing provider detail: admission
70
- -* failures the caller can act on keep their own code, everything else is
71
- -* internal.
72
- -* @param error - the thrown value.
73
- -* @param childSessionId - the addressed child.
74
- -* @param signal - the caller's cancellation.
75
- -* @returns Never — the refusal is thrown.
76
- -* @throws {RemoteError} always.
77
- -*/
78
- -function rejectPrompt(error, childSessionId, signal) {
79
- - if (isCancellation(error, signal)) throw new RemoteError("gateway/cancelled", "subagent prompt was cancelled", {}, { cause: error });
80
- - if (error instanceof AttachmentError) throw new RemoteError("subagent/attachment-invalid", error.message, { reason: error.code }, { cause: error });
81
- - if (error instanceof SubagentError) switch (error.code) {
82
- - case "MODEL_DOES_NOT_SUPPORT_IMAGES": throw new RemoteError("subagent/attachment-invalid", error.message, { reason: error.code }, { cause: error });
83
- - case "NOT_RESUMABLE": throw new RemoteError("subagent/not-resumable", "subagent cannot be resumed", { childSessionId }, { cause: error });
84
- - case "UNAUTHORIZED": throw new RemoteError("subagent/unauthorized", "subagent does not belong to this parent", { childSessionId }, { cause: error });
85
- - case "DRAINING":
86
- - case "ACTIVATION_CLOSING":
87
- - case "ACTIVATION_LIMIT_REACHED":
88
- - case "CONTINUATION_UNAVAILABLE":
89
- - case "PERSISTENCE_UNAVAILABLE": throw new RemoteError("subagent/delivery-unavailable", "subagent follow-up is temporarily unavailable", { childSessionId }, { cause: error });
90
- - default: break;
91
- - }
92
- - throw new RemoteError("gateway/internal", "subagent prompt failed", {}, { cause: error });
93
- -}
94
- -function isCancellation(error, signal) {
95
- - return signal.aborted || error instanceof SubagentError && error.code === "CANCELLED";
96
- -}
97
- -//#endregion
98
- -//#region lib/types/depth.js
99
- -/**
100
- -* Delegation-depth accounting: the recursion budget a parent passes to its
101
- -* children. Kept apart from the service so composition helpers can read it
102
- -* without importing the registry.
103
- -*
104
- -* @module @deepseek-ai/dsh-subagent/depth
105
- -*/
106
- -/**
107
- -* Read an agent's delegation depth, treating absence as top-level depth zero.
108
- -* The persisted session header is authoritative and monotone: runtime
109
- -* `AgentOptions.subagentDepth` may DEEPEN the count but can never lower it —
110
- -* a resumed child arrives with fresh options, and counting it from zero would
111
- -* let it delegate as if it were top-level.
112
- -* @param agent - the agent whose header and options carry the depth.
113
- -* @returns its non-negative safe-integer depth.
114
- -* @throws if the runtime `AgentOptions.subagentDepth` is not a non-negative safe integer.
115
- -*/
116
- -function delegationDepthOf(agent) {
117
- - const runtime = agent.options.subagentDepth;
118
- - if (runtime !== void 0 && (!Number.isSafeInteger(runtime) || runtime < 0 || Object.is(runtime, -0))) throw new TypeError("agent subagentDepth must be a non-negative safe integer");
119
- - return Math.max(agent.session.header.delegationDepth ?? 0, runtime ?? 0);
120
- -}
121
- -/**
122
- -* Reject a recursion cap that cannot represent an exact delegation depth.
123
- -* @param maxDepth - the optional runtime value to validate.
124
- -*/
125
- -function assertSubagentMaxDepth(maxDepth) {
126
- - if (maxDepth !== void 0 && (typeof maxDepth !== "number" || !Number.isSafeInteger(maxDepth) || maxDepth < 0 || Object.is(maxDepth, -0))) throw new TypeError("subagent maxDepth must be a non-negative safe integer");
127
- -}
128
- -//#endregion
129
- -//#region lib/types/types.js
130
- -/**
131
- -* The seam's consumer-facing contracts: request, result, and capability types
132
- -* for {@link SubagentProvider}, plus the `subagent/start` and `subagent/end`
133
- -* payloads that plugins and hosts observe. Internal control interfaces belong
134
- -* with their implementation — the lifecycle observer in `./lifecycle.ts`, the
135
- -* manager host in `./manager.ts` — so this module stays the published
136
- -* surface rather than a bag of everything type-shaped.
137
- -*
138
- -* @module @deepseek-ai/dsh-subagent/types
139
- -*/
140
- -/**
141
- -* Brand a string as a {@link SubagentRunId}.
142
- -* @param id - the raw run id.
143
- -* @returns the same string, branded.
144
- -*/
145
- -function SubagentRunId(id) {
146
- - return id;
147
- -}
148
- -//#endregion
149
- -//#region lib/types/lifecycle.js
150
- -/**
151
- -* Lifecycle-edge publication for managed subagent activations.
152
- -*
153
- -* Public event payloads live in `./types.ts`; the package-private observer
154
- -* retains only the identity shared by each start/end pair.
155
- -*
156
- -* @module @deepseek-ai/dsh-subagent/lifecycle
157
- -*/
158
- -/**
159
- -* Build the contained lifecycle emitter this seam publishes every edge through.
160
- -* Every listener is independently contained: a synchronous throw or a rejected
161
- -* returned promise is logged without starving peer listeners, changing the run,
162
- -* or — for provider removal, which fires from a disposer — breaking teardown.
163
- -* @param ctx - the service's own context, owning dispatch and the logger.
164
- -* @param carrier - resolve the scoped dispatch carrier for one delegating parent.
165
- -* @returns the emitter both observers and the provider registry publish through.
166
- -*/
167
- -function createLifecycleEmitter(ctx, carrier) {
168
- - return (name, info, parent) => {
169
- - const dispatchArgs = parent === void 0 ? [name, info] : [
170
- - carrier(parent),
171
- - name,
172
- - info
173
- - ];
174
- - for (const callback of ctx.events.dispatch("emit", dispatchArgs)) try {
175
- - const returned = callback(info);
176
- - Promise.resolve(returned).catch((error) => {
177
- - ctx.logger.warn(`subagent: ${name} listener rejected: ${renderThrown(error)}`);
178
- - });
179
- - } catch (error) {
180
- - ctx.logger.warn(`subagent: ${name} listener threw: ${renderThrown(error)}`);
181
- - }
182
- - };
183
- -}
184
- -/**
185
- -* Build the observer for one local or external activation's residency epoch. Creation failure before residency emits no lifecycle edge.
186
- -* @param emit - the contained lifecycle emitter.
187
- -* @param provider - the provider name recorded in the durable descriptor.
188
- -* @param childId - the durable child session id.
189
- -* @param parent - the exact live direct parent keying scoped dispatch.
190
- -* @returns the observer whose edges this epoch publishes.
191
- -*/
192
- -function createActivationObserver(emit, provider, childId, parent) {
193
- - const identity = {
194
- - runId: SubagentRunId(randomUUID()),
195
- - provider,
196
- - id: childId,
197
- - local: false
198
- - };
199
- - return {
200
- - start: (child) => {
201
- - identity.local = child !== void 0;
202
- - emit("subagent/start", identity, parent);
203
- - },
204
- - settle: ({ stopReason, output }) => {
205
- - emit("subagent/end", {
206
- - ...identity,
207
- - stopReason,
208
- - ...output.length === 0 ? {} : { lastAssistantMessage: output }
209
- - }, parent);
210
- - }
211
- - };
212
- -}
213
- -/**
214
- -* Why this child's epoch ended, for the terminal lifecycle edge and the
215
- -* manager's own parent delivery. The child's own log is authoritative:
216
- -* teardown succeeding says nothing about whether the model errored, hit its
217
- -* token ceiling, or was cancelled, so deriving the reason from disposal would
218
- -* report failed work as completed.
219
- -*
220
- -* {@link foldConsumedWork} supplies both halves the raw turn sequence cannot:
221
- -* which turn accounts for the work this epoch consumed, and whether accepted
222
- -* work was cancelled after it without any turn opening over it. A recorded
223
- -* failure still wins over a cancellation — stopping a child that had already
224
- -* failed does not turn its failure into a cancellation.
225
- -* @param events - this epoch's own event suffix.
226
- -* @returns its terminal stop reason; `completed` only for an epoch that both
227
- -* closed cleanly and had nothing left to run.
228
- -*/
229
- -function epochStopReason(events) {
230
- - const { end, droppedUnrun } = foldConsumedWork(events);
231
- - switch (end?.data.reason.kind) {
232
- - case "max-tokens": return "max-tokens";
233
- - case "aborted":
234
- - case "interrupted": return "aborted";
235
- - case "error": return "error";
236
- - case "blocked": return "refusal";
237
- - case void 0:
238
- - case "completed": return droppedUnrun ? "aborted" : "completed";
239
- - /* v8 ignore next 4 -- `forked` appears only in constructor seed history, while
240
- - * this function reads an epoch-owned suffix. `TurnEndReason` is merge-extensible,
241
- - * so a backend-added variant cannot be listed; treating an unnameable reason as
242
- - * success would report failed work as completed. */
243
- - default: return "error";
244
- - }
245
- -}
246
- -/** Render any listener-thrown value without letting coercion escape containment. */
247
- -function renderThrown(value) {
248
- - try {
249
- - return value instanceof Error ? `${value.name}: ${value.message}` : String(value);
250
- - } catch {
251
- - return "<unrenderable thrown value>";
252
- - }
253
- -}
254
- -//#endregion
255
- -//#region lib/types/child-agent.js
256
- -/**
257
- -* Shared in-process child composition: the delegation-depth budget, the
258
- -* durable session metadata, the resolved child `AgentOptions`, the delegated
259
- -* policy seed, and the scoped setup used by local activations.
260
- -*
261
- -* @module @deepseek-ai/dsh-subagent/child-agent
262
- -*/
263
- -/** Thrown when starting a child would exceed the requested depth cap. */
264
- -var SubagentDepthError = class extends Error {
265
- - attemptedDepth;
266
- - maxDepth;
267
- - constructor(attemptedDepth, maxDepth) {
268
- - super(`subagent depth ${attemptedDepth} exceeds maxDepth ${maxDepth}`);
269
- - this.attemptedDepth = attemptedDepth;
270
- - this.maxDepth = maxDepth;
271
- - this.name = "SubagentDepthError";
272
- - }
273
- -};
274
- -/**
275
- -* Resolve the child's delegation depth from its parent and enforce an optional
276
- -* cap. The persisted parent header is the monotone floor, so a resumed parent
277
- -* cannot delegate as if it were top-level.
278
- -* @param parent - the delegating parent agent.
279
- -* @param maxDepth - optional absolute cap the resolved depth must not exceed.
280
- -* @returns the child's non-negative safe-integer depth.
281
- -* @throws {SubagentDepthError} when the resolved depth exceeds `maxDepth`.
282
- -* @throws {RangeError} when the resolved depth leaves the safe-integer range.
283
- -*/
284
- -function resolveChildDepth(parent, maxDepth) {
285
- - const childDepth = delegationDepthOf(parent) + 1;
286
- - if (!Number.isSafeInteger(childDepth)) throw new RangeError("subagent child depth exceeds the safe-integer range");
287
- - if (maxDepth !== void 0 && childDepth > maxDepth) throw new SubagentDepthError(childDepth, maxDepth);
288
- - return childDepth;
289
- -}
290
- -/**
291
- -* Resolve the parent values inherited by a child. The latest request header
292
- -* owns provider, model, and reasoning effort after request-time selection;
293
- -* creation options remain the fallback before the first request and retain
294
- -* the configured output-token limit.
295
- -* @param parent - delegating parent Agent.
296
- -* @returns detached Agent options for child-option merging.
297
- -*/
298
- -function parentAgentOptionsForDelegation(parent) {
299
- - const requestConfig = parent.session.requestHeader()?.config;
300
- - if (requestConfig === void 0) return { ...parent.options };
301
- - const { provider: _createdProvider, model: _createdModel, reasoningEffort: _createdReasoningEffort, ...createdOptions } = parent.options;
302
- - return {
303
- - ...createdOptions,
304
- - provider: requestConfig.provider,
305
- - model: requestConfig.model,
306
- - ...requestConfig.reasoningEffort === void 0 ? {} : { reasoningEffort: requestConfig.reasoningEffort }
307
- - };
308
- -}
309
- -/**
310
- -* Resolve the child's `AgentOptions`: the parent's provider/model,
311
- -* reasoning-effort, and maxTokens values unless the request overrides them,
312
- -* stamped with the child's own delegation depth. Changing the route without
313
- -* naming an effort clears the parent's route-owned effort so the selected
314
- -* model resolves its own default.
315
- -* @param parent - the delegating parent whose route the child inherits.
316
- -* @param requested - per-child overrides, if any.
317
- -* @param childDepth - the resolved delegation depth to stamp.
318
- -* @returns the resolved options for `ctx.agents.create()`.
319
- -*/
320
- -function resolveChildAgentOptions(parent, requested, childDepth) {
321
- - const parentOptions = parentAgentOptionsForDelegation(parent);
322
- - const parentProvider = parentOptions.provider;
323
- - const parentModel = parentOptions.model;
324
- - const parentReasoningEffort = parentOptions.reasoningEffort;
325
- - const parentMaxTokens = parentOptions.maxTokens;
326
- - const resolved = {
327
- - ...parentProvider !== void 0 ? { provider: parentProvider } : {},
328
- - ...parentModel !== void 0 ? { model: parentModel } : {},
329
- - ...parentReasoningEffort !== void 0 ? { reasoningEffort: parentReasoningEffort } : {},
330
- - ...parentMaxTokens !== void 0 ? { maxTokens: parentMaxTokens } : {},
331
- - ...requested,
332
- - subagentDepth: childDepth
333
- - };
334
- - if ((resolved.provider !== parentProvider || resolved.model !== parentModel) && requested?.reasoningEffort === void 0) delete resolved.reasoningEffort;
335
- - return resolved;
336
- -}
337
- -/**
338
- -* Build the child session's durable creation metadata: the parent's workspace,
339
- -* its direct lineage, coarse product origin, the recursion budget that must
340
- -* survive persistence, the seed boundary that separates inherited parent
341
- -* history from child work, and the composition the child runs under.
342
- -*
343
- -* Omitted selection uses the parent's live composition, including any switch
344
- -* made while the parent was blank.
345
- -* @param parent - the delegating parent agent.
346
- -* @param childDepth - the resolved delegation depth to persist.
347
- -* @param isSeeded - whether this child inherits a parent-log prefix, including an explicitly empty one.
348
- -* @param selectedPreset - independent selection, or omission to inherit the parent.
349
- -* @returns the `meta` for `ctx.agents.create()`.
350
- -*/
351
- -function childSessionMeta(parent, childDepth, isSeeded, selectedPreset) {
352
- - const parentHeader = parent.session.header;
353
- - const agentPreset = selectedPreset ?? parent.ctx.get("agentPresets")?.composedPreset(parent.ctx);
354
- - return {
355
- - ...parentHeader.cwd !== void 0 ? { cwd: parentHeader.cwd } : {},
356
- - ...agentPreset === void 0 ? {} : { agentPreset },
357
- - parentSession: parentHeader.id,
358
- - isSeeded,
359
- - origin: "subagent",
360
- - delegationDepth: childDepth
361
- - };
362
- -}
363
- -/**
364
- -* Model-facing delegation-scope statement for every in-process child. A
365
- -* runtime-context contribution rather than a system-prompt section, so the
366
- -* deployment's system prompt stays uniform across parents and children.
367
- -*/
368
- -const SUBAGENT_DELEGATION_CONTEXT = "You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.";
369
- -/**
370
- -* Compose a child before publication and restore historical descriptor overrides.
371
- -* Explicit selection mounts the named preset; omission synchronously joins the
372
- -* parent's current generation. Registrations belong to the child's scope.
373
- -* @param childCtx - the child agent's scoped creation context.
374
- -* @param parent - the delegating parent used when no preset is selected.
375
- -* @param composition - independent preset and any overrides read from a historical descriptor.
376
- -* @returns A promise when mounting an independent preset; otherwise completes synchronously.
377
- -*/
378
- -function applyChildComposition(childCtx, parent, composition) {
379
- - if (composition.agentPreset !== void 0) {
380
- - const presets = childCtx.get("agentPresets");
381
- - if (presets === void 0) throw new SubagentError("selecting a child agent preset requires the agent-presets service", "PRESET_UNAVAILABLE");
382
- - return presets.mount(childCtx, composition.agentPreset).then(() => {
383
- - applyChildOverrides(childCtx, composition);
384
- - });
385
- - }
386
- - childCtx.get("agentPresets")?.composeFrom(childCtx, parent.ctx);
387
- - applyChildOverrides(childCtx, composition);
388
- -}
389
- -function applyChildOverrides(childCtx, composition) {
390
- - childCtx.systemPrompt.context({
391
- - name: "subagent:delegation",
392
- - order: childCtx.systemPrompt.getContextOrder("SUBAGENT_DELEGATION"),
393
- - text: SUBAGENT_DELEGATION_CONTEXT
394
- - });
395
- - if (composition.persona !== void 0) childCtx.systemPrompt.section({
396
- - name: "deployment:persona-prefix",
397
- - order: childCtx.systemPrompt.getSectionOrder("DEPLOYMENT_PERSONA_PREFIX"),
398
- - text: composition.persona
399
- - });
400
- - if (composition.toolFilter !== void 0) childCtx.tools.restrict(composition.toolFilter);
401
- -}
402
- -/**
403
- -* Capture the permission state to seed into one delegation. Call synchronously before
404
- -* the child start's first await: a later parent switch belongs to the
405
- -* parent's future, not to this child. Auto and Full access identities are
406
- -* inherited only through the in-process DSH path so either can replace a stale
407
- -* same-bundle fork value. Only the parent session's explicit sandbox override
408
- -* is captured — never deployment defaults or one-shot grants — and the approval
409
- -* policy is pinned to `'never'` regardless of the parent's own policy.
410
- -* @param parent - the delegating parent agent.
411
- -* @returns the sandbox override (or `undefined` without one) and the approval pin.
412
- -*/
413
- -function captureDelegatedPolicyOverrides(parent) {
414
- - const preset = parent.ctx.get("permissionPresets")?.current(parent.session);
415
- - return {
416
- - permissionPreset: preset === "auto" || preset === "danger-full-access" ? preset : void 0,
417
- - sandboxMode: parent.ctx.get("sandboxPolicy")?.overrideOf(parent.session),
418
- - approvalPolicy: parent.ctx.get("approval") === void 0 ? void 0 : "never"
419
- - };
420
- -}
421
- -/**
422
- -* Append the captured delegation policy onto the child's own log as
423
- -* `source: 'delegation'` events inside the unpublished creation window, so the
424
- -* child's effective policy is reconstructable from its log alone. Appends land
425
- -* after any fork seed, so fresh policy wins stale seed state; later child
426
- -* switches still win over these events.
427
- -* @param childSession - the unpublished child's session.
428
- -* @param overrides - the policy captured at delegation.
429
- -*/
430
- -function appendDelegatedPolicyOverrides(childSession, overrides) {
431
- - if (overrides.sandboxMode !== void 0) childSession.append("sandbox/mode", {
432
- - mode: overrides.sandboxMode,
433
- - source: "delegation"
434
- - });
435
- - if (overrides.approvalPolicy !== void 0) childSession.append("approval/policy", {
436
- - policy: overrides.approvalPolicy,
437
- - source: "delegation"
438
- - });
439
- - if (overrides.permissionPreset !== void 0) childSession.append("permission/preset", { preset: overrides.permissionPreset });
440
- -}
441
- -//#endregion
442
- -//#region lib/types/continuation-messages.js
443
- -/**
444
- -* Model-visible messages owned by continuable-subagent orchestration.
445
- -*
446
- -* @module @deepseek-ai/dsh-subagent/continuation-messages
447
- -*/
448
- -/** Build durable attribution for one adjacent-Agent message. */
449
- -function agentMessageSource(sender) {
450
- - return {
451
- - kind: "agent-message",
452
- - form: "relay",
453
- - senderSessionId: sender.id
454
- - };
455
- -}
456
- -/**
457
- -* Build the model-visible and durable representation of one adjacent-Agent message.
458
- -* @param sender - exact live Agent that authored the message.
459
- -* @param content - model-visible message blocks supplied by the sender.
460
- -* @returns the durable user-message representation delivered to the recipient.
461
- -*/
462
- -function createAgentMessage(sender, content) {
463
- - return createUserMessage({
464
- - content: [{
465
- - type: "text",
466
- - text: `Agent ${sender.id} sent a message: `
467
- - }, ...content],
468
- - source: agentMessageSource(sender)
469
- - });
470
- -}
471
- -/**
472
- -* Append adjacent-Agent return guidance to a continuable child's initial task.
473
- -* @param parentId - durable parent session id named in the guidance.
474
- -* @param prompt - initial model-visible task blocks.
475
- -* @returns task blocks followed by the continuable return guidance.
476
- -*/
477
- -function withContinuableReturnGuidance(parentId, prompt) {
478
- - const encodedParentId = JSON.stringify(parentId);
479
- - return [...prompt, {
480
- - type: "text",
481
- - text: `Your parent agent id is ${encodedParentId}. Before you finish, send your result to that agent with send_message({ agent_id: ${encodedParentId}, message: "<self-contained result>" }). The parent shares your workspace but does not automatically receive your transcript, tool output, or reasoning. Send earlier messages as well when a finding changes what the parent should do next; sending a message does not end your turn.`
482
- - }];
483
- -}
484
- -/**
485
- -* One line telling a parent that a background child is finished and why, in
486
- -* the parent's own task vocabulary.
487
- -* @param childId - the durable child the parent knows by id.
488
- -* @param stopReason - how the child's last ordinary turn ended.
489
- -* @param continuable - whether the child accepts a later message.
490
- -* @returns the model-facing opening line of the settlement notice.
491
- -*/
492
- -function settlementSummary(childId, stopReason, continuable) {
493
- - const subject = `Background subagent ${childId}`;
494
- - switch (stopReason) {
495
- - case "completed": return continuable ? `${subject} finished and will do no further work unless you send it more.` : `${subject} finished. It cannot receive follow-up messages.`;
496
- - case "aborted": return `${subject} was stopped before it finished.`;
497
- - case "max-tokens": return `${subject} ran out of room before it finished.`;
498
- - case "refusal": return `${subject} declined the task.`;
499
- - case "error": return `${subject} failed before it finished.`;
500
- - /* v8 ignore next 4 -- `SubagentResult['stopReason']` is merge-extensible, so this arm
501
- - * needs a backend that adds a variant; an unnameable ending is reported as unfinished
502
- - * rather than silently as success. */
503
- - default: return `${subject} ended abnormally (${String(stopReason)}) before it finished.`;
504
- - }
505
- -}
506
- -/**
507
- -* Build the runtime-owned settlement notice from the child's nonempty closing text.
508
- -* @param childId - durable child session id named in the notice.
509
- -* @param terminal - recorded terminal state for the settled Activation.
510
- -* @param continuable - whether the child can accept another task.
511
- -* @returns the durable user-message representation delivered to the parent.
512
- -*/
513
- -function createSettlementMessage(childId, terminal, continuable = true) {
514
- - const summary = settlementSummary(childId, terminal.stopReason, continuable);
515
- - const closingText = terminal.output.flatMap((block) => block.type === "text" && block.text.length > 0 ? [block] : []);
516
- - return createUserMessage({
517
- - content: [
518
- - {
519
- - type: "text",
520
- - text: summary
521
- - },
522
- - ...closingText.length === 0 ? [{
523
- - type: "text",
524
- - text: "It left no closing message."
525
- - }] : [{
526
- - type: "text",
527
- - text: "Its closing message:"
528
- - }, ...closingText],
529
- - ...terminal.structured !== void 0 ? [{
530
- - type: "text",
531
- - text: `Structured result: ${JSON.stringify(terminal.structured)}`
532
- - }] : [],
533
- - ...terminal.diagnostic !== void 0 ? [{
534
- - type: "text",
535
- - text: terminal.diagnostic
536
- - }] : []
537
- - ],
538
- - source: {
539
- - kind: "subagent-settled",
540
- - form: "notice",
541
- - summary: boundContextSummary(summary),
542
- - senderSessionId: childId
543
- - }
544
- - });
545
- -}
546
- -//#endregion
547
- -//#region lib/types/descriptor.js
548
- -/**
549
- -* The durable subagent-child descriptor: the versioned, model-hidden
550
- -* `subagent/descriptor` session event that identifies every session-backed
551
- -* subagent, including historical one-shot records. The manager appends each
552
- -* continuable child's descriptor inside its initial turn, preserving the
553
- -* declared composition required for cold resume.
554
- -*
555
- -* The descriptor deliberately snapshots explicit fields rather than the
556
- -* merge-extensible `AgentOptions` object: an unrelated extension value cannot
557
- -* make continuation fail merely because it is not JSON, and later composition
558
- -* inputs require a deliberate {@link SUBAGENT_DESCRIPTOR_VERSION} change. It
559
- -* omits `subagentDepth` — cold resume trusts the persisted header's
560
- -* `delegationDepth` as the monotone floor — and `outputSchema`, which belongs
561
- -* to one activation's result contract rather than durable child composition.
562
- -* Per-activation knobs such as `maxTokens` are omitted for the same reason as
563
- -* `outputSchema`: they budget one activation. Cold resume requires the exact
564
- -* live parent for authorization but reconstructs child options only from the
565
- -* durable descriptor, so it neither restores the prior budget nor inherits
566
- -* the parent's current one; the resumed route's defaults apply instead.
567
- -*
568
- -* @module @deepseek-ai/dsh-subagent/descriptor
569
- -*/
570
- -/**
571
- -* The current descriptor format version, stamped into every appended
572
- -* `subagent/descriptor` event and required verbatim by {@link foldSubagentDescriptor}.
573
- -* Supporting another composition input is a deliberate version change, never
574
- -* an implicit extra field.
575
- -*/
576
- -const SUBAGENT_DESCRIPTOR_VERSION = 3;
577
- -const DESCRIPTOR_BASE_KEYS = [
578
- - "version",
579
- - "mode",
580
- - "provider",
581
- - "label"
582
- -];
583
- -const ONE_SHOT_DESCRIPTOR_KEYS = new Set(DESCRIPTOR_BASE_KEYS);
584
- -const CONTINUABLE_DESCRIPTOR_KEYS = new Set([
585
- - ...DESCRIPTOR_BASE_KEYS,
586
- - "agentProvider",
587
- - "agentModel",
588
- - "agentReasoningEffort",
589
- - "persona",
590
- - "toolFilter"
591
- -]);
592
- -const TOOL_FILTER_KEYS = new Set(["allow", "deny"]);
593
- -/** Whether a persisted JSON value is an object record. */
594
- -function isRecord(value) {
595
- - return typeof value === "object" && value !== null && !Array.isArray(value);
596
- -}
597
- -/** Reject fields outside one versioned record's declared schema. */
598
- -function assertKnownKeys(value, keys, path) {
599
- - const unknown = Object.keys(value).find((key) => !keys.has(key));
600
- - if (unknown !== void 0) throw new Error(`persisted subagent descriptor ${path} has unknown field "${unknown}"`);
601
- -}
602
- -/** Read one optional string field from a persisted descriptor record. */
603
- -function optionalString(value, key) {
604
- - if (!Object.hasOwn(value, key)) return void 0;
605
- - const field = value[key];
606
- - if (typeof field !== "string") throw new Error(`persisted subagent descriptor ${key} must be a string`);
607
- - return field;
608
- -}
609
- -/** Read one optional string-array field from a persisted tool restriction. */
610
- -function optionalStringArray(value, key) {
611
- - if (!Object.hasOwn(value, key)) return void 0;
612
- - const field = value[key];
613
- - if (!Array.isArray(field)) throw new Error(`persisted subagent descriptor toolFilter.${key} must be an array of strings`);
614
- - const items = field;
615
- - if (items.some((item) => typeof item !== "string")) throw new Error(`persisted subagent descriptor toolFilter.${key} must be an array of strings`);
616
- - return items;
617
- -}
618
- -/** Validate and reconstruct a persisted tool restriction. */
619
- -function parseToolFilter(value) {
620
- - if (!isRecord(value)) throw new Error("persisted subagent descriptor toolFilter must be an object");
621
- - assertKnownKeys(value, TOOL_FILTER_KEYS, "toolFilter");
622
- - const allow = optionalStringArray(value, "allow");
623
- - const deny = optionalStringArray(value, "deny");
624
- - if (allow === void 0 && deny === void 0) throw new Error("persisted subagent descriptor toolFilter must declare allow and/or deny");
625
- - return {
626
- - ...allow !== void 0 ? { allow } : {},
627
- - ...deny !== void 0 ? { deny } : {}
628
- - };
629
- -}
630
- -/** Validate one persisted descriptor payload for the current runtime. */
631
- -function parseSubagentDescriptor(value) {
632
- - if (!isRecord(value)) throw new Error("persisted subagent descriptor payload must be an object");
633
- - const version = value["version"];
634
- - if (typeof version !== "number") throw new Error("persisted subagent descriptor version must be a number");
635
- - if (version !== 3) return void 0;
636
- - const mode = value["mode"];
637
- - if (mode !== "one-shot" && mode !== "continuable") throw new Error("persisted subagent descriptor mode must be \"one-shot\" or \"continuable\"");
638
- - assertKnownKeys(value, mode === "one-shot" ? ONE_SHOT_DESCRIPTOR_KEYS : CONTINUABLE_DESCRIPTOR_KEYS, "payload");
639
- - const provider = value["provider"];
640
- - if (typeof provider !== "string") throw new Error("persisted subagent descriptor provider must be a string");
641
- - if (mode === "one-shot") {
642
- - const label = optionalString(value, "label");
643
- - return {
644
- - version: 3,
645
- - mode,
646
- - provider,
647
- - ...label !== void 0 ? { label } : {}
648
- - };
649
- - }
650
- - const label = value["label"];
651
- - if (typeof label !== "string") throw new Error("persisted subagent descriptor label must be a string");
652
- - const agentProvider = optionalString(value, "agentProvider");
653
- - const agentModel = optionalString(value, "agentModel");
654
- - const agentReasoningEffort = optionalString(value, "agentReasoningEffort");
655
- - const persona = optionalString(value, "persona");
656
- - const toolFilter = Object.hasOwn(value, "toolFilter") ? parseToolFilter(value["toolFilter"]) : void 0;
657
- - return {
658
- - version: 3,
659
- - mode,
660
- - provider,
661
- - label,
662
- - ...agentProvider !== void 0 ? { agentProvider } : {},
663
- - ...agentModel !== void 0 ? { agentModel } : {},
664
- - ...agentReasoningEffort !== void 0 ? { agentReasoningEffort } : {},
665
- - ...persona !== void 0 ? { persona } : {},
666
- - ...toolFilter !== void 0 ? { toolFilter } : {}
667
- - };
668
- -}
669
- -/**
670
- -* Validate and detach a continuable descriptor input.
671
- -* @param input - the caller-collected continuable composition fields.
672
- -* @returns the versioned, detached continuable descriptor payload.
673
- -* @throws when a field is not losslessly JSON-serializable.
674
- -*/
675
- -function snapshotSubagentDescriptor(input) {
676
- - const snapshot = snapshotJsonValue({
677
- - version: 3,
678
- - mode: input.mode,
679
- - provider: input.provider,
680
- - label: input.label,
681
- - ...input.agentProvider !== void 0 ? { agentProvider: input.agentProvider } : {},
682
- - ...input.agentModel !== void 0 ? { agentModel: input.agentModel } : {},
683
- - ...input.agentReasoningEffort !== void 0 ? { agentReasoningEffort: input.agentReasoningEffort } : {},
684
- - ...input.persona !== void 0 ? { persona: input.persona } : {},
685
- - ...input.toolFilter !== void 0 ? { toolFilter: input.toolFilter } : {}
686
- - });
687
- - if (snapshot === void 0) throw new Error("subagent descriptor is not losslessly JSON-serializable");
688
- - return snapshot;
689
- -}
690
- -/**
691
- -* Fold a persisted child log to its supported descriptor. The first
692
- -* `subagent/descriptor` event is authoritative — the establishing provider
693
- -* appends exactly one, so a later same-type event cannot rewrite the declared
694
- -* composition.
695
- -* @param events - the loaded child session events.
696
- -* @returns the descriptor, or `undefined` when the log has none or its
697
- -* version is not {@link SUBAGENT_DESCRIPTOR_VERSION} (the child cannot be
698
- -* classified by this runtime).
699
- -* @throws when a current-version persisted payload does not match its complete
700
- -* declared schema.
701
- -*/
702
- -function foldSubagentDescriptor(events) {
703
- - const event = events.find((candidate) => candidate.type === "subagent/descriptor");
704
- - if (event === void 0) return void 0;
705
- - return parseSubagentDescriptor(event.data);
706
- -}
707
- -const sessionIdSchema = z$1.string();
708
- -const oneShotCatalogSchema = z$1.object({
709
- - version: z$1.union([z$1.literal(0), z$1.literal(1)]),
710
- - childId: sessionIdSchema,
711
- - childCreatedAt: z$1.number().int().nonnegative(),
712
- - mode: z$1.literal("one-shot"),
713
- - label: z$1.string().optional()
714
- -}).strict();
715
- -const continuableCatalogSchema = z$1.object({
716
- - version: z$1.union([z$1.literal(0), z$1.literal(1)]),
717
- - childId: sessionIdSchema,
718
- - childCreatedAt: z$1.number().int().nonnegative(),
719
- - mode: z$1.literal("continuable"),
720
- - label: z$1.string()
721
- -}).strict();
722
- -const externalCatalogSchema = oneShotCatalogSchema.extend({
723
- - version: z$1.literal(2),
724
- - mode: z$1.literal("external")
725
- -});
726
- -const unknownCatalogSchema = oneShotCatalogSchema.extend({
727
- - version: z$1.literal(1),
728
- - mode: z$1.literal("unknown")
729
- -});
730
- -const eventDataSchema = z$1.union([
731
- - oneShotCatalogSchema,
732
- - externalCatalogSchema,
733
- - continuableCatalogSchema,
734
- - unknownCatalogSchema
735
- -]);
736
- -const viewSchema = z$1.array(z$1.union([
737
- - oneShotCatalogSchema.omit({
738
- - version: true,
739
- - childId: true,
740
- - childCreatedAt: true
741
- - }).extend({
742
- - id: sessionIdSchema,
743
- - createdAt: oneShotCatalogSchema.shape.childCreatedAt
744
- - }),
745
- - externalCatalogSchema.omit({
746
- - version: true,
747
- - childId: true,
748
- - childCreatedAt: true
749
- - }).extend({
750
- - id: sessionIdSchema,
751
- - createdAt: externalCatalogSchema.shape.childCreatedAt
752
- - }),
753
- - continuableCatalogSchema.omit({
754
- - version: true,
755
- - childId: true,
756
- - childCreatedAt: true
757
- - }).extend({
758
- - id: sessionIdSchema,
759
- - createdAt: continuableCatalogSchema.shape.childCreatedAt
760
- - }),
761
- - unknownCatalogSchema.omit({
762
- - version: true,
763
- - childId: true,
764
- - childCreatedAt: true
765
- - }).extend({
766
- - id: sessionIdSchema,
767
- - createdAt: unknownCatalogSchema.shape.childCreatedAt
768
- - })
769
- -]));
770
- -const stateSchema = z$1.object({
771
- - inheritedEventCount: z$1.number().int().nonnegative(),
772
- - head: chunkedListSchema(eventDataSchema).optional()
773
- -}).strict();
774
- -/**
775
- -* Materialize complete and unknown-mode child identities from parent catalog events.
776
- -* @param state - parent catalog fold state.
777
- -* @returns current direct-child rows in parent catalog event order.
778
- -*/
779
- -function subagentCatalogEntries(state) {
780
- - const entries = [];
781
- - for (const data of iterateChunkedList(state.head)) {
782
- - const { version: _version, childId, childCreatedAt, ...descriptor } = data;
783
- - entries.push({
784
- - id: childId,
785
- - createdAt: childCreatedAt,
786
- - ...descriptor
787
- - });
788
- - }
789
- - return entries;
790
- -}
791
- -/** Parent-owned direct-child catalog projection; invalid own facts reject restoration. */
792
- -const subagentCatalogProjectionDefinition = {
793
- - key: "subagentCatalog",
794
- - stateSchema,
795
- - init: (_header, inheritedEventCount) => ({ inheritedEventCount }),
796
- - apply: (state, event) => {
797
- - if (event.type !== "subagent/catalog" || event.seq < state.inheritedEventCount) return state;
798
- - return {
799
- - ...state,
800
- - head: appendChunkedList(state.head, eventDataSchema.parse(event.data))
801
- - };
802
- - },
803
- - stateVersion: 6,
804
- - wire: {
805
- - viewSchema,
806
- - view: subagentCatalogEntries
807
- - }
808
- -};
809
- -/**
810
- -* Append a complete direct-child discovery fact to its parent Session.
811
- -* @param parent - durable direct parent receiving the discovery fact.
812
- -* @param child - established child's immutable Session metadata.
813
- -* @param descriptor - mode-discriminated creation label frozen with the child.
814
- -*/
815
- -function establishCatalogChild(parent, child, descriptor) {
816
- - parent.append("subagent/catalog", {
817
- - version: 0,
818
- - childId: child.id,
819
- - childCreatedAt: child.createdAt,
820
- - mode: descriptor.mode,
821
- - label: descriptor.label
822
- - });
823
- -}
824
- -/** Catalog payload version emitted by external execution creation. */
825
- -const EXTERNAL_SUBAGENT_CATALOG_VERSION = 2;
826
- -/**
827
- -* Record an external execution without a local child Session.
828
- -* @param parent - durable direct parent receiving the discovery fact.
829
- -* @param childId - identity returned by the external provider.
830
- -* @param label - display label assigned by the caller.
831
- -*/
832
- -function establishExternalCatalogChild(parent, childId, label) {
833
- - parent.append("subagent/catalog", {
834
- - version: EXTERNAL_SUBAGENT_CATALOG_VERSION,
835
- - childId,
836
- - childCreatedAt: Date.now(),
837
- - mode: "external",
838
- - label
839
- - });
840
- -}
841
- -//#endregion
842
- -//#region lib/types/internal.js
843
- -/**
844
- -* Continuation integration markers and host adapters outside the public
845
- -* Service Definition and model-facing Agent messaging contract.
846
- -* @module @deepseek-ai/dsh-subagent/internal
847
- -*/
848
- -/** Process-stable identity carried only by the standard adjacent-Agent messaging tool. */
849
- -const adjacentAgentSendMessageTool = Symbol.for("dsh.subagent.adjacentAgentSendMessageTool");
850
- -/**
851
- -* Test whether one visible definition is the standard adjacent-Agent messaging tool.
852
- -* @param definition - the scope-resolved `send_message` candidate.
853
- -* @returns whether the definition carries the internal standard-tool identity.
854
- -*/
855
- -function isAdjacentAgentSendMessageTool(definition) {
856
- - return definition !== void 0 && definition[adjacentAgentSendMessageTool] === true;
857
- -}
858
- -/**
859
- -* Process-stable symbol-keyed host delivery shared by the bundled runtime
860
- -* entry and this unbundled internal subpath.
861
- -* @internal
862
- -*/
863
- -const deliverSubagentPrompt = Symbol.for("dsh.subagent.deliverPrompt");
864
- -//#endregion
865
- -//#region lib/types/structured.js
866
- -/**
867
- -* Child-scoped structured-output tool, prompt instruction, terminal guard, and authoritative
868
- -* result capture for in-process subagents. Each child registers its real schema on its own
869
- -* scope, so concurrent runs do not interact and disposal leaves no global residue. The prompt
870
- -* contribution is ordinary reconstructed request state.
871
- -*
872
- -* Capture commits only after the authoritative `tools/result` succeeds; PTC mode capture also
873
- -* waits for the enclosing `run_code` result. The terminal result marker and monotonic tool
874
- -* guard prevent later calls from reopening a completed structured run.
875
- -* @module @deepseek-ai/dsh-subagent/structured
876
- -*/
877
- -/** The model-facing tool name a structured child must call to finish. */
878
- -const STRUCTURED_OUTPUT_TOOL = "structured_output";
879
- -/**
880
- -* The instruction registered as the child's trailing scoped prompt section:
881
- -* the demand travels with the
882
- -* tool, as ordinary prompt state of exactly one agent.
883
- -*/
884
- -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.`;
885
- -/**
886
- -* Attach the scoped capture tool, instruction, and enforcement to a child during
887
- -* its creation window. Child disposal removes every registration.
888
- -* @param childCtx - the child agent's scope context (`setup`'s argument).
889
- -* @param schema - the trusted, already-asserted schema subset to enforce (see
890
- -* `assertObjectJsonSchema` in dsh-tools).
891
- -* @param canComplete - whether accepted input and owned child work have finished.
892
- -* @returns the attachment handle (read `captured()` after the child settles).
893
- -*/
894
- -function attachStructuredRuntime(childCtx, schema, canComplete) {
895
- - /**
896
- - * Validated values staged by the capture tool body, awaiting THEIR OWN
897
- - * authoritative `tools/result` notification. The execution object's identity
898
- - * uniquely identifies a trip through the pipeline: adapter call ids may
899
- - * repeat across steps, but another execution can never reach this Map
900
- - * entry. This is distinct from the opaque `ToolExecutionToken` used to
901
- - * correlate nested transports. The final notification always deletes its own
902
- - * stage, whether the result succeeded or failed.
903
- - */
904
- - const staged = /* @__PURE__ */ new Map();
905
- - /** Successful nested capture waiting for its enclosing transport to commit. */
906
- - let pending;
907
- - let captured;
908
- - const schemaEntry = {
909
- - name: STRUCTURED_OUTPUT_TOOL,
910
- - 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.",
911
- - parameters: { ...schema }
912
- - };
913
- - childCtx.tools.register({
914
- - ...schemaEntry,
915
- - output: {
916
- - schema: {
917
- - type: "object",
918
- - properties: { recorded: {
919
- - type: "boolean",
920
- - const: true
921
- - } },
922
- - required: ["recorded"],
923
- - additionalProperties: false
924
- - },
925
- - render: () => [{
926
- - type: "text",
927
- - text: "Structured output recorded."
928
- - }]
929
- - },
930
- - execute(args, exec) {
931
- - const violations = validateJsonSchemaValue(schema, args);
932
- - if (violations.length > 0) throw new ToolArgsError(violations);
933
- - if (!canComplete()) throw new Error("Wait for all delegated child tasks to finish and process pending messages before submitting structured output.");
934
- - staged.set(exec, { value: args });
935
- - exec.concludeTurn();
936
- - return Promise.resolve({ recorded: true });
937
- - }
938
- - });
939
- - childCtx.systemPrompt.section({
940
- - name: `tool:${STRUCTURED_OUTPUT_TOOL}`,
941
- - order: childCtx.systemPrompt.getSectionOrder("STRUCTURED_OUTPUT"),
942
- - text: STRUCTURED_OUTPUT_INSTRUCTION
943
- - });
944
- - 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`);
945
- - childCtx.on("tools/result", function(exec, result) {
946
- - if (exec.name === "structured_output") {
947
- - const entry = staged.get(exec);
948
- - if (entry === void 0) return;
949
- - staged.delete(exec);
950
- - if (result.isError) return;
951
- - if (exec.parent === void 0) {
952
- - /* v8 ignore else -- sequential agent-loop dispatch lets the guard block every later supported call */
953
- - if (captured === void 0) captured = { value: entry.value };
954
- - } else if (captured === void 0 && pending === void 0) pending = {
955
- - parent: exec.parent,
956
- - value: entry.value
957
- - };
958
- - return;
959
- - }
960
- - if (pending?.parent !== exec.token) return;
961
- - const entry = pending;
962
- - pending = void 0;
963
- - if (result.isError) return;
964
- - /* v8 ignore else -- PTC mode serializes outer executions, so the guard blocks every later supported call */
965
- - if (captured === void 0) captured = { value: entry.value };
966
- - });
967
- - return {
968
- - captured: () => captured,
969
- - acceptsInput: () => staged.size === 0 && pending === void 0 && captured === void 0
970
- - };
971
- -}
972
- -//#endregion
973
- -//#region lib/types/assistant-output.js
974
- -/**
975
- -* Canonical selection of a child's final assistant output. Backend run results
976
- -* and `subagent/end.lastAssistantMessage` apply the same rule: select the last
977
- -* non-empty assistant message. An empty-content message records usage only
978
- -* when the loop appends it after a max-tokens step with no executable blocks,
979
- -* so it does not replace earlier output. If no non-empty message exists,
980
- -* select the accumulated assistant text. Selection is independent of the
981
- -* run's stop reason.
982
- -*
983
- -* @module @deepseek-ai/dsh-subagent/assistant-output
984
- -*/
985
- -/**
986
- -* Incremental fold of the selection rule, for backends that observe a child's
987
- -* output as it streams: session-event backends {@link push} each event, and
988
- -* transports without session events (ACP content chunks) {@link pushText} raw
989
- -* text into the same streamed fallback.
990
- -*/
991
- -var AssistantOutputFold = class {
992
- - message;
993
- - partial = [];
994
- - /**
995
- - * Fold one session event: a non-empty assistant message becomes the
996
- - * candidate final answer, while its embedded stream and any log-only attempt
997
- - * extend the streamed fallback; every other event contributes nothing.
998
- - * @param event - the next observed session event.
999
- - */
1000
- - push(event) {
1001
- - if (event.type === "assistant/message") {
1002
- - const content = event.data.message.content;
1003
- - if (content.length > 0) this.message = content;
1004
- - }
1005
- - if (event.type === "assistant/message" || event.type === "assistant/attempt") this.pushText(joinAssistantStreamText(event.data.stream));
1006
- - }
1007
- - /**
1008
- - * Extend the streamed fallback with text observed outside session events.
1009
- - * @param text - the next streamed text piece (an empty piece is a no-op).
1010
- - */
1011
- - pushText(text) {
1012
- - if (text.length > 0) this.partial.push(text);
1013
- - }
1014
- - /**
1015
- - * Select the final output folded so far.
1016
- - * @returns the last non-empty assistant message, else the accumulated
1017
- - * streamed text, or `undefined` when the child produced neither.
1018
- - */
1019
- - collect() {
1020
- - if (this.message !== void 0) return this.message;
1021
- - const text = this.partial.join("");
1022
- - return text.length > 0 ? [{
1023
- - type: "text",
1024
- - text
1025
- - }] : void 0;
1026
- - }
1027
- -};
1028
- -/**
1029
- -* Apply the selection rule to one complete child-owned event suffix.
1030
- -* @param events - the child-owned events (after any seed or epoch boundary).
1031
- -* @returns the selected output, or `undefined` when the child produced none.
1032
- -*/
1033
- -function finalAssistantOutput(events) {
1034
- - const fold = new AssistantOutputFold();
1035
- - for (const event of events) fold.push(event);
1036
- - return fold.collect();
1037
- -}
1038
- -//#endregion
1039
- -//#region lib/types/activation.js
1040
- -/** Execution-period records, capacity slots, child serialization, and local output capture.
1041
- -* @module @deepseek-ai/dsh-subagent/activation
1042
- -*/
1043
- -/** Process-local slots shared through uninterrupted continuable parent links. */
1044
- -var ActivationPool = class {
1045
- - slots = /* @__PURE__ */ new Set();
1046
- - /**
1047
- - * Reserve before reconstruction; release also tolerates unpublished rollback.
1048
- - * @param capacity - the maximum simultaneous activations in this pool.
1049
- - * @returns an idempotent slot release.
1050
- - */
1051
- - reserve(capacity) {
1052
- - if (this.slots.size >= capacity) throw new SubagentError(`subagent limit reached (active child limit: ${capacity}); wait for an existing child to finish or complete this work with the current agents`, "ACTIVATION_LIMIT_REACHED");
1053
- - const slot = Symbol();
1054
- - this.slots.add(slot);
1055
- - return () => {
1056
- - this.slots.delete(slot);
1057
- - };
1058
- - }
1059
- -};
1060
- -/**
1061
- -* Read the live Agent retained by local execution.
1062
- -* @param activation - the managed local or external execution.
1063
- -* @returns the local Agent, absent for an external run.
1064
- -*/
1065
- -function activationAgent(activation) {
1066
- - return activation.kind === "local" ? activation.handle.agent : void 0;
1067
- -}
1068
- -/**
1069
- -* Require local residency before accepting further input.
1070
- -* @param activation - execution targeted by message delivery.
1071
- -* @returns the local activation.
1072
- -* @throws when the external backend cannot accept another message.
1073
- -*/
1074
- -function requireLocalActivation(activation) {
1075
- - switch (activation.kind) {
1076
- - case "local": return activation;
1077
- - case "external": throw new SubagentError(`subagent "${activation.childId}" does not accept follow-up input`, "NOT_CONTINUABLE");
1078
- - /* v8 ignore next 2 -- Both execution kinds are handled above. */
1079
- - default: return assertNever(activation);
1080
- - }
1081
- -}
1082
- -/**
1083
- -* Retain local failures whose turn ending could not be committed.
1084
- -* @param activation - exact local Agent and epoch receiving the scoped observers.
1085
- -* @param wake - notify its settlement watcher when failure changes readiness.
1086
- -*/
1087
- -function observeLocalFailure(activation, wake) {
1088
- - const child = activation.handle.agent;
1089
- - child.ctx.on("agent/error", ({ agent }) => {
1090
- - if (agent !== child) return;
1091
- - activation.failureAt = child.session.seq;
1092
- - wake();
1093
- - });
1094
- - child.ctx.on("session/event", (session, event) => {
1095
- - if (session === child.session && event.type === "turn/end" && activation.failureAt !== void 0 && event.seq >= activation.failureAt) activation.failureAt = void 0;
1096
- - });
1097
- -}
1098
- -/**
1099
- -* Capture local output and retain failures without a later committed turn ending.
1100
- -* @param activation - the settled local execution and any structured result.
1101
- -* @returns final output, stop reason, and committed structured value.
1102
- -*/
1103
- -function captureLocalResult(activation) {
1104
- - const events = activation.handle.agent.session.snapshotEvents(activation.outputStart);
1105
- - const output = finalAssistantOutput(events) ?? [];
1106
- - const stopReason = activation.failureAt === void 0 ? epochStopReason(events) : "error";
1107
- - const structured = activation.structured;
1108
- - if (structured !== void 0) {
1109
- - const captured = structured.captured();
1110
- - if (captured !== void 0) return {
1111
- - output,
1112
- - stopReason,
1113
- - structured: captured.value
1114
- - };
1115
- - if (stopReason === "completed") return {
1116
- - output,
1117
- - stopReason: "error"
1118
- - };
1119
- - }
1120
- - return {
1121
- - output,
1122
- - stopReason
1123
- - };
1124
- -}
1125
- -/** Serialize each durable child's delivery, release, and disposal. */
1126
- -var ChildLock = class {
1127
- - tails = /* @__PURE__ */ new Map();
1128
- - /**
1129
- - * Run `operation` after every previously queued operation for `childId`.
1130
- - * @param childId - the durable child whose operations are linearized.
1131
- - * @param operation - the critical section to run in order.
1132
- - * @returns the operation's own settlement.
1133
- - */
1134
- - run(childId, operation) {
1135
- - const result = (this.tails.get(childId) ?? Promise.resolve()).then(operation, operation);
1136
- - const tail = result.then(() => void 0, () => void 0);
1137
- - this.tails.set(childId, tail);
1138
- - tail.then(() => {
1139
- - if (this.tails.get(childId) === tail) this.tails.delete(childId);
1140
- - });
1141
- - return result;
1142
- - }
1143
- -};
1144
- -//#endregion
1145
- -//#region lib/types/manager.js
1146
- -/**
1147
- -* Owns subagent startup, message admission, cold resume, and execution lifetimes.
1148
- -* One child lock orders input acceptance and closure; one activation map owns
1149
- -* capacity, parent relationships, and resource release across all providers.
1150
- -*
1151
- -* @module @deepseek-ai/dsh-subagent/manager
1152
- -*/
1153
- -var __addDisposableResource$2 = function(env, value, async) {
1154
- - if (value !== null && value !== void 0) {
1155
- - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
1156
- - var dispose, inner;
1157
- - if (async) {
1158
- - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
1159
- - dispose = value[Symbol.asyncDispose];
1160
- - }
1161
- - if (dispose === void 0) {
1162
- - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
1163
- - dispose = value[Symbol.dispose];
1164
- - if (async) inner = dispose;
1165
- - }
1166
- - if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
1167
- - if (inner) dispose = function() {
1168
- - try {
1169
- - inner.call(this);
1170
- - } catch (e) {
1171
- - return Promise.reject(e);
1172
- - }
1173
- - };
1174
- - env.stack.push({
1175
- - value,
1176
- - dispose,
1177
- - async
1178
- - });
1179
- - } else if (async) env.stack.push({ async: true });
1180
- - return value;
1181
- -};
1182
- -var __disposeResources$2 = (function(SuppressedError) {
1183
- - return function(env) {
1184
- - function fail(e) {
1185
- - env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
1186
- - env.hasError = true;
1187
- - }
1188
- - var r, s = 0;
1189
- - function next() {
1190
- - while (r = env.stack.pop()) try {
1191
- - if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
1192
- - if (r.dispose) {
1193
- - var result = r.dispose.call(r.value);
1194
- - if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
1195
- - fail(e);
1196
- - return next();
1197
- - });
1198
- - } else s |= 1;
1199
- - } catch (e) {
1200
- - fail(e);
1201
- - }
1202
- - if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
1203
- - if (env.hasError) throw env.error;
1204
- - }
1205
- - return next();
1206
- - };
1207
- -})(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
1208
- - var e = new Error(message);
1209
- - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
1210
- -});
1211
- -/** Render only the safe outer message from execution or teardown failures. */
1212
- -function failureMessage(error) {
1213
- - return error instanceof Error ? error.message : "unknown teardown failure";
1214
- -}
1215
- -/** Own subagent requests and the resources of every live activation. */
1216
- -var SubagentManager = class {
1217
- - ctx;
1218
- - host;
1219
- - maxActiveSubagents;
1220
- - /** Child session id → its live Activation. Process-local, never durable. */
1221
- - resident = /* @__PURE__ */ new Map();
1222
- - /** Root identities retain their pool across child settlement without retaining dead roots. */
1223
- - rootPools = /* @__PURE__ */ new WeakMap();
1224
- - /** Materializations admitted before drain, tracked through publication or rollback. */
1225
- - materializations = /* @__PURE__ */ new Set();
1226
- - /** Per-child serializer shared by delivery, release, and disposal. */
1227
- - locks = new ChildLock();
1228
- - /** Structural Cordis owner of every Activation handle. */
1229
- - ownerCtx;
1230
- - /**
1231
- - * Exact roots whose host teardown has begun, with the live lineage members
1232
- - * observed under each root. Entries remain until that exact root leaves the
1233
- - * Agent registry, closing admission throughout its host's teardown without
1234
- - * poisoning a later same-id replacement.
1235
- - */
1236
- - closingScopes = /* @__PURE__ */ new Map();
1237
- - draining = false;
1238
- - /**
1239
- - * Build one manager inside the service's Agent-injected context.
1240
- - * @param ctx - context providing Agents, Sessions, and teardown ownership.
1241
- - * @param host - provider dispatch and lifecycle observation owned by the service.
1242
- - * @param maxActiveSubagents - the current configured child capacity.
1243
- - */
1244
- - constructor(ctx, host, maxActiveSubagents) {
1245
- - this.ctx = ctx;
1246
- - this.host = host;
1247
- - this.maxActiveSubagents = maxActiveSubagents;
1248
- - const scope = ctx.plugin(function activationOwner() {});
1249
- - this.ownerCtx = scope.ctx;
1250
- - ctx.on("agent/disposed", ({ agent }) => {
1251
- - this.closingScopes.delete(agent);
1252
- - });
1253
- - ctx.effect(function* () {
1254
- - yield scope.dispose;
1255
- - yield () => this.drain();
1256
- - }.bind(this), "subagents.manager()");
1257
- - }
1258
- - /**
1259
- - * Interrupt one live continuable child's current turn under the supplied authority.
1260
- - * @param targetSessionId - the durable child session id to interrupt.
1261
- - * @param authority - the human parent address or exact live ancestor Agent.
1262
- - */
1263
- - interrupt(targetSessionId, authority) {
1264
- - if (authority.kind === "ancestor") {
1265
- - const caller = authority.agent;
1266
- - if (this.ctx.agents.get(caller.id) !== caller) throw new SubagentError(`interrupting "${targetSessionId}" requires the exact live ancestor agent`, "UNAUTHORIZED");
1267
- - if (caller.id === targetSessionId) throw new SubagentError(`agent "${caller.id}" cannot interrupt itself`, "UNAUTHORIZED");
1268
- - }
1269
- - const activation = this.resident.get(targetSessionId);
1270
- - if (activation === void 0) return;
1271
- - if (authority.kind === "user") {
1272
- - if (activation.parent.id !== authority.parentSessionId) throw new SubagentError(`subagent "${targetSessionId}" belongs to another parent session`, "UNAUTHORIZED");
1273
- - } else if (!activation.ancestry.has(authority.agent)) throw new SubagentError(`subagent "${targetSessionId}" is not a live descendant of agent "${authority.agent.id}"`, "UNAUTHORIZED");
1274
- - if (activation.closing !== void 0) return;
1275
- - const kind = authority.kind === "user" ? "user" : "parent";
1276
- - if (activation.kind === "local") activation.handle.agent.cancel({ kind }, { keepInbox: true });
1277
- - else {
1278
- - activation.controller.abort({ kind });
1279
- - this.dispose(activation).catch(() => void 0);
1280
- - }
1281
- - }
1282
- - /**
1283
- - * Close admission, await every already-admitted materialization through
1284
- - * publication or rollback, then dispose the stable live Activation graph
1285
- - * child-first.
1286
- - */
1287
- - async drain() {
1288
- - this.draining = true;
1289
- - for (const pending of this.materializations) pending.controller.abort();
1290
- - await Promise.all([...this.materializations].map((materialization) => materialization.settled));
1291
- - const owned = /* @__PURE__ */ new Set();
1292
- - for (const activation of this.resident.values()) for (const child of activation.ownedChildren) owned.add(child);
1293
- - const roots = [...this.resident.values()].filter((activation) => !owned.has(activation.childId));
1294
- - await this.disposeRoots(roots, "activation(s)");
1295
- - }
1296
- - /**
1297
- - * Join progressing child work, leaving idle parked inboxes resident.
1298
- - * @param parent - exact live parent whose descendants are observed.
1299
- - * @returns whether work was joined and the host must recheck parent completion.
1300
- - */
1301
- - async waitForChildren(parent) {
1302
- - let observed = false;
1303
- - while (true) {
1304
- - const pending = [...this.materializations].filter((item) => item.lineage.includes(parent));
1305
- - const children = [...this.resident.values()].filter((item) => activationAgent(item) !== parent && item.ancestry.has(parent));
1306
- - observed ||= children.some((item) => item.kind === "local" && item.handle.agent.status !== "idle");
1307
- - await Promise.all(children.flatMap((item) => item.kind === "local" ? [item.handle.agent.whenIdle()] : []));
1308
- - const waits = pending.map((item) => item.settled);
1309
- - for (const item of children) {
1310
- - if (item.kind === "external" || item.closing !== void 0) {
1311
- - waits.push(item.result.promise.catch(() => void 0));
1312
- - continue;
1313
- - }
1314
- - if (item.handle.agent.status !== "idle") {
1315
- - waits.push(item.handle.agent.whenIdle());
1316
- - continue;
1317
- - }
1318
- - if (item.ownedChildren.size > 0) {
1319
- - if ([...item.ownedChildren].some((id) => !this.resident.has(id))) waits.push(item.poke.promise);
1320
- - continue;
1321
- - }
1322
- - const inbox = item.handle.agent.inbox;
1323
- - if (item.failureAt === void 0 && (inbox.nextTurn.length > 0 || inbox.nextStep.length > 0)) continue;
1324
- - waits.push(Promise.race([item.result.promise.catch(() => void 0), item.poke.promise]));
1325
- - }
1326
- - if (waits.length > 0) {
1327
- - observed = true;
1328
- - await Promise.all(waits);
1329
- - continue;
1330
- - }
1331
- - if ([...this.materializations].some((item) => item.lineage.includes(parent) && !pending.includes(item)) || [...this.resident.values()].some((item) => activationAgent(item) !== parent && item.ancestry.has(parent) && !children.includes(item))) continue;
1332
- - return observed;
1333
- - }
1334
- - }
1335
- - /**
1336
- - * Stop the managed descendants of exact live host-owned parents.
1337
- - * @param parents - exact live roots whose managed descendants must stop.
1338
- - */
1339
- - async drainDescendants(parents) {
1340
- - const roots = new Set(parents.filter((parent) => this.ctx.agents.get(parent.id) === parent));
1341
- - if (roots.size === 0) return;
1342
- - for (const root of roots) this.closingMembers(root).add(root);
1343
- - const targets = [];
1344
- - for (const activation of this.resident.values()) {
1345
- - const child = activationAgent(activation);
1346
- - const lineage = this.liveLineage(child ?? activation.parent);
1347
- - const owners = [...roots].filter((root) => child !== root && activation.ancestry.has(root));
1348
- - if (owners.length === 0) continue;
1349
- - targets.push(activation);
1350
- - for (const owner of owners) {
1351
- - const members = this.closingMembers(owner);
1352
- - if (child !== void 0) members.add(child);
1353
- - for (const agent of lineage) members.add(agent);
1354
- - }
1355
- - }
1356
- - const materializations = [...this.materializations].filter((materialization) => {
1357
- - const owners = [...roots].filter((root) => materialization.lineage.includes(root));
1358
- - for (const owner of owners) {
1359
- - const members = this.closingMembers(owner);
1360
- - for (const agent of materialization.lineage) members.add(agent);
1361
- - }
1362
- - if (owners.length > 0) materialization.controller.abort();
1363
- - return owners.length > 0;
1364
- - });
1365
- - const ownedTargets = /* @__PURE__ */ new Set();
1366
- - for (const activation of targets) for (const child of activation.ownedChildren) ownedTargets.add(child);
1367
- - const targetRoots = targets.filter((activation) => !ownedTargets.has(activation.childId));
1368
- - for (const activation of targets) this.dispose(activation).catch(() => void 0);
1369
- - await Promise.all(materializations.map((materialization) => materialization.settled));
1370
- - await this.disposeRoots(targetRoots, "scoped activation(s)");
1371
- - }
1372
- - /**
1373
- - * Release selected resident direct children of one exact live parent.
1374
- - * @param parent - exact live direct parent authorizing the selected release.
1375
- - * @param childIds - durable direct-child ids to release when resident.
1376
- - */
1377
- - async drainChildren(parent, childIds) {
1378
- - if (this.ctx.agents.get(parent.id) !== parent) throw new SubagentError("selected child teardown requires the exact live parent agent", "UNAUTHORIZED");
1379
- - const targets = [];
1380
- - for (const childId of new Set(childIds)) {
1381
- - const activation = this.resident.get(childId);
1382
- - if (activation === void 0) continue;
1383
- - if (activation.parent.id !== parent.id || !activation.ancestry.has(parent)) throw new SubagentError(`subagent "${childId}" is not a direct child of agent "${parent.id}"`, "UNAUTHORIZED");
1384
- - targets.push(activation);
1385
- - }
1386
- - for (const activation of targets) this.dispose(activation).catch(() => void 0);
1387
- - await this.disposeRoots(targets, "selected activation(s)");
1388
- - }
1389
- - /**
1390
- - * Start one continuable background child and resolve at initial inbox acceptance.
1391
- - * Every earlier failure disposes any created handle and rolls back Activation
1392
- - * and parent ownership without returning either id.
1393
- - * @param spec - provider, delegation request, and caller cancellation.
1394
- - * @returns the durable child id and accepted initial prompt message id.
1395
- - */
1396
- - async startLocal(spec) {
1397
- - const request = spec.request;
1398
- - const parent = request.parent;
1399
- - this.assertAdmitting(parent);
1400
- - const persistence = spec.delivery === "caller" ? this.ctx.get("sessionPersistence") : this.requirePersistence();
1401
- - assertSubagentMaxDepth(request.maxDepth);
1402
- - const childId = spec.childId ?? brandString(randomUUID());
1403
- - this.assertChildIdAvailable(childId);
1404
- - const childDepth = resolveChildDepth(parent, request.maxDepth);
1405
- - const agentOptions = resolveChildAgentOptions(parent, request.agentOptions, childDepth);
1406
- - const agentProvider = agentOptions.provider;
1407
- - const agentModel = agentOptions.model;
1408
- - const agentReasoningEffort = agentOptions.reasoningEffort;
1409
- - const descriptor = snapshotSubagentDescriptor({
1410
- - mode: "continuable",
1411
- - provider: spec.provider,
1412
- - label: spec.label,
1413
- - ...agentProvider !== void 0 ? { agentProvider } : {},
1414
- - ...agentModel !== void 0 ? { agentModel } : {},
1415
- - ...agentReasoningEffort !== void 0 ? { agentReasoningEffort } : {}
1416
- - });
1417
- - const delegatedPolicies = captureDelegatedPolicyOverrides(parent);
1418
- - const releaseHold = this.holdOwnership(parent, childId);
1419
- - try {
1420
- - const cwd = await this.resolveDirectory(request, spec.signal);
1421
- - const prepared = await this.host.prepareContinuable(spec.provider, {
1422
- - sessionId: childId,
1423
- - cwd,
1424
- - parent,
1425
- - signal: spec.signal
1426
- - });
1427
- - spec.signal.throwIfAborted();
1428
- - this.assertAdmitting(parent);
1429
- - const inheritedEventCount = SessionLogOffset(prepared.seed?.length ?? 0);
1430
- - const seed = prepared.seed;
1431
- - let established;
1432
- - const messageId = await this.locks.run(childId, async () => {
1433
- - spec.signal.throwIfAborted();
1434
- - this.assertAdmitting(parent);
1435
- - this.assertChildIdAvailable(childId);
1436
- - if (spec.childId !== void 0) {
1437
- - const persisted = await persistence?.stat(childId, { signal: spec.signal });
1438
- - spec.signal.throwIfAborted();
1439
- - this.assertAdmitting(parent);
1440
- - this.assertChildIdAvailable(childId);
1441
- - if (persisted !== void 0) throw new SubagentError(`subagent "${childId}" already exists`, "DUPLICATE_CHILD");
1442
- - }
1443
- - const activation = await this.materialize({
1444
- - kind: "local",
1445
- - childId,
1446
- - provider: spec.provider,
1447
- - parent,
1448
- - create: {
1449
- - cwd,
1450
- - seed,
1451
- - meta: childSessionMeta(parent, childDepth, prepared.seed !== void 0, request.agentPreset),
1452
- - inheritedEventCount,
1453
- - delegatedPolicies,
1454
- - descriptor
1455
- - },
1456
- - agentOptions,
1457
- - composition: { agentPreset: request.agentPreset },
1458
- - signal: spec.signal,
1459
- - delivery: spec.delivery,
1460
- - outputSchema: spec.request.outputSchema
1461
- - });
1462
- - established = activation;
1463
- - const child = requireLocalActivation(activation).handle.agent;
1464
- - const childHeader = child.session.header;
1465
- - return await this.submitMaterialized(activation, spec.delivery !== "caller" && isAdjacentAgentSendMessageTool(this.ctx.get("tools")?.get("send_message", child)) ? withContinuableReturnGuidance(parent.id, request.prompt) : request.prompt, {
1466
- - source: { kind: "user" },
1467
- - signal: spec.signal,
1468
- - delivery: "queue"
1469
- - }, parent, () => {
1470
- - establishCatalogChild(parent.session, childHeader, descriptor);
1471
- - });
1472
- - });
1473
- - return {
1474
- - ...this.receipt(established),
1475
- - childId,
1476
- - messageId
1477
- - };
1478
- - } catch (error) {
1479
- - releaseHold();
1480
- - throw error;
1481
- - }
1482
- - }
1483
- - /**
1484
- - * Start an external backend under activation ownership.
1485
- - * @param spec - task, provider, cancellation, and delivery policy.
1486
- - * @returns the accepted activation and its result/disposal capabilities.
1487
- - */
1488
- - async startExternal(spec) {
1489
- - const parent = spec.request.parent;
1490
- - this.assertAdmitting(parent);
1491
- - const pendingId = brandString(randomUUID());
1492
- - const releaseHold = this.holdOwnership(parent, pendingId);
1493
- - let activation;
1494
- - try {
1495
- - const cwd = await this.resolveDirectory(spec.request, spec.signal);
1496
- - activation = await this.materialize({
1497
- - kind: "external",
1498
- - childId: pendingId,
1499
- - provider: spec.provider,
1500
- - parent,
1501
- - signal: spec.signal,
1502
- - delivery: spec.delivery,
1503
- - start: (signal) => this.host.startExternal(spec.provider, {
1504
- - ...spec.request,
1505
- - cwd,
1506
- - label: spec.label,
1507
- - signal
1508
- - })
1509
- - });
1510
- - this.assertAdmitting(parent);
1511
- - this.assertLiveParent(parent, activation.childId);
1512
- - spec.signal.throwIfAborted();
1513
- - if (spec.delivery === "parent") establishExternalCatalogChild(parent.session, activation.childId, spec.label);
1514
- - this.announce(activation);
1515
- - return this.receipt(activation);
1516
- - } catch (error) {
1517
- - if (activation !== void 0) try {
1518
- - await this.dispose(activation);
1519
- - } catch (cleanupError) {
1520
- - this.ctx.logger.warn(`subagent "${activation.childId}" admission rollback failed: ${failureMessage(cleanupError)}`);
1521
- - }
1522
- - throw error;
1523
- - } finally {
1524
- - releaseHold();
1525
- - }
1526
- - }
1527
- - /** Capture the explicit or inherited directory while the parent still owns startup. */
1528
- - async resolveDirectory(request, signal) {
1529
- - const cwd = request.cwd !== void 0 && isAbsolute(request.cwd) ? request.cwd : resolve(await this.ctx.workingDirectory.ensure(request.parent, signal), request.cwd ?? ".");
1530
- - signal.throwIfAborted();
1531
- - return cwd;
1532
- - }
1533
- - /**
1534
- - * Deliver one model-authored message to a direct continuable child or to the
1535
- - * sender's direct parent. A missing direct child cold-resumes through the
1536
- - * ordinary continuation lifecycle.
1537
- - * @param sender - exact live Agent authorizing and originating the message.
1538
- - * @param targetId - durable direct-parent or direct-child session id.
1539
- - * @param content - model-authored content to deliver.
1540
- - * @param options - caller cancellation before acceptance.
1541
- - * @returns the accepted message's inbox id.
1542
- - */
1543
- - async sendMessage(sender, targetId, content, options) {
1544
- - if (this.ctx.agents.get(sender.id) !== sender) throw new SubagentError("message delivery requires the exact live sender agent", "UNAUTHORIZED");
1545
- - this.assertAdmitting(sender);
1546
- - const senderActivation = this.resident.get(sender.id);
1547
- - if (senderActivation !== void 0 && senderActivation.kind === "local" && senderActivation.handle.agent === sender && senderActivation.parent.id === targetId) {
1548
- - options.signal.throwIfAborted();
1549
- - return this.sendToParent(senderActivation, sender, content);
1550
- - }
1551
- - if (sender.session.header.parentSession === targetId) throw new SubagentError(`agent "${sender.id}" is not a resident continuable child and cannot send to parent "${targetId}"`, "UNAUTHORIZED");
1552
- - return this.deliverToChild(sender, targetId, content, {
1553
- - signal: options.signal,
1554
- - delivery: "steer"
1555
- - });
1556
- - }
1557
- - /**
1558
- - * Queue one human-authored prompt as a distinct direct-child turn.
1559
- - * @param parent - exact live direct parent authorizing delivery.
1560
- - * @param childId - durable direct-child session id.
1561
- - * @param content - model-visible prompt blocks.
1562
- - * @param source - durable attribution for the human prompt.
1563
- - * @param signal - caller cancellation before inbox acceptance.
1564
- - * @returns the accepted durable message id.
1565
- - */
1566
- - async queuePrompt(parent, childId, content, source, signal) {
1567
- - return this.deliverToChild(parent, childId, content, {
1568
- - source,
1569
- - signal,
1570
- - delivery: "queue"
1571
- - });
1572
- - }
1573
- - /**
1574
- - * Steer one host-authored prompt to a direct continuable child.
1575
- - * @param parent - exact live direct parent authorizing delivery.
1576
- - * @param childId - durable direct-child session id.
1577
- - * @param content - model-visible prompt blocks.
1578
- - * @param source - durable attribution for the host prompt.
1579
- - * @param signal - caller cancellation before inbox acceptance.
1580
- - * @returns the accepted durable message id.
1581
- - */
1582
- - async steerPrompt(parent, childId, content, source, signal) {
1583
- - return this.deliverToChild(parent, childId, content, {
1584
- - source,
1585
- - signal,
1586
- - delivery: "steer"
1587
- - });
1588
- - }
1589
- - /** Admit local input synchronously before any teardown can begin. */
1590
- - deliver(activation, message, delivery) {
1591
- - if (activation.closing !== void 0) throw new SubagentError("subagent activation is being disposed; the message was not accepted", "ACTIVATION_CLOSING");
1592
- - const local = requireLocalActivation(activation);
1593
- - if (local.structured?.acceptsInput() === false) throw new SubagentError("subagent is submitting or has submitted its structured result; the message was not accepted", "INPUT_CLOSED");
1594
- - if (delivery === "steer") local.handle.agent.steer(message);
1595
- - else local.handle.agent.followup(message);
1596
- - }
1597
- - /**
1598
- - * Reject one child identity already owned by a live Agent or Session.
1599
- - * @param childId - proposed durable child session id.
1600
- - */
1601
- - assertChildIdAvailable(childId) {
1602
- - if (this.resident.has(childId) || this.ctx.agents.get(childId) !== void 0 || this.ctx.get("sessions")?.get(childId) !== void 0) throw new SubagentError(`subagent "${childId}" already exists`, "DUPLICATE_CHILD");
1603
- - }
1604
- - /**
1605
- - * Pre-register `childId` in a continuation-managed parent's owned set so the
1606
- - * parent cannot settle while a caller is still establishing or resuming that
1607
- - * child. Returns a releaser for the failure path; it removes only a hold
1608
- - * this call added, and leaves ownership in place once a live Activation for
1609
- - * the child exists.
1610
- - * @param parent - the live direct parent the operation is admitted under.
1611
- - * @param childId - the durable child the operation addresses.
1612
- - * @returns the failure-path releaser; a no-op when nothing was added.
1613
- - */
1614
- - holdOwnership(parent, childId) {
1615
- - const parentActivation = this.resident.get(parent.id);
1616
- - if (parentActivation === void 0 || activationAgent(parentActivation) !== parent) return () => {};
1617
- - if (parentActivation.closing !== void 0) throw new SubagentError(`subagent parent "${parent.id}" is being disposed; the child was not established`, "ACTIVATION_CLOSING");
1618
- - if (parentActivation.ownedChildren.has(childId)) return () => {};
1619
- - parentActivation.ownedChildren.add(childId);
1620
- - return () => {
1621
- - const live = this.resident.get(childId);
1622
- - /* v8 ignore next 4 -- reaching this arm needs another delivery to establish the child
1623
- - * between this operation's failure and its releaser running, which no test can schedule
1624
- - * deterministically: the ownership edge then belongs to that live Activation, so the
1625
- - * conservative keep leaves it for finishDisposal's releaseOwnership. */
1626
- - if (live !== void 0 && live.closing === void 0) return;
1627
- - if (parentActivation.ownedChildren.delete(childId)) this.wake(parentActivation);
1628
- - };
1629
- - }
1630
- - /**
1631
- - * Apply activation admission to a resident parent before delivering input.
1632
- - * @param parent - exact live Agent receiving the message.
1633
- - * @param message - durable user message to deliver.
1634
- - * @param delivery - receiving inbox destination.
1635
- - */
1636
- - sendWaking(parent, message, delivery) {
1637
- - const parentActivation = this.resident.get(parent.id);
1638
- - if (parentActivation !== void 0 && activationAgent(parentActivation) === parent) {
1639
- - try {
1640
- - this.deliver(parentActivation, message, delivery);
1641
- - } finally {
1642
- - this.wake(parentActivation);
1643
- - }
1644
- - return;
1645
- - }
1646
- - if (delivery === "steer") parent.steer(message);
1647
- - else parent.followup(message);
1648
- - }
1649
- - /**
1650
- - * Reject new admission once the manager or this exact parent tree began draining.
1651
- - * @param agent - exact live Agent whose lineage determines admission.
1652
- - */
1653
- - assertAdmitting(agent) {
1654
- - const closing = this.closingTeardownFor(agent);
1655
- - if (closing === void 0) return;
1656
- - throw new SubagentError(closing === "manager" ? "subagents are draining; the operation was not admitted" : `subagents below parent "${closing.id}" are draining; the operation was not admitted`, "DRAINING");
1657
- - }
1658
- - /**
1659
- - * Authorize one operation against the durable direct-parent lineage.
1660
- - * @param parent - exact live Agent claiming direct-parent authority.
1661
- - * @param childId - durable child session id addressed by the operation.
1662
- - * @param parentSession - durable direct-parent id recorded by the child.
1663
- - */
1664
- - authorizeLineage(parent, childId, parentSession) {
1665
- - this.assertLiveParent(parent, childId);
1666
- - if (parentSession !== parent.id) throw new SubagentError(`subagent "${childId}" belongs to another parent session`, "UNAUTHORIZED");
1667
- - }
1668
- - /** Reject parent authority after the live registry entry changes. */
1669
- - assertLiveParent(parent, childId) {
1670
- - if (this.ctx.agents.get(parent.id) !== parent) throw new SubagentError(`subagent "${childId}" delivery requires the exact live parent agent`, "UNAUTHORIZED");
1671
- - }
1672
- - /**
1673
- - * Create or resume one child Agent and publish its Activation.
1674
- - * @param inputs - reconstruction and admission inputs for the residency epoch.
1675
- - * @returns the published process-local Activation.
1676
- - */
1677
- - materialize(inputs) {
1678
- - this.assertAdmitting(inputs.parent);
1679
- - inputs.signal.throwIfAborted();
1680
- - const lineage = this.liveLineage(inputs.parent);
1681
- - const pool = this.resident.get(inputs.parent.id)?.pool ?? this.rootPool(inputs.parent);
1682
- - const releaseSlot = pool.reserve(this.maxActiveSubagents());
1683
- - const settled = Promise.withResolvers();
1684
- - const controller = new AbortController();
1685
- - const materialization = {
1686
- - lineage,
1687
- - settled: settled.promise,
1688
- - controller
1689
- - };
1690
- - this.materializations.add(materialization);
1691
- - return this.materializeTracked({
1692
- - ...inputs,
1693
- - signal: AbortSignal.any([inputs.signal, controller.signal])
1694
- - }, lineage, pool, releaseSlot).catch((error) => {
1695
- - releaseSlot();
1696
- - if (error instanceof Error && error.name === "AbortError") this.assertAdmitting(inputs.parent);
1697
- - throw error;
1698
- - }).finally(() => {
1699
- - this.materializations.delete(materialization);
1700
- - settled.resolve();
1701
- - });
1702
- - }
1703
- - /**
1704
- - * Stop and release one Activation through its memoized close transaction.
1705
- - * @param activation - exact residency epoch to close.
1706
- - * @returns the shared close transaction.
1707
- - */
1708
- - dispose(activation) {
1709
- - return this.close(activation, () => this.finishDisposal(activation, true));
1710
- - }
1711
- - /** Close admission synchronously and share one release, including startup rollback. */
1712
- - close(activation, release) {
1713
- - if (activation.closing !== void 0) return activation.closing;
1714
- - const completion = Promise.withResolvers();
1715
- - activation.closing = completion.promise;
1716
- - release().then(completion.resolve, completion.reject);
1717
- - return completion.promise;
1718
- - }
1719
- - /** Dispose independent roots and report every branch failure after all settle. */
1720
- - async disposeRoots(roots, failureSubject) {
1721
- - const reasons = (await Promise.all(roots.map(async (activation) => {
1722
- - try {
1723
- - await this.dispose(activation);
1724
- - return;
1725
- - } catch (error) {
1726
- - return error;
1727
- - }
1728
- - }))).filter((failure) => failure !== void 0);
1729
- - if (reasons.length > 0) throw new SubagentError(`subagent teardown failed for ${reasons.length} ${failureSubject}: ` + reasons.map((reason) => failureMessage(reason)).join("; "), "ACTIVATION_TEARDOWN_FAILED");
1730
- - }
1731
- - /** Return the retained member set for one exact scoped-teardown root. */
1732
- - closingMembers(root) {
1733
- - const existing = this.closingScopes.get(root);
1734
- - if (existing !== void 0) return existing;
1735
- - const members = /* @__PURE__ */ new Set();
1736
- - this.closingScopes.set(root, members);
1737
- - return members;
1738
- - }
1739
- - /** Return the exact currently resolvable ancestry from `agent` upward. */
1740
- - liveLineage(agent) {
1741
- - const lineage = [agent];
1742
- - const seen = new Set([agent.id]);
1743
- - let parentSession = agent.session.header.parentSession;
1744
- - while (parentSession !== void 0) {
1745
- - const parent = this.ctx.agents.get(parentSession);
1746
- - if (parent === void 0 || seen.has(parent.id)) break;
1747
- - lineage.push(parent);
1748
- - seen.add(parent.id);
1749
- - parentSession = parent.session.header.parentSession;
1750
- - }
1751
- - return lineage;
1752
- - }
1753
- - /** Return the teardown that closed continuable admission for this agent's lineage. */
1754
- - closingTeardownFor(agent) {
1755
- - if (this.draining) return "manager";
1756
- - const lineage = this.liveLineage(agent);
1757
- - for (const [root, members] of this.closingScopes) if (members.has(agent) || lineage.includes(root)) return root;
1758
- - }
1759
- - /** Resolve a root's pool once; descendants inherit their resident parent's pool directly. */
1760
- - rootPool(parent) {
1761
- - let pool = this.rootPools.get(parent);
1762
- - if (pool === void 0) {
1763
- - pool = new ActivationPool();
1764
- - this.rootPools.set(parent, pool);
1765
- - }
1766
- - return pool;
1767
- - }
1768
- - /** Perform one tracked materialization through publication or rollback. */
1769
- - async materializeTracked(inputs, parentLineage, pool, releaseSlot) {
1770
- - const { provider, parent } = inputs;
1771
- - let childId = inputs.childId;
1772
- - inputs.signal.throwIfAborted();
1773
- - let resource;
1774
- - if (inputs.kind === "external") {
1775
- - const controller = new AbortController();
1776
- - const cancelStartup = () => {
1777
- - controller.abort(inputs.signal.reason);
1778
- - };
1779
- - inputs.signal.addEventListener("abort", cancelStartup, { once: true });
1780
- - try {
1781
- - const run = await inputs.start(controller.signal);
1782
- - resource = {
1783
- - kind: "external",
1784
- - run,
1785
- - controller
1786
- - };
1787
- - run.result.catch(() => void 0);
1788
- - childId = run.id;
1789
- - try {
1790
- - this.assertChildIdAvailable(childId);
1791
- - } catch (error) {
1792
- - await run.dispose();
1793
- - throw error;
1794
- - }
1795
- - } finally {
1796
- - inputs.signal.removeEventListener("abort", cancelStartup);
1797
- - }
1798
- - } else {
1799
- - const { create } = inputs;
1800
- - let structured;
1801
- - const setup = async (childCtx, child) => {
1802
- - if (inputs.composition.agentPreset !== void 0) await applyChildComposition(childCtx, parent, inputs.composition);
1803
- - if (create !== void 0) {
1804
- - if (inputs.composition.agentPreset !== void 0) child.session.append("agent-preset/selected", { agentPreset: inputs.composition.agentPreset });
1805
- - child.session.append("subagent/descriptor", create.descriptor);
1806
- - appendDelegatedPolicyOverrides(child.session, create.delegatedPolicies);
1807
- - const workingDirectory = childCtx.get("workingDirectory");
1808
- - if (workingDirectory === void 0) throw new Error("local subagents require the working-directory service");
1809
- - await workingDirectory.set(child, create.cwd, inputs.signal);
1810
- - }
1811
- - if (inputs.composition.agentPreset === void 0) await applyChildComposition(childCtx, parent, inputs.composition);
1812
- - if (inputs.outputSchema !== void 0) structured = attachStructuredRuntime(childCtx, inputs.outputSchema, () => this.resident.get(childId)?.ownedChildren.size === 0 && child.inbox.nextStep.length === 0 && child.inbox.nextTurn.length === 0);
1813
- - };
1814
- - const handle = create === void 0 ? await this.ownerCtx.agents.resume({
1815
- - resumeSessionId: childId,
1816
- - parentAgent: parent,
1817
- - agentOptions: inputs.agentOptions,
1818
- - signal: inputs.signal,
1819
- - setup
1820
- - }) : await this.ownerCtx.agents.create({
1821
- - sessionId: childId,
1822
- - parentAgent: parent,
1823
- - meta: create.meta,
1824
- - ...create.seed === void 0 ? {} : { seed: create.seed },
1825
- - inheritedEventCount: create.inheritedEventCount,
1826
- - agentOptions: inputs.agentOptions,
1827
- - signal: inputs.signal,
1828
- - setup
1829
- - });
1830
- - resource = {
1831
- - kind: "local",
1832
- - handle,
1833
- - outputStart: handle.agent.session.seq,
1834
- - structured,
1835
- - failureAt: void 0,
1836
- - poke: Promise.withResolvers()
1837
- - };
1838
- - }
1839
- - const observer = this.host.observeActivation(provider, childId, parent);
1840
- - const activation = {
1841
- - pool,
1842
- - releaseSlot,
1843
- - childId,
1844
- - ...resource,
1845
- - parent,
1846
- - delivery: inputs.delivery ?? "parent",
1847
- - result: Promise.withResolvers(),
1848
- - closing: void 0,
1849
- - ancestry: new WeakSet(resource.kind === "external" ? parentLineage : [resource.handle.agent, ...parentLineage]),
1850
- - ownedChildren: /* @__PURE__ */ new Set(),
1851
- - observer,
1852
- - announced: false
1853
- - };
1854
- - activation.result.promise.catch(() => void 0);
1855
- - this.resident.set(childId, activation);
1856
- - try {
1857
- - this.assertAdmitting(parent);
1858
- - inputs.signal.throwIfAborted();
1859
- - if (this.ctx.agents.get(parent.id) !== parent) throw new SubagentError("subagent parent is no longer live", "UNAUTHORIZED");
1860
- - this.acquireOwnership(parent, childId);
1861
- - const wakeSettlement = () => {
1862
- - this.wake(activation);
1863
- - };
1864
- - if (activation.kind === "local") {
1865
- - observeLocalFailure(activation, wakeSettlement);
1866
- - activation.handle.agent.ctx.on("agent/inbox/inserted", wakeSettlement);
1867
- - activation.handle.agent.ctx.on("agent/inbox/claimed", wakeSettlement);
1868
- - activation.handle.agent.ctx.on("agent/inbox/discarded", wakeSettlement);
1869
- - }
1870
- - observer.start(activationAgent(activation));
1871
- - } catch (error) {
1872
- - /* v8 ignore next -- rollback failure must not mask the admission failure
1873
- - * that prevented this operation from returning an accepted message id. */
1874
- - await this.rollbackUnpublished(activation, error).catch(() => void 0);
1875
- - throw error;
1876
- - }
1877
- - return activation;
1878
- - }
1879
- - /**
1880
- - * Begin settlement observation after initial acceptance is recorded.
1881
- - * @param activation - accepted activation to observe.
1882
- - */
1883
- - announce(activation) {
1884
- - if (activation.announced) return;
1885
- - activation.announced = true;
1886
- - if (activation.kind === "local") this.watchLocalSettlement(activation);
1887
- - else {
1888
- - const finish = () => this.close(activation, () => this.finishDisposal(activation, false));
1889
- - activation.run.result.then(finish, finish).catch((error) => {
1890
- - this.reportTeardownFailure(activation, error);
1891
- - });
1892
- - }
1893
- - }
1894
- - /** Release an Activation whose start edge was not published. */
1895
- - rollbackUnpublished(activation, error) {
1896
- - return this.close(activation, async () => {
1897
- - try {
1898
- - await (activation.kind === "local" ? activation.handle.dispose() : activation.run.dispose());
1899
- - } finally {
1900
- - this.resident.delete(activation.childId);
1901
- - activation.releaseSlot();
1902
- - this.releaseOwnership(activation.childId);
1903
- - activation.result.reject(error);
1904
- - }
1905
- - });
1906
- - }
1907
- - /** Register the child in a continuation-managed parent's owned set. */
1908
- - acquireOwnership(parent, childId) {
1909
- - const parentActivation = this.resident.get(parent.id);
1910
- - if (parentActivation === void 0) return;
1911
- - if (parentActivation.closing !== void 0) throw new SubagentError(`subagent parent "${parent.id}" is being disposed; the child was not established`, "ACTIVATION_CLOSING");
1912
- - parentActivation.ownedChildren.add(childId);
1913
- - this.wake(parentActivation);
1914
- - }
1915
- - /** Remove one child from its live owner's set and let that owner re-check settlement. */
1916
- - releaseOwnership(childId) {
1917
- - for (const candidate of this.resident.values()) if (candidate.ownedChildren.delete(childId)) this.wake(candidate);
1918
- - }
1919
- - /** Let a settlement watcher re-check residency after relevant state changes. */
1920
- - wake(activation) {
1921
- - if (activation.kind === "external") return;
1922
- - activation.poke.resolve();
1923
- - activation.poke = Promise.withResolvers();
1924
- - }
1925
- - /** Follow one Activation to natural settlement. */
1926
- - watchLocalSettlement(activation) {
1927
- - (async () => {
1928
- - while (true) {
1929
- - const idleObservation = activation.poke;
1930
- - await activation.handle.agent.whenIdle();
1931
- - if (activation.closing !== void 0) return;
1932
- - const readiness = await this.locks.run(activation.childId, () => Promise.resolve(this.settlementState(activation, idleObservation)));
1933
- - if (readiness === "closed") return;
1934
- - if (readiness === "retry") continue;
1935
- - if (readiness === "wait") {
1936
- - await idleObservation.promise;
1937
- - continue;
1938
- - }
1939
- - const finalSeq = activation.handle.agent.session.seq;
1940
- - await this.flushFinalState(activation);
1941
- - const attempt = await this.locks.run(activation.childId, () => {
1942
- - const state = this.settlementState(activation, idleObservation);
1943
- - if (state !== "ready") return Promise.resolve(state);
1944
- - if (activation.handle.agent.session.seq !== finalSeq) return Promise.resolve("retry");
1945
- - let done;
1946
- - try {
1947
- - activation.handle.agent.runMaintenance(() => {
1948
- - done = this.close(activation, () => this.finishDisposal(activation, false));
1949
- - return Promise.resolve();
1950
- - });
1951
- - } catch (_error) {
1952
- - return Promise.resolve("retry");
1953
- - }
1954
- - return Promise.resolve({ done });
1955
- - });
1956
- - if (typeof attempt === "string") {
1957
- - if (attempt === "closed") return;
1958
- - continue;
1959
- - }
1960
- - try {
1961
- - await attempt.done;
1962
- - } catch (error) {
1963
- - this.reportTeardownFailure(activation, error);
1964
- - }
1965
- - return;
1966
- - }
1967
- - })();
1968
- - }
1969
- - /** Report disposal failure once after the natural settlement observer finishes. */
1970
- - reportTeardownFailure(activation, error) {
1971
- - this.ctx.logger.warn(`subagent "${activation.childId}" activation teardown failed: ${failureMessage(error)}`);
1972
- - }
1973
- - /** Check pending input and owned children before closing admission. */
1974
- - settlementState(activation, observation) {
1975
- - if (activation.closing !== void 0) return "closed";
1976
- - if (activation.poke !== observation) return "retry";
1977
- - const inbox = activation.handle.agent.inbox;
1978
- - if (activation.ownedChildren.size > 0) return "wait";
1979
- - if (activation.failureAt === void 0 && (inbox.nextTurn.length > 0 || inbox.nextStep.length > 0)) return "wait";
1980
- - return "ready";
1981
- - }
1982
- - /** Propagate stop synchronously and await descendant startup rollback before release. */
1983
- - async finishDisposal(activation, stop) {
1984
- - this.wake(activation);
1985
- - const { childId } = activation;
1986
- - const failures = [];
1987
- - let result = {
1988
- - output: [],
1989
- - stopReason: "error"
1990
- - };
1991
- - let resultFailure;
1992
- - let externalDisposal;
1993
- - const child = activationAgent(activation);
1994
- - const detail = (error) => child === void 0 ? failureMessage(error) : errorChain(error);
1995
- - try {
1996
- - if (activation.kind === "external") {
1997
- - if (stop) {
1998
- - activation.controller.abort({ kind: "parent" });
1999
- - externalDisposal = Promise.resolve().then(() => activation.run.dispose());
2000
- - externalDisposal.catch(() => void 0);
2001
- - }
2002
- - result = await activation.run.result;
2003
- - } else {
2004
- - if (stop) {
2005
- - activation.handle.agent.cancel({ kind: "parent" });
2006
- - const idle = activation.handle.agent.whenIdle();
2007
- - const children = [...activation.ownedChildren].map((child) => this.resident.get(child)).filter((child) => child !== void 0);
2008
- - const pending = [...this.materializations].filter((item) => item.lineage.includes(activation.handle.agent));
2009
- - const childDisposals = children.map((child) => this.dispose(child));
2010
- - for (const item of pending) item.controller.abort();
2011
- - childDisposals.push(...pending.map((item) => item.settled));
2012
- - const reasons = (await Promise.all(childDisposals.map(async (disposal) => {
2013
- - try {
2014
- - await disposal;
2015
- - return;
2016
- - } catch (error) {
2017
- - return error;
2018
- - }
2019
- - }))).filter((reason) => reason !== void 0);
2020
- - if (reasons.length > 0) failures.push(new SubagentError(`subagent "${childId}" child teardown failed: ${reasons.map((reason) => failureMessage(reason)).join("; ")}`, "ACTIVATION_TEARDOWN_FAILED"));
2021
- - await idle;
2022
- - await this.flushFinalState(activation);
2023
- - }
2024
- - result = captureLocalResult(activation);
2025
- - }
2026
- - } catch (error) {
2027
- - resultFailure = { error };
2028
- - failures.push(new SubagentError(`subagent "${childId}" activation teardown failed: ${detail(error)}`, "ACTIVATION_TEARDOWN_FAILED", { cause: error }));
2029
- - }
2030
- - try {
2031
- - if (activation.kind === "local") await activation.handle.dispose();
2032
- - else await (externalDisposal ?? activation.run.dispose());
2033
- - } catch (error) {
2034
- - failures.push(new SubagentError(`subagent "${childId}" activation handle disposal failed: ${detail(error)}`, "ACTIVATION_TEARDOWN_FAILED", { cause: error }));
2035
- - }
2036
- - let failure;
2037
- - if (failures.length === 1) failure = failures[0];
2038
- - else if (failures.length > 1) failure = new SubagentError(`subagent "${childId}" activation teardown failed at ${failures.length} boundaries: ` + failures.map((item) => detail(item)).join("; "), "ACTIVATION_TEARDOWN_FAILED", { cause: new AggregateError(failures) });
2039
- - this.resident.delete(childId);
2040
- - activation.releaseSlot();
2041
- - const terminal = failure === void 0 ? result : {
2042
- - output: [],
2043
- - stopReason: "error"
2044
- - };
2045
- - this.notifySettlement(activation, result);
2046
- - this.releaseOwnership(childId);
2047
- - activation.observer.settle(terminal);
2048
- - if (resultFailure === void 0) activation.result.resolve(result);
2049
- - else activation.result.reject(resultFailure.error);
2050
- - if (failure !== void 0) throw failure;
2051
- - }
2052
- - /** Deliver the captured execution result to the durable direct parent after cleanup. */
2053
- - notifySettlement(activation, terminal) {
2054
- - if (!activation.announced || activation.delivery === "caller") return;
2055
- - try {
2056
- - const parent = this.ctx.agents.get(activation.parent.id);
2057
- - if (parent !== activation.parent) return;
2058
- - const message = createSettlementMessage(activation.childId, terminal, activationAgent(activation) !== void 0);
2059
- - if (this.closingTeardownFor(parent) !== void 0) {
2060
- - parent.inject(message);
2061
- - return;
2062
- - }
2063
- - this.sendWaking(parent, message, parent.status === "idle" ? "queue" : "steer");
2064
- - } catch (error) {
2065
- - this.ctx.logger.warn(`subagent "${activation.childId}" settlement notice was not delivered to its parent: ` + errorChain(error));
2066
- - }
2067
- - }
2068
- - /** Request a best-effort final session flush before closing natural-settlement admission. */
2069
- - async flushFinalState(activation) {
2070
- - try {
2071
- - await activation.handle.agent.ctx.sessions.flush(activation.handle.agent.session);
2072
- - } catch (error) {
2073
- - this.ctx.logger.warn(`subagent "${activation.childId}" best-effort final session flush failed; the persisted state may be unavailable or stale on resume: ${errorChain(error)}`);
2074
- - }
2075
- - }
2076
- - /** Return capabilities bound to an exact activation instead of a future same-id instance. */
2077
- - receipt(activation) {
2078
- - return {
2079
- - childId: activation.childId,
2080
- - result: activation.result.promise,
2081
- - dispose: () => this.dispose(activation)
2082
- - };
2083
- - }
2084
- - /** Route one parent-originated delivery through residency and cold resume. */
2085
- - async deliverToChild(parent, childId, content, options) {
2086
- - this.assertAdmitting(parent);
2087
- - const releaseHold = this.holdOwnership(parent, childId);
2088
- - try {
2089
- - return await this.deliverFollowup(parent, childId, content, options);
2090
- - } catch (error) {
2091
- - releaseHold();
2092
- - throw error;
2093
- - }
2094
- - }
2095
- - /** The delivery loop behind {@link deliverToChild}, run under the parent hold. */
2096
- - async deliverFollowup(parent, childId, content, options) {
2097
- - while (true) {
2098
- - const live = await this.locks.run(childId, async () => {
2099
- - const activation = this.resident.get(childId);
2100
- - if (activation === void 0) return this.coldResume(parent, childId, content, options);
2101
- - requireLocalActivation(activation);
2102
- - const disposal = activation.closing;
2103
- - /* v8 ignore next 3 -- the send-versus-dispose cutoff needs a delivery to
2104
- - * observe the transaction inside the same critical section that opened it. */
2105
- - if (disposal !== void 0) return disposal.then(() => void 0, () => void 0);
2106
- - if (contentHasImage(content)) {
2107
- - await this.assertImageCapable(requireLocalActivation(activation).handle.agent, options.signal);
2108
- - if (activation.closing !== void 0) {
2109
- - await Promise.allSettled([activation.closing]);
2110
- - return;
2111
- - }
2112
- - }
2113
- - const messageId = this.submitAdmitted(activation, content, options, parent);
2114
- - this.announce(activation);
2115
- - return messageId;
2116
- - });
2117
- - /* v8 ignore start -- only a delivery that lost the disposal cutoff retries. */
2118
- - if (live !== void 0) return live;
2119
- - this.assertAdmitting(parent);
2120
- - options.signal.throwIfAborted();
2121
- - }
2122
- - }
2123
- - /** Deliver one resident continuable child's message to its live direct parent. */
2124
- - sendToParent(activation, sender, content) {
2125
- - /* v8 ignore next 6 -- only synchronous re-entrant teardown can open this
2126
- - * transaction between exact-agent authorization and this no-await span. */
2127
- - if (activation.closing !== void 0) throw new SubagentError(`subagent "${sender.id}" activation is being disposed; the message was not delivered`, "ACTIVATION_CLOSING");
2128
- - const parent = this.ctx.agents.get(activation.parent.id);
2129
- - if (parent !== activation.parent) throw new SubagentError("direct parent is not live; the message was not delivered", "PARENT_UNAVAILABLE");
2130
- - const message = createAgentMessage(sender, content);
2131
- - this.sendAgentMessage(parent, message);
2132
- - return message.id;
2133
- - }
2134
- - /** Send one Agent message while translating only the target's own rejection. */
2135
- - sendAgentMessage(parent, message) {
2136
- - try {
2137
- - this.sendWaking(parent, message, "steer");
2138
- - } catch (error) {
2139
- - throw new SubagentError("direct parent is not live; the message was not delivered", "PARENT_UNAVAILABLE", { cause: error });
2140
- - }
2141
- - }
2142
- - /**
2143
- - * Cold-resume a persisted child and submit the waiting turn. The descriptor
2144
- - * supplies every reconstruction input; no subagent provider is dispatched.
2145
- - */
2146
- - async coldResume(parent, childId, content, options) {
2147
- - const env_1 = {
2148
- - stack: [],
2149
- - error: void 0,
2150
- - hasError: false
2151
- - };
2152
- - try {
2153
- - const query = this.requireSessionQuery();
2154
- - let observation;
2155
- - try {
2156
- - observation = await query.observeSession(childId, { signal: options.signal });
2157
- - } catch (error) {
2158
- - options.signal.throwIfAborted();
2159
- - throw new SubagentError(`subagent "${childId}" is unavailable`, "NOT_RESUMABLE", { cause: error });
2160
- - }
2161
- - const source = __addDisposableResource$2(env_1, observation, false);
2162
- - this.assertAdmitting(parent);
2163
- - this.authorizeLineage(parent, childId, source.header.parentSession);
2164
- - const ownEvents = source.events.slice(source.inheritedEventCount);
2165
- - const descriptor = foldSubagentDescriptor(ownEvents);
2166
- - if (descriptor === void 0 || descriptor.mode !== "continuable") throw new SubagentError(`subagent "${childId}" has no supported continuation state and cannot be resumed; choose a different target`, "NOT_RESUMABLE");
2167
- - let activation;
2168
- - try {
2169
- - const independentlySelected = hasIndependentPresetSelection(ownEvents);
2170
- - const agentPreset = independentlySelected ? source.projections?.values.agentPreset : void 0;
2171
- - if (independentlySelected && typeof agentPreset !== "string") throw new SubagentError(`subagent "${childId}" has no agent preset projection for restoration`, "NOT_RESUMABLE");
2172
- - activation = await this.materialize({
2173
- - kind: "local",
2174
- - childId,
2175
- - provider: descriptor.provider,
2176
- - parent,
2177
- - agentOptions: {
2178
- - ...descriptor.agentProvider !== void 0 ? { provider: descriptor.agentProvider } : {},
2179
- - ...descriptor.agentModel !== void 0 ? { model: descriptor.agentModel } : {},
2180
- - ...descriptor.agentReasoningEffort !== void 0 ? { reasoningEffort: ReasoningEffortId(descriptor.agentReasoningEffort) } : {}
2181
- - },
2182
- - composition: {
2183
- - agentPreset: agentPreset ?? void 0,
2184
- - persona: descriptor.persona,
2185
- - toolFilter: descriptor.toolFilter
2186
- - },
2187
- - signal: options.signal
2188
- - });
2189
- - } catch (error) {
2190
- - options.signal.throwIfAborted();
2191
- - if (error instanceof SubagentError) throw error;
2192
- - throw new SubagentError(`subagent "${childId}" is unavailable`, "NOT_RESUMABLE", { cause: error });
2193
- - }
2194
- - return await this.submitMaterialized(activation, content, options, parent);
2195
- - } catch (e_1) {
2196
- - env_1.error = e_1;
2197
- - env_1.hasError = true;
2198
- - } finally {
2199
- - __disposeResources$2(env_1);
2200
- - }
2201
- - }
2202
- - /** Admit a materialized child, commit its creation fact, and release it on failure. */
2203
- - async submitMaterialized(activation, content, options, parent, commit) {
2204
- - try {
2205
- - if (contentHasImage(content)) {
2206
- - await this.assertImageCapable(requireLocalActivation(activation).handle.agent, options.signal);
2207
- - if (activation.closing !== void 0) throw new SubagentError(`subagent "${activation.childId}" is closing`, "ACTIVATION_CLOSING");
2208
- - }
2209
- - const messageId = this.submitAdmitted(activation, content, options, parent);
2210
- - commit?.();
2211
- - this.announce(activation);
2212
- - return messageId;
2213
- - } catch (error) {
2214
- - try {
2215
- - await this.dispose(activation);
2216
- - } catch (cleanupError) {
2217
- - this.ctx.logger.warn(`subagent continuation: disposal after admission or catalog append failure also failed: ${String(cleanupError)}`);
2218
- - }
2219
- - throw error;
2220
- - }
2221
- - }
2222
- - /** Build and submit one message across the final synchronous admission cutoff. */
2223
- - submitAdmitted(activation, content, options, parent) {
2224
- - const message = options.source === void 0 ? createAgentMessage(parent, content) : createUserMessage({
2225
- - content,
2226
- - source: options.source
2227
- - });
2228
- - options.signal.throwIfAborted();
2229
- - this.assertAdmitting(parent);
2230
- - this.authorizeLineage(parent, activation.childId, activation.parent.id);
2231
- - this.acquireOwnership(parent, activation.childId);
2232
- - try {
2233
- - this.deliver(activation, message, options.delivery);
2234
- - } finally {
2235
- - this.wake(activation);
2236
- - }
2237
- - return message.id;
2238
- - }
2239
- - /** Refuse image content for a child whose fixed model accepts text only. */
2240
- - async assertImageCapable(agent, signal) {
2241
- - const { provider, model } = agent.options;
2242
- - if (provider === void 0 || model === void 0) return;
2243
- - const llm = this.ctx.get("llm");
2244
- - /* v8 ignore next -- without an LLM registry, delivery defers to projection. */
2245
- - if (llm === void 0) return;
2246
- - const info = await llm.resolveModelInfo(provider, model, signal);
2247
- - if (info.inputModalities !== void 0 && !info.inputModalities.includes("image")) throw new SubagentError(`Model "${model}" does not support image input.`, "MODEL_DOES_NOT_SUPPORT_IMAGES");
2248
- - }
2249
- - /** Resolve the persistence service continuable children require, or fail loud. */
2250
- - requirePersistence() {
2251
- - const persistence = this.ctx.get("sessionPersistence");
2252
- - if (persistence === void 0) throw new SubagentError("continuable subagents require session persistence (load a dsh-session-persistence backend)", "PERSISTENCE_UNAVAILABLE");
2253
- - return persistence;
2254
- - }
2255
- - /** Resolve the Session query service used for cold child observations. */
2256
- - requireSessionQuery() {
2257
- - const query = this.ctx.get("sessionQuery");
2258
- - if (query === void 0) throw new SubagentError("continuable subagents require session query (load @deepseek-ai/dsh-session-query)", "CONTINUATION_UNAVAILABLE");
2259
- - return query;
2260
- - }
2261
- -};
2262
- -/** Creation-time selection precedes the own descriptor; historical forks can select after it. */
2263
- -function hasIndependentPresetSelection(events) {
2264
- - for (const event of events) {
2265
- - if (event.type === "subagent/descriptor") return false;
2266
- - if (event.type === "agent-preset/selected") return true;
2267
- - }
2268
- - /* v8 ignore next -- coldResume rejects logs without a supported own descriptor before this lookup. */
2269
- - return false;
2270
- -}
2271
- -//#endregion
2272
- -//#region lib/types/list-children.js
2273
- -/**
2274
- -* Direct-child and recursive descendant discovery from parent-owned catalogs.
2275
- -* Each catalog read releases its Session observation before the next branch.
2276
- -* @module @deepseek-ai/dsh-subagent
2277
- -*/
2278
- -var __addDisposableResource$1 = function(env, value, async) {
2279
- - if (value !== null && value !== void 0) {
2280
- - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
2281
- - var dispose, inner;
2282
- - if (async) {
2283
- - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
2284
- - dispose = value[Symbol.asyncDispose];
2285
- - }
2286
- - if (dispose === void 0) {
2287
- - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
2288
- - dispose = value[Symbol.dispose];
2289
- - if (async) inner = dispose;
2290
- - }
2291
- - if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
2292
- - if (inner) dispose = function() {
2293
- - try {
2294
- - inner.call(this);
2295
- - } catch (e) {
2296
- - return Promise.reject(e);
2297
- - }
2298
- - };
2299
- - env.stack.push({
2300
- - value,
2301
- - dispose,
2302
- - async
2303
- - });
2304
- - } else if (async) env.stack.push({ async: true });
2305
- - return value;
2306
- -};
2307
- -var __disposeResources$1 = (function(SuppressedError) {
2308
- - return function(env) {
2309
- - function fail(e) {
2310
- - env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
2311
- - env.hasError = true;
2312
- - }
2313
- - var r, s = 0;
2314
- - function next() {
2315
- - while (r = env.stack.pop()) try {
2316
- - if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
2317
- - if (r.dispose) {
2318
- - var result = r.dispose.call(r.value);
2319
- - if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
2320
- - fail(e);
2321
- - return next();
2322
- - });
2323
- - } else s |= 1;
2324
- - } catch (e) {
2325
- - fail(e);
2326
- - }
2327
- - if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
2328
- - if (env.hasError) throw env.error;
2329
- - }
2330
- - return next();
2331
- - };
2332
- -})(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
2333
- - var e = new Error(message);
2334
- - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
2335
- -});
2336
- -/**
2337
- -* Read one parent's durable catalog through a live-preferred Session observation.
2338
- -* @param ctx - context carrying the Session query service.
2339
- -* @param parentSessionId - parent whose direct children are requested.
2340
- -* @param signal - cancellation forwarded to the Session observation.
2341
- -* @returns direct-child rows in parent catalog event order.
2342
- -* @throws {@link SubagentError} when query or catalog projection is unavailable.
2343
- -*/
2344
- -async function listChildren(ctx, parentSessionId, signal) {
2345
- - const env_1 = {
2346
- - stack: [],
2347
- - error: void 0,
2348
- - hasError: false
2349
- - };
2350
- - try {
2351
- - const query = ctx.get("sessionQuery");
2352
- - if (query === void 0) throw new SubagentError("listing subagents requires the sessionQuery service (load @deepseek-ai/dsh-session-query)", "SUBAGENT_CONTROL_QUERY_UNAVAILABLE");
2353
- - const entries = __addDisposableResource$1(env_1, await query.observeSession(parentSessionId, { ...signal === void 0 ? {} : { signal } }), false).projections?.values.subagentCatalog;
2354
- - if (entries === void 0) throw new SubagentError("listing subagents requires the registered subagentCatalog projection", "SUBAGENT_CONTROL_PROJECTIONS_UNAVAILABLE");
2355
- - return entries;
2356
- - } catch (e_1) {
2357
- - env_1.error = e_1;
2358
- - env_1.hasError = true;
2359
- - } finally {
2360
- - __disposeResources$1(env_1);
2361
- - }
2362
- -}
2363
- -/**
2364
- -* Walk reachable parent catalogs in stable pre-order without loading Agents.
2365
- -* @see SubagentRuntime.listDescendants for failure and cancellation semantics.
2366
- -* @param ctx - context carrying the Session store and query service.
2367
- -* @param rootSessionId - parent whose catalog starts the traversal.
2368
- -* @param signal - cancellation checked around each catalog read.
2369
- -* @returns children and branch diagnostics with catalog parent and depth.
2370
- -*/
2371
- -async function listDescendants(ctx, rootSessionId, signal) {
2372
- - const sessions = ctx.get("sessions");
2373
- - if (sessions === void 0) throw new SubagentError("listing subagents requires the session store (load @deepseek-ai/dsh-session)", "SUBAGENT_CONTROL_SESSION_STORE_UNAVAILABLE");
2374
- - const readChildren = async (id) => {
2375
- - assertListingNotCancelled(signal);
2376
- - let children;
2377
- - try {
2378
- - children = await listChildren(ctx, id, signal);
2379
- - } catch (error) {
2380
- - assertListingNotCancelled(signal);
2381
- - throw error;
2382
- - }
2383
- - assertListingNotCancelled(signal);
2384
- - return children;
2385
- - };
2386
- - const stack = (await readChildren(rootSessionId)).map((entry) => ({
2387
- - entry,
2388
- - parentId: rootSessionId,
2389
- - depth: 1
2390
- - })).reverse();
2391
- - const visited = new Set([rootSessionId]);
2392
- - const result = [];
2393
- - for (let position = stack.pop(); position !== void 0; position = stack.pop()) {
2394
- - const { entry, parentId, depth } = position;
2395
- - if (visited.has(entry.id)) continue;
2396
- - visited.add(entry.id);
2397
- - let children;
2398
- - try {
2399
- - children = entry.mode === "external" ? [] : await readChildren(entry.id);
2400
- - } catch (error) {
2401
- - if (error instanceof SubagentError) throw error;
2402
- - const code = error instanceof Error && "code" in error ? error.code : void 0;
2403
- - result.push({
2404
- - kind: "diagnostic",
2405
- - id: entry.id,
2406
- - parentId,
2407
- - depth,
2408
- - reason: code === "SESSION_QUERY_CORRUPT_SESSION" || code === "SESSION_QUERY_SOURCE_CONFLICT" ? "corrupt" : "unavailable"
2409
- - });
2410
- - continue;
2411
- - }
2412
- - if (entry.mode === "unknown") result.push({
2413
- - kind: "diagnostic",
2414
- - id: entry.id,
2415
- - parentId,
2416
- - depth,
2417
- - reason: "unsupported"
2418
- - });
2419
- - else {
2420
- - const { createdAt: _createdAt, ...identity } = entry;
2421
- - result.push({
2422
- - ...identity,
2423
- - kind: "child",
2424
- - parentId,
2425
- - depth,
2426
- - activity: sessions.get(entry.id) === void 0 ? "inactive" : "running",
2427
- - hasChildren: children.length > 0
2428
- - });
2429
- - }
2430
- - for (const child of [...children].reverse()) stack.push({
2431
- - entry: child,
2432
- - parentId: entry.id,
2433
- - depth: depth + 1
2434
- - });
2435
- - }
2436
- - return result;
2437
- -}
2438
- -/** Stop the complete traversal when its caller cancels. */
2439
- -function assertListingNotCancelled(signal) {
2440
- - if (signal?.aborted) throw new SubagentError("subagent listing was cancelled", "CANCELLED");
2441
- -}
2442
- -//#endregion
2443
- -//#region lib/types/archive-admission.js
2444
- -/**
2445
- -* The `subagent` family of the Workspace registry's archive admission: which
2446
- -* subagent descendants of a Session are still inside a turn, and how they
2447
- -* stop when the Session is archived with its work.
2448
- -*
2449
- -* @module @deepseek-ai/dsh-subagent
2450
- -*/
2451
- -var __addDisposableResource = function(env, value, async) {
2452
- - if (value !== null && value !== void 0) {
2453
- - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
2454
- - var dispose, inner;
2455
- - if (async) {
2456
- - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
2457
- - dispose = value[Symbol.asyncDispose];
2458
- - }
2459
- - if (dispose === void 0) {
2460
- - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
2461
- - dispose = value[Symbol.dispose];
2462
- - if (async) inner = dispose;
2463
- - }
2464
- - if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
2465
- - if (inner) dispose = function() {
2466
- - try {
2467
- - inner.call(this);
2468
- - } catch (e) {
2469
- - return Promise.reject(e);
2470
- - }
2471
- - };
2472
- - env.stack.push({
2473
- - value,
2474
- - dispose,
2475
- - async
2476
- - });
2477
- - } else if (async) env.stack.push({ async: true });
2478
- - return value;
2479
- -};
2480
- -var __disposeResources = (function(SuppressedError) {
2481
- - return function(env) {
2482
- - function fail(e) {
2483
- - env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
2484
- - env.hasError = true;
2485
- - }
2486
- - var r, s = 0;
2487
- - function next() {
2488
- - while (r = env.stack.pop()) try {
2489
- - if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
2490
- - if (r.dispose) {
2491
- - var result = r.dispose.call(r.value);
2492
- - if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
2493
- - fail(e);
2494
- - return next();
2495
- - });
2496
- - } else s |= 1;
2497
- - } catch (e) {
2498
- - fail(e);
2499
- - }
2500
- - if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
2501
- - if (env.hasError) throw env.error;
2502
- - }
2503
- - return next();
2504
- - };
2505
- -})(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
2506
- - var e = new Error(message);
2507
- - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
2508
- -});
2509
- -/**
2510
- -* Answer `workspace/session-activity` with the running subagent descendants of
2511
- -* the asked Session, and `workspace/session-stop` by cancelling each of them
2512
- -* as their parent would. Both listeners live as long as `ctx`'s fiber.
2513
- -* @param ctx - context carrying the Agent registry; the Session query service is optional and only supplies labels.
2514
- -*/
2515
- -function installSubagentArchiveAdmission(ctx) {
2516
- - ctx.on("workspace/session-activity", async ({ sessionId }, next) => {
2517
- - const running = runningDescendants(ctx, sessionId);
2518
- - const rest = await next();
2519
- - if (running.length === 0) return rest;
2520
- - return [{
2521
- - kind: "subagent",
2522
- - items: await Promise.all(running.map((child) => describe(ctx, child)))
2523
- - }, ...rest];
2524
- - });
2525
- - ctx.on("workspace/session-stop", ({ sessionId }) => {
2526
- - for (const child of runningDescendants(ctx, sessionId)) try {
2527
- - child.cancel({ kind: "parent" });
2528
- - } catch (error) {
2529
- - ctx.logger.warn(`subagent: cancelling "${child.id}" for an archived Session failed: ${String(error)}`);
2530
- - }
2531
- - });
2532
- -}
2533
- -/**
2534
- -* Live subagent descendants inside a turn, by durable lineage: a child whose
2535
- -* header names its parent and carries the subagent origin this package
2536
- -* records, at any depth. A fork shares the lineage field without the origin
2537
- -* and is an independent conversation, so it never holds its source. Lineage
2538
- -* is read as data, so a damaged header chain that loops is visited once.
2539
- -*/
2540
- -function runningDescendants(ctx, rootId) {
2541
- - const childrenOf = /* @__PURE__ */ new Map();
2542
- - for (const agent of ctx.agents.list()) {
2543
- - const { parentSession, origin } = agent.session.header;
2544
- - if (parentSession === void 0 || origin !== "subagent") continue;
2545
- - const siblings = childrenOf.get(parentSession) ?? [];
2546
- - siblings.push(agent);
2547
- - childrenOf.set(parentSession, siblings);
2548
- - }
2549
- - const running = [];
2550
- - const pending = [rootId];
2551
- - const visited = /* @__PURE__ */ new Set();
2552
- - while (pending.length > 0) {
2553
- - const parentId = pending.shift();
2554
- - if (visited.has(parentId)) continue;
2555
- - visited.add(parentId);
2556
- - for (const child of childrenOf.get(parentId) ?? []) {
2557
- - if (child.status === "running") running.push(child);
2558
- - pending.push(child.id);
2559
- - }
2560
- - }
2561
- - return running;
2562
- -}
2563
- -/**
2564
- -* The child's activity item: its id, plus the durable creation label its
2565
- -* descriptor carries, read through a live Session observation. Without the
2566
- -* Session query service, or with a descriptor that is absent or unreadable,
2567
- -* the item names the child by id alone.
2568
- -*/
2569
- -async function describe(ctx, child) {
2570
- - const query = ctx.get("sessionQuery");
2571
- - if (query === void 0) return { id: child.id };
2572
- - try {
2573
- - const env_1 = {
2574
- - stack: [],
2575
- - error: void 0,
2576
- - hasError: false
2577
- - };
2578
- - try {
2579
- - const observation = __addDisposableResource(env_1, await query.observeSession(child.id, { projectionMode: "none" }), false);
2580
- - const label = foldSubagentDescriptor(observation.events.slice(observation.inheritedEventCount))?.label;
2581
- - return label === void 0 ? { id: child.id } : {
2582
- - id: child.id,
2583
- - label
2584
- - };
2585
- - } catch (e_1) {
2586
- - env_1.error = e_1;
2587
- - env_1.hasError = true;
2588
- - } finally {
2589
- - __disposeResources(env_1);
2590
- - }
2591
- - } catch {
2592
- - return { id: child.id };
2593
- - }
2594
- -}
2595
- -//#endregion
2596
- -//#region lib/types/projection.js
2597
- -/**
2598
- -* Pure session projections for subagent identity (mode/label) and active-turn
2599
- -* duration.
2600
- -*
2601
- -* @module @deepseek-ai/dsh-subagent/projection
2602
- -*/
2603
- -const activeIntervalSchema = z$1.object({
2604
- - since: z$1.number().int().nonnegative(),
2605
- - through: z$1.number().int().nonnegative()
2606
- -}).strict();
2607
- -const projectionSchema = z$1.object({
2608
- - settledMs: z$1.number().int().nonnegative(),
2609
- - active: activeIntervalSchema.optional(),
2610
- - lastTurnCompleted: z$1.boolean().optional()
2611
- -}).strict().transform(({ settledMs, active, lastTurnCompleted }) => ({
2612
- - settledMs,
2613
- - ...active === void 0 ? {} : { active },
2614
- - ...lastTurnCompleted === void 0 ? {} : { lastTurnCompleted }
2615
- -}));
2616
- -/**
2617
- -* Fold turn boundaries around the child's own durable descriptor.
2618
- -*
2619
- -* A fork seed may contain an ancestor descriptor and completed turns. Every
2620
- -* descriptor therefore resets the accumulated state; the healthy catalog
2621
- -* admits only a child with exactly one descriptor in its own suffix, making
2622
- -* the final reset the child's authoritative timing origin.
2623
- -*/
2624
- -const subagentTimingProjectionDefinition = {
2625
- - key: "subagentTiming",
2626
- - stateSchema: z$1.object({
2627
- - settledMs: z$1.number().int().nonnegative(),
2628
- - active: activeIntervalSchema.optional(),
2629
- - pendingTurnStart: z$1.number().int().nonnegative().optional(),
2630
- - descriptorSeen: z$1.boolean(),
2631
- - lastTurnCompleted: z$1.boolean().optional()
2632
- - }).strict(),
2633
- - init: () => ({
2634
- - descriptorSeen: false,
2635
- - settledMs: 0
2636
- - }),
2637
- - apply: (state, event) => {
2638
- - if (event.type === "turn/start") {
2639
- - const { lastTurnCompleted: _closed, ...openState } = state;
2640
- - return state.descriptorSeen ? {
2641
- - ...openState,
2642
- - active: {
2643
- - since: event.time,
2644
- - through: event.time
2645
- - }
2646
- - } : {
2647
- - ...openState,
2648
- - pendingTurnStart: event.time
2649
- - };
2650
- - }
2651
- - if (event.type === "subagent/descriptor") {
2652
- - const activeSince = state.active?.since ?? state.pendingTurnStart;
2653
- - return {
2654
- - descriptorSeen: true,
2655
- - settledMs: 0,
2656
- - ...activeSince === void 0 ? {} : { active: {
2657
- - since: activeSince,
2658
- - through: event.time
2659
- - } }
2660
- - };
2661
- - }
2662
- - if (event.type === "turn/end") {
2663
- - if (!state.descriptorSeen) {
2664
- - if (state.pendingTurnStart === void 0) return state;
2665
- - const { pendingTurnStart: _closed, ...next } = state;
2666
- - return next;
2667
- - }
2668
- - if (state.active === void 0) return state;
2669
- - const { active, ...rest } = state;
2670
- - return {
2671
- - ...rest,
2672
- - settledMs: state.settledMs + Math.max(0, event.time - active.since),
2673
- - lastTurnCompleted: event.data.reason.kind === "completed"
2674
- - };
2675
- - }
2676
- - if (state.active === void 0) return state;
2677
- - return {
2678
- - ...state,
2679
- - active: {
2680
- - ...state.active,
2681
- - through: event.time
2682
- - }
2683
- - };
2684
- - },
2685
- - wire: {
2686
- - viewSchema: projectionSchema,
2687
- - view: (state) => ({
2688
- - settledMs: state.settledMs,
2689
- - ...state.active === void 0 ? {} : { active: state.active },
2690
- - ...state.lastTurnCompleted === void 0 ? {} : { lastTurnCompleted: state.lastTurnCompleted }
2691
- - })
2692
- - },
2693
- - stateVersion: 3
2694
- -};
2695
- -const identityValueSchema = z$1.discriminatedUnion("mode", [z$1.object({
2696
- - mode: z$1.literal("one-shot"),
2697
- - label: z$1.string().optional(),
2698
- - seq: z$1.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).transform(SessionSeq)
2699
- -}).strict(), z$1.object({
2700
- - mode: z$1.literal("continuable"),
2701
- - label: z$1.string(),
2702
- - seq: z$1.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).transform(SessionSeq)
2703
- -}).strict()]);
2704
- -const identitySchema = identityValueSchema.nullable();
2705
- -const identityStateSchema = z$1.object({ identity: identityValueSchema.optional() }).strict();
2706
- -/** Interpret one `subagent/descriptor` event's identity; no value when the payload cannot be trusted. */
2707
- -function descriptorIdentity(event) {
2708
- - let descriptor;
2709
- - try {
2710
- - descriptor = foldSubagentDescriptor([event]);
2711
- - } catch {
2712
- - descriptor = void 0;
2713
- - }
2714
- - if (descriptor === void 0) return void 0;
2715
- - return descriptor.mode === "one-shot" ? {
2716
- - mode: "one-shot",
2717
- - ...descriptor.label !== void 0 ? { label: descriptor.label } : {},
2718
- - seq: event.seq
2719
- - } : {
2720
- - mode: "continuable",
2721
- - label: descriptor.label,
2722
- - seq: event.seq
2723
- - };
2724
- -}
2725
- -/**
2726
- -* Fold the durable mode/label identity from `subagent/descriptor` events,
2727
- -* last-wins: a fork seed may replay an ancestor's descriptor, and the child's
2728
- -* own descriptor must override it — the same reset discipline as
2729
- -* {@link subagentTimingProjectionDefinition}. A malformed or unknown-version
2730
- -* payload resets to the `null` sentinel instead of throwing, so a fork of a
2731
- -* healthy ancestor never inherits an identity its own descriptor failed to
2732
- -* establish — and the reset survives every JSON push frame, so a consumer
2733
- -* holding the earlier identity replaces it instead of keeping it stale;
2734
- -* `null` ⟺ no valid descriptor, with the causes deliberately undistinguished.
2735
- -*/
2736
- -const subagentIdentityProjectionDefinition = {
2737
- - key: "subagent",
2738
- - stateSchema: identityStateSchema,
2739
- - init: () => ({}),
2740
- - apply: (state, event) => {
2741
- - if (event.type !== "subagent/descriptor") return state;
2742
- - const identity = descriptorIdentity(event);
2743
- - return identity === void 0 ? {} : { identity };
2744
- - },
2745
- - wire: {
2746
- - viewSchema: identitySchema,
2747
- - view: (state) => state.identity ?? null
2748
- - },
2749
- - stateVersion: 2
2750
- -};
2751
- -//#endregion
2752
- -//#region lib/types/out-of-process.js
2753
- -/**
2754
- -* Provider-side vocabulary for OUT-OF-PROCESS subagent backends — the pieces
2755
- -* that enforce this seam's own contracts around a child in another process:
2756
- -* the no-capabilities advertisement, timing-bound validation, child
2757
- -* working-directory validation, the never-reject result settlement, and the standard
2758
- -* run-handle publication. Backends compose these with their own wire drivers;
2759
- -* the process machinery itself (spawn, env scrub, managed-range teardown)
2760
- -* belongs to the `dsh-subprocess` seam.
2761
- -*
2762
- -* @module @deepseek-ai/dsh-subagent/out-of-process
2763
- -*/
2764
- -/** Maximum UTF-8 size of {@link SubagentResult.diagnostic}. */
2765
- -const MAX_SUBAGENT_DIAGNOSTIC_BYTES = 4096;
2766
- -const DIAGNOSTIC_TRUNCATION_SUFFIX = "\n[diagnostic truncated]";
2767
- -const utf8Encoder = new TextEncoder();
2768
- -const utf8Decoder = new TextDecoder();
2769
- -/**
2770
- -* Limit provider-authored failure detail without splitting a UTF-8 sequence.
2771
- -* @param diagnostic - safe diagnostic text produced by the provider.
2772
- -* @returns the original text, or a visibly truncated value within the limit.
2773
- -*/
2774
- -function limitSubagentDiagnostic(diagnostic) {
2775
- - const bytes = utf8Encoder.encode(diagnostic);
2776
- - if (bytes.byteLength <= MAX_SUBAGENT_DIAGNOSTIC_BYTES) return diagnostic;
2777
- - let prefixBytes = MAX_SUBAGENT_DIAGNOSTIC_BYTES - utf8Encoder.encode(DIAGNOSTIC_TRUNCATION_SUFFIX).byteLength;
2778
- - while ((bytes[prefixBytes] & 192) === 128) prefixBytes -= 1;
2779
- - return utf8Decoder.decode(bytes.subarray(0, prefixBytes)) + DIAGNOSTIC_TRUNCATION_SUFFIX;
2780
- -}
2781
- -/** Enforce the byte limit on a provider-returned diagnostic. */
2782
- -function normalizeSubagentDiagnostic(result) {
2783
- - return result.diagnostic === void 0 ? result : {
2784
- - ...result,
2785
- - diagnostic: limitSubagentDiagnostic(result.diagnostic)
2786
- - };
2787
- -}
2788
- -/**
2789
- -* The capability advertisement of an out-of-process backend: NONE. A child in
2790
- -* another process cannot honor parent-enforced start features
2791
- -* (`agentOptions`/`agentPreset`/`outputSchema`/`maxDepth`), so the service rejects a
2792
- -* request needing any of them before `start` runs — never accepted-then-ignored.
2793
- -*/
2794
- -const NO_START_CAPABILITIES = Object.freeze({
2795
- - agentOptions: false,
2796
- - agentPreset: false,
2797
- - outputSchema: false,
2798
- - depthLimit: false
2799
- -});
2800
- -/**
2801
- -* Assert a configured timing bound is a positive finite number (it bounds a
2802
- -* teardown or shutdown wait; zero, negative, or NaN would skip or wedge it).
2803
- -* @param prefix - the consuming plugin's diagnostic prefix (e.g. `subagent-acp`).
2804
- -* @param name - the config field name, for the diagnostic.
2805
- -* @param value - the configured value.
2806
- -*/
2807
- -function assertPositiveFinite(prefix, name, value) {
2808
- - if (!Number.isFinite(value) || value <= 0) throw new Error(`${prefix}: ${name} must be a positive finite number`);
2809
- -}
2810
- -/**
2811
- -* Whether `path` names an existing directory the harness can ENTER. The
2812
- -* search-permission probe matters: `statSync().isDirectory()` is true for a
2813
- -* mode-600 directory, but a subprocess cwd needs `X_OK` or spawn fails EACCES.
2814
- -*/
2815
- -function isEnterableDirectory(path) {
2816
- - try {
2817
- - if (!statSync(path).isDirectory()) return false;
2818
- - accessSync(path, constants.X_OK);
2819
- - return true;
2820
- - } catch {
2821
- - return false;
2822
- - }
2823
- -}
2824
- -/**
2825
- -* Assert `cwd` can actually host the child: absolute (it doubles as the
2826
- -* child's workspace identity, and a relative path would be re-anchored to the
2827
- -* server process's launch directory) and an existing directory (fail here,
2828
- -* before the process boundary, instead of as an ambiguous spawn ENOENT).
2829
- -* @param prefix - the consuming plugin's diagnostic prefix.
2830
- -* @param label - which source supplied the value, for the diagnostic.
2831
- -* @param cwd - the candidate working directory.
2832
- -* @returns `cwd`, validated.
2833
- -*/
2834
- -function assertUsableCwd(prefix, label, cwd) {
2835
- - if (!isAbsolute(cwd)) throw new Error(`${prefix}: ${label} must be an absolute path: ${cwd}`);
2836
- - if (!isEnterableDirectory(cwd)) throw new Error(`${prefix}: ${label} is not an accessible directory: ${cwd}`);
2837
- - return cwd;
2838
- -}
2839
- -/** Normalize an unknown thrown value to an Error (the catch binding is `unknown`). */
2840
- -function toError(value) {
2841
- - /* v8 ignore next */
2842
- - return value instanceof Error ? value : new Error(String(value));
2843
- -}
2844
- -/**
2845
- -* Settle an out-of-process run result under the seam contract: `result` never
2846
- -* rejects after publication. A normally completed or rejected attempt resolves
2847
- -* as `aborted` when cancellation already settled locally; another rejection is
2848
- -* flattened to `stopReason: 'error'` through the contained diagnostic sink.
2849
- -* Provider-returned diagnostics use the same byte limit. The abort listener is
2850
- -* removed on every path.
2851
- -* @param parts - the attempt, output snapshot, cancellation state, sink, and signal wiring.
2852
- -* @returns the terminal result (never a rejection).
2853
- -*/
2854
- -async function settleRunResult(parts) {
2855
- - try {
2856
- - const result = await parts.attempt();
2857
- - return parts.cancelled() ? {
2858
- - output: parts.collectOutput(),
2859
- - stopReason: "aborted"
2860
- - } : normalizeSubagentDiagnostic(result);
2861
- - } catch (error) {
2862
- - if (parts.cancelled()) return {
2863
- - output: parts.collectOutput(),
2864
- - stopReason: "aborted"
2865
- - };
2866
- - try {
2867
- - parts.onError?.(toError(error), "error");
2868
- - } catch {}
2869
- - const collected = parts.collectDiagnostic?.();
2870
- - const diagnostic = collected === void 0 ? void 0 : limitSubagentDiagnostic(collected);
2871
- - return {
2872
- - output: parts.collectOutput(),
2873
- - ...diagnostic === void 0 ? {} : { diagnostic },
2874
- - stopReason: "error"
2875
- - };
2876
- - } finally {
2877
- - parts.signal.removeEventListener("abort", parts.onAbort);
2878
- - }
2879
- -}
2880
- -/**
2881
- -* Publish the seam run handle for an out-of-process child. `dispose()` is
2882
- -* idempotent (one memoized teardown): it removes the abort listener, settles
2883
- -* local cancellation — there is no assumption the child cooperates — and then
2884
- -* awaits the backend's teardown to actual exit.
2885
- -* @param parts - the run identity, result, cancellation wiring, and teardown.
2886
- -* @returns the external run handle.
2887
- -*/
2888
- -function subprocessRunHandle(parts) {
2889
- - let disposal;
2890
- - return {
2891
- - id: parts.id,
2892
- - result: parts.result,
2893
- - dispose() {
2894
- - if (disposal !== void 0) return disposal;
2895
- - parts.signal.removeEventListener("abort", parts.onAbort);
2896
- - parts.requestCancel();
2897
- - disposal = parts.teardown();
2898
- - return disposal;
2899
- - }
2900
- - };
2901
- -}
2902
- -//#endregion
2903
- -//#region lib/types/index.js
2904
- -var __runInitializers = function(thisArg, initializers, value) {
2905
- - var useValue = arguments.length > 2;
2906
- - for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
2907
- - return useValue ? value : void 0;
2908
- -};
2909
- -var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
2910
- - function accept(f) {
2911
- - if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
2912
- - return f;
2913
- - }
2914
- - var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
2915
- - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
2916
- - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
2917
- - var _, done = false;
2918
- - for (var i = decorators.length - 1; i >= 0; i--) {
2919
- - var context = {};
2920
- - for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
2921
- - for (var p in contextIn.access) context.access[p] = contextIn.access[p];
2922
- - context.addInitializer = function(f) {
2923
- - if (done) throw new TypeError("Cannot add initializers after decoration has completed");
2924
- - extraInitializers.push(accept(f || null));
2925
- - };
2926
- - var result = (0, decorators[i])(kind === "accessor" ? {
2927
- - get: descriptor.get,
2928
- - set: descriptor.set
2929
- - } : descriptor[key], context);
2930
- - if (kind === "accessor") {
2931
- - if (result === void 0) continue;
2932
- - if (result === null || typeof result !== "object") throw new TypeError("Object expected");
2933
- - if (_ = accept(result.get)) descriptor.get = _;
2934
- - if (_ = accept(result.set)) descriptor.set = _;
2935
- - if (_ = accept(result.init)) initializers.unshift(_);
2936
- - } else if (_ = accept(result)) if (kind === "field") initializers.unshift(_);
2937
- - else descriptor[key] = _;
2938
- - }
2939
- - if (target) Object.defineProperty(target, contextIn.name, descriptor);
2940
- - done = true;
2941
- -};
2942
- -/** Named provider registry with managed activations, durable discovery, and local child messaging. */
2943
- -let SubagentRuntime = (() => {
2944
- - let _classSuper = TypertRemoteService;
2945
- - let _instanceExtraInitializers = [];
2946
- - let _prompt_decorators;
2947
- - let _interruptByParent_decorators;
2948
- - return class SubagentRuntime extends _classSuper {
2949
- - static {
2950
- - const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
2951
- - _prompt_decorators = [Remote("prompt")];
2952
- - _interruptByParent_decorators = [Remote("interruptByParent")];
2953
- - __esDecorate(this, null, _prompt_decorators, {
2954
- - kind: "method",
2955
- - name: "prompt",
2956
- - static: false,
2957
- - private: false,
2958
- - access: {
2959
- - has: (obj) => "prompt" in obj,
2960
- - get: (obj) => obj.prompt
2961
- - },
2962
- - metadata: _metadata
2963
- - }, null, _instanceExtraInitializers);
2964
- - __esDecorate(this, null, _interruptByParent_decorators, {
2965
- - kind: "method",
2966
- - name: "interruptByParent",
2967
- - static: false,
2968
- - private: false,
2969
- - access: {
2970
- - has: (obj) => "interruptByParent" in obj,
2971
- - get: (obj) => obj.interruptByParent
2972
- - },
2973
- - metadata: _metadata
2974
- - }, null, _instanceExtraInitializers);
2975
- - if (_metadata) Object.defineProperty(this, Symbol.metadata, {
2976
- - enumerable: true,
2977
- - configurable: true,
2978
- - writable: true,
2979
- - value: _metadata
2980
- - });
2981
- - }
2982
- - config = __runInitializers(this, _instanceExtraInitializers);
2983
- - static Config = z.object({
2984
- - maxDepth: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(1).volatile(),
2985
- - maxActiveSubagents: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(8).volatile()
2986
- - });
2987
- - static inject = ["workingDirectory"];
2988
- - providers = /* @__PURE__ */ new Map();
2989
- - manager;
2990
- - /**
2991
- - * The contained lifecycle-edge publisher. Built here because scoped dispatch
2992
- - * keys its carrier by this exact service instance, whose own context filter
2993
- - * composes into the carrier.
2994
- - */
2995
- - emitLifecycle;
2996
- - constructor(ctx, config) {
2997
- - super(ctx, "subagents");
2998
- - this.config = config;
2999
- - this.emitLifecycle = createLifecycleEmitter(this.ctx, (parent) => scopeTarget(this, parent));
3000
- - ctx.inject(["agents"], (childCtx) => {
3001
- - const manager = new SubagentManager(childCtx, {
3002
- - startExternal: (name, request) => {
3003
- - return this.expectProvider(name).start(request);
3004
- - },
3005
- - prepareContinuable: (name, request) => this.prepareContinuable(name, request),
3006
- - observeActivation: (provider, childId, parent) => this.observeActivation(provider, childId, parent)
3007
- - }, () => this.config.maxActiveSubagents.get());
3008
- - this.manager = manager;
3009
- - childCtx.effect(() => () => {
3010
- - /* v8 ignore else -- one injected binding owns the slot until its fiber disposes. */
3011
- - if (this.manager === manager) this.manager = void 0;
3012
- - }, "subagents.managerBinding()");
3013
- - });
3014
- - ctx.inject(["sessionProjections"], (projectionCtx) => {
3015
- - projectionCtx.sessionProjections.register(subagentCatalogProjectionDefinition);
3016
- - projectionCtx.sessionProjections.register(subagentTimingProjectionDefinition);
3017
- - projectionCtx.sessionProjections.register(subagentIdentityProjectionDefinition);
3018
- - });
3019
- - ctx.inject(["agents"], (agentsCtx) => {
3020
- - installSubagentArchiveAdmission(agentsCtx);
3021
- - });
3022
- - }
3023
- - /**
3024
- - * Resolve a delegation tool's depth policy against the current user setting.
3025
- - * @param configured - Explicit tool limit, or provider-managed for external delegation.
3026
- - * @returns The numeric limit, or undefined when the provider owns depth enforcement.
3027
- - */
3028
- - resolveMaxDepth(configured) {
3029
- - if (configured === "provider-managed") return void 0;
3030
- - if (configured !== void 0) return configured;
3031
- - const depth = this.config.maxDepth.get();
3032
- - assertSubagentMaxDepth(depth);
3033
- - return depth;
3034
- - }
3035
- - /**
3036
- - * Establish a managed child with backend-specific execution capabilities.
3037
- - * @param spec - task, backend, and result recipient.
3038
- - * @returns identities, execution result, and exact-activation disposal. A reserved
3039
- - * childId requires a local backend and guarantees an accepted messageId.
3040
- - */
3041
- - async startActivation(spec) {
3042
- - const provider = this.expectProvider(spec.provider);
3043
- - if (spec.childId !== void 0 && provider.prepareContinuable === void 0) throw new SubagentError("reserved child ids require a local backend", "UNSUPPORTED_CAPABILITY");
3044
- - assertSubagentMaxDepth(spec.request.maxDepth);
3045
- - this.assertCapabilities(provider, {
3046
- - ...spec.request,
3047
- - signal: spec.signal
3048
- - });
3049
- - const manager = this.requireManager();
3050
- - if (this.ctx.get("agents")?.get(spec.request.parent.id) !== spec.request.parent) throw new SubagentError("subagent creation requires the exact live parent agent", "UNAUTHORIZED");
3051
- - if (spec.request.outputSchema !== void 0) assertObjectJsonSchema(spec.request.outputSchema);
3052
- - return provider.prepareContinuable === void 0 ? manager.startExternal(spec) : manager.startLocal(spec);
3053
- - }
3054
- - /**
3055
- - * Join progressing descendants without cancelling them. Idle descendants whose
3056
- - * inboxes require a later wake stay resident and do not delay host completion.
3057
- - * @param parent - the exact parent whose descendant work is observed.
3058
- - * @returns whether work was joined; hosts recheck parent idle after true.
3059
- - */
3060
- - async waitForChildren(parent) {
3061
- - return this.manager?.waitForChildren(parent) ?? false;
3062
- - }
3063
- - /**
3064
- - * Steer one model-authored message to the sender's direct parent or direct
3065
- - * continuable child. A running target admits it at the nearest step boundary;
3066
- - * an idle target starts a turn, and an absent direct child cold-resumes from
3067
- - * persistence. The service derives durable sender attribution from the exact
3068
- - * live sender. Caller cancellation stops only pre-acceptance work.
3069
- - * @param sender - exact live Agent authorizing and originating the message.
3070
- - * @param targetId - durable direct-parent or direct-child session id.
3071
- - * @param content - model-authored content to deliver.
3072
- - * @param options - caller cancellation before inbox acceptance.
3073
- - * @returns the accepted message's inbox id.
3074
- - * @throws when continuation services are unavailable, adjacency is rejected,
3075
- - * or the message was not admitted.
3076
- - */
3077
- - async sendMessage(sender, targetId, content, options) {
3078
- - return this.requireManager().sendMessage(sender, targetId, content, options);
3079
- - }
3080
- - /**
3081
- - * Deliver one host-protocol message to a direct continuable child.
3082
- - * Symbol-keyed so host adapters can preserve their own source descriptors without
3083
- - * widening the public Service Definition or impersonating an Agent sender.
3084
- - * @param parent - exact live direct parent authorizing delivery.
3085
- - * @param childId - durable direct-child session id.
3086
- - * @param content - host-authored content to deliver.
3087
- - * @param source - durable host-protocol source descriptor.
3088
- - * @param signal - caller cancellation before inbox acceptance.
3089
- - * @param delivery - Queue as a distinct turn or Steer at the nearest step.
3090
- - * @returns the accepted message's inbox id.
3091
- - */
3092
- - [deliverSubagentPrompt](parent, childId, content, source, signal, delivery) {
3093
- - return delivery === "steer" ? this.requireManager().steerPrompt(parent, childId, content, source, signal) : this.requireManager().queuePrompt(parent, childId, content, source, signal);
3094
- - }
3095
- - /**
3096
- - * Interrupt one live child's current execution under a human parent
3097
- - * address or an exact live ancestor Agent. Fire-and-return: the cancel
3098
- - * signal is issued before this returns, but the target may keep running
3099
- - * until it observes the signal. Unclaimed pending inbox work, the Activation,
3100
- - * and published descendants are preserved; claimed work is not requeued.
3101
- - * Once the interrupted Agent is idle, a waking send resumes the parked FIFO
3102
- - * queue. External backends stop their single execution. An absent target
3103
- - * is an accepted no-op, as is a manager-less composition, which cannot own a
3104
- - * live Activation.
3105
- - * @param targetSessionId - the durable child session id to interrupt.
3106
- - * @param authority - the human parent address or exact live ancestor Agent.
3107
- - * @throws {SubagentError} `UNAUTHORIZED` when the authority does not own the
3108
- - * live target.
3109
- - */
3110
- - interrupt(targetSessionId, authority) {
3111
- - this.manager?.interrupt(targetSessionId, authority);
3112
- - }
3113
- - /**
3114
- - * Close subagent admission below exact live parent Agents, stop only their
3115
- - * visible descendant Activations synchronously, then await admitted scoped
3116
- - * materializations and release those forests child-first. The scoped cutoff
3117
- - * lasts until each exact parent leaves the registry; unrelated parent trees
3118
- - * remain live.
3119
- - * @param parents - exact host-owned parent Agents entering teardown.
3120
- - * @returns once every retained descendant activation released its execution handle.
3121
- - * @throws an aggregate error after all branches settle when any failed.
3122
- - */
3123
- - async drainDescendants(parents) {
3124
- - const manager = this.manager;
3125
- - if (manager === void 0) return;
3126
- - await manager.drainDescendants(parents);
3127
- - }
3128
- - /**
3129
- - * Release selected resident direct children of one exact live
3130
- - * parent. Other children of the same parent remain admitted and resident.
3131
- - * Absent targets and a manager-less composition are accepted no-ops.
3132
- - * @param parent - exact live direct parent authorizing the selected release.
3133
- - * @param childIds - durable direct-child ids to release when resident.
3134
- - * @returns once every selected activation released its execution handle.
3135
- - * @throws {SubagentError} `UNAUTHORIZED` when a resident target belongs to a
3136
- - * different parent or the supplied parent identity is stale.
3137
- - */
3138
- - async drainChildren(parent, childIds) {
3139
- - const manager = this.manager;
3140
- - if (manager === void 0) return;
3141
- - await manager.drainChildren(parent, childIds);
3142
- - }
3143
- - /**
3144
- - * Read the parent's durable direct-child catalog without loading or resuming an Agent.
3145
- - * The service owns and releases the live-preferred Session observation.
3146
- - * @param parentSessionId - parent whose direct children are requested.
3147
- - * @param signal - cancellation forwarded to the Session query.
3148
- - * @returns catalog children in parent event order.
3149
- - * @throws {@link SubagentError} when query or catalog projection is unavailable.
3150
- - * @throws SessionQueryError when the parent cannot be read or the query is cancelled.
3151
- - */
3152
- - listChildren(parentSessionId, signal) {
3153
- - return listChildren(this.ctx, parentSessionId, signal);
3154
- - }
3155
- - /**
3156
- - * Recursively list reachable parent catalogs in stable pre-order, preserving
3157
- - * each catalog's event order. Each row carries its catalog parent and depth;
3158
- - * external children are leaves; one-shot and unknown-mode children remain
3159
- - * traversal nodes. Unknown modes
3160
- - * produce unsupported diagnostics. Unreadable child catalogs produce corrupt
3161
- - * or unavailable diagnostics and stop only that branch. Root read failures,
3162
- - * missing services or projections, and cancellation reject the whole listing.
3163
- - * Each catalog is observed once and released before the next read. No Agent
3164
- - * is loaded or resumed; Sessions absent from reachable catalogs are omitted.
3165
- - * @param rootSessionId - session whose catalog starts descendant discovery.
3166
- - * @param signal - cancellation forwarded to and checked around each catalog read.
3167
- - * @returns children and branch diagnostics in parent-catalog pre-order.
3168
- - * @throws {@link SubagentError} when listing dependencies are unavailable or the caller cancels.
3169
- - * @throws SessionQueryError when the root catalog cannot be read.
3170
- - */
3171
- - listDescendants(rootSessionId, signal) {
3172
- - return listDescendants(this.ctx, rootSessionId, signal);
3173
- - }
3174
- - /**
3175
- - * Deliver one browser-authored message to a continuable child through the
3176
- - * exact live direct parent, retaining the caller-minted request identity and
3177
- - * validated browser zone on the accepted message. Success identifies the
3178
- - * message the child's inbox accepted; later execution is independent of this
3179
- - * call. Queue delivery targets a later turn; steer delivery targets the
3180
- - * nearest step and retains the Agent loop's best-effort fallback semantics.
3181
- - * Image parts are admitted and persisted through the attachment store
3182
- - * before delivery, and the child's model must accept image input.
3183
- - * Cold resume at capacity rejects with `subagent/delivery-unavailable`.
3184
- - * @param request - durable address, delivery, minted identity, content, and optional browser zone.
3185
- - * @param signal - carrier cancellation, owning the call until inbox acceptance.
3186
- - * @returns the accepted message's inbox identity.
3187
- - * @throws {RemoteError} `gateway/bad-request`, `subagent/attachment-invalid`,
3188
- - * `subagent/invalid-time-zone`, `subagent/parent-unavailable`,
3189
- - * `subagent/not-resumable`, `subagent/unauthorized`,
3190
- - * `subagent/delivery-unavailable`, `gateway/cancelled`, or `gateway/internal`.
3191
- - */
3192
- - async prompt(request, signal) {
3193
- - const { parentSessionId, childSessionId, clientTimeZone, delivery } = request;
3194
- - validateControlRequest("subagent.prompt", request);
3195
- - const canonicalTimeZone = clientTimeZone === void 0 ? void 0 : canonicalClientTimeZone(clientTimeZone);
3196
- - if (clientTimeZone !== void 0 && canonicalTimeZone === void 0) throw new RemoteError("subagent/invalid-time-zone", "clientTimeZone must be UTC or a valid IANA Area/Location name", { value: clientTimeZone });
3197
- - const parent = this.ctx.get("agents")?.get(parentSessionId);
3198
- - if (parent === void 0) throw new RemoteError("subagent/parent-unavailable", `parent session "${parentSessionId}" is not live`, { parentSessionId });
3199
- - const principal = principalOf(this.ctx.invocation);
3200
- - const source = {
3201
- - kind: "user",
3202
- - rpcId: request.requestId,
3203
- - ...canonicalTimeZone === void 0 ? {} : { clientTimeZone: canonicalTimeZone },
3204
- - ...principal === void 0 ? {} : { principal }
3205
- - };
3206
- - try {
3207
- - let content;
3208
- - if (request.content.every((part) => part.type === "text")) content = request.content.map((part) => ({
3209
- - type: "text",
3210
- - text: part.text
3211
- - }));
3212
- - else {
3213
- - const attachments = this.ctx.get("attachments");
3214
- - if (attachments === void 0) throw new Error("subagent image prompt requires an attachment store");
3215
- - content = await attachments.admitPromptContent(request.content);
3216
- - }
3217
- - return { messageId: await this[deliverSubagentPrompt](parent, childSessionId, content, source, signal, delivery) };
3218
- - } catch (error) {
3219
- - return rejectPrompt(error, childSessionId, signal);
3220
- - }
3221
- - }
3222
- - /**
3223
- - * Remote face of {@link interrupt} under one durable parent address. No
3224
- - * catalog, history, persistence, or parent Agent lookup runs: the core
3225
- - * primitive alone authorizes the address against the live Activation, which
3226
- - * is what keeps a live child interruptible while its parent Agent is offline.
3227
- - * Absent, idle, and already-completed targets are accepted no-ops there.
3228
- - * @param childSessionId - durable child session id to interrupt.
3229
- - * @param parentSessionId - durable direct parent whose authority is claimed.
3230
- - * @param mode - required continuable-address discriminator.
3231
- - * @returns acknowledgement that the cancel signal was admitted, not that the target is quiescent.
3232
- - * @throws {RemoteError} `gateway/bad-request` for an empty id,
3233
- - * `subagent/unauthorized` when the address does not own the live target,
3234
- - * otherwise `gateway/internal`.
3235
- - */
3236
- - interruptByParent(childSessionId, parentSessionId, mode) {
3237
- - validateControlRequest("subagent.interrupt", {
3238
- - childSessionId,
3239
- - parentSessionId,
3240
- - mode
3241
- - });
3242
- - try {
3243
- - this.interrupt(childSessionId, {
3244
- - kind: "user",
3245
- - parentSessionId
3246
- - });
3247
- - } catch (error) {
3248
- - if (error instanceof SubagentError && error.code === "UNAUTHORIZED") throw new RemoteError("subagent/unauthorized", "subagent does not belong to this parent", { childSessionId }, { cause: error });
3249
- - throw new RemoteError("gateway/internal", "subagent interrupt failed", {}, { cause: error });
3250
- - }
3251
- - return { accepted: true };
3252
- - }
3253
- - /**
3254
- - * Register a provider under its name. Registration is effect-scoped and HMR
3255
- - * safe; removing a provider blocks new starts but does not revoke runs that
3256
- - * were already returned to their holders. Providers without either execution
3257
- - * method are rejected with UNSUPPORTED_CAPABILITY before registration.
3258
- - * @param provider - the trusted provider implementation.
3259
- - * @returns the exact Cordis effect disposer.
3260
- - */
3261
- - registerProvider(provider) {
3262
- - const name = provider.name;
3263
- - if (provider.start === void 0 && provider.prepareContinuable === void 0) throw new SubagentError(`subagent provider "${name}" must implement start or prepareContinuable`, "UNSUPPORTED_CAPABILITY");
3264
- - return this.ctx.effect(function* () {
3265
- - if (this.providers.has(name)) throw new SubagentError(`a subagent provider named "${name}" is already registered`, "DUPLICATE_PROVIDER");
3266
- - this.providers.set(name, provider);
3267
- - yield () => {
3268
- - this.providers.delete(name);
3269
- - this.emitLifecycle("subagent/provider-removed", name);
3270
- - };
3271
- - this.ctx.emit("subagent/provider-added", provider);
3272
- - }.bind(this), "subagents.registerProvider()");
3273
- - }
3274
- - /**
3275
- - * Look up a provider by name.
3276
- - * @param name - the provider name.
3277
- - * @returns the provider, or undefined when absent.
3278
- - */
3279
- - getProvider(name) {
3280
- - return this.providers.get(name);
3281
- - }
3282
- - /**
3283
- - * List registered provider names in insertion order.
3284
- - * @returns the registered names.
3285
- - */
3286
- - list() {
3287
- - return [...this.providers.keys()];
3288
- - }
3289
- - /**
3290
- - * Resolve one provider's detached continuable-creation contribution. Method
3291
- - * presence on the provider IS the capability, so a provider without it is
3292
- - * rejected before the manager reserves any child resources.
3293
- - */
3294
- - async prepareContinuable(name, request) {
3295
- - return this.expectProvider(name).prepareContinuable(request);
3296
- - }
3297
- - /** Look up a provider for dispatch or fail loud. */
3298
- - expectProvider(name) {
3299
- - const provider = this.providers.get(name);
3300
- - if (provider === void 0) throw new SubagentError(`no subagent provider registered for "${name}"`, "NO_PROVIDER");
3301
- - return provider;
3302
- - }
3303
- - /** Resolve the subagent manager or fail loud. */
3304
- - requireManager() {
3305
- - if (this.manager === void 0) throw new SubagentError("continuable subagents require the agents service", "CONTINUATION_UNAVAILABLE");
3306
- - return this.manager;
3307
- - }
3308
- - /**
3309
- - * Build the lifecycle observer for one continuable Activation's residency
3310
- - * epoch, so the manager publishes its edges without owning event dispatch.
3311
- - */
3312
- - observeActivation(provider, childId, parent) {
3313
- - return createActivationObserver(this.emitLifecycle, provider, childId, parent);
3314
- - }
3315
- - /** Reject the first requested capability that the provider lacks. */
3316
- - assertCapabilities(provider, request) {
3317
- - if (request.agentPreset !== void 0 && (!provider.capabilities.agentPreset || provider.inheritsParentContext)) throw new SubagentError(`subagent provider "${provider.name}" does not support independent agent preset selection`, "UNSUPPORTED_CAPABILITY");
3318
- - const needs = [
3319
- - {
3320
- - when: request.agentOptions !== void 0,
3321
- - cap: "agentOptions"
3322
- - },
3323
- - {
3324
- - when: request.outputSchema !== void 0,
3325
- - cap: "outputSchema"
3326
- - },
3327
- - {
3328
- - when: request.maxDepth !== void 0,
3329
- - cap: "depthLimit"
3330
- - }
3331
- - ];
3332
- - for (const { when, cap } of needs) if (when && !provider.capabilities[cap]) throw new SubagentError(`subagent provider "${provider.name}" does not support the "${cap}" capability`, "UNSUPPORTED_CAPABILITY");
3333
- - }
3334
- - };
3335
- -})();
3336
- -//#endregion
3337
- -export { AssistantOutputFold, NO_START_CAPABILITIES, STRUCTURED_OUTPUT_TOOL, SUBAGENT_DESCRIPTOR_VERSION, SubagentDepthError, SubagentError, SubagentRunId, SubagentRuntime, SubagentRuntime as default, appendDelegatedPolicyOverrides, applyChildComposition, assertPositiveFinite, assertSubagentMaxDepth, assertUsableCwd, captureDelegatedPolicyOverrides, childSessionMeta, delegationDepthOf, finalAssistantOutput, foldSubagentDescriptor, parentAgentOptionsForDelegation, resolveChildAgentOptions, resolveChildDepth, settleRunResult, snapshotSubagentDescriptor, subprocessRunHandle };
3338
- +import z4 from"@deepseek-ai/schemastery";import{scopeTarget}from"@deepseek-ai/dsh-scope";import{assertObjectJsonSchema}from"@deepseek-ai/dsh-tools";import{canonicalClientTimeZone}from"@deepseek-ai/dsh-util-time";import{Remote,RemoteError as RemoteError2,TypertRemoteService,principalOf}from"@deepseek-ai/dsh-typert-protocol";import{AttachmentError}from"@deepseek-ai/dsh-attachment";import{RemoteError}from"@deepseek-ai/dsh-typert-protocol";import{z}from"zod";import{HarnessError}from"@deepseek-ai/dsh-llm";var SubagentError=class extends HarnessError{constructor(message,code,options){super(message,code,options);this.name="SubagentError"}};var SESSION_ID_SCHEMA=z.string().min(1);var CONTROL_ID_SCHEMAS={"subagent.prompt":z.object({parentSessionId:SESSION_ID_SCHEMA,childSessionId:SESSION_ID_SCHEMA,mode:z.literal("continuable"),delivery:z.enum(["queue","steer"])}),"subagent.interrupt":z.object({parentSessionId:SESSION_ID_SCHEMA,childSessionId:SESSION_ID_SCHEMA,mode:z.literal("continuable")})};function validateControlRequest(method,payload){const parsed=CONTROL_ID_SCHEMAS[method].safeParse(payload);if(!parsed.success){throw new RemoteError("gateway/bad-request",`invalid payload for ${method}`,{issues:parsed.error.issues})}}function rejectPrompt(error,childSessionId,signal){if(isCancellation(error,signal)){throw new RemoteError("gateway/cancelled","subagent prompt was cancelled",{},{cause:error})}if(error instanceof AttachmentError){throw new RemoteError("subagent/attachment-invalid",error.message,{reason:error.code},{cause:error})}if(error instanceof SubagentError){switch(error.code){case"MODEL_DOES_NOT_SUPPORT_IMAGES":throw new RemoteError("subagent/attachment-invalid",error.message,{reason:error.code},{cause:error});case"NOT_RESUMABLE":throw new RemoteError("subagent/not-resumable","subagent cannot be resumed",{childSessionId},{cause:error});case"UNAUTHORIZED":throw new RemoteError("subagent/unauthorized","subagent does not belong to this parent",{childSessionId},{cause:error});case"DRAINING":case"ACTIVATION_CLOSING":case"ACTIVATION_LIMIT_REACHED":case"CONTINUATION_UNAVAILABLE":case"PERSISTENCE_UNAVAILABLE":throw new RemoteError("subagent/delivery-unavailable","subagent follow-up is temporarily unavailable",{childSessionId},{cause:error});default:break}}throw new RemoteError("gateway/internal","subagent prompt failed",{},{cause:error})}function isCancellation(error,signal){return signal.aborted||error instanceof SubagentError&&error.code==="CANCELLED"}function delegationDepthOf(agent){const runtime=agent.options.subagentDepth;if(runtime!==void 0&&(!Number.isSafeInteger(runtime)||runtime<0||Object.is(runtime,-0))){throw new TypeError("agent subagentDepth must be a non-negative safe integer")}return Math.max(agent.session.header.delegationDepth??0,runtime??0)}function assertSubagentMaxDepth(maxDepth){if(maxDepth!==void 0&&(typeof maxDepth!=="number"||!Number.isSafeInteger(maxDepth)||maxDepth<0||Object.is(maxDepth,-0))){throw new TypeError("subagent maxDepth must be a non-negative safe integer")}}import{randomUUID}from"node:crypto";import{foldConsumedWork}from"@deepseek-ai/dsh-agent";function SubagentRunId(id){return id}function createLifecycleEmitter(ctx,carrier){return(name,info,parent)=>{const dispatchArgs=parent===void 0?[name,info]:[carrier(parent),name,info];for(const callback of ctx.events.dispatch("emit",dispatchArgs)){try{const returned=callback(info);void Promise.resolve(returned).catch(error=>{ctx.logger.warn(`subagent: ${name} listener rejected: ${renderThrown(error)}`)})}catch(error){ctx.logger.warn(`subagent: ${name} listener threw: ${renderThrown(error)}`)}}}}function createActivationObserver(emit,provider,childId,parent){const identity={runId:SubagentRunId(randomUUID()),provider,id:childId,local:false};return{start:child=>{identity.local=child!==void 0;emit("subagent/start",identity,parent)},settle:({stopReason,output})=>{emit("subagent/end",{...identity,stopReason,...output.length===0?{}:{lastAssistantMessage:output}},parent)}}}function epochStopReason(events){const{end,droppedUnrun}=foldConsumedWork(events);switch(end?.data.reason.kind){case"max-tokens":return"max-tokens";case"aborted":case"interrupted":return"aborted";case"error":return"error";case"blocked":return"refusal";case void 0:case"completed":return droppedUnrun?"aborted":"completed";default:return"error"}}function renderThrown(value){try{return value instanceof Error?`${value.name}: ${value.message}`:String(value)}catch{return"<unrenderable thrown value>"}}import{randomUUID as randomUUID2}from"node:crypto";import{isAbsolute,resolve}from"node:path";import{brandString}from"@deepseek-ai/dsh-brand";import{ReasoningEffortId,contentHasImage,createUserMessage as createUserMessage2,errorChain}from"@deepseek-ai/dsh-llm";import{SessionLogOffset}from"@deepseek-ai/dsh-session";var SubagentDepthError=class extends Error{attemptedDepth;maxDepth;constructor(attemptedDepth,maxDepth){super(`subagent depth ${attemptedDepth} exceeds maxDepth ${maxDepth}`);this.attemptedDepth=attemptedDepth;this.maxDepth=maxDepth;this.name="SubagentDepthError"}};function resolveChildDepth(parent,maxDepth){const childDepth=delegationDepthOf(parent)+1;if(!Number.isSafeInteger(childDepth)){throw new RangeError("subagent child depth exceeds the safe-integer range")}if(maxDepth!==void 0&&childDepth>maxDepth){throw new SubagentDepthError(childDepth,maxDepth)}return childDepth}function parentAgentOptionsForDelegation(parent){const requestConfig=parent.session.requestHeader()?.config;if(requestConfig===void 0)return{...parent.options};const{provider:_createdProvider,model:_createdModel,reasoningEffort:_createdReasoningEffort,...createdOptions}=parent.options;return{...createdOptions,provider:requestConfig.provider,model:requestConfig.model,...requestConfig.reasoningEffort===void 0?{}:{reasoningEffort:requestConfig.reasoningEffort}}}function resolveChildAgentOptions(parent,requested,childDepth){const parentOptions=parentAgentOptionsForDelegation(parent);const parentProvider=parentOptions.provider;const parentModel=parentOptions.model;const parentReasoningEffort=parentOptions.reasoningEffort;const parentMaxTokens=parentOptions.maxTokens;const resolved={...parentProvider!==void 0?{provider:parentProvider}:{},...parentModel!==void 0?{model:parentModel}:{},...parentReasoningEffort!==void 0?{reasoningEffort:parentReasoningEffort}:{},...parentMaxTokens!==void 0?{maxTokens:parentMaxTokens}:{},...requested,subagentDepth:childDepth};const routeChanged=resolved.provider!==parentProvider||resolved.model!==parentModel;if(routeChanged&&requested?.reasoningEffort===void 0)delete resolved.reasoningEffort;return resolved}function childSessionMeta(parent,childDepth,isSeeded,selectedPreset){const parentHeader=parent.session.header;const agentPreset=selectedPreset??parent.ctx.get("agentPresets")?.composedPreset(parent.ctx);return{...parentHeader.cwd!==void 0?{cwd:parentHeader.cwd}:{},...agentPreset===void 0?{}:{agentPreset},parentSession:parentHeader.id,isSeeded,origin:"subagent",delegationDepth:childDepth}}var SUBAGENT_DELEGATION_CONTEXT="You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session \u2014 operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.";function applyChildComposition(childCtx,parent,composition){if(composition.agentPreset!==void 0){const presets=childCtx.get("agentPresets");if(presets===void 0){throw new SubagentError("selecting a child agent preset requires the agent-presets service","PRESET_UNAVAILABLE")}return presets.mount(childCtx,composition.agentPreset).then(()=>{applyChildOverrides(childCtx,composition)})}childCtx.get("agentPresets")?.composeFrom(childCtx,parent.ctx);applyChildOverrides(childCtx,composition)}function applyChildOverrides(childCtx,composition){childCtx.systemPrompt.context({name:"subagent:delegation",order:childCtx.systemPrompt.getContextOrder("SUBAGENT_DELEGATION"),text:SUBAGENT_DELEGATION_CONTEXT});if(composition.persona!==void 0){childCtx.systemPrompt.section({name:"deployment:persona-prefix",order:childCtx.systemPrompt.getSectionOrder("DEPLOYMENT_PERSONA_PREFIX"),text:composition.persona})}if(composition.toolFilter!==void 0)childCtx.tools.restrict(composition.toolFilter)}function captureDelegatedPolicyOverrides(parent){const preset=parent.ctx.get("permissionPresets")?.current(parent.session);return{permissionPreset:preset==="auto"||preset==="danger-full-access"?preset:void 0,sandboxMode:parent.ctx.get("sandboxPolicy")?.overrideOf(parent.session),approvalPolicy:parent.ctx.get("approval")===void 0?void 0:"never"}}function appendDelegatedPolicyOverrides(childSession,overrides){if(overrides.sandboxMode!==void 0){childSession.append("sandbox/mode",{mode:overrides.sandboxMode,source:"delegation"})}if(overrides.approvalPolicy!==void 0){childSession.append("approval/policy",{policy:overrides.approvalPolicy,source:"delegation"})}if(overrides.permissionPreset!==void 0){childSession.append("permission/preset",{preset:overrides.permissionPreset})}}import{symbols}from"@deepseek-ai/cordis";import{ApprovalService}from"@deepseek-ai/dsh-user-approval";var original=value=>value?.[symbols.original]??value;var refused=()=>{throw new SubagentError("fresh child approval origin is no longer current","UNAUTHORIZED")};function record(session){for(let seq=session.seq-1;seq>=0;seq--){const event=session.eventAt(seq);if(event?.type==="approval/policy")return{seq,event}}}function sameRecord(a,b){return a?.seq===b?.seq&&a?.event===b?.event}function snapshot(agent){const service=agent.ctx.get("approval"),owner=original(service);if(!owner||Object.getPrototypeOf(owner)!==ApprovalService.prototype||owner.overrideOf!==ApprovalService.prototype.overrideOf)return;const config=owner.config,configured=config.policy??"ask",override=service.overrideOf(agent.session);if(configured!=="ask"&&configured!=="never"||override!==void 0&&override!=="ask"&&override!=="never")return;return{realm:agent.ctx,session:agent.session,service:owner,config,configured,override,effective:override??configured,record:record(agent.session)}}function sameService(a,b){return!!a&&!!b&&a.realm===b.realm&&a.session===b.session&&a.service===b.service&&a.config===b.config&&a.configured===b.configured}function unrestricted(value){return value&&value.configured==="ask"&&value.effective==="ask"}function captureCreationApproval(parent,registry){try{const parentState=snapshot(parent),parentRealm=parent.ctx,agents=original(registry);const subagents=original(parent.ctx.get("subagents"));if(!unrestricted(parentState)||!subagents)return;return{beforeDefault(child){try{const value=snapshot(child);return unrestricted(value)?value:void 0}catch{return}},delegationRecord(child){return record(child.session)},candidate(child,initial,before,delegated){try{const childState=snapshot(child);if(!initial||!before||!childState||childState.configured!=="ask"||childState.override!=="never"||delegated?.event.data.policy!=="never"||!sameRecord(delegated,childState.record))return;const live=()=>{const currentParent=snapshot(parent),currentChild=snapshot(child);if(parent.ctx!==parentRealm||original(parent.ctx.get("agents"))!==agents||original(child.ctx.get("agents"))!==agents||original(parent.ctx.get("subagents"))!==subagents||registry.get(parent.id)!==parent||registry.get(child.id)!==child||!registry.isOwnedBy(child.id,parent)||child.session.header.parentSession!==parent.id||!sameService(parentState,currentParent)||!sameRecord(parentState.record,currentParent.record)||!unrestricted(currentParent)||currentParent.override!==parentState.override||!sameService(childState,currentChild))refused()};return{publish(assertActivation){const assertLive=()=>{assertActivation();live()};const origin=Object.freeze({parent,child,assertCurrent(expectedParent,expectedChild){assertLive();if(expectedParent!==parent||expectedChild!==child||snapshot(child)?.override!=="never"||!sameRecord(delegated,record(child.session)))refused()}});try{origin.assertCurrent(parent,child)}catch{return}return{origin,assertLive}}}}catch{return}}}}catch{return}}import{boundContextSummary,createUserMessage}from"@deepseek-ai/dsh-llm";function agentMessageSource(sender){return{kind:"agent-message",form:"relay",senderSessionId:sender.id}}function createAgentMessage(sender,content){return createUserMessage({content:[{type:"text",text:`Agent ${sender.id} sent a message: `},...content],source:agentMessageSource(sender)})}function withContinuableReturnGuidance(parentId,prompt){const encodedParentId=JSON.stringify(parentId);return[...prompt,{type:"text",text:`Your parent agent id is ${encodedParentId}. Before you finish, send your result to that agent with send_message({ agent_id: ${encodedParentId}, message: "<self-contained result>" }). The parent shares your workspace but does not automatically receive your transcript, tool output, or reasoning. Send earlier messages as well when a finding changes what the parent should do next; sending a message does not end your turn.`}]}function settlementSummary(childId,stopReason,continuable){const subject=`Background subagent ${childId}`;switch(stopReason){case"completed":return continuable?`${subject} finished and will do no further work unless you send it more.`:`${subject} finished. It cannot receive follow-up messages.`;case"aborted":return`${subject} was stopped before it finished.`;case"max-tokens":return`${subject} ran out of room before it finished.`;case"refusal":return`${subject} declined the task.`;case"error":return`${subject} failed before it finished.`;default:return`${subject} ended abnormally (${String(stopReason)}) before it finished.`}}function createSettlementMessage(childId,terminal,continuable=true){const summary=settlementSummary(childId,terminal.stopReason,continuable);const closingText=terminal.output.flatMap(block=>block.type==="text"&&block.text.length>0?[block]:[]);return createUserMessage({content:[{type:"text",text:summary},...closingText.length===0?[{type:"text",text:"It left no closing message."}]:[{type:"text",text:"Its closing message:"},...closingText],...terminal.structured!==void 0?[{type:"text",text:`Structured result: ${JSON.stringify(terminal.structured)}`}]:[],...terminal.diagnostic!==void 0?[{type:"text",text:terminal.diagnostic}]:[]],source:{kind:"subagent-settled",form:"notice",summary:boundContextSummary(summary),senderSessionId:childId}})}import{snapshotJsonValue}from"@deepseek-ai/dsh-util-values";var SUBAGENT_DESCRIPTOR_VERSION=3;var DESCRIPTOR_BASE_KEYS=["version","mode","provider","label"];var ONE_SHOT_DESCRIPTOR_KEYS=new Set(DESCRIPTOR_BASE_KEYS);var CONTINUABLE_DESCRIPTOR_KEYS=new Set([...DESCRIPTOR_BASE_KEYS,"agentProvider","agentModel","agentReasoningEffort","persona","toolFilter"]);var TOOL_FILTER_KEYS=new Set(["allow","deny"]);function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function assertKnownKeys(value,keys,path){const unknown=Object.keys(value).find(key=>!keys.has(key));if(unknown!==void 0){throw new Error(`persisted subagent descriptor ${path} has unknown field "${unknown}"`)}}function optionalString(value,key){if(!Object.hasOwn(value,key))return void 0;const field=value[key];if(typeof field!=="string"){throw new Error(`persisted subagent descriptor ${key} must be a string`)}return field}function optionalStringArray(value,key){if(!Object.hasOwn(value,key))return void 0;const field=value[key];if(!Array.isArray(field)){throw new Error(`persisted subagent descriptor toolFilter.${key} must be an array of strings`)}const items=field;if(items.some(item=>typeof item!=="string")){throw new Error(`persisted subagent descriptor toolFilter.${key} must be an array of strings`)}return items}function parseToolFilter(value){if(!isRecord(value)){throw new Error("persisted subagent descriptor toolFilter must be an object")}assertKnownKeys(value,TOOL_FILTER_KEYS,"toolFilter");const allow=optionalStringArray(value,"allow");const deny=optionalStringArray(value,"deny");if(allow===void 0&&deny===void 0){throw new Error("persisted subagent descriptor toolFilter must declare allow and/or deny")}return{...allow!==void 0?{allow}:{},...deny!==void 0?{deny}:{}}}function parseSubagentDescriptor(value){if(!isRecord(value)){throw new Error("persisted subagent descriptor payload must be an object")}const version=value["version"];if(typeof version!=="number"){throw new Error("persisted subagent descriptor version must be a number")}if(version!==SUBAGENT_DESCRIPTOR_VERSION)return void 0;const mode=value["mode"];if(mode!=="one-shot"&&mode!=="continuable"){throw new Error('persisted subagent descriptor mode must be "one-shot" or "continuable"')}assertKnownKeys(value,mode==="one-shot"?ONE_SHOT_DESCRIPTOR_KEYS:CONTINUABLE_DESCRIPTOR_KEYS,"payload");const provider=value["provider"];if(typeof provider!=="string"){throw new Error("persisted subagent descriptor provider must be a string")}if(mode==="one-shot"){const label2=optionalString(value,"label");return{version:SUBAGENT_DESCRIPTOR_VERSION,mode,provider,...label2!==void 0?{label:label2}:{}}}const label=value["label"];if(typeof label!=="string"){throw new Error("persisted subagent descriptor label must be a string")}const agentProvider=optionalString(value,"agentProvider");const agentModel=optionalString(value,"agentModel");const agentReasoningEffort=optionalString(value,"agentReasoningEffort");const persona=optionalString(value,"persona");const toolFilter=Object.hasOwn(value,"toolFilter")?parseToolFilter(value["toolFilter"]):void 0;return{version:SUBAGENT_DESCRIPTOR_VERSION,mode,provider,label,...agentProvider!==void 0?{agentProvider}:{},...agentModel!==void 0?{agentModel}:{},...agentReasoningEffort!==void 0?{agentReasoningEffort}:{},...persona!==void 0?{persona}:{},...toolFilter!==void 0?{toolFilter}:{}}}function snapshotSubagentDescriptor(input){const candidate={version:SUBAGENT_DESCRIPTOR_VERSION,mode:input.mode,provider:input.provider,label:input.label,...input.agentProvider!==void 0?{agentProvider:input.agentProvider}:{},...input.agentModel!==void 0?{agentModel:input.agentModel}:{},...input.agentReasoningEffort!==void 0?{agentReasoningEffort:input.agentReasoningEffort}:{},...input.persona!==void 0?{persona:input.persona}:{},...input.toolFilter!==void 0?{toolFilter:input.toolFilter}:{}};const snapshot2=snapshotJsonValue(candidate);if(snapshot2===void 0){throw new Error("subagent descriptor is not losslessly JSON-serializable")}return snapshot2}function foldSubagentDescriptor(events){const event=events.find(candidate=>candidate.type==="subagent/descriptor");if(event===void 0)return void 0;return parseSubagentDescriptor(event.data)}import{z as z2}from"zod";import{appendChunkedList,chunkedListSchema,iterateChunkedList}from"@deepseek-ai/dsh-chunked-list";var SUBAGENT_CATALOG_VERSION=0;var sessionIdSchema=z2.string();var oneShotCatalogSchema=z2.object({version:z2.union([z2.literal(0),z2.literal(1)]),childId:sessionIdSchema,childCreatedAt:z2.number().int().nonnegative(),mode:z2.literal("one-shot"),label:z2.string().optional()}).strict();var continuableCatalogSchema=z2.object({version:z2.union([z2.literal(0),z2.literal(1)]),childId:sessionIdSchema,childCreatedAt:z2.number().int().nonnegative(),mode:z2.literal("continuable"),label:z2.string()}).strict();var externalCatalogSchema=oneShotCatalogSchema.extend({version:z2.literal(2),mode:z2.literal("external")});var unknownCatalogSchema=oneShotCatalogSchema.extend({version:z2.literal(1),mode:z2.literal("unknown")});var eventDataSchema=z2.union([oneShotCatalogSchema,externalCatalogSchema,continuableCatalogSchema,unknownCatalogSchema]);var viewSchema=z2.array(z2.union([oneShotCatalogSchema.omit({version:true,childId:true,childCreatedAt:true}).extend({id:sessionIdSchema,createdAt:oneShotCatalogSchema.shape.childCreatedAt}),externalCatalogSchema.omit({version:true,childId:true,childCreatedAt:true}).extend({id:sessionIdSchema,createdAt:externalCatalogSchema.shape.childCreatedAt}),continuableCatalogSchema.omit({version:true,childId:true,childCreatedAt:true}).extend({id:sessionIdSchema,createdAt:continuableCatalogSchema.shape.childCreatedAt}),unknownCatalogSchema.omit({version:true,childId:true,childCreatedAt:true}).extend({id:sessionIdSchema,createdAt:unknownCatalogSchema.shape.childCreatedAt})]));var stateSchema=z2.object({inheritedEventCount:z2.number().int().nonnegative(),head:chunkedListSchema(eventDataSchema).optional()}).strict();function subagentCatalogEntries(state){const entries=[];for(const data of iterateChunkedList(state.head)){const{version:_version,childId,childCreatedAt,...descriptor}=data;entries.push({id:childId,createdAt:childCreatedAt,...descriptor})}return entries}var subagentCatalogProjectionDefinition={key:"subagentCatalog",stateSchema,init:(_header,inheritedEventCount)=>({inheritedEventCount}),apply:(state,event)=>{if(event.type!=="subagent/catalog"||event.seq<state.inheritedEventCount)return state;return{...state,head:appendChunkedList(state.head,eventDataSchema.parse(event.data))}},stateVersion:6,wire:{viewSchema,view:subagentCatalogEntries}};function establishCatalogChild(parent,child,descriptor){parent.append("subagent/catalog",{version:SUBAGENT_CATALOG_VERSION,childId:child.id,childCreatedAt:child.createdAt,mode:descriptor.mode,label:descriptor.label})}var EXTERNAL_SUBAGENT_CATALOG_VERSION=2;function establishExternalCatalogChild(parent,childId,label){parent.append("subagent/catalog",{version:EXTERNAL_SUBAGENT_CATALOG_VERSION,childId,childCreatedAt:Date.now(),mode:"external",label})}var adjacentAgentSendMessageTool=Symbol.for("dsh.subagent.adjacentAgentSendMessageTool");function isAdjacentAgentSendMessageTool(definition){return definition!==void 0&&definition[adjacentAgentSendMessageTool]===true}var deliverSubagentPrompt=Symbol.for("dsh.subagent.deliverPrompt");import{ToolArgsError,validateJsonSchemaValue}from"@deepseek-ai/dsh-tools";var STRUCTURED_OUTPUT_TOOL="structured_output";var 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.`;function attachStructuredRuntime(childCtx,schema,canComplete){const staged=new Map;let pending;let captured;const schemaEntry={name:STRUCTURED_OUTPUT_TOOL,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.",parameters:{...schema}};childCtx.tools.register({...schemaEntry,output:{schema:{type:"object",properties:{recorded:{type:"boolean",const:true}},required:["recorded"],additionalProperties:false},render:()=>[{type:"text",text:"Structured output recorded."}]},execute(args,exec){const violations=validateJsonSchemaValue(schema,args);if(violations.length>0)throw new ToolArgsError(violations);if(!canComplete())throw new Error("Wait for all delegated child tasks to finish and process pending messages before submitting structured output.");staged.set(exec,{value:args});exec.concludeTurn();return Promise.resolve({recorded:true})}});childCtx.systemPrompt.section({name:`tool:${STRUCTURED_OUTPUT_TOOL}`,order:childCtx.systemPrompt.getSectionOrder("STRUCTURED_OUTPUT"),text:STRUCTURED_OUTPUT_INSTRUCTION});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`);childCtx.on("tools/result",function(exec,result){if(exec.name===STRUCTURED_OUTPUT_TOOL){const entry2=staged.get(exec);if(entry2===void 0)return;staged.delete(exec);if(result.isError)return;if(exec.parent===void 0){if(captured===void 0)captured={value:entry2.value}}else{if(captured===void 0&&pending===void 0){pending={parent:exec.parent,value:entry2.value}}}return}if(pending?.parent!==exec.token)return;const entry=pending;pending=void 0;if(result.isError)return;if(captured===void 0)captured={value:entry.value}});return{captured:()=>captured,acceptsInput:()=>staged.size===0&&pending===void 0&&captured===void 0}}import{assertNever}from"@deepseek-ai/dsh-util-values";import{joinAssistantStreamText}from"@deepseek-ai/dsh-llm";var AssistantOutputFold=class{message;partial=[];push(event){if(event.type==="assistant/message"){const content=event.data.message.content;if(content.length>0)this.message=content}if(event.type==="assistant/message"||event.type==="assistant/attempt"){this.pushText(joinAssistantStreamText(event.data.stream))}}pushText(text){if(text.length>0)this.partial.push(text)}collect(){if(this.message!==void 0)return this.message;const text=this.partial.join("");return text.length>0?[{type:"text",text}]:void 0}};function finalAssistantOutput(events){const fold=new AssistantOutputFold;for(const event of events)fold.push(event);return fold.collect()}var ActivationPool=class{slots=new Set;reserve(capacity){if(this.slots.size>=capacity){throw new SubagentError(`subagent limit reached (active child limit: ${capacity}); wait for an existing child to finish or complete this work with the current agents`,"ACTIVATION_LIMIT_REACHED")}const slot=Symbol();this.slots.add(slot);return()=>{this.slots.delete(slot)}}};function activationAgent(activation){return activation.kind==="local"?activation.handle.agent:void 0}function requireLocalActivation(activation){switch(activation.kind){case"local":return activation;case"external":throw new SubagentError(`subagent "${activation.childId}" does not accept follow-up input`,"NOT_CONTINUABLE");default:return assertNever(activation)}}function observeLocalFailure(activation,wake){const child=activation.handle.agent;child.ctx.on("agent/error",({agent})=>{if(agent!==child)return;activation.failureAt=child.session.seq;wake()});child.ctx.on("session/event",(session,event)=>{if(session===child.session&&event.type==="turn/end"&&activation.failureAt!==void 0&&event.seq>=activation.failureAt){activation.failureAt=void 0}})}function captureLocalResult(activation){const events=activation.handle.agent.session.snapshotEvents(activation.outputStart);const output=finalAssistantOutput(events)??[];const stopReason=activation.failureAt===void 0?epochStopReason(events):"error";const structured=activation.structured;if(structured!==void 0){const captured=structured.captured();if(captured!==void 0)return{output,stopReason,structured:captured.value};if(stopReason==="completed")return{output,stopReason:"error"}}return{output,stopReason}}var ChildLock=class{tails=new Map;run(childId,operation){const previous=this.tails.get(childId)??Promise.resolve();const result=previous.then(operation,operation);const tail=result.then(()=>void 0,()=>void 0);this.tails.set(childId,tail);void tail.then(()=>{if(this.tails.get(childId)===tail)this.tails.delete(childId)});return result}};var __addDisposableResource=function(env,value,async){if(value!==null&&value!==void 0){if(typeof value!=="object"&&typeof value!=="function")throw new TypeError("Object expected.");var dispose,inner;if(async){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");dispose=value[Symbol.asyncDispose]}if(dispose===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");dispose=value[Symbol.dispose];if(async)inner=dispose}if(typeof dispose!=="function")throw new TypeError("Object not disposable.");if(inner)dispose=function(){try{inner.call(this)}catch(e){return Promise.reject(e)}};env.stack.push({value,dispose,async})}else if(async){env.stack.push({async:true})}return value};var __disposeResources=(function(SuppressedError2){return function(env){function fail(e){env.error=env.hasError?new SuppressedError2(e,env.error,"An error was suppressed during disposal."):e;env.hasError=true}var r,s=0;function next(){while(r=env.stack.pop()){try{if(!r.async&&s===1)return s=0,env.stack.push(r),Promise.resolve().then(next);if(r.dispose){var result=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(result).then(next,function(e){fail(e);return next()})}else s|=1}catch(e){fail(e)}}if(s===1)return env.hasError?Promise.reject(env.error):Promise.resolve();if(env.hasError)throw env.error}return next()}})(typeof SuppressedError==="function"?SuppressedError:function(error,suppressed,message){var e=new Error(message);return e.name="SuppressedError",e.error=error,e.suppressed=suppressed,e});function failureMessage(error){return error instanceof Error?error.message:"unknown teardown failure"}var SubagentManager=class{ctx;host;maxActiveSubagents;resident=new Map;approvalOrigins=new WeakMap;creationApprovalOf(child){const proof=this.approvalOrigins.get(child);if(!proof)return;try{proof.assertLive();return proof.origin}catch{return}}rootPools=new WeakMap;materializations=new Set;locks=new ChildLock;ownerCtx;closingScopes=new Map;draining=false;constructor(ctx,host,maxActiveSubagents){this.ctx=ctx;this.host=host;this.maxActiveSubagents=maxActiveSubagents;const scope=ctx.plugin(function activationOwner(){});this.ownerCtx=scope.ctx;ctx.on("agent/disposed",({agent})=>{this.closingScopes.delete(agent)});ctx.effect(function*(){yield scope.dispose;yield()=>this.drain()}.bind(this),"subagents.manager()")}interrupt(targetSessionId,authority){if(authority.kind==="ancestor"){const caller=authority.agent;if(this.ctx.agents.get(caller.id)!==caller){throw new SubagentError(`interrupting "${targetSessionId}" requires the exact live ancestor agent`,"UNAUTHORIZED")}if(caller.id===targetSessionId){throw new SubagentError(`agent "${caller.id}" cannot interrupt itself`,"UNAUTHORIZED")}}const activation=this.resident.get(targetSessionId);if(activation===void 0)return;if(authority.kind==="user"){if(activation.parent.id!==authority.parentSessionId){throw new SubagentError(`subagent "${targetSessionId}" belongs to another parent session`,"UNAUTHORIZED")}}else if(!activation.ancestry.has(authority.agent)){throw new SubagentError(`subagent "${targetSessionId}" is not a live descendant of agent "${authority.agent.id}"`,"UNAUTHORIZED")}if(activation.closing!==void 0)return;const kind=authority.kind==="user"?"user":"parent";if(activation.kind==="local"){activation.handle.agent.cancel({kind},{keepInbox:true})}else{activation.controller.abort({kind});void this.dispose(activation).catch(()=>void 0)}}async drain(){this.draining=true;for(const pending of this.materializations)pending.controller.abort();await Promise.all([...this.materializations].map(materialization=>materialization.settled));const owned=new Set;for(const activation of this.resident.values()){for(const child of activation.ownedChildren)owned.add(child)}const roots=[...this.resident.values()].filter(activation=>!owned.has(activation.childId));await this.disposeRoots(roots,"activation(s)")}async waitForChildren(parent){let observed=false;while(true){const pending=[...this.materializations].filter(item=>item.lineage.includes(parent));const children=[...this.resident.values()].filter(item=>activationAgent(item)!==parent&&item.ancestry.has(parent));observed||=children.some(item=>item.kind==="local"&&item.handle.agent.status!=="idle");await Promise.all(children.flatMap(item=>item.kind==="local"?[item.handle.agent.whenIdle()]:[]));const waits=pending.map(item=>item.settled);for(const item of children){if(item.kind==="external"||item.closing!==void 0){waits.push(item.result.promise.catch(()=>void 0));continue}if(item.handle.agent.status!=="idle"){waits.push(item.handle.agent.whenIdle());continue}if(item.ownedChildren.size>0){if([...item.ownedChildren].some(id=>!this.resident.has(id)))waits.push(item.poke.promise);continue}const inbox=item.handle.agent.inbox;if(item.failureAt===void 0&&(inbox.nextTurn.length>0||inbox.nextStep.length>0))continue;waits.push(Promise.race([item.result.promise.catch(()=>void 0),item.poke.promise]))}if(waits.length>0){observed=true;await Promise.all(waits);continue}if([...this.materializations].some(item=>item.lineage.includes(parent)&&!pending.includes(item))||[...this.resident.values()].some(item=>activationAgent(item)!==parent&&item.ancestry.has(parent)&&!children.includes(item)))continue;return observed}}async drainDescendants(parents){const roots=new Set(parents.filter(parent=>this.ctx.agents.get(parent.id)===parent));if(roots.size===0)return;for(const root of roots){this.closingMembers(root).add(root)}const targets=[];for(const activation of this.resident.values()){const child=activationAgent(activation);const lineage=this.liveLineage(child??activation.parent);const owners=[...roots].filter(root=>child!==root&&activation.ancestry.has(root));if(owners.length===0)continue;targets.push(activation);for(const owner of owners){const members=this.closingMembers(owner);if(child!==void 0)members.add(child);for(const agent of lineage)members.add(agent)}}const materializations=[...this.materializations].filter(materialization=>{const owners=[...roots].filter(root=>materialization.lineage.includes(root));for(const owner of owners){const members=this.closingMembers(owner);for(const agent of materialization.lineage)members.add(agent)}if(owners.length>0)materialization.controller.abort();return owners.length>0});const ownedTargets=new Set;for(const activation of targets){for(const child of activation.ownedChildren)ownedTargets.add(child)}const targetRoots=targets.filter(activation=>!ownedTargets.has(activation.childId));for(const activation of targets){const disposal=this.dispose(activation);void disposal.catch(()=>void 0)}await Promise.all(materializations.map(materialization=>materialization.settled));await this.disposeRoots(targetRoots,"scoped activation(s)")}async drainChildren(parent,childIds){if(this.ctx.agents.get(parent.id)!==parent){throw new SubagentError("selected child teardown requires the exact live parent agent","UNAUTHORIZED")}const targets=[];for(const childId of new Set(childIds)){const activation=this.resident.get(childId);if(activation===void 0)continue;if(activation.parent.id!==parent.id||!activation.ancestry.has(parent)){throw new SubagentError(`subagent "${childId}" is not a direct child of agent "${parent.id}"`,"UNAUTHORIZED")}targets.push(activation)}for(const activation of targets){const disposal=this.dispose(activation);void disposal.catch(()=>void 0)}await this.disposeRoots(targets,"selected activation(s)")}async startLocal(spec){const request=spec.request;const parent=request.parent;this.assertAdmitting(parent);const persistence=spec.delivery==="caller"?this.ctx.get("sessionPersistence"):this.requirePersistence();assertSubagentMaxDepth(request.maxDepth);const childId=spec.childId??brandString(randomUUID2());this.assertChildIdAvailable(childId);const childDepth=resolveChildDepth(parent,request.maxDepth);const agentOptions=resolveChildAgentOptions(parent,request.agentOptions,childDepth);const agentProvider=agentOptions.provider;const agentModel=agentOptions.model;const agentReasoningEffort=agentOptions.reasoningEffort;const descriptor=snapshotSubagentDescriptor({mode:"continuable",provider:spec.provider,label:spec.label,...agentProvider!==void 0?{agentProvider}:{},...agentModel!==void 0?{agentModel}:{},...agentReasoningEffort!==void 0?{agentReasoningEffort}:{}});const delegatedPolicies=captureDelegatedPolicyOverrides(parent);const approvalOrigin=captureCreationApproval(parent,this.ctx.agents);const releaseHold=this.holdOwnership(parent,childId);try{const cwd=await this.resolveDirectory(request,spec.signal);const prepared=await this.host.prepareContinuable(spec.provider,{sessionId:childId,cwd,parent,signal:spec.signal});spec.signal.throwIfAborted();this.assertAdmitting(parent);const inheritedEventCount=SessionLogOffset(prepared.seed?.length??0);const seed=prepared.seed;let established;const messageId=await this.locks.run(childId,async()=>{spec.signal.throwIfAborted();this.assertAdmitting(parent);this.assertChildIdAvailable(childId);if(spec.childId!==void 0){const persisted=await persistence?.stat(childId,{signal:spec.signal});spec.signal.throwIfAborted();this.assertAdmitting(parent);this.assertChildIdAvailable(childId);if(persisted!==void 0){throw new SubagentError(`subagent "${childId}" already exists`,"DUPLICATE_CHILD")}}const activation=await this.materialize({kind:"local",childId,provider:spec.provider,parent,create:{cwd,seed,meta:childSessionMeta(parent,childDepth,prepared.seed!==void 0,request.agentPreset),inheritedEventCount,delegatedPolicies,approvalOrigin,descriptor},agentOptions,composition:{agentPreset:request.agentPreset},signal:spec.signal,delivery:spec.delivery,outputSchema:spec.request.outputSchema});established=activation;const child=requireLocalActivation(activation).handle.agent;const childHeader=child.session.header;return await this.submitMaterialized(activation,spec.delivery!=="caller"&&isAdjacentAgentSendMessageTool(this.ctx.get("tools")?.get("send_message",child))?withContinuableReturnGuidance(parent.id,request.prompt):request.prompt,{source:{kind:"user"},signal:spec.signal,delivery:"queue"},parent,()=>{establishCatalogChild(parent.session,childHeader,descriptor)})});return{...this.receipt(established),childId,messageId}}catch(error){releaseHold();throw error}}async startExternal(spec){const parent=spec.request.parent;this.assertAdmitting(parent);const pendingId=brandString(randomUUID2());const releaseHold=this.holdOwnership(parent,pendingId);let activation;try{const cwd=await this.resolveDirectory(spec.request,spec.signal);activation=await this.materialize({kind:"external",childId:pendingId,provider:spec.provider,parent,signal:spec.signal,delivery:spec.delivery,start:signal=>this.host.startExternal(spec.provider,{...spec.request,cwd,label:spec.label,signal})});this.assertAdmitting(parent);this.assertLiveParent(parent,activation.childId);spec.signal.throwIfAborted();if(spec.delivery==="parent"){establishExternalCatalogChild(parent.session,activation.childId,spec.label)}this.announce(activation);return this.receipt(activation)}catch(error){if(activation!==void 0){try{await this.dispose(activation)}catch(cleanupError){this.ctx.logger.warn(`subagent "${activation.childId}" admission rollback failed: ${failureMessage(cleanupError)}`)}}throw error}finally{releaseHold()}}async resolveDirectory(request,signal){const cwd=request.cwd!==void 0&&isAbsolute(request.cwd)?request.cwd:resolve(await this.ctx.workingDirectory.ensure(request.parent,signal),request.cwd??".");signal.throwIfAborted();return cwd}async sendMessage(sender,targetId,content,options){if(this.ctx.agents.get(sender.id)!==sender){throw new SubagentError("message delivery requires the exact live sender agent","UNAUTHORIZED")}this.assertAdmitting(sender);const senderActivation=this.resident.get(sender.id);if(senderActivation!==void 0&&senderActivation.kind==="local"&&senderActivation.handle.agent===sender&&senderActivation.parent.id===targetId){options.signal.throwIfAborted();return this.sendToParent(senderActivation,sender,content)}if(sender.session.header.parentSession===targetId){throw new SubagentError(`agent "${sender.id}" is not a resident continuable child and cannot send to parent "${targetId}"`,"UNAUTHORIZED")}return this.deliverToChild(sender,targetId,content,{signal:options.signal,delivery:"steer"})}async queuePrompt(parent,childId,content,source,signal){return this.deliverToChild(parent,childId,content,{source,signal,delivery:"queue"})}async steerPrompt(parent,childId,content,source,signal){return this.deliverToChild(parent,childId,content,{source,signal,delivery:"steer"})}deliver(activation,message,delivery){if(activation.closing!==void 0){throw new SubagentError("subagent activation is being disposed; the message was not accepted","ACTIVATION_CLOSING")}const local=requireLocalActivation(activation);if(local.structured?.acceptsInput()===false){throw new SubagentError("subagent is submitting or has submitted its structured result; the message was not accepted","INPUT_CLOSED")}if(delivery==="steer")local.handle.agent.steer(message);else local.handle.agent.followup(message)}assertChildIdAvailable(childId){if(this.resident.has(childId)||this.ctx.agents.get(childId)!==void 0||this.ctx.get("sessions")?.get(childId)!==void 0){throw new SubagentError(`subagent "${childId}" already exists`,"DUPLICATE_CHILD")}}holdOwnership(parent,childId){const parentActivation=this.resident.get(parent.id);if(parentActivation===void 0||activationAgent(parentActivation)!==parent)return()=>{};if(parentActivation.closing!==void 0){throw new SubagentError(`subagent parent "${parent.id}" is being disposed; the child was not established`,"ACTIVATION_CLOSING")}if(parentActivation.ownedChildren.has(childId))return()=>{};parentActivation.ownedChildren.add(childId);return()=>{const live=this.resident.get(childId);if(live!==void 0&&live.closing===void 0)return;if(parentActivation.ownedChildren.delete(childId))this.wake(parentActivation)}}sendWaking(parent,message,delivery){const parentActivation=this.resident.get(parent.id);if(parentActivation!==void 0&&activationAgent(parentActivation)===parent){try{this.deliver(parentActivation,message,delivery)}finally{this.wake(parentActivation)}return}if(delivery==="steer")parent.steer(message);else parent.followup(message)}assertAdmitting(agent){const closing=this.closingTeardownFor(agent);if(closing===void 0)return;throw new SubagentError(closing==="manager"?"subagents are draining; the operation was not admitted":`subagents below parent "${closing.id}" are draining; the operation was not admitted`,"DRAINING")}authorizeLineage(parent,childId,parentSession){this.assertLiveParent(parent,childId);if(parentSession!==parent.id){throw new SubagentError(`subagent "${childId}" belongs to another parent session`,"UNAUTHORIZED")}}assertLiveParent(parent,childId){if(this.ctx.agents.get(parent.id)!==parent){throw new SubagentError(`subagent "${childId}" delivery requires the exact live parent agent`,"UNAUTHORIZED")}}materialize(inputs){this.assertAdmitting(inputs.parent);inputs.signal.throwIfAborted();const lineage=this.liveLineage(inputs.parent);const pool=this.resident.get(inputs.parent.id)?.pool??this.rootPool(inputs.parent);const releaseSlot=pool.reserve(this.maxActiveSubagents());const settled=Promise.withResolvers();const controller=new AbortController;const materialization={lineage,settled:settled.promise,controller};this.materializations.add(materialization);return this.materializeTracked({...inputs,signal:AbortSignal.any([inputs.signal,controller.signal])},lineage,pool,releaseSlot).catch(error=>{releaseSlot();if(error instanceof Error&&error.name==="AbortError")this.assertAdmitting(inputs.parent);throw error}).finally(()=>{this.materializations.delete(materialization);settled.resolve()})}dispose(activation){return this.close(activation,()=>this.finishDisposal(activation,true))}close(activation,release){if(activation.closing!==void 0)return activation.closing;const completion=Promise.withResolvers();activation.closing=completion.promise;void release().then(completion.resolve,completion.reject);return completion.promise}async disposeRoots(roots,failureSubject){const failures=await Promise.all(roots.map(async activation=>{try{await this.dispose(activation);return void 0}catch(error){return error}}));const reasons=failures.filter(failure=>failure!==void 0);if(reasons.length>0){throw new SubagentError(`subagent teardown failed for ${reasons.length} ${failureSubject}: `+reasons.map(reason=>failureMessage(reason)).join("; "),"ACTIVATION_TEARDOWN_FAILED")}}closingMembers(root){const existing=this.closingScopes.get(root);if(existing!==void 0)return existing;const members=new Set;this.closingScopes.set(root,members);return members}liveLineage(agent){const lineage=[agent];const seen=new Set([agent.id]);let parentSession=agent.session.header.parentSession;while(parentSession!==void 0){const parent=this.ctx.agents.get(parentSession);if(parent===void 0||seen.has(parent.id))break;lineage.push(parent);seen.add(parent.id);parentSession=parent.session.header.parentSession}return lineage}closingTeardownFor(agent){if(this.draining)return"manager";const lineage=this.liveLineage(agent);for(const[root,members]of this.closingScopes){if(members.has(agent)||lineage.includes(root))return root}return void 0}rootPool(parent){let pool=this.rootPools.get(parent);if(pool===void 0){pool=new ActivationPool;this.rootPools.set(parent,pool)}return pool}async materializeTracked(inputs,parentLineage,pool,releaseSlot){const{provider,parent}=inputs;let childId=inputs.childId;inputs.signal.throwIfAborted();let resource;if(inputs.kind==="external"){const controller=new AbortController;const cancelStartup=()=>{controller.abort(inputs.signal.reason)};inputs.signal.addEventListener("abort",cancelStartup,{once:true});try{const run=await inputs.start(controller.signal);resource={kind:"external",run,controller};void run.result.catch(()=>void 0);childId=run.id;try{this.assertChildIdAvailable(childId)}catch(error){await run.dispose();throw error}}finally{inputs.signal.removeEventListener("abort",cancelStartup)}}else{const{create}=inputs;let structured;let approvalOriginCandidate;const setup=async(childCtx,child)=>{const initialApproval=create?.approvalOrigin?.beforeDefault(child);let beforeDefault,delegatedRecord;if(inputs.composition.agentPreset!==void 0){await applyChildComposition(childCtx,parent,inputs.composition)}if(create!==void 0){if(inputs.composition.agentPreset!==void 0){child.session.append("agent-preset/selected",{agentPreset:inputs.composition.agentPreset})}child.session.append("subagent/descriptor",create.descriptor);beforeDefault=create.approvalOrigin?.beforeDefault(child);appendDelegatedPolicyOverrides(child.session,create.delegatedPolicies);delegatedRecord=create.approvalOrigin?.delegationRecord(child);const workingDirectory=childCtx.get("workingDirectory");if(workingDirectory===void 0)throw new Error("local subagents require the working-directory service");await workingDirectory.set(child,create.cwd,inputs.signal)}if(inputs.composition.agentPreset===void 0)await applyChildComposition(childCtx,parent,inputs.composition);approvalOriginCandidate=create?.approvalOrigin?.candidate(child,initialApproval,beforeDefault,delegatedRecord);if(inputs.outputSchema!==void 0){structured=attachStructuredRuntime(childCtx,inputs.outputSchema,()=>this.resident.get(childId)?.ownedChildren.size===0&&child.inbox.nextStep.length===0&&child.inbox.nextTurn.length===0)}};const handle=create===void 0?await this.ownerCtx.agents.resume({resumeSessionId:childId,parentAgent:parent,agentOptions:inputs.agentOptions,signal:inputs.signal,setup}):await this.ownerCtx.agents.create({sessionId:childId,parentAgent:parent,meta:create.meta,...create.seed===void 0?{}:{seed:create.seed},inheritedEventCount:create.inheritedEventCount,agentOptions:inputs.agentOptions,signal:inputs.signal,setup});resource={kind:"local",handle,outputStart:handle.agent.session.seq,structured,failureAt:void 0,poke:Promise.withResolvers(),approvalOriginCandidate}}const observer=this.host.observeActivation(provider,childId,parent);const activation={pool,releaseSlot,childId,...resource,parent,delivery:inputs.delivery??"parent",result:Promise.withResolvers(),closing:void 0,ancestry:new WeakSet(resource.kind==="external"?parentLineage:[resource.handle.agent,...parentLineage]),ownedChildren:new Set,observer,announced:false};void activation.result.promise.catch(()=>void 0);this.resident.set(childId,activation);try{this.assertAdmitting(parent);inputs.signal.throwIfAborted();if(this.ctx.agents.get(parent.id)!==parent)throw new SubagentError("subagent parent is no longer live","UNAUTHORIZED");this.acquireOwnership(parent,childId);const wakeSettlement=()=>{this.wake(activation)};if(activation.kind==="local"){observeLocalFailure(activation,wakeSettlement);activation.handle.agent.ctx.on("agent/inbox/inserted",wakeSettlement);activation.handle.agent.ctx.on("agent/inbox/claimed",wakeSettlement);activation.handle.agent.ctx.on("agent/inbox/discarded",wakeSettlement)}observer.start(activationAgent(activation))}catch(error){await this.rollbackUnpublished(activation,error).catch(()=>void 0);throw error}return activation}announce(activation){if(activation.announced)return;activation.announced=true;if(activation.kind==="local"){this.watchLocalSettlement(activation)}else{const finish=()=>this.close(activation,()=>this.finishDisposal(activation,false));void activation.run.result.then(finish,finish).catch(error=>{this.reportTeardownFailure(activation,error)})}}rollbackUnpublished(activation,error){return this.close(activation,async()=>{try{await(activation.kind==="local"?activation.handle.dispose():activation.run.dispose())}finally{this.resident.delete(activation.childId);activation.releaseSlot();this.releaseOwnership(activation.childId);activation.result.reject(error)}})}acquireOwnership(parent,childId){const parentActivation=this.resident.get(parent.id);if(parentActivation===void 0)return;if(parentActivation.closing!==void 0){throw new SubagentError(`subagent parent "${parent.id}" is being disposed; the child was not established`,"ACTIVATION_CLOSING")}parentActivation.ownedChildren.add(childId);this.wake(parentActivation)}releaseOwnership(childId){for(const candidate of this.resident.values()){if(candidate.ownedChildren.delete(childId))this.wake(candidate)}}wake(activation){if(activation.kind==="external")return;activation.poke.resolve();activation.poke=Promise.withResolvers()}watchLocalSettlement(activation){void(async()=>{while(true){const idleObservation=activation.poke;await activation.handle.agent.whenIdle();if(activation.closing!==void 0)return;const readiness=await this.locks.run(activation.childId,()=>Promise.resolve(this.settlementState(activation,idleObservation)));if(readiness==="closed")return;if(readiness==="retry")continue;if(readiness==="wait"){await idleObservation.promise;continue}const finalSeq=activation.handle.agent.session.seq;await this.flushFinalState(activation);const attempt=await this.locks.run(activation.childId,()=>{const state=this.settlementState(activation,idleObservation);if(state!=="ready")return Promise.resolve(state);if(activation.handle.agent.session.seq!==finalSeq){return Promise.resolve("retry")}let done;try{void activation.handle.agent.runMaintenance(()=>{done=this.close(activation,()=>this.finishDisposal(activation,false));return Promise.resolve()})}catch(_error){return Promise.resolve("retry")}return Promise.resolve({done})});if(typeof attempt==="string"){if(attempt==="closed")return;continue}try{await attempt.done}catch(error){this.reportTeardownFailure(activation,error)}return}})()}reportTeardownFailure(activation,error){this.ctx.logger.warn(`subagent "${activation.childId}" activation teardown failed: ${failureMessage(error)}`)}settlementState(activation,observation){if(activation.closing!==void 0)return"closed";if(activation.poke!==observation)return"retry";const inbox=activation.handle.agent.inbox;if(activation.ownedChildren.size>0)return"wait";if(activation.failureAt===void 0&&(inbox.nextTurn.length>0||inbox.nextStep.length>0))return"wait";return"ready"}async finishDisposal(activation,stop){this.wake(activation);const{childId}=activation;const failures=[];let result={output:[],stopReason:"error"};let resultFailure;let externalDisposal;const child=activationAgent(activation);const detail=error=>child===void 0?failureMessage(error):errorChain(error);try{if(activation.kind==="external"){if(stop){activation.controller.abort({kind:"parent"});externalDisposal=Promise.resolve().then(()=>activation.run.dispose());void externalDisposal.catch(()=>void 0)}result=await activation.run.result}else{if(stop){activation.handle.agent.cancel({kind:"parent"});const idle=activation.handle.agent.whenIdle();const children=[...activation.ownedChildren].map(child2=>this.resident.get(child2)).filter(child2=>child2!==void 0);const pending=[...this.materializations].filter(item=>item.lineage.includes(activation.handle.agent));const childDisposals=children.map(child2=>this.dispose(child2));for(const item of pending)item.controller.abort();childDisposals.push(...pending.map(item=>item.settled));const childFailures=await Promise.all(childDisposals.map(async disposal=>{try{await disposal;return void 0}catch(error){return error}}));const reasons=childFailures.filter(reason=>reason!==void 0);if(reasons.length>0){failures.push(new SubagentError(`subagent "${childId}" child teardown failed: ${reasons.map(reason=>failureMessage(reason)).join("; ")}`,"ACTIVATION_TEARDOWN_FAILED"))}await idle;await this.flushFinalState(activation)}result=captureLocalResult(activation)}}catch(error){resultFailure={error};failures.push(new SubagentError(`subagent "${childId}" activation teardown failed: ${detail(error)}`,"ACTIVATION_TEARDOWN_FAILED",{cause:error}))}try{if(activation.kind==="local")await activation.handle.dispose();else await(externalDisposal??activation.run.dispose())}catch(error){failures.push(new SubagentError(`subagent "${childId}" activation handle disposal failed: ${detail(error)}`,"ACTIVATION_TEARDOWN_FAILED",{cause:error}))}let failure;if(failures.length===1){failure=failures[0]}else if(failures.length>1){failure=new SubagentError(`subagent "${childId}" activation teardown failed at ${failures.length} boundaries: `+failures.map(item=>detail(item)).join("; "),"ACTIVATION_TEARDOWN_FAILED",{cause:new AggregateError(failures)})}this.resident.delete(childId);activation.releaseSlot();const terminal=failure===void 0?result:{output:[],stopReason:"error"};this.notifySettlement(activation,result);this.releaseOwnership(childId);activation.observer.settle(terminal);if(resultFailure===void 0)activation.result.resolve(result);else activation.result.reject(resultFailure.error);if(failure!==void 0)throw failure}notifySettlement(activation,terminal){if(!activation.announced||activation.delivery==="caller")return;try{const parent=this.ctx.agents.get(activation.parent.id);if(parent!==activation.parent)return;const message=createSettlementMessage(activation.childId,terminal,activationAgent(activation)!==void 0);if(this.closingTeardownFor(parent)!==void 0){parent.inject(message);return}this.sendWaking(parent,message,parent.status==="idle"?"queue":"steer")}catch(error){this.ctx.logger.warn(`subagent "${activation.childId}" settlement notice was not delivered to its parent: `+errorChain(error))}}async flushFinalState(activation){try{await activation.handle.agent.ctx.sessions.flush(activation.handle.agent.session)}catch(error){this.ctx.logger.warn(`subagent "${activation.childId}" best-effort final session flush failed; the persisted state may be unavailable or stale on resume: ${errorChain(error)}`)}}receipt(activation){return{childId:activation.childId,result:activation.result.promise,dispose:()=>this.dispose(activation)}}async deliverToChild(parent,childId,content,options){this.assertAdmitting(parent);const releaseHold=this.holdOwnership(parent,childId);try{return await this.deliverFollowup(parent,childId,content,options)}catch(error){releaseHold();throw error}}async deliverFollowup(parent,childId,content,options){while(true){const live=await this.locks.run(childId,async()=>{const activation=this.resident.get(childId);if(activation===void 0)return this.coldResume(parent,childId,content,options);requireLocalActivation(activation);const disposal=activation.closing;if(disposal!==void 0){return disposal.then(()=>void 0,()=>void 0)}if(contentHasImage(content)){await this.assertImageCapable(requireLocalActivation(activation).handle.agent,options.signal);if(activation.closing!==void 0){await Promise.allSettled([activation.closing]);return void 0}}const messageId=this.submitAdmitted(activation,content,options,parent);this.announce(activation);return messageId});if(live!==void 0)return live;this.assertAdmitting(parent);options.signal.throwIfAborted()}}sendToParent(activation,sender,content){if(activation.closing!==void 0){throw new SubagentError(`subagent "${sender.id}" activation is being disposed; the message was not delivered`,"ACTIVATION_CLOSING")}const parent=this.ctx.agents.get(activation.parent.id);if(parent!==activation.parent){throw new SubagentError("direct parent is not live; the message was not delivered","PARENT_UNAVAILABLE")}const message=createAgentMessage(sender,content);this.sendAgentMessage(parent,message);return message.id}sendAgentMessage(parent,message){try{this.sendWaking(parent,message,"steer")}catch(error){throw new SubagentError("direct parent is not live; the message was not delivered","PARENT_UNAVAILABLE",{cause:error})}}async coldResume(parent,childId,content,options){const env_1={stack:[],error:void 0,hasError:false};try{const query=this.requireSessionQuery();let observation;try{observation=await query.observeSession(childId,{signal:options.signal})}catch(error){options.signal.throwIfAborted();throw new SubagentError(`subagent "${childId}" is unavailable`,"NOT_RESUMABLE",{cause:error})}const source=__addDisposableResource(env_1,observation,false);this.assertAdmitting(parent);this.authorizeLineage(parent,childId,source.header.parentSession);const ownEvents=source.events.slice(source.inheritedEventCount);const descriptor=foldSubagentDescriptor(ownEvents);if(descriptor===void 0||descriptor.mode!=="continuable"){throw new SubagentError(`subagent "${childId}" has no supported continuation state and cannot be resumed; choose a different target`,"NOT_RESUMABLE")}let activation;try{const independentlySelected=hasIndependentPresetSelection(ownEvents);const agentPreset=independentlySelected?source.projections?.values.agentPreset:void 0;if(independentlySelected&&typeof agentPreset!=="string"){throw new SubagentError(`subagent "${childId}" has no agent preset projection for restoration`,"NOT_RESUMABLE")}activation=await this.materialize({kind:"local",childId,provider:descriptor.provider,parent,agentOptions:{...descriptor.agentProvider!==void 0?{provider:descriptor.agentProvider}:{},...descriptor.agentModel!==void 0?{model:descriptor.agentModel}:{},...descriptor.agentReasoningEffort!==void 0?{reasoningEffort:ReasoningEffortId(descriptor.agentReasoningEffort)}:{}},composition:{agentPreset:agentPreset??void 0,persona:descriptor.persona,toolFilter:descriptor.toolFilter},signal:options.signal})}catch(error){options.signal.throwIfAborted();if(error instanceof SubagentError)throw error;throw new SubagentError(`subagent "${childId}" is unavailable`,"NOT_RESUMABLE",{cause:error})}return await this.submitMaterialized(activation,content,options,parent)}catch(e_1){env_1.error=e_1;env_1.hasError=true}finally{__disposeResources(env_1)}}async submitMaterialized(activation,content,options,parent,commit){try{if(contentHasImage(content)){await this.assertImageCapable(requireLocalActivation(activation).handle.agent,options.signal);if(activation.closing!==void 0){throw new SubagentError(`subagent "${activation.childId}" is closing`,"ACTIVATION_CLOSING")}}const messageId=this.submitAdmitted(activation,content,options,parent);commit?.();this.announce(activation);if(activation.kind==="local"&&activation.approvalOriginCandidate){const child=activation.handle.agent;const proof=activation.approvalOriginCandidate.publish(()=>{this.assertAdmitting(parent);if(this.draining||!activation.announced||activation.closing!==void 0||this.resident.get(child.id)!==activation||activation.parent!==parent||activation.handle.agent!==child)throw new SubagentError("child activation is no longer live","UNAUTHORIZED")});if(proof)this.approvalOrigins.set(child,proof);activation.approvalOriginCandidate=void 0}return messageId}catch(error){try{await this.dispose(activation)}catch(cleanupError){this.ctx.logger.warn(`subagent continuation: disposal after admission or catalog append failure also failed: ${String(cleanupError)}`)}throw error}}submitAdmitted(activation,content,options,parent){const message=options.source===void 0?createAgentMessage(parent,content):createUserMessage2({content,source:options.source});options.signal.throwIfAborted();this.assertAdmitting(parent);this.authorizeLineage(parent,activation.childId,activation.parent.id);this.acquireOwnership(parent,activation.childId);try{this.deliver(activation,message,options.delivery)}finally{this.wake(activation)}return message.id}async assertImageCapable(agent,signal){const{provider,model}=agent.options;if(provider===void 0||model===void 0)return;const llm=this.ctx.get("llm");if(llm===void 0)return;const info=await llm.resolveModelInfo(provider,model,signal);if(info.inputModalities!==void 0&&!info.inputModalities.includes("image")){throw new SubagentError(`Model "${model}" does not support image input.`,"MODEL_DOES_NOT_SUPPORT_IMAGES")}}requirePersistence(){const persistence=this.ctx.get("sessionPersistence");if(persistence===void 0){throw new SubagentError("continuable subagents require session persistence (load a dsh-session-persistence backend)","PERSISTENCE_UNAVAILABLE")}return persistence}requireSessionQuery(){const query=this.ctx.get("sessionQuery");if(query===void 0){throw new SubagentError("continuable subagents require session query (load @deepseek-ai/dsh-session-query)","CONTINUATION_UNAVAILABLE")}return query}};var manager_default=SubagentManager;function hasIndependentPresetSelection(events){for(const event of events){if(event.type==="subagent/descriptor")return false;if(event.type==="agent-preset/selected")return true}return false}var __addDisposableResource2=function(env,value,async){if(value!==null&&value!==void 0){if(typeof value!=="object"&&typeof value!=="function")throw new TypeError("Object expected.");var dispose,inner;if(async){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");dispose=value[Symbol.asyncDispose]}if(dispose===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");dispose=value[Symbol.dispose];if(async)inner=dispose}if(typeof dispose!=="function")throw new TypeError("Object not disposable.");if(inner)dispose=function(){try{inner.call(this)}catch(e){return Promise.reject(e)}};env.stack.push({value,dispose,async})}else if(async){env.stack.push({async:true})}return value};var __disposeResources2=(function(SuppressedError2){return function(env){function fail(e){env.error=env.hasError?new SuppressedError2(e,env.error,"An error was suppressed during disposal."):e;env.hasError=true}var r,s=0;function next(){while(r=env.stack.pop()){try{if(!r.async&&s===1)return s=0,env.stack.push(r),Promise.resolve().then(next);if(r.dispose){var result=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(result).then(next,function(e){fail(e);return next()})}else s|=1}catch(e){fail(e)}}if(s===1)return env.hasError?Promise.reject(env.error):Promise.resolve();if(env.hasError)throw env.error}return next()}})(typeof SuppressedError==="function"?SuppressedError:function(error,suppressed,message){var e=new Error(message);return e.name="SuppressedError",e.error=error,e.suppressed=suppressed,e});async function listChildren(ctx,parentSessionId,signal){const env_1={stack:[],error:void 0,hasError:false};try{const query=ctx.get("sessionQuery");if(query===void 0){throw new SubagentError("listing subagents requires the sessionQuery service (load @deepseek-ai/dsh-session-query)","SUBAGENT_CONTROL_QUERY_UNAVAILABLE")}const parent=__addDisposableResource2(env_1,await query.observeSession(parentSessionId,{...signal===void 0?{}:{signal}}),false);const entries=parent.projections?.values.subagentCatalog;if(entries===void 0){throw new SubagentError("listing subagents requires the registered subagentCatalog projection","SUBAGENT_CONTROL_PROJECTIONS_UNAVAILABLE")}return entries}catch(e_1){env_1.error=e_1;env_1.hasError=true}finally{__disposeResources2(env_1)}}async function listDescendants(ctx,rootSessionId,signal){const sessions=ctx.get("sessions");if(sessions===void 0){throw new SubagentError("listing subagents requires the session store (load @deepseek-ai/dsh-session)","SUBAGENT_CONTROL_SESSION_STORE_UNAVAILABLE")}const readChildren=async id=>{assertListingNotCancelled(signal);let children;try{children=await listChildren(ctx,id,signal)}catch(error){assertListingNotCancelled(signal);throw error}assertListingNotCancelled(signal);return children};const stack=(await readChildren(rootSessionId)).map(entry=>({entry,parentId:rootSessionId,depth:1})).reverse();const visited=new Set([rootSessionId]);const result=[];for(let position=stack.pop();position!==void 0;position=stack.pop()){const{entry,parentId,depth}=position;if(visited.has(entry.id))continue;visited.add(entry.id);let children;try{children=entry.mode==="external"?[]:await readChildren(entry.id)}catch(error){if(error instanceof SubagentError)throw error;const code=error instanceof Error&&"code"in error?error.code:void 0;result.push({kind:"diagnostic",id:entry.id,parentId,depth,reason:code==="SESSION_QUERY_CORRUPT_SESSION"||code==="SESSION_QUERY_SOURCE_CONFLICT"?"corrupt":"unavailable"});continue}if(entry.mode==="unknown"){result.push({kind:"diagnostic",id:entry.id,parentId,depth,reason:"unsupported"})}else{const{createdAt:_createdAt,...identity}=entry;result.push({...identity,kind:"child",parentId,depth,activity:sessions.get(entry.id)===void 0?"inactive":"running",hasChildren:children.length>0})}for(const child of[...children].reverse()){stack.push({entry:child,parentId:entry.id,depth:depth+1})}}return result}function assertListingNotCancelled(signal){if(signal?.aborted){throw new SubagentError("subagent listing was cancelled","CANCELLED")}}var __addDisposableResource3=function(env,value,async){if(value!==null&&value!==void 0){if(typeof value!=="object"&&typeof value!=="function")throw new TypeError("Object expected.");var dispose,inner;if(async){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");dispose=value[Symbol.asyncDispose]}if(dispose===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");dispose=value[Symbol.dispose];if(async)inner=dispose}if(typeof dispose!=="function")throw new TypeError("Object not disposable.");if(inner)dispose=function(){try{inner.call(this)}catch(e){return Promise.reject(e)}};env.stack.push({value,dispose,async})}else if(async){env.stack.push({async:true})}return value};var __disposeResources3=(function(SuppressedError2){return function(env){function fail(e){env.error=env.hasError?new SuppressedError2(e,env.error,"An error was suppressed during disposal."):e;env.hasError=true}var r,s=0;function next(){while(r=env.stack.pop()){try{if(!r.async&&s===1)return s=0,env.stack.push(r),Promise.resolve().then(next);if(r.dispose){var result=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(result).then(next,function(e){fail(e);return next()})}else s|=1}catch(e){fail(e)}}if(s===1)return env.hasError?Promise.reject(env.error):Promise.resolve();if(env.hasError)throw env.error}return next()}})(typeof SuppressedError==="function"?SuppressedError:function(error,suppressed,message){var e=new Error(message);return e.name="SuppressedError",e.error=error,e.suppressed=suppressed,e});function installSubagentArchiveAdmission(ctx){ctx.on("workspace/session-activity",async({sessionId},next)=>{const running=runningDescendants(ctx,sessionId);const rest=await next();if(running.length===0)return rest;const own={kind:"subagent",items:await Promise.all(running.map(child=>describe(ctx,child)))};return[own,...rest]});ctx.on("workspace/session-stop",({sessionId})=>{for(const child of runningDescendants(ctx,sessionId)){try{child.cancel({kind:"parent"})}catch(error){ctx.logger.warn(`subagent: cancelling "${child.id}" for an archived Session failed: ${String(error)}`)}}})}function runningDescendants(ctx,rootId){const childrenOf=new Map;for(const agent of ctx.agents.list()){const{parentSession,origin}=agent.session.header;if(parentSession===void 0||origin!=="subagent")continue;const siblings=childrenOf.get(parentSession)??[];siblings.push(agent);childrenOf.set(parentSession,siblings)}const running=[];const pending=[rootId];const visited=new Set;while(pending.length>0){const parentId=pending.shift();if(visited.has(parentId))continue;visited.add(parentId);for(const child of childrenOf.get(parentId)??[]){if(child.status==="running")running.push(child);pending.push(child.id)}}return running}async function describe(ctx,child){const query=ctx.get("sessionQuery");if(query===void 0)return{id:child.id};try{const env_1={stack:[],error:void 0,hasError:false};try{const observation=__addDisposableResource3(env_1,await query.observeSession(child.id,{projectionMode:"none"}),false);const label=foldSubagentDescriptor(observation.events.slice(observation.inheritedEventCount))?.label;return label===void 0?{id:child.id}:{id:child.id,label}}catch(e_1){env_1.error=e_1;env_1.hasError=true}finally{__disposeResources3(env_1)}}catch{return{id:child.id}}}import{z as z3}from"zod";import{SessionSeq}from"@deepseek-ai/dsh-session";var activeIntervalSchema=z3.object({since:z3.number().int().nonnegative(),through:z3.number().int().nonnegative()}).strict();var projectionSchema=z3.object({settledMs:z3.number().int().nonnegative(),active:activeIntervalSchema.optional(),lastTurnCompleted:z3.boolean().optional()}).strict().transform(({settledMs,active,lastTurnCompleted})=>({settledMs,...active===void 0?{}:{active},...lastTurnCompleted===void 0?{}:{lastTurnCompleted}}));var timingStateSchema=z3.object({settledMs:z3.number().int().nonnegative(),active:activeIntervalSchema.optional(),pendingTurnStart:z3.number().int().nonnegative().optional(),descriptorSeen:z3.boolean(),lastTurnCompleted:z3.boolean().optional()}).strict();var subagentTimingProjectionDefinition={key:"subagentTiming",stateSchema:timingStateSchema,init:()=>({descriptorSeen:false,settledMs:0}),apply:(state,event)=>{if(event.type==="turn/start"){const{lastTurnCompleted:_closed,...openState}=state;return state.descriptorSeen?{...openState,active:{since:event.time,through:event.time}}:{...openState,pendingTurnStart:event.time}}if(event.type==="subagent/descriptor"){const activeSince=state.active?.since??state.pendingTurnStart;return{descriptorSeen:true,settledMs:0,...activeSince===void 0?{}:{active:{since:activeSince,through:event.time}}}}if(event.type==="turn/end"){if(!state.descriptorSeen){if(state.pendingTurnStart===void 0)return state;const{pendingTurnStart:_closed,...next}=state;return next}if(state.active===void 0)return state;const{active,...rest}=state;return{...rest,settledMs:state.settledMs+Math.max(0,event.time-active.since),lastTurnCompleted:event.data.reason.kind==="completed"}}if(state.active===void 0)return state;return{...state,active:{...state.active,through:event.time}}},wire:{viewSchema:projectionSchema,view:state=>({settledMs:state.settledMs,...state.active===void 0?{}:{active:state.active},...state.lastTurnCompleted===void 0?{}:{lastTurnCompleted:state.lastTurnCompleted}})},stateVersion:3};var identityValueSchema=z3.discriminatedUnion("mode",[z3.object({mode:z3.literal("one-shot"),label:z3.string().optional(),seq:z3.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).transform(SessionSeq)}).strict(),z3.object({mode:z3.literal("continuable"),label:z3.string(),seq:z3.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).transform(SessionSeq)}).strict()]);var identitySchema=identityValueSchema.nullable();var identityStateSchema=z3.object({identity:identityValueSchema.optional()}).strict();function descriptorIdentity(event){let descriptor;try{descriptor=foldSubagentDescriptor([event])}catch{descriptor=void 0}if(descriptor===void 0)return void 0;return descriptor.mode==="one-shot"?{mode:"one-shot",...descriptor.label!==void 0?{label:descriptor.label}:{},seq:event.seq}:{mode:"continuable",label:descriptor.label,seq:event.seq}}var subagentIdentityProjectionDefinition={key:"subagent",stateSchema:identityStateSchema,init:()=>({}),apply:(state,event)=>{if(event.type!=="subagent/descriptor")return state;const identity=descriptorIdentity(event);return identity===void 0?{}:{identity}},wire:{viewSchema:identitySchema,view:state=>state.identity??null},stateVersion:2};import{accessSync,constants,statSync}from"node:fs";import{isAbsolute as isAbsolute2}from"node:path";var MAX_SUBAGENT_DIAGNOSTIC_BYTES=4096;var DIAGNOSTIC_TRUNCATION_SUFFIX="\n[diagnostic truncated]";var utf8Encoder=new TextEncoder;var utf8Decoder=new TextDecoder;function limitSubagentDiagnostic(diagnostic){const bytes=utf8Encoder.encode(diagnostic);if(bytes.byteLength<=MAX_SUBAGENT_DIAGNOSTIC_BYTES)return diagnostic;const suffixBytes=utf8Encoder.encode(DIAGNOSTIC_TRUNCATION_SUFFIX).byteLength;let prefixBytes=MAX_SUBAGENT_DIAGNOSTIC_BYTES-suffixBytes;while((bytes[prefixBytes]&192)===128){prefixBytes-=1}return utf8Decoder.decode(bytes.subarray(0,prefixBytes))+DIAGNOSTIC_TRUNCATION_SUFFIX}function normalizeSubagentDiagnostic(result){return result.diagnostic===void 0?result:{...result,diagnostic:limitSubagentDiagnostic(result.diagnostic)}}var NO_START_CAPABILITIES=Object.freeze({agentOptions:false,agentPreset:false,outputSchema:false,depthLimit:false});function assertPositiveFinite(prefix,name,value){if(!Number.isFinite(value)||value<=0){throw new Error(`${prefix}: ${name} must be a positive finite number`)}}function isEnterableDirectory(path){try{if(!statSync(path).isDirectory())return false;accessSync(path,constants.X_OK);return true}catch{return false}}function assertUsableCwd(prefix,label,cwd){if(!isAbsolute2(cwd)){throw new Error(`${prefix}: ${label} must be an absolute path: ${cwd}`)}if(!isEnterableDirectory(cwd)){throw new Error(`${prefix}: ${label} is not an accessible directory: ${cwd}`)}return cwd}function toError(value){return value instanceof Error?value:new Error(String(value))}async function settleRunResult(parts){try{const result=await parts.attempt();return parts.cancelled()?{output:parts.collectOutput(),stopReason:"aborted"}:normalizeSubagentDiagnostic(result)}catch(error){if(parts.cancelled())return{output:parts.collectOutput(),stopReason:"aborted"};try{parts.onError?.(toError(error),"error")}catch{}const collected=parts.collectDiagnostic?.();const diagnostic=collected===void 0?void 0:limitSubagentDiagnostic(collected);return{output:parts.collectOutput(),...diagnostic===void 0?{}:{diagnostic},stopReason:"error"}}finally{parts.signal.removeEventListener("abort",parts.onAbort)}}function subprocessRunHandle(parts){let disposal;return{id:parts.id,result:parts.result,dispose(){if(disposal!==void 0)return disposal;parts.signal.removeEventListener("abort",parts.onAbort);parts.requestCancel();disposal=parts.teardown();return disposal}}}var __runInitializers=function(thisArg,initializers,value){var useValue=arguments.length>2;for(var i=0;i<initializers.length;i++){value=useValue?initializers[i].call(thisArg,value):initializers[i].call(thisArg)}return useValue?value:void 0};var __esDecorate=function(ctor,descriptorIn,decorators,contextIn,initializers,extraInitializers){function accept(f){if(f!==void 0&&typeof f!=="function")throw new TypeError("Function expected");return f}var kind=contextIn.kind,key=kind==="getter"?"get":kind==="setter"?"set":"value";var target=!descriptorIn&&ctor?contextIn["static"]?ctor:ctor.prototype:null;var descriptor=descriptorIn||(target?Object.getOwnPropertyDescriptor(target,contextIn.name):{});var _,done=false;for(var i=decorators.length-1;i>=0;i--){var context={};for(var p in contextIn)context[p]=p==="access"?{}:contextIn[p];for(var p in contextIn.access)context.access[p]=contextIn.access[p];context.addInitializer=function(f){if(done)throw new TypeError("Cannot add initializers after decoration has completed");extraInitializers.push(accept(f||null))};var result=(0,decorators[i])(kind==="accessor"?{get:descriptor.get,set:descriptor.set}:descriptor[key],context);if(kind==="accessor"){if(result===void 0)continue;if(result===null||typeof result!=="object")throw new TypeError("Object expected");if(_=accept(result.get))descriptor.get=_;if(_=accept(result.set))descriptor.set=_;if(_=accept(result.init))initializers.unshift(_)}else if(_=accept(result)){if(kind==="field")initializers.unshift(_);else descriptor[key]=_}}if(target)Object.defineProperty(target,contextIn.name,descriptor);done=true};var SubagentRuntime=(()=>{let _classSuper=TypertRemoteService;let _instanceExtraInitializers=[];let _prompt_decorators;let _interruptByParent_decorators;return class SubagentRuntime extends _classSuper{static{const _metadata=typeof Symbol==="function"&&Symbol.metadata?Object.create(_classSuper[Symbol.metadata]??null):void 0;_prompt_decorators=[Remote("prompt")];_interruptByParent_decorators=[Remote("interruptByParent")];__esDecorate(this,null,_prompt_decorators,{kind:"method",name:"prompt",static:false,private:false,access:{has:obj=>"prompt"in obj,get:obj=>obj.prompt},metadata:_metadata},null,_instanceExtraInitializers);__esDecorate(this,null,_interruptByParent_decorators,{kind:"method",name:"interruptByParent",static:false,private:false,access:{has:obj=>"interruptByParent"in obj,get:obj=>obj.interruptByParent},metadata:_metadata},null,_instanceExtraInitializers);if(_metadata)Object.defineProperty(this,Symbol.metadata,{enumerable:true,configurable:true,writable:true,value:_metadata})}config=__runInitializers(this,_instanceExtraInitializers);static Config=z4.object({maxDepth:z4.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(1).volatile(),maxActiveSubagents:z4.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(8).volatile()});static inject=["workingDirectory"];providers=new Map;manager;creationApprovalOf(child){return this.manager?.creationApprovalOf(child)}emitLifecycle;constructor(ctx,config){super(ctx,"subagents");this.config=config;this.emitLifecycle=createLifecycleEmitter(this.ctx,parent=>scopeTarget(this,parent));ctx.inject(["agents"],childCtx=>{const manager=new manager_default(childCtx,{startExternal:(name,request)=>{const provider=this.expectProvider(name);return provider.start(request)},prepareContinuable:(name,request)=>this.prepareContinuable(name,request),observeActivation:(provider,childId,parent)=>this.observeActivation(provider,childId,parent)},()=>this.config.maxActiveSubagents.get());this.manager=manager;childCtx.effect(()=>()=>{if(this.manager===manager)this.manager=void 0},"subagents.managerBinding()")});ctx.inject(["sessionProjections"],projectionCtx=>{projectionCtx.sessionProjections.register(subagentCatalogProjectionDefinition);projectionCtx.sessionProjections.register(subagentTimingProjectionDefinition);projectionCtx.sessionProjections.register(subagentIdentityProjectionDefinition)});ctx.inject(["agents"],agentsCtx=>{installSubagentArchiveAdmission(agentsCtx)})}resolveMaxDepth(configured){if(configured==="provider-managed")return void 0;if(configured!==void 0)return configured;const depth=this.config.maxDepth.get();assertSubagentMaxDepth(depth);return depth}async startActivation(spec){const provider=this.expectProvider(spec.provider);if(spec.childId!==void 0&&provider.prepareContinuable===void 0){throw new SubagentError("reserved child ids require a local backend","UNSUPPORTED_CAPABILITY")}assertSubagentMaxDepth(spec.request.maxDepth);this.assertCapabilities(provider,{...spec.request,signal:spec.signal});const manager=this.requireManager();if(this.ctx.get("agents")?.get(spec.request.parent.id)!==spec.request.parent){throw new SubagentError("subagent creation requires the exact live parent agent","UNAUTHORIZED")}if(spec.request.outputSchema!==void 0)assertObjectJsonSchema(spec.request.outputSchema);return provider.prepareContinuable===void 0?manager.startExternal(spec):manager.startLocal(spec)}async waitForChildren(parent){return this.manager?.waitForChildren(parent)??false}async sendMessage(sender,targetId,content,options){return this.requireManager().sendMessage(sender,targetId,content,options)}[deliverSubagentPrompt](parent,childId,content,source,signal,delivery){return delivery==="steer"?this.requireManager().steerPrompt(parent,childId,content,source,signal):this.requireManager().queuePrompt(parent,childId,content,source,signal)}interrupt(targetSessionId,authority){this.manager?.interrupt(targetSessionId,authority)}async drainDescendants(parents){const manager=this.manager;if(manager===void 0)return;await manager.drainDescendants(parents)}async drainChildren(parent,childIds){const manager=this.manager;if(manager===void 0)return;await manager.drainChildren(parent,childIds)}listChildren(parentSessionId,signal){return listChildren(this.ctx,parentSessionId,signal)}listDescendants(rootSessionId,signal){return listDescendants(this.ctx,rootSessionId,signal)}async prompt(request,signal){const{parentSessionId,childSessionId,clientTimeZone,delivery}=request;validateControlRequest("subagent.prompt",request);const canonicalTimeZone=clientTimeZone===void 0?void 0:canonicalClientTimeZone(clientTimeZone);if(clientTimeZone!==void 0&&canonicalTimeZone===void 0){throw new RemoteError2("subagent/invalid-time-zone","clientTimeZone must be UTC or a valid IANA Area/Location name",{value:clientTimeZone})}const parent=this.ctx.get("agents")?.get(parentSessionId);if(parent===void 0){throw new RemoteError2("subagent/parent-unavailable",`parent session "${parentSessionId}" is not live`,{parentSessionId})}const principal=principalOf(this.ctx.invocation);const source={kind:"user",rpcId:request.requestId,...canonicalTimeZone===void 0?{}:{clientTimeZone:canonicalTimeZone},...principal===void 0?{}:{principal}};try{let content;if(request.content.every(part=>part.type==="text")){content=request.content.map(part=>({type:"text",text:part.text}))}else{const attachments=this.ctx.get("attachments");if(attachments===void 0)throw new Error("subagent image prompt requires an attachment store");content=await attachments.admitPromptContent(request.content)}return{messageId:await this[deliverSubagentPrompt](parent,childSessionId,content,source,signal,delivery)}}catch(error){return rejectPrompt(error,childSessionId,signal)}}interruptByParent(childSessionId,parentSessionId,mode){validateControlRequest("subagent.interrupt",{childSessionId,parentSessionId,mode});try{this.interrupt(childSessionId,{kind:"user",parentSessionId})}catch(error){if(error instanceof SubagentError&&error.code==="UNAUTHORIZED"){throw new RemoteError2("subagent/unauthorized","subagent does not belong to this parent",{childSessionId},{cause:error})}throw new RemoteError2("gateway/internal","subagent interrupt failed",{},{cause:error})}return{accepted:true}}registerProvider(provider){const name=provider.name;if(provider.start===void 0&&provider.prepareContinuable===void 0){throw new SubagentError(`subagent provider "${name}" must implement start or prepareContinuable`,"UNSUPPORTED_CAPABILITY")}return this.ctx.effect(function*(){if(this.providers.has(name)){throw new SubagentError(`a subagent provider named "${name}" is already registered`,"DUPLICATE_PROVIDER")}this.providers.set(name,provider);yield()=>{this.providers.delete(name);this.emitLifecycle("subagent/provider-removed",name)};this.ctx.emit("subagent/provider-added",provider)}.bind(this),"subagents.registerProvider()")}getProvider(name){return this.providers.get(name)}list(){return[...this.providers.keys()]}async prepareContinuable(name,request){const provider=this.expectProvider(name);return provider.prepareContinuable(request)}expectProvider(name){const provider=this.providers.get(name);if(provider===void 0){throw new SubagentError(`no subagent provider registered for "${name}"`,"NO_PROVIDER")}return provider}requireManager(){if(this.manager===void 0){throw new SubagentError("continuable subagents require the agents service","CONTINUATION_UNAVAILABLE")}return this.manager}observeActivation(provider,childId,parent){return createActivationObserver(this.emitLifecycle,provider,childId,parent)}assertCapabilities(provider,request){if(request.agentPreset!==void 0&&(!provider.capabilities.agentPreset||provider.inheritsParentContext)){throw new SubagentError(`subagent provider "${provider.name}" does not support independent agent preset selection`,"UNSUPPORTED_CAPABILITY")}const needs=[{when:request.agentOptions!==void 0,cap:"agentOptions"},{when:request.outputSchema!==void 0,cap:"outputSchema"},{when:request.maxDepth!==void 0,cap:"depthLimit"}];for(const{when,cap}of needs){if(when&&!provider.capabilities[cap]){throw new SubagentError(`subagent provider "${provider.name}" does not support the "${cap}" capability`,"UNSUPPORTED_CAPABILITY")}}}}})();var index_default=SubagentRuntime;export{AssistantOutputFold,NO_START_CAPABILITIES,STRUCTURED_OUTPUT_TOOL,SUBAGENT_DESCRIPTOR_VERSION,SubagentDepthError,SubagentError,SubagentRunId,SubagentRuntime,appendDelegatedPolicyOverrides,applyChildComposition,assertPositiveFinite,assertSubagentMaxDepth,assertUsableCwd,captureDelegatedPolicyOverrides,childSessionMeta,index_default as default,delegationDepthOf,finalAssistantOutput,foldSubagentDescriptor,parentAgentOptionsForDelegation,resolveChildAgentOptions,resolveChildDepth,settleRunResult,snapshotSubagentDescriptor,subprocessRunHandle};
3339
- diff --git a/lib/types/creation-approval.d.ts b/lib/types/creation-approval.d.ts
3340
- new file mode 100644
3341
- index 0000000000000000000000000000000000000000..0d0e2281e284661bf5745bdc53fd72ffb45eab3e
3342
- --- /dev/null
3343
- +++ b/lib/types/creation-approval.d.ts
3344
- @@ -0,0 +1,8 @@
3345
- +import type { Agent } from '@deepseek-ai/dsh-agent';
3346
- +/** Live creation fact, not permission. Never reconstructed from history or provider data. */
3347
- +export interface LiveChildApprovalOrigin {
3348
- + readonly parent: Agent;
3349
- + readonly child: Agent;
3350
- + /** Requires the exact native delegation record as well as live ownership and policy ceilings. */
3351
- + assertCurrent(parent: Agent, child: Agent): void;
3352
- +}
3353
- diff --git a/lib/types/creation-approval.js b/lib/types/creation-approval.js
3354
- new file mode 100644
3355
- index 0000000000000000000000000000000000000000..67a48b82105a2ae8d501d505be4aa883fd4862cb
3356
- --- /dev/null
3357
- +++ b/lib/types/creation-approval.js
3358
- @@ -0,0 +1,60 @@
3359
- +import { symbols } from '@deepseek-ai/cordis';
3360
- +import { ApprovalService } from '@deepseek-ai/dsh-user-approval';
3361
- +import { SubagentError } from './error.js';
3362
- +const original = value => value?.[symbols.original] ?? value;
3363
- +const refused = () => { throw new SubagentError('fresh child approval origin is no longer current', 'UNAUTHORIZED'); };
3364
- +function record(session) {
3365
- + for (let seq = session.seq - 1; seq >= 0; seq--) {
3366
- + const event = session.eventAt(seq);
3367
- + if (event?.type === 'approval/policy') return { seq, event };
3368
- + }
3369
- +}
3370
- +function sameRecord(a, b) { return a?.seq === b?.seq && a?.event === b?.event; }
3371
- +function snapshot(agent) {
3372
- + const service = agent.ctx.get('approval'), owner = original(service);
3373
- + if (!owner || Object.getPrototypeOf(owner) !== ApprovalService.prototype || owner.overrideOf !== ApprovalService.prototype.overrideOf) return;
3374
- + const config = owner.config, configured = config.policy ?? 'ask', override = service.overrideOf(agent.session);
3375
- + if (configured !== 'ask' && configured !== 'never' || override !== undefined && override !== 'ask' && override !== 'never') return;
3376
- + return { realm: agent.ctx, session: agent.session, service: owner, config, configured, override, effective: override ?? configured, record: record(agent.session) };
3377
- +}
3378
- +function sameService(a, b) {
3379
- + return !!a && !!b && a.realm === b.realm && a.session === b.session && a.service === b.service && a.config === b.config && a.configured === b.configured;
3380
- +}
3381
- +function unrestricted(value) { return value && value.configured === 'ask' && value.effective === 'ask'; }
3382
- +
3383
- +/** Captured by startLocal before its first await; no other creation path mints this fact. */
3384
- +export function captureCreationApproval(parent, registry) {
3385
- + try {
3386
- + const parentState = snapshot(parent), parentRealm = parent.ctx, agents = original(registry);
3387
- + const subagents = original(parent.ctx.get('subagents'));
3388
- + if (!unrestricted(parentState) || !subagents) return;
3389
- + return {
3390
- + beforeDefault(child) { try { const value = snapshot(child); return unrestricted(value) ? value : undefined; } catch { return; } },
3391
- + delegationRecord(child) { return record(child.session); },
3392
- + candidate(child, initial, before, delegated) {
3393
- + try {
3394
- + const childState = snapshot(child);
3395
- + if (!initial || !before || !childState || childState.configured !== 'ask' || childState.override !== 'never'
3396
- + || delegated?.event.data.policy !== 'never' || !sameRecord(delegated, childState.record)) return;
3397
- + const live = () => {
3398
- + const currentParent = snapshot(parent), currentChild = snapshot(child);
3399
- + if (parent.ctx !== parentRealm || original(parent.ctx.get('agents')) !== agents || original(child.ctx.get('agents')) !== agents
3400
- + || original(parent.ctx.get('subagents')) !== subagents || registry.get(parent.id) !== parent || registry.get(child.id) !== child
3401
- + || !registry.isOwnedBy(child.id, parent) || child.session.header.parentSession !== parent.id
3402
- + || !sameService(parentState, currentParent) || !sameRecord(parentState.record, currentParent.record)
3403
- + || !unrestricted(currentParent) || currentParent.override !== parentState.override || !sameService(childState, currentChild)) refused();
3404
- + };
3405
- + return { publish(assertActivation) {
3406
- + const assertLive = () => { assertActivation(); live(); };
3407
- + const origin = Object.freeze({ parent, child, assertCurrent(expectedParent, expectedChild) {
3408
- + assertLive();
3409
- + if (expectedParent !== parent || expectedChild !== child || snapshot(child)?.override !== 'never' || !sameRecord(delegated, record(child.session))) refused();
3410
- + } });
3411
- + try { origin.assertCurrent(parent, child); } catch { return; }
3412
- + return { origin, assertLive };
3413
- + } };
3414
- + } catch { return; }
3415
- + },
3416
- + };
3417
- + } catch { return; }
3418
- +}
3419
- diff --git a/lib/types/index.d.ts b/lib/types/index.d.ts
3420
- index 1d8e649715fc15ba2a4aafd4ff28abf48f1c7714..855b832a197b3b04f209843c52b50421362d37c3 100644
3421
- --- a/lib/types/index.d.ts
3422
- +++ b/lib/types/index.d.ts
3423
- @@ -103,6 +103,8 @@ export interface Config {
3424
- }
3425
- /** Named provider registry with managed activations, durable discovery, and local child messaging. */
3426
- export declare class SubagentRuntime extends TypertRemoteService {
3427
- + /** Fresh live creation fact; assertCurrent is required before interpreting default never. */
3428
- + creationApprovalOf(child: Agent): import('./creation-approval.js').LiveChildApprovalOrigin | undefined;
3429
- private config;
3430
- static Config: z<Schemastery.ObjectS<NoInfer<{
3431
- maxDepth: z<number, number, "volatile-defined">;
3432
- @@ -315,5 +317,6 @@ export declare class SubagentRuntime extends TypertRemoteService {
3433
- /** Reject the first requested capability that the provider lacks. */
3434
- private assertCapabilities;
3435
- }
3436
- +export type { LiveChildApprovalOrigin } from './creation-approval.js';
3437
- export default SubagentRuntime;
3438
- //# sourceMappingURL=index.d.ts.map
3439
- diff --git a/lib/types/index.js b/lib/types/index.js
3440
- index 8d4a7e8c7048c5e7c0c0b153c17317ec3e067255..b03f3bc3384c42a7ca50544bd256ca60654b9345 100644
3441
- --- a/lib/types/index.js
3442
- +++ b/lib/types/index.js
3443
- @@ -78,6 +78,7 @@ let SubagentRuntime = (() => {
3444
- static inject = ['workingDirectory'];
3445
- providers = new Map();
3446
- manager;
3447
- + creationApprovalOf(child) { return this.manager?.creationApprovalOf(child); }
3448
- /**
3449
- * The contained lifecycle-edge publisher. Built here because scoped dispatch
3450
- * keys its carrier by this exact service instance, whose own context filter
3451
- diff --git a/lib/types/manager.js b/lib/types/manager.js
3452
- index 228318234cb4764e371cfac9a34700406833fbd9..51c580f4577e0f265fef79bd6d4779d234b289f1 100644
3453
- --- a/lib/types/manager.js
3454
- +++ b/lib/types/manager.js
3455
- @@ -63,6 +63,7 @@ import { brandString } from '@deepseek-ai/dsh-brand';
3456
- import { ReasoningEffortId, contentHasImage, createUserMessage, errorChain } from '@deepseek-ai/dsh-llm';
3457
- import { SessionLogOffset } from '@deepseek-ai/dsh-session';
3458
- import { appendDelegatedPolicyOverrides, applyChildComposition, captureDelegatedPolicyOverrides, childSessionMeta, resolveChildAgentOptions, resolveChildDepth, } from "./child-agent.js";
3459
- +import { captureCreationApproval } from './creation-approval.js';
3460
- import { createAgentMessage, withContinuableReturnGuidance, createSettlementMessage } from "./continuation-messages.js";
3461
- import { assertSubagentMaxDepth } from "./depth.js";
3462
- import { foldSubagentDescriptor, snapshotSubagentDescriptor } from "./descriptor.js";
3463
- @@ -82,6 +83,12 @@ export class SubagentManager {
3464
- maxActiveSubagents;
3465
- /** Child session id → its live Activation. Process-local, never durable. */
3466
- resident = new Map();
3467
- + approvalOrigins = new WeakMap();
3468
- + creationApprovalOf(child) {
3469
- + const proof = this.approvalOrigins.get(child);
3470
- + if (!proof) return;
3471
- + try { proof.assertLive(); return proof.origin; } catch { return; }
3472
- + }
3473
- /** Root identities retain their pool across child settlement without retaining dead roots. */
3474
- rootPools = new WeakMap();
3475
- /** Materializations admitted before drain, tracked through publication or rollback. */
3476
- @@ -339,6 +346,7 @@ export class SubagentManager {
3477
- // Capture before the first await: a later parent switch belongs to the
3478
- // parent's future, not to this child.
3479
- const delegatedPolicies = captureDelegatedPolicyOverrides(parent);
3480
- + const approvalOrigin = captureCreationApproval(parent, this.ctx.agents);
3481
- // An idle continuation-managed parent must not settle while a caller is
3482
- // still creating its child. A turn-scoped delegation does not need this,
3483
- // but the service is also callable outside a turn.
3484
- @@ -380,6 +388,7 @@ export class SubagentManager {
3485
- meta: childSessionMeta(parent, childDepth, prepared.seed !== undefined, request.agentPreset),
3486
- inheritedEventCount,
3487
- delegatedPolicies,
3488
- + approvalOrigin,
3489
- descriptor,
3490
- },
3491
- agentOptions,
3492
- @@ -759,7 +768,10 @@ export class SubagentManager {
3493
- else {
3494
- const { create } = inputs;
3495
- let structured;
3496
- + let approvalOriginCandidate;
3497
- const setup = async (childCtx, child) => {
3498
- + const initialApproval = create?.approvalOrigin?.beforeDefault(child);
3499
- + let beforeDefault, delegatedRecord;
3500
- // Only fresh creation appends the descriptor and delegated policy after
3501
- // the inherited marker; a cold resume replays those persisted events.
3502
- if (inputs.composition.agentPreset !== undefined) {
3503
- @@ -770,7 +782,9 @@ export class SubagentManager {
3504
- child.session.append('agent-preset/selected', { agentPreset: inputs.composition.agentPreset });
3505
- }
3506
- child.session.append('subagent/descriptor', create.descriptor);
3507
- + beforeDefault = create.approvalOrigin?.beforeDefault(child);
3508
- appendDelegatedPolicyOverrides(child.session, create.delegatedPolicies);
3509
- + delegatedRecord = create.approvalOrigin?.delegationRecord(child);
3510
- const workingDirectory = childCtx.get('workingDirectory');
3511
- if (workingDirectory === undefined)
3512
- throw new Error('local subagents require the working-directory service');
3513
- @@ -778,6 +792,7 @@ export class SubagentManager {
3514
- }
3515
- if (inputs.composition.agentPreset === undefined)
3516
- await applyChildComposition(childCtx, parent, inputs.composition);
3517
- + approvalOriginCandidate = create?.approvalOrigin?.candidate(child, initialApproval, beforeDefault, delegatedRecord);
3518
- if (inputs.outputSchema !== undefined) {
3519
- structured = attachStructuredRuntime(childCtx, inputs.outputSchema, () => this.resident.get(childId)?.ownedChildren.size === 0
3520
- && child.inbox.nextStep.length === 0
3521
- @@ -802,7 +817,7 @@ export class SubagentManager {
3522
- signal: inputs.signal,
3523
- setup,
3524
- });
3525
- - resource = { kind: 'local', handle, outputStart: handle.agent.session.seq, structured, failureAt: undefined, poke: Promise.withResolvers() };
3526
- + resource = { kind: 'local', handle, outputStart: handle.agent.session.seq, structured, failureAt: undefined, poke: Promise.withResolvers(), approvalOriginCandidate };
3527
- }
3528
- const observer = this.host.observeActivation(provider, childId, parent);
3529
- const activation = {
3530
- @@ -1241,6 +1256,16 @@ export class SubagentManager {
3531
- const messageId = this.submitAdmitted(activation, content, options, parent);
3532
- commit?.();
3533
- this.announce(activation);
3534
- + if (activation.kind === 'local' && activation.approvalOriginCandidate) {
3535
- + const child = activation.handle.agent;
3536
- + const proof = activation.approvalOriginCandidate.publish(() => {
3537
- + this.assertAdmitting(parent);
3538
- + if (this.draining || !activation.announced || activation.closing !== undefined || this.resident.get(child.id) !== activation
3539
- + || activation.parent !== parent || activation.handle.agent !== child) throw new SubagentError('child activation is no longer live', 'UNAUTHORIZED');
3540
- + });
3541
- + if (proof) this.approvalOrigins.set(child, proof);
3542
- + activation.approvalOriginCandidate = undefined;
3543
- + }
3544
- return messageId;
3545
- }
3546
- catch (error) {