@otium-team/negotium 0.0.0-stage → 0.23.11

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 (572) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +329 -2
  3. package/bin/codex-sdk-window-hide.mjs +40 -0
  4. package/bin/negotium.mjs +22 -0
  5. package/dist/agent-helpers.js +23903 -0
  6. package/dist/agent-helpers.js.map +171 -0
  7. package/dist/background-bash.js +535 -0
  8. package/dist/background-bash.js.map +16 -0
  9. package/dist/browser-runtime.js +2336 -0
  10. package/dist/browser-runtime.js.map +35 -0
  11. package/dist/canonical-mcp-bridge.js +14 -0
  12. package/dist/canonical-mcp-bridge.js.map +9 -0
  13. package/dist/chunk-0fenxbe6.js +173 -0
  14. package/dist/chunk-0fenxbe6.js.map +12 -0
  15. package/dist/chunk-2mx7fq49.js +6 -0
  16. package/dist/chunk-2mx7fq49.js.map +9 -0
  17. package/dist/chunk-ad7kxsaq.js +202 -0
  18. package/dist/chunk-ad7kxsaq.js.map +9 -0
  19. package/dist/chunk-da9ad838.js +3927 -0
  20. package/dist/chunk-da9ad838.js.map +47 -0
  21. package/dist/chunk-f7p0h1gs.js +54 -0
  22. package/dist/chunk-f7p0h1gs.js.map +10 -0
  23. package/dist/chunk-jtv8yzy1.js +206 -0
  24. package/dist/chunk-jtv8yzy1.js.map +10 -0
  25. package/dist/chunk-mxxwx5mg.js +375 -0
  26. package/dist/chunk-mxxwx5mg.js.map +13 -0
  27. package/dist/cron.js +1 -0
  28. package/dist/hosted-agent.js +5919 -0
  29. package/dist/hosted-agent.js.map +62 -0
  30. package/dist/main.js +60536 -0
  31. package/dist/main.js.map +338 -0
  32. package/dist/mcp-catalog.js +39 -0
  33. package/dist/mcp-catalog.js.map +10 -0
  34. package/dist/mcp-factories.js +26572 -0
  35. package/dist/mcp-factories.js.map +181 -0
  36. package/dist/mcp-servers.js +50 -0
  37. package/dist/mcp-servers.js.map +10 -0
  38. package/dist/media.js +570 -0
  39. package/dist/media.js.map +15 -0
  40. package/dist/outbox.js +354 -0
  41. package/dist/outbox.js.map +15 -0
  42. package/dist/platform-runtime.js +73 -0
  43. package/dist/platform-runtime.js.map +12 -0
  44. package/dist/prompts.js +892 -0
  45. package/dist/prompts.js.map +15 -0
  46. package/dist/query-runtime.js +1073 -0
  47. package/dist/query-runtime.js.map +26 -0
  48. package/dist/registry.js +336 -0
  49. package/dist/registry.js.map +14 -0
  50. package/dist/rollout.js +57 -0
  51. package/dist/rollout.js.map +10 -0
  52. package/dist/runtime/cron/background-sessions.ts +119 -0
  53. package/dist/runtime/cron/context.ts +123 -0
  54. package/dist/runtime/cron/host.ts +67 -0
  55. package/dist/runtime/cron/index.ts +95 -0
  56. package/dist/runtime/cron/mcp-server.ts +556 -0
  57. package/dist/runtime/cron/module.ts +174 -0
  58. package/dist/runtime/cron/package.json +6 -0
  59. package/dist/runtime/cron/schedule.ts +211 -0
  60. package/dist/runtime/cron/scheduler.ts +444 -0
  61. package/dist/runtime/cron/scripts.ts +203 -0
  62. package/dist/runtime/cron/store.ts +1163 -0
  63. package/dist/runtime/cron/summarize.ts +115 -0
  64. package/dist/runtime/package.json +6 -0
  65. package/dist/runtime/scripts/faster-whisper-wrapper.py +87 -0
  66. package/dist/runtime/src/agents/api-topic-agent-switch.ts +179 -0
  67. package/dist/runtime/src/agents/archiver.ts +677 -0
  68. package/dist/runtime/src/agents/auth-check.ts +156 -0
  69. package/dist/runtime/src/agents/claude-notices.ts +130 -0
  70. package/dist/runtime/src/agents/claude-provider.ts +866 -0
  71. package/dist/runtime/src/agents/claude-registry.ts +117 -0
  72. package/dist/runtime/src/agents/claude-runtime-inspection.ts +43 -0
  73. package/dist/runtime/src/agents/codex-app-server.ts +138 -0
  74. package/dist/runtime/src/agents/codex-native-multi-agent.ts +360 -0
  75. package/dist/runtime/src/agents/codex-provider.ts +1193 -0
  76. package/dist/runtime/src/agents/codex-registry.ts +116 -0
  77. package/dist/runtime/src/agents/codex-tier-resolver.ts +74 -0
  78. package/dist/runtime/src/agents/codex-tree-kill.ts +54 -0
  79. package/dist/runtime/src/agents/codex-tree-manager.ts +230 -0
  80. package/dist/runtime/src/agents/codex-vault-hook-bridge.ts +240 -0
  81. package/dist/runtime/src/agents/codex-vault-hook.mjs +50 -0
  82. package/dist/runtime/src/agents/codex-windows-wrapper.ts +174 -0
  83. package/dist/runtime/src/agents/compaction-support.ts +75 -0
  84. package/dist/runtime/src/agents/compaction-tool-projection.ts +125 -0
  85. package/dist/runtime/src/agents/contracts.ts +75 -0
  86. package/dist/runtime/src/agents/deep-map.ts +13 -0
  87. package/dist/runtime/src/agents/execution-host.ts +118 -0
  88. package/dist/runtime/src/agents/explicit-agent-switch.ts +106 -0
  89. package/dist/runtime/src/agents/fixtures/claude-attachments.jsonl +2 -0
  90. package/dist/runtime/src/agents/fixtures/codex-shell.jsonl +5 -0
  91. package/dist/runtime/src/agents/fork.ts +100 -0
  92. package/dist/runtime/src/agents/hosted-agent.ts +78 -0
  93. package/dist/runtime/src/agents/idle-archiver.ts +225 -0
  94. package/dist/runtime/src/agents/idle-compact.ts +225 -0
  95. package/dist/runtime/src/agents/index.ts +225 -0
  96. package/dist/runtime/src/agents/maestro-provider.ts +246 -0
  97. package/dist/runtime/src/agents/maestro-registry.ts +189 -0
  98. package/dist/runtime/src/agents/mcp-tools/ask-user.ts +653 -0
  99. package/dist/runtime/src/agents/mcp-tools/common.ts +23 -0
  100. package/dist/runtime/src/agents/mcp-tools/inline-assets.ts +203 -0
  101. package/dist/runtime/src/agents/mcp-tools/publish-html.ts +183 -0
  102. package/dist/runtime/src/agents/mcp-tools/request-vault.ts +684 -0
  103. package/dist/runtime/src/agents/mcp-tools/self-config.ts +353 -0
  104. package/dist/runtime/src/agents/mcp-tools/spawn-subagent.ts +1349 -0
  105. package/dist/runtime/src/agents/mcp-tools/visual-compat.ts +18 -0
  106. package/dist/runtime/src/agents/mcp-tools/visuals.ts +60 -0
  107. package/dist/runtime/src/agents/memory-archive-policy.ts +54 -0
  108. package/dist/runtime/src/agents/model-catalog.ts +439 -0
  109. package/dist/runtime/src/agents/public-helpers.ts +149 -0
  110. package/dist/runtime/src/agents/registry.ts +35 -0
  111. package/dist/runtime/src/agents/rollout/claude.ts +336 -0
  112. package/dist/runtime/src/agents/rollout/codex.ts +910 -0
  113. package/dist/runtime/src/agents/rollout/index.ts +26 -0
  114. package/dist/runtime/src/agents/rollout/shared.ts +293 -0
  115. package/dist/runtime/src/agents/self-config-core.ts +704 -0
  116. package/dist/runtime/src/agents/task-events.ts +59 -0
  117. package/dist/runtime/src/agents/tool-format.ts +613 -0
  118. package/dist/runtime/src/agents/topic-agent-switch.ts +189 -0
  119. package/dist/runtime/src/agents/topic-cleanup.ts +285 -0
  120. package/dist/runtime/src/agents/vault-tool-policy.ts +36 -0
  121. package/dist/runtime/src/application/execute-external-user-turn.ts +23 -0
  122. package/dist/runtime/src/application/submit-runtime-gateway-turn.ts +420 -0
  123. package/dist/runtime/src/application/submit-user-message.ts +60 -0
  124. package/dist/runtime/src/application/switch-topic-effort.ts +48 -0
  125. package/dist/runtime/src/application/switch-topic-model.ts +79 -0
  126. package/dist/runtime/src/application/topic-service.ts +186 -0
  127. package/dist/runtime/src/application/vault-command.ts +170 -0
  128. package/dist/runtime/src/bus.ts +403 -0
  129. package/dist/runtime/src/config-public.ts +2 -0
  130. package/dist/runtime/src/cron-host.ts +33 -0
  131. package/dist/runtime/src/cron-mcp-host.ts +5 -0
  132. package/dist/runtime/src/identifiers.ts +49 -0
  133. package/dist/runtime/src/index.ts +573 -0
  134. package/dist/runtime/src/mcp/agent-health-server.ts +8 -0
  135. package/dist/runtime/src/mcp/canonical-bridge-config.ts +84 -0
  136. package/dist/runtime/src/mcp/canonical-proxy-server.ts +308 -0
  137. package/dist/runtime/src/mcp/compaction-log-server.ts +25 -0
  138. package/dist/runtime/src/mcp/decision-server.ts +21 -0
  139. package/dist/runtime/src/mcp/dm-ipc.ts +60 -0
  140. package/dist/runtime/src/mcp/factories/agent-health.ts +394 -0
  141. package/dist/runtime/src/mcp/factories/compaction-log.ts +135 -0
  142. package/dist/runtime/src/mcp/factories/decision.ts +186 -0
  143. package/dist/runtime/src/mcp/factories/index.ts +73 -0
  144. package/dist/runtime/src/mcp/factories/session-comm.ts +184 -0
  145. package/dist/runtime/src/mcp/factories/session-history.ts +103 -0
  146. package/dist/runtime/src/mcp/factories/stdio-protection.ts +24 -0
  147. package/dist/runtime/src/mcp/factories/system-health.ts +259 -0
  148. package/dist/runtime/src/mcp/factories/task.ts +185 -0
  149. package/dist/runtime/src/mcp/factories/token-stats.ts +145 -0
  150. package/dist/runtime/src/mcp/factories/vault.ts +32 -0
  151. package/dist/runtime/src/mcp/mcp-helpers.ts +40 -0
  152. package/dist/runtime/src/mcp/peer-bridge.ts +119 -0
  153. package/dist/runtime/src/mcp/runtime-spec.ts +473 -0
  154. package/dist/runtime/src/mcp/session-comm/actor-policy.ts +160 -0
  155. package/dist/runtime/src/mcp/session-comm/bridge-ipc-config.ts +27 -0
  156. package/dist/runtime/src/mcp/session-comm/context.ts +113 -0
  157. package/dist/runtime/src/mcp/session-comm/default-host.ts +723 -0
  158. package/dist/runtime/src/mcp/session-comm/history-target.ts +89 -0
  159. package/dist/runtime/src/mcp/session-comm/history-tools.ts +113 -0
  160. package/dist/runtime/src/mcp/session-comm/hub-remote-session.ts +553 -0
  161. package/dist/runtime/src/mcp/session-comm/limits.ts +8 -0
  162. package/dist/runtime/src/mcp/session-comm/peer-forward.ts +251 -0
  163. package/dist/runtime/src/mcp/session-comm/runtime.ts +128 -0
  164. package/dist/runtime/src/mcp/session-comm/server.ts +1036 -0
  165. package/dist/runtime/src/mcp/session-comm/tell-permissions.ts +79 -0
  166. package/dist/runtime/src/mcp/session-comm/topic-catalog.ts +155 -0
  167. package/dist/runtime/src/mcp/session-comm/topic-config.ts +137 -0
  168. package/dist/runtime/src/mcp/session-comm/topics.ts +313 -0
  169. package/dist/runtime/src/mcp/session-history-limits.ts +36 -0
  170. package/dist/runtime/src/mcp/session-history-reader.ts +359 -0
  171. package/dist/runtime/src/mcp/session-history-server.ts +19 -0
  172. package/dist/runtime/src/mcp/stdio-protect.ts +7 -0
  173. package/dist/runtime/src/mcp/system-health-server.ts +5 -0
  174. package/dist/runtime/src/mcp/task-server.ts +17 -0
  175. package/dist/runtime/src/mcp/token-stats-server.ts +10 -0
  176. package/dist/runtime/src/mcp/vault-server.ts +12 -0
  177. package/dist/runtime/src/mcp/wiki-search-index.ts +359 -0
  178. package/dist/runtime/src/mcp/wiki-server.ts +2386 -0
  179. package/dist/runtime/src/mcp-runtime-host.ts +81 -0
  180. package/dist/runtime/src/media/file-events.ts +33 -0
  181. package/dist/runtime/src/media/text-extractor.ts +334 -0
  182. package/dist/runtime/src/media/video.ts +92 -0
  183. package/dist/runtime/src/node-host.ts +200 -0
  184. package/dist/runtime/src/outbox/coalescing-runner.ts +157 -0
  185. package/dist/runtime/src/outbox/file-ops.ts +267 -0
  186. package/dist/runtime/src/outbox/index.ts +26 -0
  187. package/dist/runtime/src/outbox/utils.ts +74 -0
  188. package/dist/runtime/src/platform/background-bash/context.ts +9 -0
  189. package/dist/runtime/src/platform/background-bash/manager.ts +292 -0
  190. package/dist/runtime/src/platform/background-bash/output-buffer.ts +323 -0
  191. package/dist/runtime/src/platform/config-helpers.ts +47 -0
  192. package/dist/runtime/src/platform/config.ts +618 -0
  193. package/dist/runtime/src/platform/constants.ts +30 -0
  194. package/dist/runtime/src/platform/debug-users.ts +14 -0
  195. package/dist/runtime/src/platform/delay.ts +1 -0
  196. package/dist/runtime/src/platform/error.ts +9 -0
  197. package/dist/runtime/src/platform/file-utils.ts +35 -0
  198. package/dist/runtime/src/platform/ipc.ts +55 -0
  199. package/dist/runtime/src/platform/jsonl.ts +277 -0
  200. package/dist/runtime/src/platform/lifecycle.ts +176 -0
  201. package/dist/runtime/src/platform/log-rotation.ts +45 -0
  202. package/dist/runtime/src/platform/logger.ts +42 -0
  203. package/dist/runtime/src/platform/maestro-bootstrap-env.ts +3 -0
  204. package/dist/runtime/src/platform/mcp-catalog-policy.ts +63 -0
  205. package/dist/runtime/src/platform/mcp-config.ts +1329 -0
  206. package/dist/runtime/src/platform/memoize-import.ts +26 -0
  207. package/dist/runtime/src/platform/modules.ts +145 -0
  208. package/dist/runtime/src/platform/node-plugins.ts +46 -0
  209. package/dist/runtime/src/platform/paths.ts +62 -0
  210. package/dist/runtime/src/platform/playwright/browser-processes.ts +300 -0
  211. package/dist/runtime/src/platform/playwright/capability.ts +5 -0
  212. package/dist/runtime/src/platform/playwright/headed-launch.ts +61 -0
  213. package/dist/runtime/src/platform/playwright/manager-utils.ts +128 -0
  214. package/dist/runtime/src/platform/playwright/manager.ts +1502 -0
  215. package/dist/runtime/src/platform/playwright/mcp-transport.ts +35 -0
  216. package/dist/runtime/src/platform/playwright/profile-management.ts +33 -0
  217. package/dist/runtime/src/platform/playwright/public-runtime.ts +52 -0
  218. package/dist/runtime/src/platform/playwright/transport-probe.ts +89 -0
  219. package/dist/runtime/src/platform/playwright/vault-broker.ts +261 -0
  220. package/dist/runtime/src/platform/public-runtime.ts +18 -0
  221. package/dist/runtime/src/prompts/agents/wiki-archiver.md +194 -0
  222. package/dist/runtime/src/prompts/builders.ts +696 -0
  223. package/dist/runtime/src/prompts/sessions/_shared-tools.md +38 -0
  224. package/dist/runtime/src/prompts/sessions/channel-system.md +13 -0
  225. package/dist/runtime/src/prompts/sessions/manager-system.md +34 -0
  226. package/dist/runtime/src/prompts/sessions/surfaces/cli.md +6 -0
  227. package/dist/runtime/src/prompts/sessions/surfaces/otium-manager.md +18 -0
  228. package/dist/runtime/src/prompts/sessions/surfaces/otium.md +6 -0
  229. package/dist/runtime/src/prompts/sessions/surfaces/telegram.md +5 -0
  230. package/dist/runtime/src/prompts/sessions/surfaces/terminal.md +6 -0
  231. package/dist/runtime/src/prompts/sessions/topic-system.md +9 -0
  232. package/dist/runtime/src/prompts/sessions/visual-design.md +38 -0
  233. package/dist/runtime/src/query/active-rooms.ts +508 -0
  234. package/dist/runtime/src/query/index.ts +23 -0
  235. package/dist/runtime/src/query/public-runtime.ts +28 -0
  236. package/dist/runtime/src/query/room-query-registry.ts +217 -0
  237. package/dist/runtime/src/query/session-inbox-cleanup.ts +45 -0
  238. package/dist/runtime/src/query/session-inbox-path.ts +42 -0
  239. package/dist/runtime/src/query/state.ts +116 -0
  240. package/dist/runtime/src/query/types.ts +8 -0
  241. package/dist/runtime/src/runtime/actor-topic-reach.ts +123 -0
  242. package/dist/runtime/src/runtime/actor-topic-scope.ts +255 -0
  243. package/dist/runtime/src/runtime/ask-callbacks.ts +217 -0
  244. package/dist/runtime/src/runtime/attachments.ts +149 -0
  245. package/dist/runtime/src/runtime/background-session-policy.ts +1 -0
  246. package/dist/runtime/src/runtime/background-sessions.ts +288 -0
  247. package/dist/runtime/src/runtime/bashrs-completions.ts +350 -0
  248. package/dist/runtime/src/runtime/channel-context.ts +115 -0
  249. package/dist/runtime/src/runtime/context-warning.ts +131 -0
  250. package/dist/runtime/src/runtime/cron-sessions.ts +35 -0
  251. package/dist/runtime/src/runtime/delivery-ack.ts +112 -0
  252. package/dist/runtime/src/runtime/errors.ts +70 -0
  253. package/dist/runtime/src/runtime/event-heartbeat.ts +77 -0
  254. package/dist/runtime/src/runtime/file-hooks.ts +81 -0
  255. package/dist/runtime/src/runtime/footer.ts +23 -0
  256. package/dist/runtime/src/runtime/gateway-capabilities.ts +22 -0
  257. package/dist/runtime/src/runtime/inbox.ts +1307 -0
  258. package/dist/runtime/src/runtime/playwright-turn-abort.ts +59 -0
  259. package/dist/runtime/src/runtime/public-helpers.ts +78 -0
  260. package/dist/runtime/src/runtime/remote-session-grant.ts +221 -0
  261. package/dist/runtime/src/runtime/remote-session-inbox.ts +943 -0
  262. package/dist/runtime/src/runtime/remote-session-reply-outbox.ts +168 -0
  263. package/dist/runtime/src/runtime/task-format.ts +18 -0
  264. package/dist/runtime/src/runtime/tasks.ts +53 -0
  265. package/dist/runtime/src/runtime/thread-context.ts +123 -0
  266. package/dist/runtime/src/runtime/thread-read.ts +67 -0
  267. package/dist/runtime/src/runtime/topic-config.ts +29 -0
  268. package/dist/runtime/src/runtime/turn-event-stream.ts +1051 -0
  269. package/dist/runtime/src/runtime/turn-runner.ts +2284 -0
  270. package/dist/runtime/src/runtime/turn-session.ts +116 -0
  271. package/dist/runtime/src/runtime/usage-alert.ts +51 -0
  272. package/dist/runtime/src/runtime/user-turn-envelope.ts +94 -0
  273. package/dist/runtime/src/runtime/visual-html.ts +175 -0
  274. package/dist/runtime/src/runtime/visual-store.ts +480 -0
  275. package/dist/runtime/src/runtime/visuals.ts +209 -0
  276. package/dist/runtime/src/runtime-gateway.ts +848 -0
  277. package/dist/runtime/src/security/sanitize.ts +27 -0
  278. package/dist/runtime/src/security/sensitive-path.ts +41 -0
  279. package/dist/runtime/src/storage/activity-log.ts +167 -0
  280. package/dist/runtime/src/storage/api-messages.ts +766 -0
  281. package/dist/runtime/src/storage/api-topic-brief.ts +134 -0
  282. package/dist/runtime/src/storage/api-topic-config.ts +197 -0
  283. package/dist/runtime/src/storage/api-topics.ts +1647 -0
  284. package/dist/runtime/src/storage/app-settings.ts +50 -0
  285. package/dist/runtime/src/storage/ask-user-gates.ts +359 -0
  286. package/dist/runtime/src/storage/browser-profiles.ts +186 -0
  287. package/dist/runtime/src/storage/conversation-migration.ts +180 -0
  288. package/dist/runtime/src/storage/conversations.ts +377 -0
  289. package/dist/runtime/src/storage/decisions.ts +231 -0
  290. package/dist/runtime/src/storage/forum/agent-settings.ts +20 -0
  291. package/dist/runtime/src/storage/forum/index.ts +4 -0
  292. package/dist/runtime/src/storage/forum/repository.ts +283 -0
  293. package/dist/runtime/src/storage/forum/schema.ts +314 -0
  294. package/dist/runtime/src/storage/forum-db.ts +4 -0
  295. package/dist/runtime/src/storage/remote-session.ts +1028 -0
  296. package/dist/runtime/src/storage/runtime-events.ts +209 -0
  297. package/dist/runtime/src/storage/runtime-gateway-submissions.ts +132 -0
  298. package/dist/runtime/src/storage/runtime-leases.ts +190 -0
  299. package/dist/runtime/src/storage/runtime-process-leases.ts +288 -0
  300. package/dist/runtime/src/storage/runtime-topic-state.ts +181 -0
  301. package/dist/runtime/src/storage/runtime-turn-requests.ts +805 -0
  302. package/dist/runtime/src/storage/self-schedules.ts +306 -0
  303. package/dist/runtime/src/storage/session-asks.ts +468 -0
  304. package/dist/runtime/src/storage/session-inbox-signal.ts +76 -0
  305. package/dist/runtime/src/storage/session-inbox.ts +161 -0
  306. package/dist/runtime/src/storage/sqlite.ts +154 -0
  307. package/dist/runtime/src/storage/storage-contract.ts +54 -0
  308. package/dist/runtime/src/storage/storage-host.ts +336 -0
  309. package/dist/runtime/src/storage/storage-public-host.ts +16 -0
  310. package/dist/runtime/src/storage/storage-public.ts +66 -0
  311. package/dist/runtime/src/storage/tasks.ts +172 -0
  312. package/dist/runtime/src/storage/token-stats.ts +432 -0
  313. package/dist/runtime/src/storage/topic-archive-state.ts +226 -0
  314. package/dist/runtime/src/storage/topic-archive.ts +169 -0
  315. package/dist/runtime/src/storage/topic-host-mcp-grants.ts +54 -0
  316. package/dist/runtime/src/storage/topic-link-records.ts +1085 -0
  317. package/dist/runtime/src/storage/topic-settings.ts +67 -0
  318. package/dist/runtime/src/storage/topic-tool-capabilities.ts +89 -0
  319. package/dist/runtime/src/storage/topic-transcript.ts +98 -0
  320. package/dist/runtime/src/storage/vault-crypto-core.ts +65 -0
  321. package/dist/runtime/src/storage/vault-crypto.ts +31 -0
  322. package/dist/runtime/src/storage/vault-public.ts +27 -0
  323. package/dist/runtime/src/storage/vault-request-gates.ts +359 -0
  324. package/dist/runtime/src/storage/vault.ts +388 -0
  325. package/dist/runtime/src/storage/wiki-summary-names.ts +52 -0
  326. package/dist/runtime/src/storage/wiki.ts +90 -0
  327. package/dist/runtime/src/topics/claim-abort.ts +190 -0
  328. package/dist/runtime/src/topics/create.ts +192 -0
  329. package/dist/runtime/src/topics/derive.ts +600 -0
  330. package/dist/runtime/src/topics/lifecycle.ts +425 -0
  331. package/dist/runtime/src/topics/links.ts +7 -0
  332. package/dist/runtime/src/topics/personal-general.ts +91 -0
  333. package/dist/runtime/src/topics/session.ts +1041 -0
  334. package/dist/runtime/src/topics/update.ts +287 -0
  335. package/dist/runtime/src/types/api.ts +582 -0
  336. package/dist/runtime/src/types.ts +395 -0
  337. package/dist/runtime/src/version.ts +1 -0
  338. package/dist/runtime/tsconfig.json +13 -0
  339. package/dist/runtime-gateway.js +453 -0
  340. package/dist/runtime-gateway.js.map +10 -0
  341. package/dist/runtime-helpers.js +1794 -0
  342. package/dist/runtime-helpers.js.map +40 -0
  343. package/dist/sqlite.js +68 -0
  344. package/dist/sqlite.js.map +10 -0
  345. package/dist/storage.js +5194 -0
  346. package/dist/storage.js.map +47 -0
  347. package/dist/types/apps/negotium/src/mcp-servers.d.ts +20 -0
  348. package/dist/types/packages/core/src/agents/api-topic-agent-switch.d.ts +38 -0
  349. package/dist/types/packages/core/src/agents/archiver.d.ts +87 -0
  350. package/dist/types/packages/core/src/agents/auth-check.d.ts +19 -0
  351. package/dist/types/packages/core/src/agents/claude-notices.d.ts +15 -0
  352. package/dist/types/packages/core/src/agents/claude-provider.d.ts +25 -0
  353. package/dist/types/packages/core/src/agents/claude-registry.d.ts +3 -0
  354. package/dist/types/packages/core/src/agents/claude-runtime-inspection.d.ts +9 -0
  355. package/dist/types/packages/core/src/agents/codex-app-server.d.ts +13 -0
  356. package/dist/types/packages/core/src/agents/codex-native-multi-agent.d.ts +20 -0
  357. package/dist/types/packages/core/src/agents/codex-provider.d.ts +64 -0
  358. package/dist/types/packages/core/src/agents/codex-registry.d.ts +3 -0
  359. package/dist/types/packages/core/src/agents/codex-tier-resolver.d.ts +10 -0
  360. package/dist/types/packages/core/src/agents/codex-tree-kill.d.ts +13 -0
  361. package/dist/types/packages/core/src/agents/codex-tree-manager.d.ts +28 -0
  362. package/dist/types/packages/core/src/agents/codex-vault-hook-bridge.d.ts +28 -0
  363. package/dist/types/packages/core/src/agents/codex-windows-wrapper.d.ts +30 -0
  364. package/dist/types/packages/core/src/agents/compaction-support.d.ts +5 -0
  365. package/dist/types/packages/core/src/agents/compaction-tool-projection.d.ts +9 -0
  366. package/dist/types/packages/core/src/agents/contracts.d.ts +68 -0
  367. package/dist/types/packages/core/src/agents/deep-map.d.ts +2 -0
  368. package/dist/types/packages/core/src/agents/execution-host.d.ts +33 -0
  369. package/dist/types/packages/core/src/agents/explicit-agent-switch.d.ts +26 -0
  370. package/dist/types/packages/core/src/agents/fork.d.ts +50 -0
  371. package/dist/types/packages/core/src/agents/hosted-agent.d.ts +15 -0
  372. package/dist/types/packages/core/src/agents/idle-archiver.d.ts +35 -0
  373. package/dist/types/packages/core/src/agents/idle-compact.d.ts +37 -0
  374. package/dist/types/packages/core/src/agents/index.d.ts +8 -0
  375. package/dist/types/packages/core/src/agents/maestro-provider.d.ts +75 -0
  376. package/dist/types/packages/core/src/agents/maestro-registry.d.ts +3 -0
  377. package/dist/types/packages/core/src/agents/mcp-tools/ask-user.d.ts +147 -0
  378. package/dist/types/packages/core/src/agents/mcp-tools/common.d.ts +14 -0
  379. package/dist/types/packages/core/src/agents/mcp-tools/inline-assets.d.ts +24 -0
  380. package/dist/types/packages/core/src/agents/mcp-tools/publish-html.d.ts +18 -0
  381. package/dist/types/packages/core/src/agents/mcp-tools/request-vault.d.ts +124 -0
  382. package/dist/types/packages/core/src/agents/mcp-tools/self-config.d.ts +45 -0
  383. package/dist/types/packages/core/src/agents/mcp-tools/spawn-subagent.d.ts +148 -0
  384. package/dist/types/packages/core/src/agents/mcp-tools/visual-compat.d.ts +55 -0
  385. package/dist/types/packages/core/src/agents/mcp-tools/visuals.d.ts +70 -0
  386. package/dist/types/packages/core/src/agents/memory-archive-policy.d.ts +24 -0
  387. package/dist/types/packages/core/src/agents/model-catalog.d.ts +132 -0
  388. package/dist/types/packages/core/src/agents/public-helpers.d.ts +17 -0
  389. package/dist/types/packages/core/src/agents/registry.d.ts +5 -0
  390. package/dist/types/packages/core/src/agents/rollout/claude.d.ts +77 -0
  391. package/dist/types/packages/core/src/agents/rollout/codex.d.ts +119 -0
  392. package/dist/types/packages/core/src/agents/rollout/index.d.ts +6 -0
  393. package/dist/types/packages/core/src/agents/rollout/shared.d.ts +56 -0
  394. package/dist/types/packages/core/src/agents/self-config-core.d.ts +199 -0
  395. package/dist/types/packages/core/src/agents/task-events.d.ts +19 -0
  396. package/dist/types/packages/core/src/agents/tool-format.d.ts +25 -0
  397. package/dist/types/packages/core/src/agents/topic-cleanup.d.ts +83 -0
  398. package/dist/types/packages/core/src/agents/vault-tool-policy.d.ts +2 -0
  399. package/dist/types/packages/core/src/bus.d.ts +138 -0
  400. package/dist/types/packages/core/src/identifiers.d.ts +27 -0
  401. package/dist/types/packages/core/src/mcp/canonical-bridge-config.d.ts +21 -0
  402. package/dist/types/packages/core/src/mcp/factories/agent-health.d.ts +5 -0
  403. package/dist/types/packages/core/src/mcp/factories/compaction-log.d.ts +8 -0
  404. package/dist/types/packages/core/src/mcp/factories/decision.d.ts +18 -0
  405. package/dist/types/packages/core/src/mcp/factories/index.d.ts +13 -0
  406. package/dist/types/packages/core/src/mcp/factories/session-comm.d.ts +38 -0
  407. package/dist/types/packages/core/src/mcp/factories/session-history.d.ts +11 -0
  408. package/dist/types/packages/core/src/mcp/factories/stdio-protection.d.ts +10 -0
  409. package/dist/types/packages/core/src/mcp/factories/system-health.d.ts +37 -0
  410. package/dist/types/packages/core/src/mcp/factories/task.d.ts +13 -0
  411. package/dist/types/packages/core/src/mcp/factories/token-stats.d.ts +20 -0
  412. package/dist/types/packages/core/src/mcp/factories/vault.d.ts +9 -0
  413. package/dist/types/packages/core/src/mcp/mcp-helpers.d.ts +26 -0
  414. package/dist/types/packages/core/src/mcp/peer-bridge.d.ts +92 -0
  415. package/dist/types/packages/core/src/mcp/runtime-spec.d.ts +147 -0
  416. package/dist/types/packages/core/src/mcp/session-comm/actor-policy.d.ts +120 -0
  417. package/dist/types/packages/core/src/mcp/session-comm/bridge-ipc-config.d.ts +6 -0
  418. package/dist/types/packages/core/src/mcp/session-comm/context.d.ts +44 -0
  419. package/dist/types/packages/core/src/mcp/session-comm/history-tools.d.ts +31 -0
  420. package/dist/types/packages/core/src/mcp/session-comm/hub-remote-session.d.ts +149 -0
  421. package/dist/types/packages/core/src/mcp/session-comm/limits.d.ts +8 -0
  422. package/dist/types/packages/core/src/mcp/session-comm/peer-forward.d.ts +85 -0
  423. package/dist/types/packages/core/src/mcp/session-comm/tell-permissions.d.ts +29 -0
  424. package/dist/types/packages/core/src/mcp/session-comm/topic-catalog.d.ts +59 -0
  425. package/dist/types/packages/core/src/mcp/session-history-limits.d.ts +20 -0
  426. package/dist/types/packages/core/src/mcp/session-history-reader.d.ts +35 -0
  427. package/dist/types/packages/core/src/mcp/wiki-search-index.d.ts +59 -0
  428. package/dist/types/packages/core/src/mcp/wiki-server.d.ts +53 -0
  429. package/dist/types/packages/core/src/media/file-events.d.ts +14 -0
  430. package/dist/types/packages/core/src/media/text-extractor.d.ts +34 -0
  431. package/dist/types/packages/core/src/outbox/coalescing-runner.d.ts +68 -0
  432. package/dist/types/packages/core/src/outbox/file-ops.d.ts +79 -0
  433. package/dist/types/packages/core/src/outbox/index.d.ts +3 -0
  434. package/dist/types/packages/core/src/outbox/utils.d.ts +16 -0
  435. package/dist/types/packages/core/src/platform/background-bash/context.d.ts +1 -0
  436. package/dist/types/packages/core/src/platform/background-bash/manager.d.ts +34 -0
  437. package/dist/types/packages/core/src/platform/config-helpers.d.ts +20 -0
  438. package/dist/types/packages/core/src/platform/config.d.ts +178 -0
  439. package/dist/types/packages/core/src/platform/constants.d.ts +20 -0
  440. package/dist/types/packages/core/src/platform/delay.d.ts +1 -0
  441. package/dist/types/packages/core/src/platform/error.d.ts +6 -0
  442. package/dist/types/packages/core/src/platform/file-utils.d.ts +16 -0
  443. package/dist/types/packages/core/src/platform/ipc.d.ts +32 -0
  444. package/dist/types/packages/core/src/platform/jsonl.d.ts +46 -0
  445. package/dist/types/packages/core/src/platform/lifecycle.d.ts +40 -0
  446. package/dist/types/packages/core/src/platform/logger.d.ts +20 -0
  447. package/dist/types/packages/core/src/platform/maestro-bootstrap-env.d.ts +0 -0
  448. package/dist/types/packages/core/src/platform/mcp-catalog-policy.d.ts +73 -0
  449. package/dist/types/packages/core/src/platform/mcp-config.d.ts +286 -0
  450. package/dist/types/packages/core/src/platform/memoize-import.d.ts +15 -0
  451. package/dist/types/packages/core/src/platform/paths.d.ts +18 -0
  452. package/dist/types/packages/core/src/platform/playwright/browser-processes.d.ts +60 -0
  453. package/dist/types/packages/core/src/platform/playwright/capability.d.ts +1 -0
  454. package/dist/types/packages/core/src/platform/playwright/headed-launch.d.ts +13 -0
  455. package/dist/types/packages/core/src/platform/playwright/manager-utils.d.ts +34 -0
  456. package/dist/types/packages/core/src/platform/playwright/manager.d.ts +194 -0
  457. package/dist/types/packages/core/src/platform/playwright/mcp-transport.d.ts +4 -0
  458. package/dist/types/packages/core/src/platform/playwright/profile-management.d.ts +8 -0
  459. package/dist/types/packages/core/src/platform/playwright/public-runtime.d.ts +6 -0
  460. package/dist/types/packages/core/src/platform/playwright/transport-probe.d.ts +13 -0
  461. package/dist/types/packages/core/src/platform/playwright/vault-broker.d.ts +6 -0
  462. package/dist/types/packages/core/src/platform/public-runtime.d.ts +3 -0
  463. package/dist/types/packages/core/src/prompts/builders.d.ts +78 -0
  464. package/dist/types/packages/core/src/query/active-rooms.d.ts +234 -0
  465. package/dist/types/packages/core/src/query/public-runtime.d.ts +4 -0
  466. package/dist/types/packages/core/src/query/room-query-registry.d.ts +71 -0
  467. package/dist/types/packages/core/src/query/session-inbox-cleanup.d.ts +5 -0
  468. package/dist/types/packages/core/src/query/session-inbox-path.d.ts +8 -0
  469. package/dist/types/packages/core/src/query/state.d.ts +25 -0
  470. package/dist/types/packages/core/src/query/types.d.ts +6 -0
  471. package/dist/types/packages/core/src/runtime/actor-topic-reach.d.ts +63 -0
  472. package/dist/types/packages/core/src/runtime/actor-topic-scope.d.ts +127 -0
  473. package/dist/types/packages/core/src/runtime/ask-callbacks.d.ts +53 -0
  474. package/dist/types/packages/core/src/runtime/attachments.d.ts +36 -0
  475. package/dist/types/packages/core/src/runtime/background-session-policy.d.ts +1 -0
  476. package/dist/types/packages/core/src/runtime/background-sessions.d.ts +27 -0
  477. package/dist/types/packages/core/src/runtime/bashrs-completions.d.ts +50 -0
  478. package/dist/types/packages/core/src/runtime/channel-context.d.ts +13 -0
  479. package/dist/types/packages/core/src/runtime/context-warning.d.ts +46 -0
  480. package/dist/types/packages/core/src/runtime/cron-sessions.d.ts +9 -0
  481. package/dist/types/packages/core/src/runtime/errors.d.ts +6 -0
  482. package/dist/types/packages/core/src/runtime/event-heartbeat.d.ts +17 -0
  483. package/dist/types/packages/core/src/runtime/file-hooks.d.ts +38 -0
  484. package/dist/types/packages/core/src/runtime/playwright-turn-abort.d.ts +12 -0
  485. package/dist/types/packages/core/src/runtime/public-helpers.d.ts +17 -0
  486. package/dist/types/packages/core/src/runtime/remote-session-grant.d.ts +91 -0
  487. package/dist/types/packages/core/src/runtime/remote-session-inbox.d.ts +206 -0
  488. package/dist/types/packages/core/src/runtime/remote-session-reply-outbox.d.ts +37 -0
  489. package/dist/types/packages/core/src/runtime/task-format.d.ts +4 -0
  490. package/dist/types/packages/core/src/runtime/tasks.d.ts +3 -0
  491. package/dist/types/packages/core/src/runtime/thread-context.d.ts +62 -0
  492. package/dist/types/packages/core/src/runtime/topic-config.d.ts +24 -0
  493. package/dist/types/packages/core/src/runtime/turn-event-stream.d.ts +47 -0
  494. package/dist/types/packages/core/src/runtime/turn-runner.d.ts +284 -0
  495. package/dist/types/packages/core/src/runtime/turn-session.d.ts +49 -0
  496. package/dist/types/packages/core/src/runtime/usage-alert.d.ts +11 -0
  497. package/dist/types/packages/core/src/runtime/user-turn-envelope.d.ts +37 -0
  498. package/dist/types/packages/core/src/runtime/visual-html.d.ts +13 -0
  499. package/dist/types/packages/core/src/runtime/visual-store.d.ts +71 -0
  500. package/dist/types/packages/core/src/runtime/visuals.d.ts +33 -0
  501. package/dist/types/packages/core/src/runtime-gateway.d.ts +224 -0
  502. package/dist/types/packages/core/src/security/sanitize.d.ts +16 -0
  503. package/dist/types/packages/core/src/security/sensitive-path.d.ts +1 -0
  504. package/dist/types/packages/core/src/storage/activity-log.d.ts +25 -0
  505. package/dist/types/packages/core/src/storage/api-messages.d.ts +156 -0
  506. package/dist/types/packages/core/src/storage/api-topic-brief.d.ts +39 -0
  507. package/dist/types/packages/core/src/storage/api-topic-config.d.ts +23 -0
  508. package/dist/types/packages/core/src/storage/api-topics.d.ts +274 -0
  509. package/dist/types/packages/core/src/storage/app-settings.d.ts +4 -0
  510. package/dist/types/packages/core/src/storage/ask-user-gates.d.ts +65 -0
  511. package/dist/types/packages/core/src/storage/browser-profiles.d.ts +31 -0
  512. package/dist/types/packages/core/src/storage/conversations.d.ts +149 -0
  513. package/dist/types/packages/core/src/storage/decisions.d.ts +45 -0
  514. package/dist/types/packages/core/src/storage/forum/agent-settings.d.ts +3 -0
  515. package/dist/types/packages/core/src/storage/forum/index.d.ts +4 -0
  516. package/dist/types/packages/core/src/storage/forum/repository.d.ts +42 -0
  517. package/dist/types/packages/core/src/storage/forum/schema.d.ts +38 -0
  518. package/dist/types/packages/core/src/storage/forum-db.d.ts +2 -0
  519. package/dist/types/packages/core/src/storage/remote-session.d.ts +318 -0
  520. package/dist/types/packages/core/src/storage/runtime-events.d.ts +33 -0
  521. package/dist/types/packages/core/src/storage/runtime-leases.d.ts +27 -0
  522. package/dist/types/packages/core/src/storage/runtime-process-leases.d.ts +47 -0
  523. package/dist/types/packages/core/src/storage/runtime-topic-state.d.ts +39 -0
  524. package/dist/types/packages/core/src/storage/runtime-turn-requests.d.ts +138 -0
  525. package/dist/types/packages/core/src/storage/self-schedules.d.ts +54 -0
  526. package/dist/types/packages/core/src/storage/session-asks.d.ts +78 -0
  527. package/dist/types/packages/core/src/storage/session-inbox-signal.d.ts +35 -0
  528. package/dist/types/packages/core/src/storage/session-inbox.d.ts +36 -0
  529. package/dist/types/packages/core/src/storage/sqlite.d.ts +20 -0
  530. package/dist/types/packages/core/src/storage/storage-contract.d.ts +46 -0
  531. package/dist/types/packages/core/src/storage/storage-host.d.ts +41 -0
  532. package/dist/types/packages/core/src/storage/storage-public-host.d.ts +7 -0
  533. package/dist/types/packages/core/src/storage/storage-public.d.ts +45 -0
  534. package/dist/types/packages/core/src/storage/tasks.d.ts +49 -0
  535. package/dist/types/packages/core/src/storage/token-stats.d.ts +69 -0
  536. package/dist/types/packages/core/src/storage/topic-archive-state.d.ts +33 -0
  537. package/dist/types/packages/core/src/storage/topic-archive.d.ts +42 -0
  538. package/dist/types/packages/core/src/storage/topic-host-mcp-grants.d.ts +5 -0
  539. package/dist/types/packages/core/src/storage/topic-link-records.d.ts +281 -0
  540. package/dist/types/packages/core/src/storage/topic-settings.d.ts +19 -0
  541. package/dist/types/packages/core/src/storage/topic-tool-capabilities.d.ts +37 -0
  542. package/dist/types/packages/core/src/storage/topic-transcript.d.ts +38 -0
  543. package/dist/types/packages/core/src/storage/vault-crypto-core.d.ts +6 -0
  544. package/dist/types/packages/core/src/storage/vault-crypto.d.ts +12 -0
  545. package/dist/types/packages/core/src/storage/vault-public.d.ts +3 -0
  546. package/dist/types/packages/core/src/storage/vault-request-gates.d.ts +69 -0
  547. package/dist/types/packages/core/src/storage/vault.d.ts +49 -0
  548. package/dist/types/packages/core/src/storage/wiki-summary-names.d.ts +13 -0
  549. package/dist/types/packages/core/src/storage/wiki.d.ts +15 -0
  550. package/dist/types/packages/core/src/topics/derive.d.ts +83 -0
  551. package/dist/types/packages/core/src/topics/lifecycle.d.ts +75 -0
  552. package/dist/types/packages/core/src/topics/links.d.ts +2 -0
  553. package/dist/types/packages/core/src/topics/personal-general.d.ts +15 -0
  554. package/dist/types/packages/core/src/topics/session.d.ts +70 -0
  555. package/dist/types/packages/core/src/types/api.d.ts +546 -0
  556. package/dist/types/packages/core/src/types.d.ts +384 -0
  557. package/dist/types/packages/core/src/version.d.ts +1 -0
  558. package/dist/types/packages/module-cron/src/background-sessions.d.ts +2 -0
  559. package/dist/types/packages/module-cron/src/context.d.ts +15 -0
  560. package/dist/types/packages/module-cron/src/host.d.ts +23 -0
  561. package/dist/types/packages/module-cron/src/index.d.ts +14 -0
  562. package/dist/types/packages/module-cron/src/module.d.ts +13 -0
  563. package/dist/types/packages/module-cron/src/schedule.d.ts +23 -0
  564. package/dist/types/packages/module-cron/src/scheduler.d.ts +46 -0
  565. package/dist/types/packages/module-cron/src/scripts.d.ts +29 -0
  566. package/dist/types/packages/module-cron/src/store.d.ts +152 -0
  567. package/dist/types/packages/module-cron/src/summarize.d.ts +4 -0
  568. package/dist/vault.js +850 -0
  569. package/dist/vault.js.map +18 -0
  570. package/install-bash-rs.mjs +90 -0
  571. package/install-browser-rs.mjs +83 -0
  572. package/package.json +171 -4
