@toddzheng024/dscode-desktop 0.0.0-stage → 0.7.33

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