somora 2026.930.1

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 (404) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +364 -0
  3. package/bin/node-version.d.mts +3 -0
  4. package/bin/node-version.mjs +45 -0
  5. package/bin/somora.mjs +77 -0
  6. package/config.example.yaml +896 -0
  7. package/docs/agents.md +677 -0
  8. package/docs/api.md +3194 -0
  9. package/docs/browser.md +317 -0
  10. package/docs/builder.md +331 -0
  11. package/docs/cache-strategy.md +373 -0
  12. package/docs/compaction.md +253 -0
  13. package/docs/display.md +154 -0
  14. package/docs/dream-phases.md +891 -0
  15. package/docs/files.md +387 -0
  16. package/docs/imagegen.md +366 -0
  17. package/docs/images/somora-hero.png +0 -0
  18. package/docs/images/somora-mobile-2026-05-23.png +0 -0
  19. package/docs/images/somora-tui-2026-05-23.png +0 -0
  20. package/docs/images/somora-web-2026-05-23.png +0 -0
  21. package/docs/index.md +178 -0
  22. package/docs/lsp.md +93 -0
  23. package/docs/mcp.md +332 -0
  24. package/docs/memory.md +407 -0
  25. package/docs/mobile.md +310 -0
  26. package/docs/models.md +379 -0
  27. package/docs/projects.md +425 -0
  28. package/docs/realtime-voice.md +293 -0
  29. package/docs/resources.md +230 -0
  30. package/docs/sampling.md +128 -0
  31. package/docs/security.md +189 -0
  32. package/docs/sentinel.md +295 -0
  33. package/docs/setup.md +1217 -0
  34. package/docs/skills.md +501 -0
  35. package/docs/team.md +189 -0
  36. package/docs/thinking.md +463 -0
  37. package/docs/tmux.md +399 -0
  38. package/docs/tools.md +117 -0
  39. package/docs/videogen.md +191 -0
  40. package/docs/voice.md +288 -0
  41. package/docs/web.md +893 -0
  42. package/docs/wiki.md +583 -0
  43. package/npm-shrinkwrap.json +5670 -0
  44. package/package.json +116 -0
  45. package/src/attachments/store.ts +196 -0
  46. package/src/browser/change-stream.ts +31 -0
  47. package/src/browser/display.ts +108 -0
  48. package/src/browser/policy.ts +121 -0
  49. package/src/browser/screencast.ts +374 -0
  50. package/src/browser/service.ts +1337 -0
  51. package/src/browser/session.ts +15 -0
  52. package/src/browser/snapshot.ts +40 -0
  53. package/src/cli/auth.ts +117 -0
  54. package/src/cli/codex.ts +41 -0
  55. package/src/cli/lsp.ts +71 -0
  56. package/src/cli/resolvers/clawhub.ts +400 -0
  57. package/src/cli/setup.ts +835 -0
  58. package/src/cli/skill.ts +619 -0
  59. package/src/cli/somora.ts +548 -0
  60. package/src/cli/systemd-unit.ts +72 -0
  61. package/src/cli/team.ts +148 -0
  62. package/src/cli/tui/activity-stream.ts +121 -0
  63. package/src/cli/tui/api.ts +479 -0
  64. package/src/cli/tui/app.tsx +1169 -0
  65. package/src/cli/tui/autocomplete.tsx +55 -0
  66. package/src/cli/tui/commands.ts +913 -0
  67. package/src/cli/tui/dream-glyphs.ts +22 -0
  68. package/src/cli/tui/footer.tsx +15 -0
  69. package/src/cli/tui/format.ts +28 -0
  70. package/src/cli/tui/header.tsx +279 -0
  71. package/src/cli/tui/index.tsx +120 -0
  72. package/src/cli/tui/markdown.tsx +63 -0
  73. package/src/cli/tui/sampling.ts +162 -0
  74. package/src/cli/tui/separator.tsx +13 -0
  75. package/src/cli/tui/state.ts +42 -0
  76. package/src/cli/tui/stream.ts +330 -0
  77. package/src/cli/tui/thinking-text.ts +54 -0
  78. package/src/cli/tui/turn-views.tsx +499 -0
  79. package/src/cli/tui/types.ts +410 -0
  80. package/src/cli/tui/work-queue.ts +161 -0
  81. package/src/cli/update-args.ts +55 -0
  82. package/src/cli/wiki.ts +406 -0
  83. package/src/compaction/index.ts +28 -0
  84. package/src/compaction/midturn.ts +210 -0
  85. package/src/compaction/policy.ts +154 -0
  86. package/src/compaction/summarize.ts +691 -0
  87. package/src/compaction/template.ts +90 -0
  88. package/src/compaction/types.ts +148 -0
  89. package/src/config/loader.ts +276 -0
  90. package/src/config/reload.ts +43 -0
  91. package/src/config/types.ts +2292 -0
  92. package/src/dream/deep-actions.ts +324 -0
  93. package/src/dream/deep-dispatcher.ts +237 -0
  94. package/src/dream/deep-llm.ts +388 -0
  95. package/src/dream/deep-prompts.ts +106 -0
  96. package/src/dream/deep-runner.ts +757 -0
  97. package/src/dream/deep-skip-cache.ts +199 -0
  98. package/src/dream/deep-worker.ts +229 -0
  99. package/src/dream/json-salvage.ts +34 -0
  100. package/src/dream/judge.ts +188 -0
  101. package/src/dream/loop-state.ts +286 -0
  102. package/src/dream/lucid-actions.ts +303 -0
  103. package/src/dream/lucid-batches.ts +94 -0
  104. package/src/dream/lucid-prompt.ts +82 -0
  105. package/src/dream/lucid-runner.ts +744 -0
  106. package/src/dream/lucid-storage.ts +277 -0
  107. package/src/dream/lucid-structure.ts +102 -0
  108. package/src/dream/lucid-types.ts +137 -0
  109. package/src/dream/lucid-worker.ts +224 -0
  110. package/src/dream/rem-dedup.ts +502 -0
  111. package/src/dream/rem-extract.ts +782 -0
  112. package/src/dream/rem-reset-run.ts +67 -0
  113. package/src/dream/rem-runner.ts +696 -0
  114. package/src/dream/rem-worker.ts +527 -0
  115. package/src/dream/review-window.ts +71 -0
  116. package/src/dream/scheduler-state.ts +129 -0
  117. package/src/dream/storage.ts +497 -0
  118. package/src/dream/types.ts +133 -0
  119. package/src/dream/wiki-context.ts +133 -0
  120. package/src/engine/a2a.ts +33 -0
  121. package/src/engine/availability.ts +63 -0
  122. package/src/engine/claude-cli.ts +969 -0
  123. package/src/engine/codex-app-server-client.ts +294 -0
  124. package/src/engine/codex-bin.ts +49 -0
  125. package/src/engine/codex-cli.ts +1014 -0
  126. package/src/engine/codex-dynamic-tools.ts +239 -0
  127. package/src/engine/codex-home.ts +63 -0
  128. package/src/engine/codex-thread-config.ts +74 -0
  129. package/src/engine/context-budget.ts +257 -0
  130. package/src/engine/engine-meta-labels.ts +211 -0
  131. package/src/engine/grok-cli.ts +941 -0
  132. package/src/engine/inline-think.ts +59 -0
  133. package/src/engine/model-availability.ts +105 -0
  134. package/src/engine/openai-compatible.ts +2464 -0
  135. package/src/engine/reasoning-retry.ts +83 -0
  136. package/src/engine/registry.ts +13 -0
  137. package/src/engine/replay.ts +195 -0
  138. package/src/engine/sampling.ts +90 -0
  139. package/src/engine/thinking-params.ts +264 -0
  140. package/src/engine/types.ts +269 -0
  141. package/src/engine/user-tag.ts +24 -0
  142. package/src/imagegen/aspect.ts +128 -0
  143. package/src/imagegen/generate.ts +642 -0
  144. package/src/imagegen/references.ts +75 -0
  145. package/src/imagegen/types.ts +154 -0
  146. package/src/lsp/client.ts +183 -0
  147. package/src/lsp/fake-server.helper.mjs +42 -0
  148. package/src/lsp/format.ts +29 -0
  149. package/src/lsp/index.ts +21 -0
  150. package/src/lsp/manager.ts +238 -0
  151. package/src/lsp/registry.ts +151 -0
  152. package/src/mcp/config.ts +117 -0
  153. package/src/mcp/hub/audit.ts +55 -0
  154. package/src/mcp/hub/bridge.ts +115 -0
  155. package/src/mcp/hub/catalog.ts +69 -0
  156. package/src/mcp/hub/credentials.ts +406 -0
  157. package/src/mcp/hub/env-expand.ts +14 -0
  158. package/src/mcp/hub/manager.ts +770 -0
  159. package/src/mcp/hub/normalize.ts +213 -0
  160. package/src/mcp/server.ts +368 -0
  161. package/src/mcp/tool-schema.ts +20 -0
  162. package/src/media/capabilities.ts +392 -0
  163. package/src/media/records.ts +175 -0
  164. package/src/media/store.ts +217 -0
  165. package/src/media/types.ts +69 -0
  166. package/src/memory/chunking.ts +168 -0
  167. package/src/memory/embeddings.ts +262 -0
  168. package/src/memory/index.ts +15 -0
  169. package/src/memory/inject.ts +197 -0
  170. package/src/memory/manager.ts +996 -0
  171. package/src/memory/registry.ts +176 -0
  172. package/src/memory/rescan.ts +101 -0
  173. package/src/memory/retrieval.ts +586 -0
  174. package/src/memory/shared-index.ts +372 -0
  175. package/src/memory/slug.ts +39 -0
  176. package/src/memory/storage.ts +385 -0
  177. package/src/memory/watcher.ts +134 -0
  178. package/src/multimodal/blocks.ts +101 -0
  179. package/src/multimodal/dimensions.ts +214 -0
  180. package/src/multimodal/load.ts +86 -0
  181. package/src/multimodal/mime.ts +135 -0
  182. package/src/multimodal/pdf-render.ts +80 -0
  183. package/src/multimodal/user-content.ts +266 -0
  184. package/src/persona/files.ts +144 -0
  185. package/src/persona/loader.ts +598 -0
  186. package/src/persona/skill-gating-store.ts +59 -0
  187. package/src/persona/tool-gating-store.ts +113 -0
  188. package/src/projects/focus.ts +186 -0
  189. package/src/projects/prompt-block.ts +106 -0
  190. package/src/projects/scheme.ts +107 -0
  191. package/src/projects/store.ts +144 -0
  192. package/src/projects/types.ts +73 -0
  193. package/src/sentinel/dispatcher.ts +97 -0
  194. package/src/sentinel/schedule.ts +271 -0
  195. package/src/sentinel/scheduler.ts +840 -0
  196. package/src/sentinel/store.ts +259 -0
  197. package/src/sentinel/types.ts +221 -0
  198. package/src/server/activity-stream.ts +160 -0
  199. package/src/server/ask-calls.ts +137 -0
  200. package/src/server/ask-wait-graph.ts +171 -0
  201. package/src/server/async-tasks.ts +199 -0
  202. package/src/server/builder-busy.ts +86 -0
  203. package/src/server/builder-prompt.ts +204 -0
  204. package/src/server/builder-questions.ts +117 -0
  205. package/src/server/builder-session.ts +249 -0
  206. package/src/server/chat-aborts.ts +83 -0
  207. package/src/server/claude-config-dir.ts +71 -0
  208. package/src/server/claude-credential-sync.ts +454 -0
  209. package/src/server/env-file.ts +100 -0
  210. package/src/server/env.ts +115 -0
  211. package/src/server/heal-session.ts +151 -0
  212. package/src/server/history-page.ts +46 -0
  213. package/src/server/index.ts +7244 -0
  214. package/src/server/lockfile.ts +89 -0
  215. package/src/server/logger.ts +67 -0
  216. package/src/server/logs.ts +187 -0
  217. package/src/server/loopback-fetch.ts +130 -0
  218. package/src/server/openai-client.ts +89 -0
  219. package/src/server/prompt-assembly.ts +334 -0
  220. package/src/server/restart-reconcile.ts +139 -0
  221. package/src/server/run-turn-fallback.ts +275 -0
  222. package/src/server/run-turn-types.ts +91 -0
  223. package/src/server/run-turn.ts +1474 -0
  224. package/src/server/sanitize-assistant-text.ts +112 -0
  225. package/src/server/session-export.ts +220 -0
  226. package/src/server/session-queue.ts +376 -0
  227. package/src/server/session-workdir.ts +49 -0
  228. package/src/server/sse-h2-safe.ts +61 -0
  229. package/src/server/sse-liveness.ts +162 -0
  230. package/src/server/sse-serializer.ts +161 -0
  231. package/src/server/start-turn.ts +249 -0
  232. package/src/server/steer-inbox.ts +107 -0
  233. package/src/server/tls-keeper.ts +153 -0
  234. package/src/server/tool-format.ts +167 -0
  235. package/src/server/turn-framing.ts +52 -0
  236. package/src/server/turn-origin-kind.ts +74 -0
  237. package/src/server/turn-origin.ts +40 -0
  238. package/src/server/work-ledger.ts +975 -0
  239. package/src/server/workspace.ts +114 -0
  240. package/src/setup/config-edit.ts +201 -0
  241. package/src/setup/presets.ts +71 -0
  242. package/src/setup/prompt.ts +163 -0
  243. package/src/setup/tailscale.ts +44 -0
  244. package/src/skills/bin-checks.ts +227 -0
  245. package/src/skills/bootstrap.ts +347 -0
  246. package/src/skills/env-scope.ts +175 -0
  247. package/src/skills/gating.ts +71 -0
  248. package/src/skills/lint.ts +202 -0
  249. package/src/skills/load.ts +368 -0
  250. package/src/skills/path-helpers.ts +102 -0
  251. package/src/skills/registry.ts +178 -0
  252. package/src/ssh/exec.ts +142 -0
  253. package/src/ssh/index.ts +12 -0
  254. package/src/ssh/known-hosts.ts +109 -0
  255. package/src/ssh/pool.ts +307 -0
  256. package/src/storage/sessions.ts +602 -0
  257. package/src/team/render.ts +149 -0
  258. package/src/team/resolve.ts +122 -0
  259. package/src/team/store.ts +124 -0
  260. package/src/team/types.ts +111 -0
  261. package/src/team/write.ts +95 -0
  262. package/src/testing/isolated-home.mts +46 -0
  263. package/src/tmux/attention-watcher.ts +272 -0
  264. package/src/tmux/attention.ts +336 -0
  265. package/src/tmux/list.ts +91 -0
  266. package/src/tmux/origin-store.ts +102 -0
  267. package/src/tmux/tui-markers.ts +267 -0
  268. package/src/tools/agents/ask-cancel.ts +94 -0
  269. package/src/tools/agents/ask-result.ts +235 -0
  270. package/src/tools/agents/ask.ts +704 -0
  271. package/src/tools/agents/builder-dispatch.ts +217 -0
  272. package/src/tools/agents/images.ts +104 -0
  273. package/src/tools/agents/index.ts +42 -0
  274. package/src/tools/agents/long-task-timeouts.ts +39 -0
  275. package/src/tools/agents/session-list.ts +136 -0
  276. package/src/tools/agents/session-model.ts +106 -0
  277. package/src/tools/agents/spawn.ts +845 -0
  278. package/src/tools/agents/status.ts +589 -0
  279. package/src/tools/browser/index.ts +6 -0
  280. package/src/tools/browser/ops.ts +145 -0
  281. package/src/tools/browser/tools.ts +184 -0
  282. package/src/tools/builder/short-descriptions.ts +80 -0
  283. package/src/tools/builder/tools.ts +222 -0
  284. package/src/tools/docs/index.ts +1 -0
  285. package/src/tools/docs/tools.ts +228 -0
  286. package/src/tools/dream/index.ts +11 -0
  287. package/src/tools/dream/tools.ts +1002 -0
  288. package/src/tools/exec/allowlist.ts +233 -0
  289. package/src/tools/exec/background-detach.helper.mts +27 -0
  290. package/src/tools/exec/blacklist.ts +336 -0
  291. package/src/tools/exec/concurrency.ts +150 -0
  292. package/src/tools/exec/fit-output.ts +82 -0
  293. package/src/tools/exec/index.ts +7 -0
  294. package/src/tools/exec/internal-env.ts +89 -0
  295. package/src/tools/exec/job-store.ts +403 -0
  296. package/src/tools/exec/local.ts +649 -0
  297. package/src/tools/exec/remote.ts +399 -0
  298. package/src/tools/exec/tools.ts +934 -0
  299. package/src/tools/file/analyze.ts +378 -0
  300. package/src/tools/file/index.ts +2 -0
  301. package/src/tools/file/local.ts +707 -0
  302. package/src/tools/file/lsp-hook.ts +72 -0
  303. package/src/tools/file/persona-guard.ts +61 -0
  304. package/src/tools/file/policy.ts +292 -0
  305. package/src/tools/file/read-format.ts +129 -0
  306. package/src/tools/file/remote.ts +680 -0
  307. package/src/tools/file/replace.ts +507 -0
  308. package/src/tools/file/search-window.ts +224 -0
  309. package/src/tools/file/tools.ts +658 -0
  310. package/src/tools/file/write-scope.ts +182 -0
  311. package/src/tools/gating.ts +106 -0
  312. package/src/tools/image/budget.ts +82 -0
  313. package/src/tools/image/index.ts +7 -0
  314. package/src/tools/image/tools.ts +601 -0
  315. package/src/tools/index.ts +99 -0
  316. package/src/tools/memory/index.ts +12 -0
  317. package/src/tools/memory/tools.ts +399 -0
  318. package/src/tools/projects/index.ts +1 -0
  319. package/src/tools/projects/tools.ts +643 -0
  320. package/src/tools/registry.ts +427 -0
  321. package/src/tools/resources/index.ts +8 -0
  322. package/src/tools/resources/tools.ts +176 -0
  323. package/src/tools/resources/visibility.ts +60 -0
  324. package/src/tools/sentinel/index.ts +1 -0
  325. package/src/tools/sentinel/tools.ts +592 -0
  326. package/src/tools/skill/index.ts +4 -0
  327. package/src/tools/skill/tools.ts +285 -0
  328. package/src/tools/time/index.ts +5 -0
  329. package/src/tools/time/tools.ts +123 -0
  330. package/src/tools/tmux/index.ts +1 -0
  331. package/src/tools/tmux/local.ts +277 -0
  332. package/src/tools/tmux/remote.ts +168 -0
  333. package/src/tools/tmux/tools.ts +1064 -0
  334. package/src/tools/tool-output.ts +97 -0
  335. package/src/tools/types.ts +227 -0
  336. package/src/tools/video/index.ts +1 -0
  337. package/src/tools/video/tools.ts +425 -0
  338. package/src/tools/web/fetch.ts +337 -0
  339. package/src/tools/web/index.ts +4 -0
  340. package/src/tools/web/tools.ts +186 -0
  341. package/src/tools/wiki/index.ts +1 -0
  342. package/src/tools/wiki/tools.ts +445 -0
  343. package/src/tts/cache-gc.ts +128 -0
  344. package/src/tts/prepare-for-tts.ts +114 -0
  345. package/src/tts/service.ts +332 -0
  346. package/src/types/events.ts +695 -0
  347. package/src/types/turn-origin.ts +53 -0
  348. package/src/version.ts +21 -0
  349. package/src/videogen/dialects.ts +222 -0
  350. package/src/videogen/generate.ts +484 -0
  351. package/src/videogen/jobs.ts +178 -0
  352. package/src/videogen/runner.ts +125 -0
  353. package/src/videogen/wake.ts +119 -0
  354. package/src/voice/realtime/call.ts +948 -0
  355. package/src/voice/realtime/consult.ts +293 -0
  356. package/src/voice/realtime/fake-provider.ts +134 -0
  357. package/src/voice/realtime/manager.ts +384 -0
  358. package/src/voice/realtime/openai-provider.ts +471 -0
  359. package/src/voice/realtime/persona.ts +227 -0
  360. package/src/voice/realtime/session-match.ts +116 -0
  361. package/src/voice/realtime/types.ts +182 -0
  362. package/src/wiki/conflict.ts +113 -0
  363. package/src/wiki/explorer.ts +578 -0
  364. package/src/wiki/index-builder.ts +172 -0
  365. package/src/wiki/language.ts +134 -0
  366. package/src/wiki/log-builder.ts +150 -0
  367. package/src/wiki/map.ts +258 -0
  368. package/src/wiki/migration/analyze.ts +304 -0
  369. package/src/wiki/migration/execute.ts +689 -0
  370. package/src/wiki/migration/refine.ts +402 -0
  371. package/src/wiki/migration/store.ts +100 -0
  372. package/src/wiki/move-page.ts +57 -0
  373. package/src/wiki/structure-file.ts +192 -0
  374. package/src/wiki/taxonomy.ts +140 -0
  375. package/src/wiki/templates.ts +163 -0
  376. package/src/wiki/types.ts +133 -0
  377. package/templates/skills/README.md +24 -0
  378. package/templates/skills/_templates/api-wrapper/SKILL.md +26 -0
  379. package/templates/skills/_templates/cli-wrapper/BOOTSTRAP.md +32 -0
  380. package/templates/skills/_templates/cli-wrapper/SKILL.md +24 -0
  381. package/templates/skills/_templates/default/SKILL.md +25 -0
  382. package/templates/skills/builder-handover/SKILL.md +96 -0
  383. package/templates/skills/builder-handover/assets/ORDER.md +12 -0
  384. package/templates/skills/skill-author/SKILL.md +110 -0
  385. package/tsconfig.json +22 -0
  386. package/web/dist/assets/index-BaVv6pB2.js +631 -0
  387. package/web/dist/assets/index-BaVv6pB2.js.map +1 -0
  388. package/web/dist/assets/index-V3FV3Z25.css +32 -0
  389. package/web/dist/favicon.svg +8 -0
  390. package/web/dist/index.html +20 -0
  391. package/web/package.json +36 -0
  392. package/web/tsconfig.json +25 -0
  393. package/web-mobile/dist/apple-touch-icon.png +0 -0
  394. package/web-mobile/dist/assets/index-BqKt7IMx.css +1 -0
  395. package/web-mobile/dist/assets/index-X_vRr6cd.js +88 -0
  396. package/web-mobile/dist/assets/index-X_vRr6cd.js.map +1 -0
  397. package/web-mobile/dist/favicon.svg +8 -0
  398. package/web-mobile/dist/icon-192.png +0 -0
  399. package/web-mobile/dist/icon-512.png +0 -0
  400. package/web-mobile/dist/index.html +27 -0
  401. package/web-mobile/dist/manifest.webmanifest +32 -0
  402. package/web-mobile/dist/service-worker.js +90 -0
  403. package/web-mobile/package.json +28 -0
  404. package/web-mobile/tsconfig.json +25 -0