@@ -0,0 +1,1349 @@
1
+ // spawn_subagent runtime MCP tool — agent-initiated delegation to a child
2
+ // agent room (clawgram parity). The tool returns immediately (fire-and-forget):
3
+ // the child topic runs its own fresh session, a live card message in the parent
4
+ // room tracks its lifecycle, and the child's final response is injected back
5
+ // into the parent as an AI turn on completion.
6
+ //
7
+ // Watches are in-memory (same accepted tradeoff as the ask-callback registry in
8
+ // routes/sessions.ts); `sweepStaleSubagentCards` marks orphans failed on boot.
9
+
10
+ import { z } from "zod";
11
+ import { errorResult, type SharedMcpTool, textResult } from "#agents/mcp-tools/common";
12
+ import { WsHub } from "#bus";
13
+ import { logger } from "#platform/logger";
14
+ import { hasActiveQuery } from "#query/state";
15
+ import { actorOwnedTopicIds, actorReachableTopicIds } from "#runtime/actor-topic-reach";
16
+ import {
17
+ appendApiMessage,
18
+ getApiMessage,
19
+ listApiMessagesByKind,
20
+ updateApiMessageSubagentCard,
21
+ } from "#storage/api-messages";
22
+ import {
23
+ getTopic,
24
+ getTopicMemoryOrigin,
25
+ grantSubagentTellTarget,
26
+ listSubagentTellTargetIds,
27
+ listTopics,
28
+ revokeSubagentTellTarget,
29
+ upsertTopic,
30
+ } from "#storage/api-topics";
31
+ import { getRuntimeTurnLease, RUNTIME_INSTANCE_ID } from "#storage/runtime-leases";
32
+ import { getRuntimeUserTurnRequest } from "#storage/runtime-turn-requests";
33
+ import { wikiBriefStorageKey, wikiSummarySlug } from "#storage/wiki-summary-names";
34
+ import { type ActorTopicScope, type AgentKind, isAgentKind } from "#types";
35
+ import type { MessageDto, SubagentCardDto, SubagentReportMode, TopicDto } from "#types/api";
36
+
37
+ const MAX_TASK_CHARS = 8000;
38
+ const MAX_NAME_CHARS = 80;
39
+ const MAX_LIVE_CHILDREN_PER_PARENT = 5;
40
+ const MAX_PREPARED_CHILDREN_PER_PARENT = 10;
41
+ export const MAX_SUBAGENT_DEPTH = 2;
42
+ const RESULT_SUMMARY_CHARS = 300;
43
+
44
+ export interface SubagentLifecycleLimits {
45
+ readonly maxDepth: number;
46
+ readonly maxLiveChildrenPerParent: number;
47
+ readonly maxPreparedChildrenPerParent: number;
48
+ }
49
+
50
+ export interface SpawnSubagentToolContext {
51
+ userId: string;
52
+ topicId: string;
53
+ queryId?: string;
54
+ agent: AgentKind;
55
+ model?: string;
56
+ /** Surface of the room the turn runs in; the actor rules apply on `otium`. */
57
+ surface?: string;
58
+ /**
59
+ * Hub-asserted rooms the person who sent the message may see and owns. On
60
+ * `otium` a human turn carries one and it is authoritative: the management
61
+ * tools list only the asserted-visible workers and act only on the
62
+ * asserted-owned ones. Absent on turns no person started (the spawn, the
63
+ * report back, the follow-up), which keep the room's own lineage.
64
+ */
65
+ actorTopicScope?: ActorTopicScope;
66
+ }
67
+
68
+ export type SubagentToolContext = Pick<
69
+ SpawnSubagentToolContext,
70
+ "userId" | "topicId" | "surface" | "actorTopicScope"
71
+ >;
72
+
73
+ export interface SubagentToolDefinitionOptions {
74
+ /** Otium owns provider routing, so its public tools inherit execution and omit overrides. */
75
+ executionOverrides?: boolean;
76
+ }
77
+
78
+ export interface SubagentWatch {
79
+ parentTopicId: string;
80
+ childTopicId: string;
81
+ cardMessageId: string;
82
+ name: string;
83
+ userId: string;
84
+ startedAt: string;
85
+ reportMode: SubagentReportMode;
86
+ queryId?: string;
87
+ running: boolean;
88
+ }
89
+
90
+ export interface SubagentLifecycleHost<
91
+ TContext extends SpawnSubagentToolContext = SpawnSubagentToolContext,
92
+ > {
93
+ storage: {
94
+ getTopic(topicId: string): TopicDto | null | undefined;
95
+ listTopics(): TopicDto[];
96
+ getTopicMemoryOrigin(topicId: string): TopicDto | null;
97
+ upsertTopic(topic: TopicDto): void;
98
+ getMessage(topicId: string, messageId: string): MessageDto | null | undefined;
99
+ listSubagentMessages(): MessageDto[];
100
+ appendMessage(message: MessageDto, options?: { notify?: boolean }): void;
101
+ updateSubagentCard(
102
+ topicId: string,
103
+ messageId: string,
104
+ card: SubagentCardDto,
105
+ editedAt: string,
106
+ ): MessageDto | null;
107
+ publishMessage(topicId: string, message: MessageDto): void;
108
+ publishCardUpdate(
109
+ topicId: string,
110
+ messageId: string,
111
+ update: { subagentCard: SubagentCardDto; editedAt: string },
112
+ ): void;
113
+ };
114
+ topic: {
115
+ createDerived(input: {
116
+ context: TContext;
117
+ parentTopicId: string;
118
+ userId: string;
119
+ name?: string;
120
+ agent?: AgentKind;
121
+ model?: string;
122
+ memoryTopicId?: string;
123
+ }): Promise<
124
+ | { ok: true; topic: TopicDto | null }
125
+ | { ok: false; reason: "busy" | "title-conflict"; message?: string }
126
+ >;
127
+ delete(topic: TopicDto, userId: string): Promise<void>;
128
+ };
129
+ task: {
130
+ dispatch(input: {
131
+ child: TopicDto;
132
+ parent: TopicDto;
133
+ userId: string;
134
+ prompt: string;
135
+ requestId: string;
136
+ onDispatched(queryId: string): void;
137
+ }): Promise<{ accepted: boolean; error?: string }>;
138
+ };
139
+ sessionCommunication: {
140
+ notifyParent(input: {
141
+ watch: SubagentWatch;
142
+ prompt: string;
143
+ requestId: string;
144
+ }): Promise<boolean>;
145
+ listTellTargetIds(sourceTopicId: string): string[];
146
+ grantTellTarget(sourceTopicId: string, targetTopicId: string, grantedByTopicId: string): void;
147
+ revokeTellTarget(sourceTopicId: string, targetTopicId: string): boolean;
148
+ };
149
+ runtime: {
150
+ ownerId: string;
151
+ now(): string;
152
+ ownerIsAlive(ownerId: string): boolean;
153
+ childExecutionQueryId(childTopicId: string): string | null;
154
+ childExecutionIsRecoverable(childTopicId: string): boolean;
155
+ };
156
+ config: {
157
+ limits?: Partial<SubagentLifecycleLimits>;
158
+ resolveAgentModel(input: {
159
+ context: TContext;
160
+ agent: AgentKind;
161
+ model?: string;
162
+ hasOverride: boolean;
163
+ }): Promise<{ model?: string; error?: string }>;
164
+ memoryFilenames(topic: TopicDto): string[];
165
+ };
166
+ }
167
+
168
+ export interface SubagentLifecycle<
169
+ TContext extends SpawnSubagentToolContext = SpawnSubagentToolContext,
170
+ > {
171
+ computeSubagentDepth(topicId: string): number;
172
+ canSpawnSubagentsFromTopic(topicId: string): boolean;
173
+ takeSubagentWatch(queryId: string): SubagentWatch | null;
174
+ cancelSubagentWatchForDeletedTopic(childTopicId: string): void;
175
+ settleSubagentSuccess(watch: SubagentWatch, finalText: string): Promise<void>;
176
+ settleSubagentFailure(queryId: string, reason: string): Promise<void>;
177
+ sweepStaleSubagentCards(): void;
178
+ subagentReportMode(childTopicId: string): SubagentReportMode;
179
+ createSubagentManagementToolDefinitions(ctx: SubagentToolContext): SharedMcpTool[];
180
+ createSpawnSubagentToolDefinition(
181
+ ctx: TContext,
182
+ options?: SubagentToolDefinitionOptions,
183
+ ): SharedMcpTool;
184
+ createPrepareSubagentToolDefinition(
185
+ ctx: TContext,
186
+ options?: SubagentToolDefinitionOptions,
187
+ ): SharedMcpTool;
188
+ }
189
+
190
+ function activeQueryUserId(topic: TopicDto | null | undefined): string | undefined {
191
+ return topic?.participants.find((participant) => hasActiveQuery(participant.userId, topic.id))
192
+ ?.userId;
193
+ }
194
+
195
+ function persistedWatchUserId(topic: TopicDto | null | undefined): string | undefined {
196
+ return (
197
+ activeQueryUserId(topic) ??
198
+ topic?.participants.find((participant) => participant.role === "owner")?.userId ??
199
+ topic?.participants[0]?.userId
200
+ );
201
+ }
202
+
203
+ export function createSubagentLifecycle<TContext extends SpawnSubagentToolContext>(
204
+ host: SubagentLifecycleHost<TContext>,
205
+ ): SubagentLifecycle<TContext> {
206
+ const runtimeOwnerId = host.runtime.ownerId;
207
+ const limits = Object.freeze({
208
+ maxDepth: host.config.limits?.maxDepth ?? MAX_SUBAGENT_DEPTH,
209
+ maxLiveChildrenPerParent:
210
+ host.config.limits?.maxLiveChildrenPerParent ?? MAX_LIVE_CHILDREN_PER_PARENT,
211
+ maxPreparedChildrenPerParent:
212
+ host.config.limits?.maxPreparedChildrenPerParent ?? MAX_PREPARED_CHILDREN_PER_PARENT,
213
+ });
214
+ for (const [name, value] of Object.entries(limits)) {
215
+ if (!Number.isInteger(value) || value < 1) {
216
+ throw new Error(`subagent lifecycle ${name} must be a positive integer`);
217
+ }
218
+ }
219
+ const watchesByChild = new Map<string, SubagentWatch>();
220
+ const childByQueryId = new Map<string, string>();
221
+
222
+ function resolveMemoryTopicSelection(
223
+ rawSelection: unknown,
224
+ userId: string,
225
+ ): { topicId?: string; error?: string } {
226
+ if (rawSelection === undefined || rawSelection === null) return {};
227
+ if (typeof rawSelection !== "string" || !rawSelection.trim()) {
228
+ return { error: "Error: memory_topic must be a topic id, title, or topic/*.md path." };
229
+ }
230
+
231
+ const selection = rawSelection.trim();
232
+ if (
233
+ selection.includes("\\") ||
234
+ selection.startsWith("/") ||
235
+ selection.split("/").some((part) => part === "..") ||
236
+ (selection.includes("/") && !selection.startsWith("topic/"))
237
+ ) {
238
+ return { error: "Error: memory_topic must name a file under topic/." };
239
+ }
240
+ const key = selection.startsWith("topic/") ? selection.slice("topic/".length) : selection;
241
+ if (!key || key.includes("/")) {
242
+ return { error: "Error: memory_topic must name one topic/*.md file." };
243
+ }
244
+
245
+ const accessible = host.storage
246
+ .listTopics()
247
+ .filter((topic) => topic.participants.some((participant) => participant.userId === userId));
248
+ const exactId = accessible.find((topic) => topic.id === key);
249
+ const matches = exactId
250
+ ? [exactId]
251
+ : accessible.filter((topic) => {
252
+ const [canonicalFilename, legacyFilename] = host.config.memoryFilenames(topic);
253
+ return (
254
+ key.toLowerCase() === topic.title.toLowerCase() ||
255
+ key === canonicalFilename ||
256
+ key === legacyFilename
257
+ );
258
+ });
259
+ if (matches.length === 0) {
260
+ return { error: `Error: memory topic '${selection}' was not found or is not accessible.` };
261
+ }
262
+ const canonicalNamespaces = new Set(
263
+ matches.map((topic) => host.config.memoryFilenames(topic)[0]),
264
+ );
265
+ if (canonicalNamespaces.size > 1) {
266
+ return {
267
+ error: `Error: memory topic '${selection}' is ambiguous; use its topic id or canonical topic/*.md filename.`,
268
+ };
269
+ }
270
+ const origin = host.storage.getTopicMemoryOrigin(matches[0]!.id) ?? matches[0]!;
271
+ // The matched topic is accessible, but its memory chain may resolve to a
272
+ // root origin the user does not participate in; fail closed like
273
+ // listMemoryTopicNames instead of granting memory access transitively.
274
+ if (!origin.participants.some((participant) => participant.userId === userId)) {
275
+ return { error: `Error: memory topic '${selection}' was not found or is not accessible.` };
276
+ }
277
+ return { topicId: origin.id };
278
+ }
279
+
280
+ function countLiveChildren(parentTopicId: string): number {
281
+ let n = 0;
282
+ for (const watch of watchesByChild.values()) {
283
+ if (watch.parentTopicId === parentTopicId) n += 1;
284
+ }
285
+ return n;
286
+ }
287
+
288
+ /**
289
+ * Walk the parent chain and count how many subagent ancestors this topic has.
290
+ * Runs on every turn/MCP build, so it walks per-parent lookups (depth-capped)
291
+ * instead of scanning the whole topic table.
292
+ */
293
+ function computeSubagentDepth(topicId: string): number {
294
+ let depth = 0;
295
+ let current = host.storage.getTopic(topicId);
296
+ const visited = new Set<string>();
297
+ while (current) {
298
+ if (visited.has(current.id)) return limits.maxDepth;
299
+ visited.add(current.id);
300
+ if (current.isSubagent) depth += 1;
301
+ if (!current.parentTopicId || current.parentTopicId === current.id) break;
302
+ current = host.storage.getTopic(current.parentTopicId);
303
+ }
304
+ return depth;
305
+ }
306
+
307
+ function canSpawnSubagentsFromTopic(topicId: string): boolean {
308
+ const topic = host.storage.getTopic(topicId);
309
+ return topic?.kind === "agent" && computeSubagentDepth(topicId) < limits.maxDepth;
310
+ }
311
+
312
+ /** Read-merge-write the parent card and broadcast the patch. */
313
+ function patchSubagentCard(
314
+ parentTopicId: string,
315
+ cardMessageId: string,
316
+ patch: Partial<SubagentCardDto>,
317
+ ): void {
318
+ const current = host.storage.getMessage(parentTopicId, cardMessageId)?.subagentCard;
319
+ if (!current) return;
320
+ const next: SubagentCardDto = { ...current, ...patch };
321
+ const editedAt = host.runtime.now();
322
+ if (!host.storage.updateSubagentCard(parentTopicId, cardMessageId, next, editedAt)) return;
323
+ host.storage.publishCardUpdate(parentTopicId, cardMessageId, {
324
+ subagentCard: next,
325
+ editedAt,
326
+ });
327
+ }
328
+
329
+ function registerWatchDispatch(watch: SubagentWatch, queryId: string): void {
330
+ // Re-dispatch (defer drain, session-expired retry, supersede-requeue) hands
331
+ // the same child a new queryId — drop the stale mapping first.
332
+ if (watch.queryId) childByQueryId.delete(watch.queryId);
333
+ watch.queryId = queryId;
334
+ watchesByChild.set(watch.childTopicId, watch);
335
+ childByQueryId.set(queryId, watch.childTopicId);
336
+ if (!watch.running) {
337
+ watch.running = true;
338
+ patchSubagentCard(watch.parentTopicId, watch.cardMessageId, { status: "running" });
339
+ }
340
+ }
341
+
342
+ /** Claim the watch for a finished child turn (delete-on-take). */
343
+ function takeSubagentWatch(queryId: string): SubagentWatch | null {
344
+ const childTopicId = childByQueryId.get(queryId);
345
+ if (!childTopicId) return recoverPersistedSubagentWatch(queryId);
346
+ childByQueryId.delete(queryId);
347
+ const watch = watchesByChild.get(childTopicId);
348
+ if (!watch || watch.queryId !== queryId) return null;
349
+ watchesByChild.delete(childTopicId);
350
+ return watch;
351
+ }
352
+
353
+ function watchFromPersistedCard(
354
+ message: MessageDto,
355
+ card: SubagentCardDto,
356
+ queryId?: string,
357
+ ): SubagentWatch | null {
358
+ const child = host.storage.getTopic(card.subagentTopicId);
359
+ const userId = persistedWatchUserId(child);
360
+ if (!userId) return null;
361
+ return {
362
+ parentTopicId: message.topicId,
363
+ childTopicId: card.subagentTopicId,
364
+ cardMessageId: message.id,
365
+ name: card.name,
366
+ userId,
367
+ startedAt: card.startedAt ?? card.createdAt ?? message.createdAt,
368
+ reportMode: card.reportMode ?? "auto",
369
+ queryId,
370
+ running: card.status === "running",
371
+ };
372
+ }
373
+
374
+ function recoverPersistedSubagentWatch(queryId: string): SubagentWatch | null {
375
+ for (const message of host.storage.listSubagentMessages()) {
376
+ const card = message.subagentCard;
377
+ if (!card || (card.status !== "spawned" && card.status !== "running")) continue;
378
+ if (host.runtime.childExecutionQueryId(card.subagentTopicId) !== queryId) continue;
379
+ return watchFromPersistedCard(message, card, queryId);
380
+ }
381
+ return null;
382
+ }
383
+
384
+ function dropWatch(watch: SubagentWatch): void {
385
+ watchesByChild.delete(watch.childTopicId);
386
+ if (watch.queryId) childByQueryId.delete(watch.queryId);
387
+ }
388
+
389
+ /** Drop deferred/in-flight bookkeeping when a subagent room is hard-deleted. */
390
+ function cancelSubagentWatchForDeletedTopic(childTopicId: string): void {
391
+ const watch = watchesByChild.get(childTopicId);
392
+ if (!watch) return;
393
+ dropWatch(watch);
394
+ patchSubagentCard(watch.parentTopicId, watch.cardMessageId, {
395
+ status: "failed",
396
+ errorMessage: "subagent room was deleted",
397
+ finishedAt: host.runtime.now(),
398
+ });
399
+ }
400
+
401
+ /** Last-resort delivery: a plain system message in the parent room. */
402
+ function appendParentSystemNote(watch: SubagentWatch, prompt: string): void {
403
+ const now = host.runtime.now();
404
+ const msg: MessageDto = {
405
+ id: `subagent-note-${watch.childTopicId}-${now}`,
406
+ topicId: watch.parentTopicId,
407
+ authorId: "system",
408
+ text: prompt,
409
+ kind: "system",
410
+ createdAt: now,
411
+ };
412
+ host.storage.appendMessage(msg);
413
+ host.storage.publishMessage(watch.parentTopicId, msg);
414
+ }
415
+
416
+ /**
417
+ * Deliver a completion/failure notice to the parent room as a hidden AI turn,
418
+ * falling back to a system message. NEVER throws — the caller has already
419
+ * taken the watch, so a lost exception here would silently swallow the result
420
+ * with nothing left to retry.
421
+ */
422
+ async function notifyParent(
423
+ watch: SubagentWatch,
424
+ prompt: string,
425
+ noteKind: "done" | "fail",
426
+ ): Promise<void> {
427
+ try {
428
+ const requestId = `subagent-${noteKind}-${watch.childTopicId}`;
429
+ if (!(await host.sessionCommunication.notifyParent({ watch, prompt, requestId }))) {
430
+ appendParentSystemNote(watch, prompt);
431
+ }
432
+ } catch (err) {
433
+ logger.warn(
434
+ { err, parentTopicId: watch.parentTopicId, childTopicId: watch.childTopicId, noteKind },
435
+ "subagent: parent AI notify failed — falling back to system message",
436
+ );
437
+ try {
438
+ appendParentSystemNote(watch, prompt);
439
+ } catch (fallbackErr) {
440
+ logger.error(
441
+ {
442
+ err: fallbackErr,
443
+ parentTopicId: watch.parentTopicId,
444
+ childTopicId: watch.childTopicId,
445
+ },
446
+ "subagent: parent delivery lost — system-message fallback also failed",
447
+ );
448
+ }
449
+ }
450
+ }
451
+
452
+ /** Settle a finished child run. NEVER rejects — call sites fire-and-forget. */
453
+ async function settleSubagentSuccess(watch: SubagentWatch, finalText: string): Promise<void> {
454
+ const summary = finalText.replace(/\s+/g, " ").trim().slice(0, RESULT_SUMMARY_CHARS);
455
+ try {
456
+ patchSubagentCard(watch.parentTopicId, watch.cardMessageId, {
457
+ status: "completed",
458
+ resultSummary: summary || "(no text response)",
459
+ finishedAt: host.runtime.now(),
460
+ });
461
+ } catch (err) {
462
+ logger.warn(
463
+ { err, parentTopicId: watch.parentTopicId, cardMessageId: watch.cardMessageId },
464
+ "subagent: completed-card update failed",
465
+ );
466
+ }
467
+ if (watch.reportMode === "auto") {
468
+ await notifyParent(
469
+ watch,
470
+ `[Subagent completed ← ${watch.name}]\n이 메시지는 spawn_subagent로 위임한 작업의 자동 완료 회신입니다. 결과를 확인하고 필요하면 이어서 진행하세요.\n\n${finalText || "(no text response)"}`,
471
+ "done",
472
+ );
473
+ }
474
+ }
475
+
476
+ /** Settle a failed child run. NEVER rejects — call sites fire-and-forget. */
477
+ async function settleSubagentFailure(queryId: string, reason: string): Promise<void> {
478
+ const watch = takeSubagentWatch(queryId);
479
+ if (!watch) return;
480
+ try {
481
+ patchSubagentCard(watch.parentTopicId, watch.cardMessageId, {
482
+ status: "failed",
483
+ errorMessage: reason,
484
+ finishedAt: host.runtime.now(),
485
+ });
486
+ } catch (err) {
487
+ logger.warn(
488
+ { err, parentTopicId: watch.parentTopicId, cardMessageId: watch.cardMessageId },
489
+ "subagent: failed-card update failed",
490
+ );
491
+ }
492
+ if (watch.reportMode === "auto") {
493
+ await notifyParent(
494
+ watch,
495
+ `[Subagent failed ← ${watch.name}]\nspawn_subagent로 위임한 작업이 실패했습니다: ${reason}`,
496
+ "fail",
497
+ );
498
+ }
499
+ }
500
+
501
+ /**
502
+ * Boot-time sweep: watches don't survive a restart, so any card still marked
503
+ * spawned/running belongs to a run whose completion can no longer be tracked.
504
+ */
505
+ function sweepStaleSubagentCards(): void {
506
+ for (const msg of host.storage.listSubagentMessages()) {
507
+ const card = msg.subagentCard;
508
+ if (!card || (card.status !== "spawned" && card.status !== "running")) continue;
509
+ if (card.runtimeOwnerId && host.runtime.ownerIsAlive(card.runtimeOwnerId)) continue;
510
+ const queryId = host.runtime.childExecutionQueryId(card.subagentTopicId);
511
+ if (host.runtime.childExecutionIsRecoverable(card.subagentTopicId)) {
512
+ const watch = watchFromPersistedCard(msg, card, queryId ?? undefined);
513
+ if (watch && queryId) registerWatchDispatch(watch, queryId);
514
+ continue;
515
+ }
516
+ if (!card.runtimeOwnerId) continue;
517
+ patchSubagentCard(msg.topicId, msg.id, {
518
+ status: "failed",
519
+ errorMessage: "server restarted while the subagent was running",
520
+ finishedAt: host.runtime.now(),
521
+ });
522
+ logger.info(
523
+ { topicId: msg.topicId, messageId: msg.id, child: card.subagentTopicId },
524
+ "subagent: swept stale card on boot",
525
+ );
526
+ }
527
+ }
528
+
529
+ function reportModeFromInput(input: { report_mode?: unknown }): SubagentReportMode {
530
+ return input.report_mode === "tell" || input.report_mode === "status-only"
531
+ ? input.report_mode
532
+ : "auto";
533
+ }
534
+
535
+ function findSubagentCardMessage(childTopicId: string): MessageDto | undefined {
536
+ return host.storage
537
+ .listSubagentMessages()
538
+ .filter((message) => message.subagentCard?.subagentTopicId === childTopicId)
539
+ .at(-1);
540
+ }
541
+
542
+ function subagentReportMode(childTopicId: string): SubagentReportMode {
543
+ return (
544
+ host.storage.getTopic(childTopicId)?.subagentReportMode ??
545
+ findSubagentCardMessage(childTopicId)?.subagentCard?.reportMode ??
546
+ "auto"
547
+ );
548
+ }
549
+
550
+ async function startSubagentCard(
551
+ ctx: SubagentToolContext,
552
+ cardMessage: MessageDto,
553
+ ): Promise<ReturnType<typeof textResult>> {
554
+ const card = cardMessage.subagentCard;
555
+ if (!card) return errorResult("Error: subagent card is missing.");
556
+ if (card.status !== "ready") {
557
+ return errorResult(`Error: subagent cannot start from status '${card.status}'.`);
558
+ }
559
+ const child = host.storage.getTopic(card.subagentTopicId);
560
+ const parent = host.storage.getTopic(cardMessage.topicId);
561
+ if (!child || !parent)
562
+ return errorResult("Error: subagent room or its direct parent is missing.");
563
+ if (countLiveChildren(cardMessage.topicId) >= limits.maxLiveChildrenPerParent) {
564
+ return errorResult(
565
+ `Error: this room already has ${limits.maxLiveChildrenPerParent} subagents running.`,
566
+ );
567
+ }
568
+
569
+ const startedAt = host.runtime.now();
570
+ const watch: SubagentWatch = {
571
+ parentTopicId: cardMessage.topicId,
572
+ childTopicId: child.id,
573
+ cardMessageId: cardMessage.id,
574
+ name: child.title,
575
+ userId: ctx.userId,
576
+ startedAt,
577
+ reportMode: card.reportMode ?? "auto",
578
+ running: false,
579
+ };
580
+ watchesByChild.set(child.id, watch);
581
+ patchSubagentCard(cardMessage.topicId, cardMessage.id, {
582
+ runtimeOwnerId,
583
+ status: "spawned",
584
+ startedAt,
585
+ finishedAt: undefined,
586
+ errorMessage: undefined,
587
+ resultSummary: undefined,
588
+ });
589
+
590
+ const reportInstruction =
591
+ watch.reportMode === "tell"
592
+ ? `\n\nReport your result to "${parent.title}" with tell_session; your final response will not be forwarded automatically.`
593
+ : watch.reportMode === "status-only"
594
+ ? "\n\nDo not send a completion report to the parent; only the lifecycle card will be updated."
595
+ : "";
596
+ const childPrompt = `[Delegated task from ${parent.title}]\n\n${card.task}${reportInstruction}`;
597
+ const dispatch = await host.task.dispatch({
598
+ child,
599
+ parent,
600
+ userId: ctx.userId,
601
+ prompt: childPrompt,
602
+ requestId: `subagent-task-${child.id}-${startedAt}`,
603
+ onDispatched: (queryId) => registerWatchDispatch(watch, queryId),
604
+ });
605
+ if (!dispatch.accepted && !watch.queryId) {
606
+ dropWatch(watch);
607
+ patchSubagentCard(cardMessage.topicId, cardMessage.id, {
608
+ status: "failed",
609
+ errorMessage: dispatch.error ?? "the subagent turn could not be dispatched",
610
+ finishedAt: host.runtime.now(),
611
+ });
612
+ return errorResult(
613
+ dispatch.error
614
+ ? `Error: ${dispatch.error}`
615
+ : "Error: subagent room exists but its AI turn could not start.",
616
+ );
617
+ }
618
+ return textResult(`Subagent started: ${child.title} (${child.id})`);
619
+ }
620
+
621
+ async function createSubagent(
622
+ ctx: TContext,
623
+ input: {
624
+ task?: unknown;
625
+ name?: unknown;
626
+ agent?: unknown;
627
+ model?: unknown;
628
+ report_mode?: unknown;
629
+ memory_topic?: unknown;
630
+ },
631
+ startImmediately: boolean,
632
+ ) {
633
+ const parent = host.storage.getTopic(ctx.topicId);
634
+ if (!parent) return errorResult(`Error: topic '${ctx.topicId}' not found.`);
635
+ if (!parent.participants.some((p) => p.userId === ctx.userId)) {
636
+ return errorResult("Error: user is not a member of this topic.");
637
+ }
638
+ if (parent.kind !== "agent") {
639
+ return errorResult("Error: spawn_subagent is only available in agent rooms.");
640
+ }
641
+ const depth = computeSubagentDepth(ctx.topicId);
642
+ if (depth >= limits.maxDepth) {
643
+ return errorResult(
644
+ `Error: subagent depth limit reached (current ${depth}, max ${limits.maxDepth}).`,
645
+ );
646
+ }
647
+
648
+ const task = typeof input.task === "string" ? input.task.trim() : "";
649
+ if (!task) return errorResult("Error: task is required.");
650
+ if (task.length > MAX_TASK_CHARS) {
651
+ return errorResult(`Error: task is too long (max ${MAX_TASK_CHARS} chars).`);
652
+ }
653
+ const name =
654
+ typeof input.name === "string"
655
+ ? input.name
656
+ .replace(/[\n\t]/g, " ")
657
+ .trim()
658
+ .slice(0, MAX_NAME_CHARS)
659
+ : undefined;
660
+ const agentOverride = isAgentKind(input.agent) ? input.agent : undefined;
661
+ const modelOverride =
662
+ typeof input.model === "string" && input.model.trim() ? input.model.trim() : undefined;
663
+ const reportMode = reportModeFromInput(input);
664
+ const memorySelection = resolveMemoryTopicSelection(input.memory_topic, ctx.userId);
665
+ if (memorySelection.error) return errorResult(memorySelection.error);
666
+
667
+ if (startImmediately && countLiveChildren(ctx.topicId) >= limits.maxLiveChildrenPerParent) {
668
+ return errorResult(
669
+ `Error: this room already has ${limits.maxLiveChildrenPerParent} subagents running. Wait for one to finish before spawning another.`,
670
+ );
671
+ }
672
+ if (!startImmediately) {
673
+ // Prepared-but-unstarted rooms consume real topics/workspaces; cap them so
674
+ // a create_subagent loop cannot allocate unbounded resources.
675
+ const preparedChildren = host.storage
676
+ .listTopics()
677
+ .filter(
678
+ (topic) =>
679
+ topic.parentTopicId === ctx.topicId &&
680
+ topic.isSubagent &&
681
+ subagentStatus(ctx.topicId, topic.id) === "ready",
682
+ ).length;
683
+ if (preparedChildren >= limits.maxPreparedChildrenPerParent) {
684
+ return errorResult(
685
+ `Error: this room already has ${limits.maxPreparedChildrenPerParent} prepared subagents. Start or delete one before creating another.`,
686
+ );
687
+ }
688
+ }
689
+
690
+ // Preflight the overrides before creating anything — a bad agent/model would
691
+ // otherwise leave a dead child room with a card that fails on first turn.
692
+ const targetAgent = agentOverride ?? ctx.agent;
693
+ const resolved = await host.config.resolveAgentModel({
694
+ context: ctx,
695
+ agent: targetAgent,
696
+ model: modelOverride,
697
+ hasOverride: Boolean(agentOverride || modelOverride),
698
+ });
699
+ if (resolved.error) return errorResult(resolved.error);
700
+ const resolvedModelOverride = resolved.model;
701
+
702
+ const derived = await host.topic.createDerived({
703
+ context: ctx,
704
+ parentTopicId: ctx.topicId,
705
+ userId: ctx.userId,
706
+ name,
707
+ agent: agentOverride,
708
+ model: resolvedModelOverride,
709
+ memoryTopicId: memorySelection.topicId,
710
+ });
711
+ if (!derived.ok) {
712
+ if (derived.reason === "title-conflict") {
713
+ return errorResult(
714
+ `Error: ${derived.message ?? "topic title conflict"}. Try a different name.`,
715
+ );
716
+ }
717
+ return errorResult(
718
+ "Error: the source topic is busy (active turn or maintenance). Retry shortly.",
719
+ );
720
+ }
721
+ const child = derived.topic;
722
+ if (!child) {
723
+ return errorResult(
724
+ "Error: failed to create the subagent room (restricted or missing source topic).",
725
+ );
726
+ }
727
+ child.subagentReportMode = reportMode;
728
+ host.storage.upsertTopic(child);
729
+
730
+ const now = host.runtime.now();
731
+ const card: SubagentCardDto = {
732
+ subagentTopicId: child.id,
733
+ name: child.title,
734
+ task,
735
+ status: "ready",
736
+ reportMode,
737
+ createdAt: now,
738
+ };
739
+ const cardMsg: MessageDto = {
740
+ id: `subagent-${child.id}`,
741
+ topicId: ctx.topicId,
742
+ authorId: "ai",
743
+ text: `🤖 Subagent "${child.title}" spawned`,
744
+ queryId: ctx.queryId,
745
+ agentType: ctx.agent,
746
+ model: ctx.model,
747
+ kind: "subagent",
748
+ subagentCard: card,
749
+ createdAt: now,
750
+ };
751
+ host.storage.appendMessage(cardMsg, { notify: false });
752
+ host.storage.publishMessage(ctx.topicId, cardMsg);
753
+
754
+ if (!startImmediately) {
755
+ return textResult(
756
+ `Subagent prepared: ${child.title} (${child.id}). Use start_subagent to run it.`,
757
+ );
758
+ }
759
+ const started = await startSubagentCard(ctx, cardMsg);
760
+ if (started.isError) return started;
761
+
762
+ logger.info(
763
+ { parentTopicId: ctx.topicId, childTopicId: child.id, name: child.title },
764
+ "subagent: spawned",
765
+ );
766
+ return textResult(
767
+ [
768
+ `Subagent "${child.title}" spawned (room id: ${child.id}) and is now working in the background.`,
769
+ reportMode === "auto"
770
+ ? "Its final result will be delivered back into this room automatically when it finishes."
771
+ : reportMode === "tell"
772
+ ? "It must report with tell_session; its final response is not forwarded automatically."
773
+ : "Only lifecycle status will be reported.",
774
+ "Do NOT wait or poll — finish your current turn normally.",
775
+ ].join("\n"),
776
+ );
777
+ }
778
+
779
+ /**
780
+ * The actor's asserted reach, when there is one to apply. Only an `otium`
781
+ * turn that carries the hub's assertion narrows the tree; everywhere else
782
+ * (other surfaces, or a turn no person started) `null` means "the node's
783
+ * own participant and lineage checks decide", as before. The same
784
+ * `actorReachableTopicIds`/`actorOwnedTopicIds` rules the cross-room tools
785
+ * use, so "visible" and "owned" mean the same thing in every tool.
786
+ */
787
+ function assertedActorScope(
788
+ ctx: SubagentToolContext,
789
+ ): { visible: ReadonlySet<string>; owned: ReadonlySet<string> } | null {
790
+ if (ctx.surface !== "otium" || !ctx.actorTopicScope) return null;
791
+ const input = {
792
+ surface: ctx.surface,
793
+ currentTopicId: ctx.topicId,
794
+ actorTopicScope: ctx.actorTopicScope,
795
+ };
796
+ const visible = actorReachableTopicIds(input);
797
+ const owned = actorOwnedTopicIds(input);
798
+ return visible && owned ? { visible, owned } : null;
799
+ }
800
+
801
+ /**
802
+ * The subagent tree the calling turn may see, and which of it it may act on.
803
+ * `children` is the visible descendant list (what `list_subagents` shows);
804
+ * `owned` says whether a listed child may be started, deleted or given a
805
+ * grant. Without an assertion everything in the tree is owned by the room
806
+ * that spawned it; with one, both follow the hub's word and a child outside
807
+ * it is simply not in the tree — the same "not found" a stranger gets.
808
+ */
809
+ function ownedSubagentTree(ctx: SubagentToolContext) {
810
+ const parent = host.storage.getTopic(ctx.topicId);
811
+ if (!parent) return { ok: false, error: `Error: topic '${ctx.topicId}' not found.` } as const;
812
+ if (!parent.participants.some((participant) => participant.userId === ctx.userId)) {
813
+ return { ok: false, error: "Error: user is not a member of this topic." } as const;
814
+ }
815
+ if (parent.kind !== "agent") {
816
+ return {
817
+ ok: false,
818
+ error: "Error: subagent management is only available in agent rooms.",
819
+ } as const;
820
+ }
821
+ const actorScope = assertedActorScope(ctx);
822
+ // Subagents inherit the room's participants and roles verbatim (see
823
+ // createDerivedTopic), so anyone who legitimately belongs to `parent` —
824
+ // owner or member — belongs equally to every subagent spawned under it;
825
+ // requiring ctx.userId specifically to hold the "owner" role in each
826
+ // descendant would let the room owner manage subagents a non-owner
827
+ // member triggered while locking that same member out of the room they
828
+ // spawned. Gate the whole subtree on the *root's* owner staying the
829
+ // descendant's owner instead: that still excludes topics that merely
830
+ // happen to nest under `parent` without actually belonging to its
831
+ // subagent tree (e.g. a differently-owned room reparented here).
832
+ const rootOwnerId = parent.participants.find(
833
+ (participant) => participant.role === "owner",
834
+ )?.userId;
835
+ const descendants: TopicDto[] = rootOwnerId
836
+ ? (() => {
837
+ const topics = host.storage.listTopics();
838
+ const byParent = new Map<string, typeof topics>();
839
+ for (const topic of topics) {
840
+ if (!topic.parentTopicId || !topic.isSubagent) continue;
841
+ const siblings = byParent.get(topic.parentTopicId) ?? [];
842
+ siblings.push(topic);
843
+ byParent.set(topic.parentTopicId, siblings);
844
+ }
845
+ // `listTopics()` orders by recency, which ties for siblings created
846
+ // (and never messaged) in the same millisecond — so the tree this
847
+ // walk produces would come out in an arbitrary order for exactly the
848
+ // workers a single spawn call created. Break the tie on creation time
849
+ // then id, so the listing an agent sees is stable across calls.
850
+ for (const siblings of byParent.values()) {
851
+ siblings.sort(
852
+ (a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id),
853
+ );
854
+ }
855
+ const descendants: typeof topics = [];
856
+ const visited = new Set<string>([ctx.topicId]);
857
+ const visit = (parentId: string) => {
858
+ for (const child of byParent.get(parentId) ?? []) {
859
+ if (visited.has(child.id)) continue;
860
+ visited.add(child.id);
861
+ if (
862
+ !child.participants.some(
863
+ (participant) =>
864
+ participant.userId === rootOwnerId && participant.role === "owner",
865
+ )
866
+ ) {
867
+ continue;
868
+ }
869
+ descendants.push(child);
870
+ visit(child.id);
871
+ }
872
+ };
873
+ visit(ctx.topicId);
874
+ return descendants;
875
+ })()
876
+ : [];
877
+ const children = actorScope
878
+ ? descendants.filter((child) => actorScope.visible.has(child.id))
879
+ : descendants;
880
+ return {
881
+ ok: true,
882
+ parent,
883
+ children,
884
+ owned: (childId: string) =>
885
+ children.some((child) => child.id === childId) &&
886
+ (!actorScope || actorScope.owned.has(childId)),
887
+ /** Whether `topicId` may be named as a grant target: the room itself or a visible child. */
888
+ visibleTarget: (topicId: string) =>
889
+ topicId === ctx.topicId || children.some((child) => child.id === topicId),
890
+ /**
891
+ * Existing grant targets a person may be shown. Ancestor grants can point
892
+ * at rooms the hub never listed for this actor; on an asserted turn those
893
+ * ids are left out of the answer (a room the actor cannot see must not be
894
+ * discoverable through a child's connection list). Turns without an
895
+ * assertion see every grant, as before.
896
+ */
897
+ visibleTellTargets: (targetIds: readonly string[]) =>
898
+ actorScope
899
+ ? targetIds.filter(
900
+ (targetId) =>
901
+ targetId === ctx.topicId ||
902
+ actorScope.visible.has(targetId) ||
903
+ children.some((child) => child.id === targetId),
904
+ )
905
+ : [...targetIds],
906
+ } as const;
907
+ }
908
+
909
+ function subagentStatus(
910
+ parentTopicId: string,
911
+ childTopicId: string,
912
+ ): SubagentCardDto["status"] | "unknown" {
913
+ const watch = watchesByChild.get(childTopicId);
914
+ if (watch?.running) return "running";
915
+ const card = host.storage
916
+ .listSubagentMessages()
917
+ .filter(
918
+ (message) =>
919
+ message.topicId === parentTopicId &&
920
+ message.subagentCard?.subagentTopicId === childTopicId,
921
+ )
922
+ .at(-1)?.subagentCard;
923
+ if (!card || card.status === "failed") {
924
+ // The in-memory watch map (and the boot-time sweep that marks orphans
925
+ // failed) doesn't survive a restart. Before trusting a possibly-stale
926
+ // snapshot, reconcile against the same durable active-query marker
927
+ // peek_session / list_active_queries read for any child participant.
928
+ if (activeQueryUserId(host.storage.getTopic(childTopicId))) return "running";
929
+ }
930
+ return card?.status ?? "unknown";
931
+ }
932
+
933
+ function listMemoryTopicNames(ctx: SubagentToolContext): { names?: string[]; error?: string } {
934
+ const current = host.storage.getTopic(ctx.topicId);
935
+ if (!current) return { error: `Error: topic '${ctx.topicId}' not found.` };
936
+ if (!current.participants.some((participant) => participant.userId === ctx.userId)) {
937
+ return { error: "Error: user is not a member of this topic." };
938
+ }
939
+
940
+ const sources = new Map<string, string>();
941
+ for (const topic of host.storage.listTopics()) {
942
+ if (!topic.participants.some((participant) => participant.userId === ctx.userId)) continue;
943
+ const origin = host.storage.getTopicMemoryOrigin(topic.id) ?? topic;
944
+ if (!origin.participants.some((participant) => participant.userId === ctx.userId)) continue;
945
+ const [canonicalFilename] = host.config.memoryFilenames(origin);
946
+ sources.set(canonicalFilename, origin.title);
947
+ }
948
+ return {
949
+ names: [...sources.values()].sort((left, right) =>
950
+ left.localeCompare(right, undefined, { sensitivity: "base" }),
951
+ ),
952
+ };
953
+ }
954
+
955
+ function createSubagentManagementToolDefinitions(ctx: SubagentToolContext): SharedMcpTool[] {
956
+ return [
957
+ {
958
+ name: "list_memory_topics",
959
+ description:
960
+ "List the names of accessible topic-memory sources. Pass one returned name as memory_topic when creating or spawning a subagent.",
961
+ schema: {},
962
+ async handler() {
963
+ const result = listMemoryTopicNames(ctx);
964
+ if (result.error) return errorResult(result.error);
965
+ return textResult(result.names?.length ? result.names.join("\n") : "(no memory topics)");
966
+ },
967
+ },
968
+ {
969
+ name: "list_subagents",
970
+ description:
971
+ "List the full descendant subagent tree, statuses, and tell_session connections managed by this room.",
972
+ schema: {},
973
+ async handler() {
974
+ const result = ownedSubagentTree(ctx);
975
+ if (!result.ok) return errorResult(result.error);
976
+ const children = result.children.map((child) => ({
977
+ topic_id: child.id,
978
+ name: child.title,
979
+ parent_topic_id: child.parentTopicId,
980
+ status: subagentStatus(child.parentTopicId ?? ctx.topicId, child.id),
981
+ agent: child.agent ?? null,
982
+ model: child.defaultModel ?? null,
983
+ tell_target_topic_ids: result.visibleTellTargets(
984
+ host.sessionCommunication.listTellTargetIds(child.id),
985
+ ),
986
+ created_at: child.createdAt,
987
+ }));
988
+ return textResult(JSON.stringify({ subagents: children }, null, 2));
989
+ },
990
+ },
991
+ {
992
+ name: "start_subagent",
993
+ description: "Start a prepared descendant subagent task.",
994
+ schema: {
995
+ topic_id: z.string().describe("Prepared subagent room id."),
996
+ },
997
+ async handler(input) {
998
+ const result = ownedSubagentTree(ctx);
999
+ if (!result.ok) return errorResult(result.error);
1000
+ const topicId = String(input.topic_id ?? "").trim();
1001
+ if (!result.owned(topicId)) {
1002
+ return errorResult("Error: topic is not a descendant subagent managed by this room.");
1003
+ }
1004
+ const cardMessage = findSubagentCardMessage(topicId);
1005
+ if (!cardMessage)
1006
+ return errorResult("Error: no lifecycle card exists for this subagent.");
1007
+ return startSubagentCard(ctx, cardMessage);
1008
+ },
1009
+ },
1010
+ {
1011
+ name: "delete_subagent",
1012
+ description:
1013
+ "Permanently delete one descendant subagent room managed by the current room. " +
1014
+ "This removes its conversation, workspace, runtime state, and topic. Keep it when follow-up work is likely.",
1015
+ schema: {
1016
+ topic_id: z
1017
+ .string()
1018
+ .describe("Exact subagent room id returned by list_subagents; names are not accepted."),
1019
+ },
1020
+ async handler(input) {
1021
+ const result = ownedSubagentTree(ctx);
1022
+ if (!result.ok) return errorResult(result.error);
1023
+ const topicId = typeof input.topic_id === "string" ? input.topic_id.trim() : "";
1024
+ const child = result.owned(topicId)
1025
+ ? result.children.find((candidate) => candidate.id === topicId)
1026
+ : undefined;
1027
+ if (!child) {
1028
+ return errorResult(
1029
+ "Error: no owned descendant subagent with that topic_id exists under this room.",
1030
+ );
1031
+ }
1032
+ try {
1033
+ await host.topic.delete(child, ctx.userId);
1034
+ return textResult(`Subagent deleted: ${child.title} (${child.id})`);
1035
+ } catch (err) {
1036
+ const message = err instanceof Error ? err.message : String(err);
1037
+ return errorResult(`Error: failed to delete subagent '${child.title}': ${message}`);
1038
+ }
1039
+ },
1040
+ },
1041
+ {
1042
+ name: "grant_subagent_tell",
1043
+ description:
1044
+ "Allow one descendant subagent to tell_session another topic in this managed subagent tree. " +
1045
+ "Direct-parent reporting is always allowed and does not need a grant.",
1046
+ schema: {
1047
+ subagent_topic_id: z.string().describe("Source descendant subagent topic id."),
1048
+ target_topic_id: z
1049
+ .string()
1050
+ .describe("Target topic id: this manager room or another descendant in its tree."),
1051
+ },
1052
+ async handler(input) {
1053
+ const result = ownedSubagentTree(ctx);
1054
+ if (!result.ok) return errorResult(result.error);
1055
+ const sourceId = String(input.subagent_topic_id ?? "").trim();
1056
+ const targetId = String(input.target_topic_id ?? "").trim();
1057
+ if (!result.owned(sourceId)) {
1058
+ return errorResult("Error: source is not a descendant subagent managed by this room.");
1059
+ }
1060
+ if (!result.visibleTarget(targetId)) {
1061
+ return errorResult("Error: target is outside this room's managed subagent tree.");
1062
+ }
1063
+ if (host.storage.getTopic(sourceId)?.parentTopicId === targetId) {
1064
+ return textResult(
1065
+ "No grant needed: a subagent can always report to its direct parent.",
1066
+ );
1067
+ }
1068
+ host.sessionCommunication.grantTellTarget(sourceId, targetId, ctx.topicId);
1069
+ return textResult(`tell_session grant added: ${sourceId} -> ${targetId}`);
1070
+ },
1071
+ },
1072
+ {
1073
+ name: "revoke_subagent_tell",
1074
+ description:
1075
+ "Remove an extra tell_session connection previously granted to a descendant subagent.",
1076
+ schema: {
1077
+ subagent_topic_id: z.string().describe("Source descendant subagent topic id."),
1078
+ target_topic_id: z.string().describe("Granted target topic id."),
1079
+ },
1080
+ async handler(input) {
1081
+ const result = ownedSubagentTree(ctx);
1082
+ if (!result.ok) return errorResult(result.error);
1083
+ const sourceId = String(input.subagent_topic_id ?? "").trim();
1084
+ const targetId = String(input.target_topic_id ?? "").trim();
1085
+ if (!result.owned(sourceId)) {
1086
+ return errorResult("Error: source is not a descendant subagent managed by this room.");
1087
+ }
1088
+ if (!result.visibleTarget(targetId)) {
1089
+ return errorResult("Error: target is outside this room's managed subagent tree.");
1090
+ }
1091
+ const removed = host.sessionCommunication.revokeTellTarget(sourceId, targetId);
1092
+ return textResult(removed ? "tell_session grant removed." : "No matching grant existed.");
1093
+ },
1094
+ },
1095
+ ];
1096
+ }
1097
+
1098
+ function createSpawnSubagentToolDefinition(
1099
+ ctx: TContext,
1100
+ options: SubagentToolDefinitionOptions = {},
1101
+ ): SharedMcpTool {
1102
+ const executionOverrideSchema =
1103
+ options.executionOverrides === false
1104
+ ? {}
1105
+ : {
1106
+ agent: z
1107
+ .enum(["claude", "codex", "maestro"])
1108
+ .optional()
1109
+ .describe("Agent backend override. Defaults to this room's agent."),
1110
+ model: z
1111
+ .string()
1112
+ .optional()
1113
+ .describe(
1114
+ `Best-fit model override from the system prompt catalog. Omit agent+model to inherit ${ctx.agent}/${ctx.model ?? "default"}; overriding agent without model uses that agent's default.`,
1115
+ ),
1116
+ };
1117
+ return {
1118
+ name: "spawn_subagent",
1119
+ description:
1120
+ "Delegate a self-contained task to a subagent that works in its own new agent room. " +
1121
+ "Returns immediately; the subagent runs in the background and reports according to report_mode. " +
1122
+ "The fresh room has no parent conversation history; it receives the task plus the selected or inherited topic memory. " +
1123
+ "Use for parallelizable or long-running side work. Do not use provider built-in Task/Agent subagents.",
1124
+ schema: {
1125
+ task: z
1126
+ .string()
1127
+ .describe(
1128
+ "Self-contained task brief. The worker has topic memory but no parent conversation history, so include all task-specific context.",
1129
+ ),
1130
+ name: z
1131
+ .string()
1132
+ .optional()
1133
+ .describe("Short name for the subagent room. Auto-generated when omitted."),
1134
+ ...executionOverrideSchema,
1135
+ memory_topic: z
1136
+ .string()
1137
+ .optional()
1138
+ .describe(
1139
+ "Optional knowledge source: an accessible topic id/title or topic/*.md brief. Defaults to the parent room's effective topic brief.",
1140
+ ),
1141
+ report_mode: z
1142
+ .enum(["auto", "tell", "status-only"])
1143
+ .optional()
1144
+ .describe(
1145
+ "Completion reporting: auto injects the final result, tell requires tell_session, status-only updates only the lifecycle card.",
1146
+ ),
1147
+ },
1148
+ async handler(input) {
1149
+ return createSubagent(ctx, input, true);
1150
+ },
1151
+ };
1152
+ }
1153
+
1154
+ function createPrepareSubagentToolDefinition(
1155
+ ctx: TContext,
1156
+ options: SubagentToolDefinitionOptions = {},
1157
+ ): SharedMcpTool {
1158
+ return {
1159
+ name: "create_subagent",
1160
+ description:
1161
+ "Create a prepared subagent room and task definition without starting its AI turn. " +
1162
+ "Use start_subagent when the team is ready to run it.",
1163
+ schema: {
1164
+ task: z.string().describe("Self-contained task brief for the subagent."),
1165
+ name: z.string().optional().describe("Short room name. Auto-generated when omitted."),
1166
+ ...(options.executionOverrides === false
1167
+ ? {}
1168
+ : {
1169
+ agent: z.enum(["claude", "codex", "maestro"]).optional(),
1170
+ model: z.string().optional(),
1171
+ }),
1172
+ memory_topic: z
1173
+ .string()
1174
+ .optional()
1175
+ .describe(
1176
+ "Optional accessible topic id/title or topic/*.md brief to use as this worker's knowledge source. Defaults to the parent.",
1177
+ ),
1178
+ report_mode: z.enum(["auto", "tell", "status-only"]).optional(),
1179
+ },
1180
+ async handler(input) {
1181
+ return createSubagent(ctx, input, false);
1182
+ },
1183
+ };
1184
+ }
1185
+
1186
+ return {
1187
+ computeSubagentDepth,
1188
+ canSpawnSubagentsFromTopic,
1189
+ takeSubagentWatch,
1190
+ cancelSubagentWatchForDeletedTopic,
1191
+ settleSubagentSuccess,
1192
+ settleSubagentFailure,
1193
+ sweepStaleSubagentCards,
1194
+ subagentReportMode,
1195
+ createSubagentManagementToolDefinitions,
1196
+ createSpawnSubagentToolDefinition,
1197
+ createPrepareSubagentToolDefinition,
1198
+ };
1199
+ }
1200
+
1201
+ function processOwnerIsAlive(ownerId: string): boolean {
1202
+ const ownerPid = Number.parseInt(ownerId.split("-", 1)[0] ?? "", 10);
1203
+ if (!Number.isSafeInteger(ownerPid) || ownerPid <= 0) return true;
1204
+ try {
1205
+ process.kill(ownerPid, 0);
1206
+ return true;
1207
+ } catch (error) {
1208
+ return (error as NodeJS.ErrnoException).code !== "ESRCH";
1209
+ }
1210
+ }
1211
+
1212
+ const defaultSubagentLifecycleHost: SubagentLifecycleHost = {
1213
+ storage: {
1214
+ getTopic,
1215
+ listTopics,
1216
+ getTopicMemoryOrigin,
1217
+ upsertTopic,
1218
+ getMessage: getApiMessage,
1219
+ listSubagentMessages: () => listApiMessagesByKind("subagent"),
1220
+ appendMessage: appendApiMessage,
1221
+ updateSubagentCard: updateApiMessageSubagentCard,
1222
+ publishMessage: (topicId, message) => WsHub.get().broadcastMessage(topicId, message),
1223
+ publishCardUpdate: (topicId, messageId, update) =>
1224
+ WsHub.get().broadcastMessageUpdated(topicId, messageId, update),
1225
+ },
1226
+ topic: {
1227
+ async createDerived(input) {
1228
+ const { createDerivedTopic, TopicDeriveBusyError, TopicTitleConflictError } = await import(
1229
+ "#topics/derive"
1230
+ );
1231
+ try {
1232
+ const topic = await createDerivedTopic(input.parentTopicId, input.userId, false, {
1233
+ name: input.name,
1234
+ subagent: {
1235
+ agent: input.agent,
1236
+ model: input.model,
1237
+ memoryTopicId: input.memoryTopicId,
1238
+ },
1239
+ });
1240
+ return { ok: true, topic };
1241
+ } catch (error) {
1242
+ if (error instanceof TopicTitleConflictError) {
1243
+ return { ok: false, reason: "title-conflict", message: error.message };
1244
+ }
1245
+ if (error instanceof TopicDeriveBusyError) return { ok: false, reason: "busy" };
1246
+ throw error;
1247
+ }
1248
+ },
1249
+ async delete(topic, userId) {
1250
+ const { deleteTopicCascade } = await import("#topics/lifecycle");
1251
+ await deleteTopicCascade(topic, userId);
1252
+ },
1253
+ },
1254
+ task: {
1255
+ async dispatch(input) {
1256
+ const { triggerTopicAiTurn } = await import("#runtime/turn-runner");
1257
+ const { getRoomQuery } = await import("#query/active-rooms");
1258
+ const queryId = triggerTopicAiTurn(input.child.id, input.userId, input.prompt, undefined, {
1259
+ origin: `subagent-task:${input.parent.title}`,
1260
+ requestId: input.requestId,
1261
+ injectAuthorId: "ai",
1262
+ onDispatched: input.onDispatched,
1263
+ });
1264
+ return { accepted: Boolean(queryId || getRoomQuery(input.child.id)) };
1265
+ },
1266
+ },
1267
+ sessionCommunication: {
1268
+ async notifyParent({ watch, prompt, requestId }) {
1269
+ const parent = getTopic(watch.parentTopicId);
1270
+ if (!parent) return true;
1271
+ const { triggerTopicAiTurn } = await import("#runtime/turn-runner");
1272
+ const queryId = parent.agent
1273
+ ? triggerTopicAiTurn(watch.parentTopicId, watch.userId, prompt, undefined, {
1274
+ origin: `subagent:${watch.name}`,
1275
+ requestId,
1276
+ hideInjectMessage: true,
1277
+ })
1278
+ : null;
1279
+ if (queryId) return true;
1280
+ const { interSessionQueue } = await import("#query/active-rooms");
1281
+ return Boolean(parent.agent && interSessionQueue.hasRequest(parent.id, requestId));
1282
+ },
1283
+ listTellTargetIds: listSubagentTellTargetIds,
1284
+ grantTellTarget: grantSubagentTellTarget,
1285
+ revokeTellTarget: revokeSubagentTellTarget,
1286
+ },
1287
+ runtime: {
1288
+ ownerId: RUNTIME_INSTANCE_ID,
1289
+ now: () => new Date().toISOString(),
1290
+ ownerIsAlive: processOwnerIsAlive,
1291
+ childExecutionQueryId(childTopicId) {
1292
+ const lease = getRuntimeTurnLease(childTopicId);
1293
+ if (lease) return lease.queryId;
1294
+ return getRuntimeUserTurnRequest(childTopicId)?.runningQueryId ?? null;
1295
+ },
1296
+ childExecutionIsRecoverable(childTopicId) {
1297
+ if (getRuntimeUserTurnRequest(childTopicId)) return true;
1298
+ const lease = getRuntimeTurnLease(childTopicId);
1299
+ if (lease && processOwnerIsAlive(lease.ownerId)) return true;
1300
+ return Boolean(activeQueryUserId(getTopic(childTopicId)));
1301
+ },
1302
+ },
1303
+ config: {
1304
+ async resolveAgentModel({ context, agent, model, hasOverride }) {
1305
+ let resolvedModel = model;
1306
+ if (model) {
1307
+ const { resolveModelForAgent } = await import("#agents/model-catalog");
1308
+ const { getRegistry } = await import("#agents/registry");
1309
+ const registry = getRegistry(agent);
1310
+ if (!registry.validateModel(model)) {
1311
+ return { error: `Error: model '${model}' is not valid for agent '${agent}'.` };
1312
+ }
1313
+ resolvedModel = resolveModelForAgent(agent, model, registry);
1314
+ }
1315
+ if (hasOverride) {
1316
+ const { checkAgentModelAuth } = await import("#agents/auth-check");
1317
+ const { getRegistry } = await import("#agents/registry");
1318
+ const targetModel = resolvedModel ?? getRegistry(agent).defaultModel;
1319
+ const auth = checkAgentModelAuth(agent, targetModel, undefined, context.userId);
1320
+ if (!auth.ok) {
1321
+ return { error: `Error: agent '${agent}' is not available: ${auth.error}` };
1322
+ }
1323
+ }
1324
+ return { model: resolvedModel };
1325
+ },
1326
+ memoryFilenames: (topic) => [
1327
+ `${wikiBriefStorageKey(topic.title, topic.id)}.md`,
1328
+ `${wikiSummarySlug(topic.title)}.md`,
1329
+ ],
1330
+ },
1331
+ };
1332
+
1333
+ const defaultSubagentLifecycle = createSubagentLifecycle(defaultSubagentLifecycleHost);
1334
+
1335
+ export const computeSubagentDepth = defaultSubagentLifecycle.computeSubagentDepth;
1336
+ export const canSpawnSubagentsFromTopic = defaultSubagentLifecycle.canSpawnSubagentsFromTopic;
1337
+ export const takeSubagentWatch = defaultSubagentLifecycle.takeSubagentWatch;
1338
+ export const cancelSubagentWatchForDeletedTopic =
1339
+ defaultSubagentLifecycle.cancelSubagentWatchForDeletedTopic;
1340
+ export const settleSubagentSuccess = defaultSubagentLifecycle.settleSubagentSuccess;
1341
+ export const settleSubagentFailure = defaultSubagentLifecycle.settleSubagentFailure;
1342
+ export const sweepStaleSubagentCards = defaultSubagentLifecycle.sweepStaleSubagentCards;
1343
+ export const subagentReportMode = defaultSubagentLifecycle.subagentReportMode;
1344
+ export const createSubagentManagementToolDefinitions =
1345
+ defaultSubagentLifecycle.createSubagentManagementToolDefinitions;
1346
+ export const createSpawnSubagentToolDefinition =
1347
+ defaultSubagentLifecycle.createSpawnSubagentToolDefinition;
1348
+ export const createPrepareSubagentToolDefinition =
1349
+ defaultSubagentLifecycle.createPrepareSubagentToolDefinition;