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,589 @@
1
+ // subagent_status / subagent_result — companion tools to
2
+ // spawn_subagent's wait:false (default) async path. Used by the
3
+ // orchestrator agent to poll progress and pull final results out.
4
+
5
+ import { z } from 'zod';
6
+ import { findWaitCycle, registerWait } from '../../server/ask-wait-graph.ts';
7
+ import {
8
+ cancelTaskCascade,
9
+ getTask,
10
+ listTasksForAgent,
11
+ markResultFetched,
12
+ waitForTaskCompletion,
13
+ type AsyncTaskEntry,
14
+ } from '../../server/async-tasks.ts';
15
+ import { loopbackFetch } from '../../server/loopback-fetch.ts';
16
+ import type { ChatTurnResult } from '../../server/run-turn-types.ts';
17
+ import type { ToolDefinition } from '../types.ts';
18
+ import { longTaskDefaultMs, longTaskMaxMs } from './long-task-timeouts.ts';
19
+
20
+ // In-process MCP child path runs without server-side task store
21
+ // access; we route status/result HTTP calls back to the main server
22
+ // just like spawn-async itself does.
23
+ async function fetchStatusViaHttp(task_id: string): Promise<AsyncTaskEntry | null> {
24
+ const host = process.env.SOMORA_HOST || '127.0.0.1';
25
+ const port = process.env.SOMORA_PORT || '18737';
26
+ // SOMORA_TLS=1 → loopback must use HTTPS to match the cert hostname.
27
+ const scheme = process.env.SOMORA_TLS === '1' ? 'https' : 'http';
28
+ const res = await loopbackFetch(
29
+ `${scheme}://${host}:${port}/spawn-status?task_id=${encodeURIComponent(task_id)}`,
30
+ );
31
+ if (res.status === 404) return null;
32
+ if (!res.ok) {
33
+ const body = await res.text().catch(() => '');
34
+ throw new Error(`spawn-status HTTP ${res.status}: ${body.slice(0, 300)}`);
35
+ }
36
+ return (await res.json()) as AsyncTaskEntry;
37
+ }
38
+
39
+ export async function fetchResultViaHttp(
40
+ task_id: string,
41
+ opts: {
42
+ wait_until_done?: boolean;
43
+ timeout_ms?: number;
44
+ /** Caller turn identity for the server-side circular-wait guard —
45
+ * see /spawn-result in src/server/index.ts. */
46
+ waiter_agent?: string;
47
+ waiter_session?: string;
48
+ } = {},
49
+ ): Promise<{
50
+ task_id: string;
51
+ state: string;
52
+ result?: ChatTurnResult;
53
+ error?: string;
54
+ circular_wait?: boolean;
55
+ chain?: string[];
56
+ } | null> {
57
+ const host = process.env.SOMORA_HOST || '127.0.0.1';
58
+ const port = process.env.SOMORA_PORT || '18737';
59
+ const scheme = process.env.SOMORA_TLS === '1' ? 'https' : 'http';
60
+ const params = new URLSearchParams({ task_id });
61
+ if (opts.wait_until_done) params.set('wait_until_done', '1');
62
+ if (opts.timeout_ms !== undefined) params.set('timeout_ms', String(opts.timeout_ms));
63
+ if (opts.waiter_agent && opts.waiter_session) {
64
+ params.set('waiter_agent', opts.waiter_agent);
65
+ params.set('waiter_session', opts.waiter_session);
66
+ }
67
+ const res = await loopbackFetch(`${scheme}://${host}:${port}/spawn-result?${params.toString()}`);
68
+ if (res.status === 404) return null;
69
+ if (res.status === 409) {
70
+ return (await res.json()) as {
71
+ task_id: string;
72
+ state: string;
73
+ error?: string;
74
+ circular_wait?: boolean;
75
+ chain?: string[];
76
+ };
77
+ }
78
+ if (!res.ok) {
79
+ const body = await res.text().catch(() => '');
80
+ throw new Error(`spawn-result HTTP ${res.status}: ${body.slice(0, 300)}`);
81
+ }
82
+ return (await res.json()) as { task_id: string; state: string; result?: ChatTurnResult };
83
+ }
84
+
85
+ const StatusInput = z.object({ task_id: z.string().min(1) }).strict();
86
+
87
+ export const subagentStatus: ToolDefinition<z.infer<typeof StatusInput>> = {
88
+ name: 'subagent_status',
89
+ toolset: 'agents',
90
+ description:
91
+ 'Check the status of a sub-agent task spawned with wait:false. Returns running/done/failed ' +
92
+ 'plus the target agent + session and timestamps. Cheap — call this freely. Use it when ' +
93
+ 'the user asks about progress ("are the subs done yet?"). Use subagent_result to fetch the ' +
94
+ 'actual answer once state is "done".',
95
+ inputSchema: StatusInput,
96
+ jsonSchema: {
97
+ type: 'object',
98
+ properties: { task_id: { type: 'string', description: 'task_id from a wait:false spawn_subagent return value.' } },
99
+ required: ['task_id'],
100
+ additionalProperties: false,
101
+ },
102
+ async handler(input) {
103
+ // In-process first; HTTP fallback if not present (MCP child path).
104
+ let entry = getTask(input.task_id);
105
+ if (!entry) {
106
+ const remote = await fetchStatusViaHttp(input.task_id);
107
+ if (!remote) throw new Error(`subagent_status: task '${input.task_id}' not found`);
108
+ entry = remote;
109
+ }
110
+ return {
111
+ task_id: entry.task_id,
112
+ state: entry.state,
113
+ parent_agent: entry.parent_agent,
114
+ parent_session: entry.parent_session,
115
+ target_agent: entry.target_agent,
116
+ target_session: entry.target_session,
117
+ started_at: entry.started_at,
118
+ ...(entry.finished_at !== undefined ? { finished_at: entry.finished_at } : {}),
119
+ ...(entry.error ? { error: entry.error } : {}),
120
+ };
121
+ },
122
+ };
123
+
124
+ const ResultInput = z
125
+ .object({
126
+ task_id: z.string().min(1),
127
+ wait_until_done: z
128
+ .boolean()
129
+ .default(false)
130
+ .describe(
131
+ 'When true, the tool blocks server-side until the task finishes (or timeout_ms elapses) ' +
132
+ 'instead of erroring on "still running". Use this to avoid burning your own ' +
133
+ 'agent-loop tool-call rounds on a polling loop.',
134
+ ),
135
+ timeout_ms: z
136
+ .number()
137
+ .int()
138
+ .min(1_000)
139
+ // Schema cap is the absolute hard ceiling we'll ever permit; the
140
+ // *effective* per-call cap is agentLoop.longTaskMaxTimeoutMs (read
141
+ // at handler time via longTaskMaxMs()). Set the schema cap higher
142
+ // than any reasonable config value so config drives it, not zod.
143
+ .max(7_200_000) // 2 h schema ceiling — config caps further
144
+ .optional()
145
+ .describe(
146
+ 'Max ms to wait when wait_until_done. Defaults to ' +
147
+ 'agentLoop.longTaskDefaultTimeoutMs (5 min) and is hard-capped at ' +
148
+ 'agentLoop.longTaskMaxTimeoutMs (30 min). Pass higher than the ' +
149
+ 'cap and the cap wins; the sub keeps running in the background.',
150
+ ),
151
+ })
152
+ .strict();
153
+
154
+ // OpenClaw-style buffer: when the tool is waiting up to N ms internally,
155
+ // give the engine race N + this much before it pulls the rug. Keeps the
156
+ // inner+outer timing aligned without races at the boundary.
157
+ const TIMEOUT_BUFFER_MS = 2_000;
158
+
159
+ /**
160
+ * Hint returned instead of blocking when the sub is (directly or via a
161
+ * chain) waiting on the CALLER's own turn. Blocking here would deadlock
162
+ * until both timeouts fire: the caller holds its session lock while
163
+ * waiting, and the sub's pending agent_ask to the caller queues on
164
+ * exactly that lock. The teaching hint makes the situation self-healing
165
+ * — the caller finishes its turn, the sub's queued question runs and
166
+ * gets answered, the sub completes, and the result is fetchable on the
167
+ * caller's next turn. See src/server/ask-wait-graph.ts.
168
+ */
169
+ function circularWaitHint(chain?: string[]): string {
170
+ return (
171
+ `deadlock guard: this sub is currently blocked waiting on YOUR turn` +
172
+ (chain && chain.length > 0 ? ` (wait chain: ${chain.join(' → ')})` : '') +
173
+ `. Blocking on its result now would hang both of you. Finish your current turn — ` +
174
+ `the sub's pending question to you will then be answered in your session ` +
175
+ `automatically — and fetch the result with subagent_result in a later turn.`
176
+ );
177
+ }
178
+
179
+ export const subagentResult: ToolDefinition<z.infer<typeof ResultInput>> = {
180
+ name: 'subagent_result',
181
+ toolset: 'agents',
182
+ description:
183
+ 'Fetch the result of a sub-agent task. Returns one of three states: ' +
184
+ '"done" (with result text + usage), "failed" (with error), or "pending" ' +
185
+ '(task still running). `follow_ups` lists texts that arrived AFTER the sub\'s report ' +
186
+ '— the outcome of sub-agents the sub itself started and did not wait for; you are woken with a ' +
187
+ '[subagent attention] follow-up when one lands. `outcome` is the runtime verdict, never read from the text: ' +
188
+ '"completed" (the sub answered), "partial" (the engine had to force a finish at the ' +
189
+ 'round cap / tool budget and the sub then answered), "degraded" (the text is a somora ' +
190
+ 'marker — the sub looped or never answered; its tool work may still be intact, see ' +
191
+ '`files_written` / `media`), "failed". `outcome_reason` names the trigger. `tool_calls` ' +
192
+ 'and `rounds` say how much work happened, `files_written` lists files the sub created ' +
193
+ 'or edited via file_write/file_patch. When the sub generated images or videos, `media` lists them ' +
194
+ '(absolute `path`, `url`, `prompt`) straight from the media store — use those paths, ' +
195
+ 'do not search the filesystem or the transcript for them. `media` is present even when ' +
196
+ 'the result text is a degraded marker (the model failed to phrase its final answer), so ' +
197
+ 'check it before calling a task a failure. ' +
198
+ 'Pass `wait_until_done: true` to block server-side until the task finishes — much more ' +
199
+ 'efficient than polling subagent_status in a loop, since each poll burns one of your own ' +
200
+ 'agent-loop tool-call rounds. Default `timeout_ms` is 5min (configurable via ' +
201
+ 'agentLoop.longTaskDefaultTimeoutMs); hard cap 30min (longTaskMaxTimeoutMs). ' +
202
+ 'IMPORTANT: state "pending" is NOT an error — the sub is still working. Do NOT immediately ' +
203
+ 'retry; either wait and call subagent_status later, or call this again with a higher ' +
204
+ 'timeout_ms. Repeated pending returns mean the sub legitimately needs more time. ' +
205
+ 'Deadlock guard: if the sub is itself blocked waiting on YOUR turn (e.g. it agent_asked ' +
206
+ 'you and the call is queued behind your current turn), wait_until_done returns "pending" ' +
207
+ 'immediately with an explanatory hint instead of blocking — finish your turn first.',
208
+ inputSchema: ResultInput,
209
+ jsonSchema: {
210
+ type: 'object',
211
+ properties: {
212
+ task_id: { type: 'string' },
213
+ wait_until_done: { type: 'boolean', description: 'Block until task finishes. Default false.' },
214
+ timeout_ms: {
215
+ type: 'integer',
216
+ minimum: 1000,
217
+ description:
218
+ 'Max wait in ms. Defaults to agentLoop.longTaskDefaultTimeoutMs ' +
219
+ '(5 min); capped at longTaskMaxTimeoutMs (30 min).',
220
+ },
221
+ },
222
+ required: ['task_id'],
223
+ additionalProperties: false,
224
+ },
225
+ // Engine-level race must accommodate the tool's internal wait. Without
226
+ // wait_until_done the tool returns immediately, so 30s is plenty. With
227
+ // wait_until_done the inner wait is the caller's clamped timeout — give
228
+ // the engine that + 2s buffer to round-trip the reply. Read config
229
+ // values at call time so a runtime config change takes effect on the
230
+ // next invocation.
231
+ defaultTimeoutMs: 30_000,
232
+ timeoutFromInput: (input) => {
233
+ if (!input.wait_until_done) return undefined;
234
+ // longTaskDefaultMs/longTaskMaxMs are read at call time (not module
235
+ // load), so a config change takes effect on the next invocation
236
+ // without a server restart. The actual clamping happens here; the
237
+ // tool's static maxTimeoutMs below is just an upper safety fence.
238
+ const requested = input.timeout_ms ?? longTaskDefaultMs();
239
+ const clamped = Math.min(requested, longTaskMaxMs());
240
+ return clamped + TIMEOUT_BUFFER_MS;
241
+ },
242
+ // Static safety fence in case timeoutFromInput is bypassed somehow;
243
+ // 2h + buffer comfortably accommodates any reasonable longTaskMaxMs
244
+ // setting without re-evaluating per-call.
245
+ maxTimeoutMs: 7_200_000 + TIMEOUT_BUFFER_MS,
246
+ async handler(input, ctx) {
247
+ // Resolve effective timeout once per call; reused for the actual
248
+ // wait below and surfaced in the pending hint so the caller knows
249
+ // what value got applied (especially when their requested value was
250
+ // clamped down by longTaskMaxMs).
251
+ const effectiveTimeoutMs = input.wait_until_done
252
+ ? Math.min(input.timeout_ms ?? longTaskDefaultMs(), longTaskMaxMs())
253
+ : 0;
254
+ let local = getTask(input.task_id);
255
+ if (local) {
256
+ // getTask only hits in the MAIN SERVER process (the MCP child has
257
+ // its own empty task map and falls through to HTTP below), so the
258
+ // wait-graph here is the authoritative instance.
259
+ if (local.state === 'running' && input.wait_until_done) {
260
+ // wait_until_done is a blocking A2A wait like agent_ask /
261
+ // spawn wait:true — it must be cycle-CHECKED (the sub may
262
+ // already be waiting on this caller) and edge-REGISTERED (so
263
+ // other calls see this wait). Unlike agent_ask we don't error
264
+ // on a cycle: the task is legitimately still running, so we
265
+ // return state:'pending' with a hint instead of blocking into
266
+ // a guaranteed dual-timeout hang.
267
+ const waiter = ctx.session
268
+ ? { agent: ctx.agent, session: ctx.session }
269
+ : undefined;
270
+ const target = { agent: local.target_agent, session: local.target_session };
271
+ if (waiter) {
272
+ const cycle = findWaitCycle(waiter, target);
273
+ if (cycle) {
274
+ return {
275
+ task_id: local.task_id,
276
+ state: 'pending' as const,
277
+ target_agent: local.target_agent,
278
+ target_session: local.target_session,
279
+ hint: circularWaitHint(cycle),
280
+ };
281
+ }
282
+ }
283
+ const releaseWait = waiter ? registerWait(waiter, target) : undefined;
284
+ try {
285
+ local = (await waitForTaskCompletion(input.task_id, effectiveTimeoutMs)) ?? local;
286
+ } finally {
287
+ releaseWait?.();
288
+ }
289
+ }
290
+ if (local.state === 'running') {
291
+ return {
292
+ task_id: local.task_id,
293
+ state: 'pending' as const,
294
+ target_agent: local.target_agent,
295
+ target_session: local.target_session,
296
+ hint: input.wait_until_done
297
+ ? 'sub still running after timeout_ms; call again with a higher timeout_ms or check subagent_status later'
298
+ : 'sub still running; pass wait_until_done:true to block, or call subagent_status to peek',
299
+ };
300
+ }
301
+ // Terminal state delivered → suppress the pending attention wake
302
+ // (the parent has the answer now, a wake would be noise).
303
+ markResultFetched(local.task_id);
304
+ if (local.state === 'failed' || local.state === 'cancelled') {
305
+ return {
306
+ task_id: local.task_id,
307
+ state: local.state,
308
+ target_agent: local.target_agent,
309
+ target_session: local.target_session,
310
+ error: local.error ?? 'unknown error',
311
+ };
312
+ }
313
+ return {
314
+ task_id: local.task_id,
315
+ state: 'done' as const,
316
+ target_agent: local.target_agent,
317
+ target_session: local.target_session,
318
+ result: local.result?.finalText ?? '',
319
+ outcome: local.result?.outcome ?? 'completed',
320
+ ...(local.result?.outcome_reason ? { outcome_reason: local.result.outcome_reason } : {}),
321
+ tool_calls: local.result?.tool_calls ?? 0,
322
+ ...(local.result?.rounds !== undefined ? { rounds: local.result.rounds } : {}),
323
+ ...(local.result?.model ? { model: `${local.result.provider}/${local.result.model}` } : {}),
324
+ ...(local.result?.fallback ? { fallback: local.result.fallback } : {}),
325
+ ...(local.result?.files_written?.length ? { files_written: local.result.files_written } : {}),
326
+ ...(local.result?.media?.length ? { media: local.result.media } : {}),
327
+ ...(local.result?.follow_ups?.length ? { follow_ups: local.result.follow_ups } : {}),
328
+ usage: local.result?.usage,
329
+ ms: local.result?.ms,
330
+ };
331
+ }
332
+ // HTTP fallback (MCP child) — pass the wait params through. The
333
+ // circular-wait guard runs server-side in /spawn-result (the child
334
+ // can't see the main server's wait-graph); waiter_* carry this
335
+ // turn's identity over.
336
+ const remote = await fetchResultViaHttp(input.task_id, {
337
+ wait_until_done: input.wait_until_done,
338
+ timeout_ms: input.timeout_ms,
339
+ ...(ctx.session ? { waiter_agent: ctx.agent, waiter_session: ctx.session } : {}),
340
+ });
341
+ if (!remote) throw new Error(`subagent_result: task '${input.task_id}' not found`);
342
+ if (remote.state === 'running') {
343
+ return {
344
+ task_id: remote.task_id,
345
+ state: 'pending' as const,
346
+ hint: remote.circular_wait
347
+ ? circularWaitHint(remote.chain)
348
+ : input.wait_until_done
349
+ ? 'sub still running after timeout_ms; call again with a higher timeout_ms or check subagent_status later'
350
+ : 'sub still running; pass wait_until_done:true to block, or call subagent_status to peek',
351
+ };
352
+ }
353
+ if (remote.state === 'failed' || remote.state === 'cancelled') {
354
+ return {
355
+ task_id: remote.task_id,
356
+ state: remote.state,
357
+ error: remote.error ?? 'unknown error',
358
+ };
359
+ }
360
+ return {
361
+ task_id: remote.task_id,
362
+ state: 'done' as const,
363
+ result: remote.result?.finalText ?? '',
364
+ outcome: remote.result?.outcome ?? 'completed',
365
+ ...(remote.result?.outcome_reason ? { outcome_reason: remote.result.outcome_reason } : {}),
366
+ tool_calls: remote.result?.tool_calls ?? 0,
367
+ ...(remote.result?.rounds !== undefined ? { rounds: remote.result.rounds } : {}),
368
+ ...(remote.result?.model ? { model: `${remote.result.provider}/${remote.result.model}` } : {}),
369
+ ...(remote.result?.fallback ? { fallback: remote.result.fallback } : {}),
370
+ ...(remote.result?.files_written?.length ? { files_written: remote.result.files_written } : {}),
371
+ ...(remote.result?.media?.length ? { media: remote.result.media } : {}),
372
+ ...(remote.result?.follow_ups?.length ? { follow_ups: remote.result.follow_ups } : {}),
373
+ usage: remote.result?.usage,
374
+ ms: remote.result?.ms,
375
+ };
376
+ },
377
+ };
378
+
379
+ // ─────────────────────────────────────────────────────────────────────
380
+ // subagent_list — enumerate spawn tasks initiated by the calling agent
381
+ // ─────────────────────────────────────────────────────────────────────
382
+
383
+ async function fetchListViaHttp(parent_agent: string): Promise<AsyncTaskEntry[]> {
384
+ const host = process.env.SOMORA_HOST || '127.0.0.1';
385
+ const port = process.env.SOMORA_PORT || '18737';
386
+ const scheme = process.env.SOMORA_TLS === '1' ? 'https' : 'http';
387
+ const res = await loopbackFetch(
388
+ `${scheme}://${host}:${port}/spawn-list?parent_agent=${encodeURIComponent(parent_agent)}`,
389
+ );
390
+ if (!res.ok) {
391
+ const body = await res.text().catch(() => '');
392
+ throw new Error(`spawn-list HTTP ${res.status}: ${body.slice(0, 300)}`);
393
+ }
394
+ const json = (await res.json()) as { tasks: AsyncTaskEntry[] };
395
+ return json.tasks;
396
+ }
397
+
398
+ const ListInput = z
399
+ .object({
400
+ state: z
401
+ .enum(['running', 'done', 'failed', 'cancelled', 'all'])
402
+ .default('all')
403
+ .describe(
404
+ 'Filter by task state. "running" shows only active subs, "done"/"failed"/"cancelled" ' +
405
+ 'only finished, "all" (default) returns everything still in the registry. Tasks are ' +
406
+ 'kept in memory for the server\'s lifetime and lost on restart.',
407
+ ),
408
+ limit: z
409
+ .number()
410
+ .int()
411
+ .min(1)
412
+ .max(500)
413
+ .default(50)
414
+ .describe('Max entries to return after sort. Newest tasks come first.'),
415
+ })
416
+ .strict();
417
+
418
+ export const subagentList: ToolDefinition<z.infer<typeof ListInput>> = {
419
+ name: 'subagent_list',
420
+ toolset: 'agents',
421
+ description:
422
+ 'List sub-agent tasks YOU spawned (this agent\'s own subs only — no peer-agent visibility). ' +
423
+ 'Use this when you need to know what\'s still running in the background, e.g. "are the ' +
424
+ 'research subs done yet before I summarize?", "did anything from earlier finish?", or just ' +
425
+ 'a sanity-check before composing a reply that depends on prior spawns. ' +
426
+ 'Returns one entry per task with task_id, state, target_agent/session, started_at, ' +
427
+ 'finished_at (if done). Sorted newest-first. ' +
428
+ 'Tasks live in the server\'s in-memory registry only — server restarts wipe them ' +
429
+ '(JSONL session files persist independently). To inspect a specific task in detail, ' +
430
+ 'use subagent_status (state + timestamps) or subagent_result (final answer).',
431
+ inputSchema: ListInput,
432
+ jsonSchema: {
433
+ type: 'object',
434
+ properties: {
435
+ state: {
436
+ type: 'string',
437
+ enum: ['running', 'done', 'failed', 'cancelled', 'all'],
438
+ default: 'all',
439
+ description: 'Filter by task state.',
440
+ },
441
+ limit: { type: 'integer', minimum: 1, maximum: 500, default: 50 },
442
+ },
443
+ additionalProperties: false,
444
+ },
445
+ async handler(input, ctx) {
446
+ // In-process first; HTTP fallback for MCP-child path (subprocess
447
+ // doesn't share the async-tasks Map with the main server).
448
+ let entries = listTasksForAgent(ctx.agent);
449
+ if (entries.length === 0) {
450
+ // Either no tasks for this agent OR we're an MCP child without
451
+ // direct access. The HTTP endpoint distinguishes — empty list
452
+ // back means "really none".
453
+ try {
454
+ entries = await fetchListViaHttp(ctx.agent);
455
+ } catch {
456
+ // HTTP fallback failed (server unreachable); treat as no tasks
457
+ // rather than throwing — list is best-effort discovery.
458
+ entries = [];
459
+ }
460
+ }
461
+ const filtered = input.state === 'all'
462
+ ? entries
463
+ : entries.filter((e) => e.state === input.state);
464
+ // Newest first by started_at.
465
+ filtered.sort((a, b) => b.started_at - a.started_at);
466
+ const truncated = filtered.length > input.limit;
467
+ const tasks = filtered.slice(0, input.limit).map((t) => ({
468
+ task_id: t.task_id,
469
+ state: t.state,
470
+ target_agent: t.target_agent,
471
+ target_session: t.target_session,
472
+ started_at: t.started_at,
473
+ ...(t.finished_at !== undefined ? { finished_at: t.finished_at } : {}),
474
+ ...(t.error ? { error: t.error } : {}),
475
+ }));
476
+ return {
477
+ count: tasks.length,
478
+ truncated,
479
+ tasks,
480
+ };
481
+ },
482
+ };
483
+
484
+ // ─────────────────────────────────────────────────────────────────────
485
+ // subagent_cancel — abort a running spawn tree (2026-07-28 feedback)
486
+ // ─────────────────────────────────────────────────────────────────────
487
+
488
+ async function fetchCancelViaHttp(
489
+ task_id: string,
490
+ requesting_agent: string,
491
+ reason?: string,
492
+ ): Promise<{ cancelled: string[]; skipped: Array<{ task_id: string; state: string }> } | null> {
493
+ const host = process.env.SOMORA_HOST || '127.0.0.1';
494
+ const port = process.env.SOMORA_PORT || '18737';
495
+ const scheme = process.env.SOMORA_TLS === '1' ? 'https' : 'http';
496
+ const res = await loopbackFetch(`${scheme}://${host}:${port}/spawn-cancel`, {
497
+ method: 'POST',
498
+ headers: { 'Content-Type': 'application/json' },
499
+ body: JSON.stringify({ task_id, requesting_agent, ...(reason ? { reason } : {}) }),
500
+ });
501
+ if (res.status === 404) return null;
502
+ if (!res.ok) {
503
+ const body = await res.text().catch(() => '');
504
+ throw new Error(`spawn-cancel HTTP ${res.status}: ${body.slice(0, 300)}`);
505
+ }
506
+ return (await res.json()) as {
507
+ cancelled: string[];
508
+ skipped: Array<{ task_id: string; state: string }>;
509
+ };
510
+ }
511
+
512
+ const CancelInput = z
513
+ .object({
514
+ task_id: z.string().min(1),
515
+ reason: z
516
+ .string()
517
+ .max(300)
518
+ .optional()
519
+ .describe('Optional short reason recorded on the cancelled task(s) for the audit trail.'),
520
+ })
521
+ .strict();
522
+
523
+ export const subagentCancel: ToolDefinition<z.infer<typeof CancelInput>> = {
524
+ name: 'subagent_cancel',
525
+ toolset: 'agents',
526
+ description:
527
+ 'Cancel a sub-agent task spawned with wait:false, running or still waiting in its ' +
528
+ 'session queue — INCLUDING any child-subs it spawned itself (cascade over the whole spawn ' +
529
+ 'tree). The in-flight LLM call is aborted ' +
530
+ 'via the same signal the Stop button uses; files the sub already wrote to disk stay ' +
531
+ 'untouched, and its session JSONL remains inspectable. Use this when a spawn turned out ' +
532
+ 'wrong (bad instructions, wrong model, cost concerns) instead of waiting it out or ' +
533
+ 'restarting the server. Only the agent that spawned the task can cancel it. ' +
534
+ 'Already-finished tasks are reported as skipped — cancelling them is a no-op.',
535
+ inputSchema: CancelInput,
536
+ jsonSchema: {
537
+ type: 'object',
538
+ properties: {
539
+ task_id: {
540
+ type: 'string',
541
+ description: 'task_id from a wait:false spawn_subagent return value.',
542
+ },
543
+ reason: {
544
+ type: 'string',
545
+ maxLength: 300,
546
+ description: 'Optional short reason recorded on the cancelled task(s).',
547
+ },
548
+ },
549
+ required: ['task_id'],
550
+ additionalProperties: false,
551
+ },
552
+ async handler(input, ctx) {
553
+ const reason = input.reason?.trim()
554
+ ? `cancelled by ${ctx.agent}: ${input.reason.trim()}`
555
+ : `cancelled by ${ctx.agent}`;
556
+ // In-process first (main server); HTTP fallback for the MCP child.
557
+ const local = getTask(input.task_id);
558
+ if (local) {
559
+ if (local.parent_agent !== ctx.agent) {
560
+ throw new Error(
561
+ `subagent_cancel: task '${input.task_id}' was spawned by '${local.parent_agent}', ` +
562
+ `not by you — only the spawning agent can cancel it`,
563
+ );
564
+ }
565
+ const outcome = cancelTaskCascade(input.task_id, reason);
566
+ if (!outcome) throw new Error(`subagent_cancel: task '${input.task_id}' not found`);
567
+ return {
568
+ task_id: input.task_id,
569
+ cancelled: outcome.cancelled,
570
+ skipped: outcome.skipped,
571
+ hint:
572
+ outcome.cancelled.length > 0
573
+ ? 'Cancelled subs keep their session JSONL and any files they wrote — inspect via /sessions if needed.'
574
+ : 'Nothing was running — all tasks in the tree already finished.',
575
+ };
576
+ }
577
+ const remote = await fetchCancelViaHttp(input.task_id, ctx.agent, input.reason);
578
+ if (!remote) throw new Error(`subagent_cancel: task '${input.task_id}' not found`);
579
+ return {
580
+ task_id: input.task_id,
581
+ cancelled: remote.cancelled,
582
+ skipped: remote.skipped,
583
+ hint:
584
+ remote.cancelled.length > 0
585
+ ? 'Cancelled subs keep their session JSONL and any files they wrote — inspect via /sessions if needed.'
586
+ : 'Nothing was running — all tasks in the tree already finished.',
587
+ };
588
+ },
589
+ };
@@ -0,0 +1,6 @@
1
+ import type { ToolDefinition } from '../types.ts';
2
+ import { browserTool } from './tools.ts';
3
+
4
+ export function browserTools(): ToolDefinition[] {
5
+ return [browserTool as unknown as ToolDefinition];
6
+ }