@@ -0,0 +1,845 @@
1
+ // spawn_subagent + spawn_subagents — A2A delegation tools (Modus 1).
2
+ //
3
+ // Runs a sealed task in a fresh session of a target persona (defaults
4
+ // to a clone of the caller). Each spawn:
5
+ // - creates a sub-session with slug `sub-<parent>-<ms-ts>` (or
6
+ // `sub-self-<ms-ts>` for self-clones)
7
+ // - records spawn-meta on the session: { kind, parent_agent,
8
+ // parent_session, task_summary }
9
+ // - runs through the full somora pipeline (memory inject, tools,
10
+ // self-pointer with sub-context note, fallback engine)
11
+ // - returns the final assistant text + session slug for traceability
12
+ //
13
+ // Caps:
14
+ // - subagent_depth max 3 (configurable via SOMORA_MAX_SUBAGENT_DEPTH)
15
+ // - per-agent concurrent spawns: 4
16
+ // - global concurrent spawns: 16
17
+ //
18
+ // Memory + Dream: sub-sessions are normal sessions in the target
19
+ // persona's session-dir. Auto-inject runs per turn; the auto-dream
20
+ // worker picks them up like any other session.
21
+
22
+ import { z } from 'zod';
23
+ import { describeModelRefs, resolveAnyRef } from '../../config/types.ts';
24
+ import { loadPersona } from '../../persona/loader.ts';
25
+ import { completeTask, failTask, getTask, newTaskId, registerTask, type AsyncTaskEntry, markResultFetched, waitForTaskCompletion } from '../../server/async-tasks.ts';
26
+ import { registerWait } from '../../server/ask-wait-graph.ts';
27
+ import { logger } from '../../server/logger.ts';
28
+ import { classifyFetchError, loopbackFetch } from '../../server/loopback-fetch.ts';
29
+ import type { ChatTurnResolveDeps, ChatTurnResult } from '../../server/run-turn-types.ts';
30
+ import { startTurn } from '../../server/start-turn.ts';
31
+ import { createSession, sessionMetaStore } from '../../storage/sessions.ts';
32
+ import type { ToolDefinition } from '../types.ts';
33
+ import {
34
+ IMAGES_FIELD_DESCRIPTION,
35
+ MAX_IMAGES_PER_MESSAGE,
36
+ uploadLocalAttachments,
37
+ type AttachmentRef,
38
+ } from './images.ts';
39
+ import { longTaskMaxMs } from './long-task-timeouts.ts';
40
+ import { fetchResultViaHttp } from './status.ts';
41
+
42
+ const MAX_SUBAGENT_DEPTH = parseInt(process.env.SOMORA_MAX_SUBAGENT_DEPTH ?? '3', 10) || 3;
43
+ const MAX_CONCURRENT_PER_AGENT = 4;
44
+ const MAX_CONCURRENT_GLOBAL = 16;
45
+
46
+ // Process-wide concurrency tracker. Survives only as long as the
47
+ // somora process — sub-spawns across server restarts are fresh starts.
48
+ const activeByAgent = new Map<string, number>();
49
+ let activeGlobal = 0;
50
+
51
+ /** Try to reserve a spawn slot. Returns null on success, or an error
52
+ * message string on cap-rejection. Slot must be paired with
53
+ * releaseSpawnSlot() — release in a finally so a thrown background
54
+ * doesn't leak the counter. Same semantics for sync and async paths;
55
+ * the bug audit 2026-05-16 found the async path skipped accounting
56
+ * entirely, letting agents fan out way past the per-agent cap.
57
+ *
58
+ * Cap fairness (2026-07-28 feedback): spawns issued BY a sub
59
+ * (fromDepth ≥ 1) may fill the per-agent cap only up to cap-1 — the
60
+ * last slot is reserved for top-level spawns, so an orchestrator sub
61
+ * fanning out into children can never lock the main agent out of
62
+ * spawning (e.g. a replacement or corrective sub). */
63
+ export function reserveSpawnSlot(targetPersona: string, fromDepth = 0): string | null {
64
+ if (activeGlobal >= MAX_CONCURRENT_GLOBAL) {
65
+ return `spawn_subagent: global concurrent cap (${MAX_CONCURRENT_GLOBAL}) reached`;
66
+ }
67
+ const perAgent = activeByAgent.get(targetPersona) ?? 0;
68
+ const effectiveCap = fromDepth >= 1 ? MAX_CONCURRENT_PER_AGENT - 1 : MAX_CONCURRENT_PER_AGENT;
69
+ if (perAgent >= effectiveCap) {
70
+ return (
71
+ `spawn_subagent: per-agent concurrent cap for '${targetPersona}' ` +
72
+ `(${effectiveCap}${fromDepth >= 1 ? ` of ${MAX_CONCURRENT_PER_AGENT}; the last slot is reserved for top-level spawns` : ''}) reached`
73
+ );
74
+ }
75
+ activeByAgent.set(targetPersona, perAgent + 1);
76
+ activeGlobal++;
77
+ return null;
78
+ }
79
+
80
+ export function releaseSpawnSlot(targetPersona: string): void {
81
+ const cur = activeByAgent.get(targetPersona) ?? 0;
82
+ if (cur > 0) activeByAgent.set(targetPersona, cur - 1);
83
+ if (activeGlobal > 0) activeGlobal--;
84
+ }
85
+
86
+ interface SpawnDeps {
87
+ chatTurnDeps: ChatTurnResolveDeps;
88
+ }
89
+
90
+ let injectedDeps: SpawnDeps | null = null;
91
+
92
+ /**
93
+ * Server boot calls this once with the shared chatTurnDeps so the
94
+ * spawn tools can run the full chat pipeline without re-resolving
95
+ * server wiring on each call.
96
+ */
97
+ export function configureSpawnTools(deps: SpawnDeps): void {
98
+ injectedDeps = deps;
99
+ }
100
+
101
+ const TaskSchema = z.object({
102
+ persona: z
103
+ .string()
104
+ .min(1)
105
+ .optional()
106
+ .describe('Target agent name. Omit to spawn a clone of the caller (<your-agent> → <your-agent>-clone).'),
107
+ model: z
108
+ .string()
109
+ .min(1)
110
+ .optional()
111
+ .describe(
112
+ 'Model override — an alias or "provider/modelId" EXACTLY as configured in config.yaml; ' +
113
+ 'invented names are rejected. Omit (recommended) to use the persona\'s default.',
114
+ ),
115
+ task: z.string().min(1),
116
+ /**
117
+ * Optional per-spawn agent-loop override. Default global maxRounds=8
118
+ * is fine for sealed research subs; orchestrator subs that
119
+ * themselves spawn + poll can hit the cap fast — pass e.g.
120
+ * { maxRounds: 32 } for those.
121
+ */
122
+ maxRounds: z
123
+ .number()
124
+ .int()
125
+ .min(1)
126
+ .max(100)
127
+ .optional()
128
+ .describe(
129
+ 'Per-spawn override of agentLoop.maxRounds (the server config value; 8 if unset). Use higher (e.g. 32) for ' +
130
+ 'orchestrator subs that spawn further sub-subs and poll their results.',
131
+ ),
132
+ attention: z
133
+ .boolean()
134
+ .optional()
135
+ .describe(
136
+ 'Async spawns only: when the sub finishes and you have not fetched its result, you get ' +
137
+ 'an automatic [subagent attention] wake turn (default). Ignored when you started the sub while answering another agent or a voice call. Pass false to opt out for ' +
138
+ 'subs whose results you will poll yourself or that need no follow-up.',
139
+ ),
140
+ images: z
141
+ .array(z.string().min(1))
142
+ .max(MAX_IMAGES_PER_MESSAGE)
143
+ .optional()
144
+ .describe(IMAGES_FIELD_DESCRIPTION),
145
+ });
146
+
147
+ // ─────────────────────────────────────────────────────────────────────
148
+ // spawn_subagent (single)
149
+ // ─────────────────────────────────────────────────────────────────────
150
+
151
+ const SingleInput = TaskSchema.extend({
152
+ wait: z
153
+ .boolean()
154
+ .default(false)
155
+ .describe(
156
+ 'When true: block this turn until the sub returns its final answer (good for "I need ' +
157
+ 'the result NOW to compose my reply"). When false (default): fire-and-forget — returns ' +
158
+ 'a task_id immediately, sub runs in the background. Check progress with subagent_status, ' +
159
+ 'fetch the answer with subagent_result.',
160
+ ),
161
+ }).strict();
162
+
163
+ export const spawnSubagent: ToolDefinition<z.infer<typeof SingleInput>> = {
164
+ name: 'spawn_subagent',
165
+ toolset: 'agents',
166
+ description:
167
+ 'Spawn a sub-agent to handle a sealed task. The sub runs in a fresh session of the ' +
168
+ 'target persona (defaults to a clone of you), goes through normal memory+tool+thinking ' +
169
+ 'flow, and produces a final answer. ' +
170
+ 'Default is fire-and-forget (wait:false): you get a task_id back immediately and your ' +
171
+ 'turn ends — the user can keep chatting with you while the sub runs. When it finishes ' +
172
+ 'you get a [subagent attention] wake turn automatically (opt out with attention:false); ' +
173
+ 'use subagent_status / subagent_result to check earlier, subagent_cancel to abort a ' +
174
+ 'running sub INCLUDING its child-spawns. ' +
175
+ 'Set wait:true for synchronous "I need the result NOW to write my reply" delegations. ' +
176
+ 'Either way, if the sub itself started work that finishes after its report (its own subs), ' +
177
+ 'that outcome reaches you later on its own as a follow-up wake — you never have to poll for it. ' +
178
+ 'Depth cap: 3 (a sub itself can spawn further subs up to that limit). ' +
179
+ 'Per-agent concurrent cap: 4 — NOTE: subs spawned by your subs count against YOUR cap ' +
180
+ 'too (child spawns may only fill 3 of the 4 slots; the last is reserved for you), and a ' +
181
+ 'self-clone sub inherits your persona default model unless you pass model explicitly — ' +
182
+ 'an expensive orchestrator spawning expensive children multiplies cost fast. ' +
183
+ 'Cross-engine OK — <agent-a>-on-opus can spawn <agent-b>-on-gpt55. ' +
184
+ 'Sub sessions stay visible in /sessions of the target persona with a "sub from X/Y" marker.',
185
+ inputSchema: SingleInput,
186
+ jsonSchema: {
187
+ type: 'object',
188
+ properties: {
189
+ persona: {
190
+ type: 'string',
191
+ description: 'Target agent name (e.g. "<agent-name>", "<other-agent>"). Omit for a clone of yourself.',
192
+ },
193
+ model: {
194
+ type: 'string',
195
+ description:
196
+ 'Model override — an alias or "provider/modelId" EXACTLY as configured in config.yaml; ' +
197
+ 'invented names are rejected. Omit (recommended) to use the persona\'s default.',
198
+ },
199
+ task: { type: 'string', description: 'The task / question for the sub. Will become its first user message.' },
200
+ maxRounds: {
201
+ type: 'integer',
202
+ minimum: 1,
203
+ maximum: 100,
204
+ description:
205
+ 'Per-spawn override of agentLoop.maxRounds (the server config value; 8 if unset). Use higher (e.g. 32) for ' +
206
+ 'orchestrator subs that spawn further sub-subs and poll their results.',
207
+ },
208
+ attention: {
209
+ type: 'boolean',
210
+ description:
211
+ 'Async spawns only: automatic [subagent attention] wake turn when the sub finishes ' +
212
+ 'unfetched (default true). Pass false to opt out. Ignored when you started the sub while ' +
213
+ 'answering another agent or a voice call: they wait for the outcome and are told through ' +
214
+ 'the follow-up, which needs that wake.',
215
+ },
216
+ images: {
217
+ type: 'array',
218
+ items: { type: 'string' },
219
+ maxItems: MAX_IMAGES_PER_MESSAGE,
220
+ description: IMAGES_FIELD_DESCRIPTION,
221
+ },
222
+ wait: {
223
+ type: 'boolean',
224
+ description:
225
+ 'When true: block this turn until the sub returns its final answer. When false ' +
226
+ '(default): fire-and-forget — returns a task_id immediately, sub runs in the ' +
227
+ 'background. Check progress with subagent_status, fetch the answer with subagent_result.',
228
+ },
229
+ },
230
+ required: ['task'],
231
+ additionalProperties: false,
232
+ },
233
+ // wait:false returns immediately (just registers + kicks off async),
234
+ // 30s is plenty. wait:true blocks for the full sub turn — sized off
235
+ // agentLoop.longTaskMaxTimeoutMs (default 30 min) so a sync spawn can
236
+ // legitimately wait for slow local models without artificial cutoff.
237
+ // The sub itself caps via its own agentLoop.maxRounds; this is just
238
+ // a runaway guard. Read at call time so config changes take effect
239
+ // without restart.
240
+ defaultTimeoutMs: 30_000,
241
+ timeoutFromInput: (input) => (input.wait ? longTaskMaxMs() : undefined),
242
+ // Static safety fence; actual cap is dynamic via timeoutFromInput.
243
+ maxTimeoutMs: 7_200_000,
244
+ async handler(input, ctx) {
245
+ const result = await runOneSpawn({
246
+ ctx,
247
+ wait: input.wait,
248
+ task: {
249
+ task: input.task,
250
+ ...(input.persona ? { persona: input.persona } : {}),
251
+ ...(input.model ? { model: input.model } : {}),
252
+ ...(input.maxRounds ? { maxRounds: input.maxRounds } : {}),
253
+ ...(input.attention !== undefined ? { attention: input.attention } : {}),
254
+ ...(input.images && input.images.length > 0 ? { images: input.images } : {}),
255
+ },
256
+ });
257
+ return result;
258
+ },
259
+ };
260
+
261
+ // ─────────────────────────────────────────────────────────────────────
262
+ // spawn_subagents (parallel batch)
263
+ // ─────────────────────────────────────────────────────────────────────
264
+
265
+ const BatchInput = z
266
+ .object({
267
+ tasks: z
268
+ .array(TaskSchema)
269
+ .min(1)
270
+ .max(8)
271
+ .describe('Up to 8 tasks. Run in parallel; results returned together.'),
272
+ wait: z
273
+ .boolean()
274
+ .default(false)
275
+ .describe(
276
+ 'Default false (fire-and-forget): each task gets its own task_id, all run in ' +
277
+ 'parallel in the background and the tool returns at once — your turn goes on. true blocks until all ' +
278
+ 'complete and returns results inline.',
279
+ ),
280
+ })
281
+ .strict();
282
+
283
+ export const spawnSubagents: ToolDefinition<z.infer<typeof BatchInput>> = {
284
+ name: 'spawn_subagents',
285
+ toolset: 'agents',
286
+ description:
287
+ 'Spawn multiple sub-agents in parallel. Each task is a {persona?, model?, task} record; ' +
288
+ 'omitting persona = clone of you. Useful for fan-out queries: send the same task to ' +
289
+ 'multiple personas to compare perspectives, or different focused tasks at once. ' +
290
+ 'Returns one result per task in the same order. Same caps as spawn_subagent.',
291
+ inputSchema: BatchInput,
292
+ jsonSchema: {
293
+ type: 'object',
294
+ properties: {
295
+ tasks: {
296
+ type: 'array',
297
+ minItems: 1,
298
+ maxItems: 8,
299
+ items: {
300
+ type: 'object',
301
+ properties: {
302
+ persona: { type: 'string' },
303
+ model: {
304
+ type: 'string',
305
+ description:
306
+ 'Model override — alias or "provider/modelId" exactly as configured; omit for the persona default.',
307
+ },
308
+ task: { type: 'string' },
309
+ maxRounds: {
310
+ type: 'integer',
311
+ minimum: 1,
312
+ maximum: 100,
313
+ description:
314
+ 'Per-spawn override of agentLoop.maxRounds (the server config value; 8 if unset). Use higher (e.g. 32) ' +
315
+ 'for orchestrator subs that spawn further sub-subs and poll their results.',
316
+ },
317
+ attention: {
318
+ type: 'boolean',
319
+ description:
320
+ 'Async spawns only: automatic [subagent attention] wake turn when the sub ' +
321
+ 'finishes unfetched (default true). Pass false to opt out.',
322
+ },
323
+ images: {
324
+ type: 'array',
325
+ items: { type: 'string' },
326
+ maxItems: MAX_IMAGES_PER_MESSAGE,
327
+ description: IMAGES_FIELD_DESCRIPTION,
328
+ },
329
+ },
330
+ required: ['task'],
331
+ additionalProperties: false,
332
+ },
333
+ },
334
+ wait: {
335
+ type: 'boolean',
336
+ description:
337
+ 'Default false (fire-and-forget): each task gets its own task_id, all run in ' +
338
+ 'parallel in the background and the tool returns at once — your turn goes on. true blocks until all ' +
339
+ 'complete and returns results inline.',
340
+ },
341
+ },
342
+ required: ['tasks'],
343
+ additionalProperties: false,
344
+ },
345
+ // Same posture as spawn_subagent: wait:false is instant, wait:true
346
+ // blocks for all subs — sized off agentLoop.longTaskMaxTimeoutMs.
347
+ defaultTimeoutMs: 30_000,
348
+ timeoutFromInput: (input) => (input.wait ? longTaskMaxMs() : undefined),
349
+ maxTimeoutMs: 7_200_000,
350
+ async handler(input, ctx) {
351
+ const settled = await Promise.allSettled(
352
+ input.tasks.map((t) => runOneSpawn({ ctx, wait: input.wait, task: t })),
353
+ );
354
+ const results = settled.map((s, i) => {
355
+ if (s.status === 'fulfilled') return s.value;
356
+ const err = (s.reason as Error).message;
357
+ const t = input.tasks[i]!;
358
+ return {
359
+ ok: false as const,
360
+ persona: t.persona ?? ctx.agent,
361
+ error: err,
362
+ ms: 0,
363
+ };
364
+ });
365
+ return { count: results.length, results };
366
+ },
367
+ };
368
+
369
+
370
+ // ─────────────────────────────────────────────────────────────────────
371
+ // shared spawn machinery
372
+ // ─────────────────────────────────────────────────────────────────────
373
+
374
+ interface OneSpawnArgs {
375
+ ctx: import('../types.ts').ToolContext;
376
+ wait: boolean;
377
+ task: {
378
+ persona?: string;
379
+ model?: string;
380
+ task: string;
381
+ maxRounds?: number;
382
+ /** Attention-wake opt-out (async spawns). Default: wake. */
383
+ attention?: boolean;
384
+ /** Absolute paths of images the sub has to look at. */
385
+ images?: string[];
386
+ };
387
+ }
388
+
389
+ interface OneSpawnSyncResult {
390
+ ok: boolean;
391
+ wait: 'sync';
392
+ /** Since 2026-09-13 every spawn is a task; wait:true awaits it. */
393
+ task_id: string;
394
+ /** `pending` when the wait ran out before the sub finished — it keeps
395
+ * running, the parent is woken when it is done. */
396
+ state?: 'pending';
397
+ hint?: string;
398
+ persona: string;
399
+ agent_kind: 'self-clone' | 'named';
400
+ session_slug: string;
401
+ model: string;
402
+ result?: string;
403
+ /** Runtime verdict — see ChatTurnResult.outcome. */
404
+ outcome?: ChatTurnResult['outcome'];
405
+ outcome_reason?: string;
406
+ tool_calls?: number;
407
+ rounds?: number;
408
+ fallback?: ChatTurnResult['fallback'];
409
+ files_written?: string[];
410
+ media?: ChatTurnResult['media'];
411
+ error?: string;
412
+ ms: number;
413
+ thinkingActive: boolean;
414
+ }
415
+
416
+ interface OneSpawnAsyncResult {
417
+ ok: true;
418
+ wait: 'async';
419
+ task_id: string;
420
+ persona: string;
421
+ agent_kind: 'self-clone' | 'named';
422
+ session_slug: string;
423
+ hint: string;
424
+ }
425
+
426
+ type OneSpawnResult = OneSpawnSyncResult | OneSpawnAsyncResult;
427
+
428
+ async function runOneSpawn(args: OneSpawnArgs): Promise<OneSpawnResult> {
429
+ // injectedDeps absent is the normal MCP-child case (configureSpawnTools
430
+ // only runs in the main server). The handler dispatches to the HTTP
431
+ // fallback further down — this guard would have killed that path.
432
+ const { ctx, task } = args;
433
+ const parentDepth = ctx.subagentDepth ?? 0;
434
+ if (parentDepth >= MAX_SUBAGENT_DEPTH) {
435
+ throw new Error(
436
+ `spawn_subagent: recursion depth ${parentDepth} exceeds limit ${MAX_SUBAGENT_DEPTH}`,
437
+ );
438
+ }
439
+ const isSelfClone = !task.persona || task.persona === ctx.agent;
440
+ const targetPersona = task.persona ?? ctx.agent;
441
+ const personaCheck = await loadPersona(targetPersona);
442
+ if (!personaCheck) {
443
+ throw new Error(`spawn_subagent: persona '${targetPersona}' not found`);
444
+ }
445
+ // Validate a model override BEFORE creating the session + reserving a
446
+ // slot: an invented name ("myprovider/model-that-does-not-exist") otherwise fails
447
+ // deep inside the sub's first turn, leaving a dead session behind and
448
+ // an error that doesn't say what WOULD have worked (2026-08-24 report).
449
+ if (task.model && !resolveAnyRef(ctx.config, task.model)) {
450
+ throw new Error(
451
+ `spawn_subagent: model '${task.model}' is not configured — pass an alias or ` +
452
+ `provider/modelId exactly as listed in config.yaml, or omit \`model\` to use ` +
453
+ `${targetPersona}'s default (${personaCheck.model ?? 'unset'}). ` +
454
+ `Available: ${describeModelRefs(ctx.config)}`,
455
+ );
456
+ }
457
+ // Pictures for the brief. Uploaded BEFORE a slot is reserved and a
458
+ // session created: a wrong path is the caller's typo, and it should
459
+ // cost neither. The refs then travel every dispatch path below, the
460
+ // same ones the task text travels (2026-09-11: an orchestrator could
461
+ // only name a file, and a path is just text to a model that sees).
462
+ const briefAttachments: AttachmentRef[] =
463
+ task.images && task.images.length > 0
464
+ ? await uploadLocalAttachments(task.images, spawnBase())
465
+ : [];
466
+
467
+ // Concurrency — slot must be held across the full lifetime of the
468
+ // sub-turn (sync + async both). reserveSpawnSlot also increments the
469
+ // counters atomically; the matching releaseSpawnSlot lives in the
470
+ // finally of each path (sync: line below; async: inside the
471
+ // background IIFE in spawnAsyncInProcess + the HTTP route).
472
+ const slotErr = reserveSpawnSlot(targetPersona, parentDepth);
473
+ if (slotErr) throw new Error(slotErr);
474
+
475
+ // Slug carries ms + random suffix so parallel spawns in the same
476
+ // millisecond don't collide (Math.random() collision in 4 lowercase
477
+ // alphanums is ~1/1.7M, paired with ms it's ~1/1.7B per same-ms
478
+ // pair). createSession also has its own collision-retry as a safety
479
+ // net. The slug stem `sub-self`/`sub-<parent>` stays grep-friendly
480
+ // for /sessions listings.
481
+ const ms = String(Date.now() % 1000).padStart(3, '0');
482
+ const rand = Math.random().toString(36).slice(2, 6).padEnd(4, '0');
483
+ const slug = isSelfClone
484
+ ? `sub-self-${ms}-${rand}`
485
+ : `sub-${ctx.agent}-${ms}-${rand}`;
486
+ const sessionId = await createSession(targetPersona, slug);
487
+ // Attach the spawn meta block so /sessions can label this entry
488
+ // "sub from <parent>" without re-deriving from the slug.
489
+ const existingMeta = await sessionMetaStore.get(targetPersona, sessionId);
490
+ // A helper works where its parent works: the pinned project (and its
491
+ // folder) carries over. A builder helper runs unattended and builds —
492
+ // it has a sealed task, nobody to ask, no plan phase of its own.
493
+ const targetKind = personaCheck.kind;
494
+ const parentMeta = ctx.session ? ((await sessionMetaStore.get(ctx.agent, ctx.session)) as Record<string, unknown>) : {};
495
+ const inherited: Record<string, unknown> = {};
496
+ if (typeof parentMeta.workdir === 'string') inherited.workdir = parentMeta.workdir;
497
+ if (typeof parentMeta.projectSlug === 'string') {
498
+ inherited.projectSlug = parentMeta.projectSlug;
499
+ inherited.projectLinkedAt = new Date().toISOString();
500
+ }
501
+ if (targetKind === 'builder') {
502
+ inherited.builderMode = 'unattended';
503
+ inherited.builderPhase = 'build';
504
+ inherited.builderInitializedAt = Date.now();
505
+ if (typeof parentMeta.builderPlanPath === 'string') inherited.builderPlanPath = parentMeta.builderPlanPath;
506
+ }
507
+ await sessionMetaStore.set(targetPersona, sessionId, {
508
+ ...existingMeta,
509
+ ...inherited,
510
+ spawn: {
511
+ kind: isSelfClone ? 'self-sub' : 'sub',
512
+ parent_agent: ctx.agent,
513
+ parent_session: ctx.session ?? '?',
514
+ task_summary: task.task.slice(0, 200),
515
+ },
516
+ });
517
+
518
+ // ─── one path: the sub is a background task; wait:true awaits it ──
519
+ //
520
+ // Until 2026-09-13 wait:true was its own code path: no task id, no
521
+ // lock, no abort registration, and after the tool's 30-minute wait the
522
+ // child kept running with a result nobody could fetch (birdseye L8,
523
+ // L9, L16). Now every spawn registers a task and starts it in the
524
+ // background — in-process or through /spawn-async — and wait:true
525
+ // simply waits for that task's result. Same tool, same result shape;
526
+ // but the sub is stoppable, subagent_cancel reaches it, and a sub that
527
+ // outlives the wait wakes its parent when it finishes.
528
+ //
529
+ // The slot reserved above belongs to the background task from here on
530
+ // (in-process: the IIFE releases it; HTTP: the server owns its own and
531
+ // the child's local reservation is released at once).
532
+ let task_id: string;
533
+ try {
534
+ if (injectedDeps) {
535
+ task_id = await spawnAsyncInProcess({
536
+ targetPersona,
537
+ sessionId,
538
+ taskText: task.task,
539
+ parentAgent: ctx.agent,
540
+ parentSession: ctx.session ?? '?',
541
+ parentDepth,
542
+ modelOverride: task.model,
543
+ maxRoundsOverride: task.maxRounds,
544
+ attention: task.attention,
545
+ attachments: briefAttachments,
546
+ });
547
+ } else {
548
+ // MCP-child HTTP path: the SERVER process owns the task lifetime
549
+ // and releases ITS own slot when the task finishes. The slot we
550
+ // reserved lives in THIS per-turn child process and has no
551
+ // lifetime to track here — release it now, or it leaks for the
552
+ // rest of the child's life and caps the orchestrator at the
553
+ // per-agent/global limit forever within the turn (Juni-Audit
554
+ // 2026-06).
555
+ task_id = await spawnAsyncViaHttp({
556
+ targetAgent: targetPersona,
557
+ targetSession: sessionId,
558
+ taskText: task.task,
559
+ parentAgent: ctx.agent,
560
+ parentSession: ctx.session ?? '?',
561
+ parentDepth,
562
+ modelOverride: task.model,
563
+ maxRoundsOverride: task.maxRounds,
564
+ attention: task.attention,
565
+ attachments: briefAttachments,
566
+ });
567
+ releaseSpawnSlot(targetPersona);
568
+ }
569
+ } catch (err) {
570
+ // Slot release on synchronous setup failure — the background
571
+ // never actually started, so no IIFE finally will fire.
572
+ releaseSpawnSlot(targetPersona);
573
+ throw err;
574
+ }
575
+ logger.info({
576
+ msg: args.wait ? 'spawn_subagent.start_sync' : 'spawn_subagent.async_started',
577
+ task_id,
578
+ parent_agent: ctx.agent,
579
+ parent_session: ctx.session,
580
+ target: targetPersona,
581
+ session: sessionId,
582
+ depth: parentDepth + 1,
583
+ via: injectedDeps ? 'in-process' : 'http',
584
+ });
585
+ if (!args.wait) {
586
+ return {
587
+ ok: true,
588
+ wait: 'async',
589
+ task_id,
590
+ persona: targetPersona,
591
+ agent_kind: isSelfClone ? 'self-clone' : 'named',
592
+ session_slug: slug,
593
+ hint:
594
+ `Sub is running in the background. Check progress with subagent_status({ task_id: "${task_id}" }) ` +
595
+ `or fetch the answer with subagent_result({ task_id: "${task_id}" }).`,
596
+ };
597
+ }
598
+
599
+ // ─── wait:true: block on the task ─────────────────────────────────
600
+ // The parent's turn BLOCKS on the sub — that wait must be visible in
601
+ // the A2A wait-graph, or a cycle routed through this spawn (parent
602
+ // waits sub, sub asks X, X asks parent) is undetectable and deadlocks
603
+ // silently (see src/server/ask-wait-graph.ts). In-process the edge is
604
+ // registered here; over HTTP, /spawn-result registers it from the
605
+ // waiter_* query. No cycle CHECK is needed: the sub-session is fresh.
606
+ const releaseWait =
607
+ injectedDeps && ctx.session
608
+ ? registerWait(
609
+ { agent: ctx.agent, session: ctx.session },
610
+ { agent: targetPersona, session: sessionId },
611
+ )
612
+ : undefined;
613
+ // Answer before the engine's own race on this tool call (longTaskMax)
614
+ // would cut us off — a sub that needs longer keeps running and wakes
615
+ // the parent when it is done.
616
+ const budgetMs = Math.max(30_000, longTaskMaxMs() - 5_000);
617
+ const startedAt = Date.now();
618
+ try {
619
+ const entry = injectedDeps
620
+ ? await waitForTaskCompletion(task_id, budgetMs)
621
+ : await fetchResultViaHttp(task_id, {
622
+ wait_until_done: true,
623
+ timeout_ms: budgetMs,
624
+ ...(ctx.session ? { waiter_agent: ctx.agent, waiter_session: ctx.session } : {}),
625
+ });
626
+ const state = entry?.state;
627
+ if (!entry || state === 'running') {
628
+ logger.info({ msg: 'spawn_subagent.sync_timeout', task_id, target: targetPersona, session: sessionId, ms: Date.now() - startedAt });
629
+ return {
630
+ ok: false,
631
+ wait: 'sync',
632
+ state: 'pending',
633
+ task_id,
634
+ persona: targetPersona,
635
+ agent_kind: isSelfClone ? 'self-clone' : 'named',
636
+ session_slug: slug,
637
+ model: task.model ?? '',
638
+ hint:
639
+ `The sub is still working after ${Math.round(budgetMs / 60_000)} minutes. It keeps running; you are ` +
640
+ `woken when it finishes, or fetch it with subagent_result({ task_id: "${task_id}" }). Do not spawn it again.`,
641
+ ms: Date.now() - startedAt,
642
+ thinkingActive: false,
643
+ };
644
+ }
645
+ // The parent has the result in hand: no attention wake for it.
646
+ if (injectedDeps) markResultFetched(task_id);
647
+ const result: ChatTurnResult | undefined = entry.result;
648
+ const error = entry.error ?? result?.error;
649
+ logger.info({
650
+ msg: 'spawn_subagent.done',
651
+ task_id,
652
+ target: targetPersona,
653
+ session: sessionId,
654
+ state,
655
+ ms: Date.now() - startedAt,
656
+ bytes: result?.finalText.length ?? 0,
657
+ });
658
+ return {
659
+ ok: state === 'done' && !error,
660
+ wait: 'sync',
661
+ task_id,
662
+ persona: targetPersona,
663
+ agent_kind: isSelfClone ? 'self-clone' : 'named',
664
+ session_slug: slug,
665
+ model: result?.model ?? task.model ?? '',
666
+ ...(result ? { result: result.finalText } : {}),
667
+ ...(result?.outcome ? { outcome: result.outcome } : state === 'cancelled' ? { outcome: 'failed' as const } : {}),
668
+ ...(result?.outcome_reason ? { outcome_reason: result.outcome_reason } : {}),
669
+ ...(result ? { tool_calls: result.tool_calls } : {}),
670
+ ...(result?.rounds !== undefined ? { rounds: result.rounds } : {}),
671
+ ...(result?.fallback ? { fallback: result.fallback } : {}),
672
+ ...(result?.files_written?.length ? { files_written: result.files_written } : {}),
673
+ ...(result?.media?.length ? { media: result.media } : {}),
674
+ ...(error ? { error } : {}),
675
+ ms: Date.now() - startedAt,
676
+ thinkingActive: result?.thinkingActive ?? false,
677
+ };
678
+ } finally {
679
+ releaseWait?.();
680
+ }
681
+ }
682
+
683
+ /** startTurn without a pre-flight never skips; a null here is a bug. */
684
+ async function startSubTurn(args: Parameters<typeof startTurn>[0]): Promise<ChatTurnResult> {
685
+ const result = await startTurn(args);
686
+ if (!result) throw new Error('spawn_subagent: turn did not start');
687
+ return result;
688
+ }
689
+
690
+ /**
691
+ * In-process async dispatch: register the task, kick off the turn
692
+ * as a background promise, return the task_id. completeTask /
693
+ * failTask write the result back into the shared task store.
694
+ */
695
+ async function spawnAsyncInProcess(args: {
696
+ targetPersona: string;
697
+ sessionId: string;
698
+ taskText: string;
699
+ parentAgent: string;
700
+ parentSession: string;
701
+ parentDepth: number;
702
+ modelOverride?: string;
703
+ maxRoundsOverride?: number;
704
+ attention?: boolean;
705
+ attachments?: AttachmentRef[];
706
+ }): Promise<string> {
707
+ if (!injectedDeps) throw new Error('spawnAsyncInProcess called without injectedDeps');
708
+ const task_id = newTaskId();
709
+ registerTask({
710
+ task_id,
711
+ parent_agent: args.parentAgent,
712
+ parent_session: args.parentSession,
713
+ parent_depth: args.parentDepth,
714
+ target_agent: args.targetPersona,
715
+ target_session: args.sessionId,
716
+ started_at: Date.now(),
717
+ text: args.taskText,
718
+ ...(args.attention !== undefined ? { attention: args.attention } : {}),
719
+ });
720
+ void (async () => {
721
+ // startTurn holds the per-session lock (two parallel async-spawns
722
+ // on the same session serialize) and registers the abort controller
723
+ // under the sub's (agent, session), so subagent_cancel and the Stop
724
+ // button cut the in-flight LLM call through the same signal.
725
+ try {
726
+ const result = await startSubTurn({
727
+ agent: args.targetPersona,
728
+ session: args.sessionId,
729
+ text: args.taskText,
730
+ turnId: task_id,
731
+ workId: task_id,
732
+ origin: {
733
+ kind: 'subagent',
734
+ depth: args.parentDepth + 1,
735
+ taskId: task_id,
736
+ ...(args.parentSession !== '?' ? { parent: { agent: args.parentAgent, session: args.parentSession } } : {}),
737
+ },
738
+ ...(args.attachments && args.attachments.length > 0
739
+ ? { attachments: args.attachments }
740
+ : {}),
741
+ ...(args.modelOverride ? { modelOverride: args.modelOverride } : {}),
742
+ ...(args.maxRoundsOverride
743
+ ? { agentLoopOverride: { maxRounds: args.maxRoundsOverride } }
744
+ : {}),
745
+ deps: injectedDeps!.chatTurnDeps,
746
+ });
747
+ // completeTask/failTask are no-ops when the task was already
748
+ // cancelled — the registry state stays 'cancelled'.
749
+ completeTask(task_id, result);
750
+ } catch (err) {
751
+ failTask(task_id, (err as Error).message);
752
+ } finally {
753
+ // Release the concurrency slot reserved by runOneSpawn — the
754
+ // background promise's lifetime IS the slot lifetime.
755
+ releaseSpawnSlot(args.targetPersona);
756
+ }
757
+ })();
758
+ return task_id;
759
+ }
760
+
761
+ /**
762
+ * HTTP async dispatch: call /spawn-async on the localhost server. The
763
+ * server registers the task and runs it in its own process; we just
764
+ * return the task_id. status / result also go through HTTP later.
765
+ */
766
+ async function spawnAsyncViaHttp(args: {
767
+ targetAgent: string;
768
+ targetSession: string;
769
+ taskText: string;
770
+ parentAgent: string;
771
+ parentSession: string;
772
+ parentDepth: number;
773
+ modelOverride?: string;
774
+ maxRoundsOverride?: number;
775
+ attention?: boolean;
776
+ attachments?: AttachmentRef[];
777
+ }): Promise<string> {
778
+ const host = process.env.SOMORA_HOST || '127.0.0.1';
779
+ const port = process.env.SOMORA_PORT || '18737';
780
+ // SOMORA_TLS=1 → server is HTTP/2-over-TLS; loopback must use
781
+ // https://<publicHost> (see spawnBase below).
782
+ const scheme = process.env.SOMORA_TLS === '1' ? 'https' : 'http';
783
+ let res;
784
+ try {
785
+ res = await loopbackFetch(`${scheme}://${host}:${port}/spawn-async`, {
786
+ method: 'POST',
787
+ headers: { 'Content-Type': 'application/json' },
788
+ body: JSON.stringify({
789
+ agent: args.targetAgent,
790
+ session: args.targetSession,
791
+ text: args.taskText,
792
+ ...(args.attachments && args.attachments.length > 0
793
+ ? { attachments: args.attachments }
794
+ : {}),
795
+ // Deliberately NO from_agent: a spawn task brief is not an A2A
796
+ // message. Labeling it would render a peer-agent bubble + fire
797
+ // unread badges in the sub's session, and the sub's engine
798
+ // would frame the brief as inbound mail from the parent —
799
+ // while the in-process async path and BOTH sync paths deliver
800
+ // the same brief unlabeled. Parent attribution for the task
801
+ // registry travels via parent_agent below (Juni-Audit 2026-07,
802
+ // decision: briefs are neutral).
803
+ parent_agent: args.parentAgent,
804
+ parent_session: args.parentSession,
805
+ subagent_depth: args.parentDepth + 1,
806
+ ...(args.modelOverride ? { model: args.modelOverride } : {}),
807
+ ...(args.maxRoundsOverride ? { max_rounds: args.maxRoundsOverride } : {}),
808
+ ...(args.attention !== undefined ? { attention: args.attention } : {}),
809
+ }),
810
+ });
811
+ } catch (err) {
812
+ const c = classifyFetchError(err);
813
+ throw new Error(
814
+ `spawn-async [${c.category}${c.code ? '/' + c.code : ''}]: ${c.message}` +
815
+ (c.hint ? ` — hint: ${c.hint}` : ''),
816
+ );
817
+ }
818
+ if (!res.ok) {
819
+ const body = await res.text().catch(() => '');
820
+ throw new Error(`spawn-async HTTP ${res.status}: ${body.slice(0, 300)}`);
821
+ }
822
+ const data = (await res.json()) as { task_id: string };
823
+ return data.task_id;
824
+ }
825
+
826
+ /**
827
+ * MCP-child fallback: when spawn_subagent is invoked from inside a
828
+ * claude-cli or codex-cli MCP server (configureSpawnTools never ran
829
+ * here), reach back to the somora HTTP server on localhost. Same
830
+ * inputs, same eventual JSONL state — just routed through HTTP rather
831
+ * than a direct in-process call.
832
+ *
833
+ * Server host/port from SOMORA_HOST + SOMORA_PORT env (set by the
834
+ * parent server on launch). Falls back to 127.0.0.1:18737.
835
+ */
836
+ /** Loopback base for this process — same rules the HTTP fallbacks use:
837
+ * SOMORA_HOST/PORT from the parent, https when the server runs TLS. */
838
+ function spawnBase(): string {
839
+ const host = process.env.SOMORA_HOST || '127.0.0.1';
840
+ const port = process.env.SOMORA_PORT || '18737';
841
+ const scheme = process.env.SOMORA_TLS === '1' ? 'https' : 'http';
842
+ return `${scheme}://${host}:${port}`;
843
+ }
844
+
845
+