@otium-team/negotium 0.0.0-stage → 0.23.13

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 +23090 -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 +2334 -0
  10. package/dist/browser-runtime.js.map +35 -0
  11. package/dist/canonical-mcp-bridge.js +13 -0
  12. package/dist/canonical-mcp-bridge.js.map +9 -0
  13. package/dist/chunk-22kg3fsw.js +79 -0
  14. package/dist/chunk-22kg3fsw.js.map +9 -0
  15. package/dist/chunk-d4j77adx.js +336 -0
  16. package/dist/chunk-d4j77adx.js.map +13 -0
  17. package/dist/chunk-mk9x18jn.js +172 -0
  18. package/dist/chunk-mk9x18jn.js.map +12 -0
  19. package/dist/chunk-qd0vtfm2.js +3923 -0
  20. package/dist/chunk-qd0vtfm2.js.map +47 -0
  21. package/dist/chunk-wf7ny8eq.js +206 -0
  22. package/dist/chunk-wf7ny8eq.js.map +10 -0
  23. package/dist/chunk-ww8a4ej4.js +54 -0
  24. package/dist/chunk-ww8a4ej4.js.map +10 -0
  25. package/dist/cron.js +1 -0
  26. package/dist/hosted-agent.js +5982 -0
  27. package/dist/hosted-agent.js.map +62 -0
  28. package/dist/main.js +60229 -0
  29. package/dist/main.js.map +340 -0
  30. package/dist/mcp-catalog.js +39 -0
  31. package/dist/mcp-catalog.js.map +10 -0
  32. package/dist/mcp-factories.js +25767 -0
  33. package/dist/mcp-factories.js.map +181 -0
  34. package/dist/mcp-servers.js +50 -0
  35. package/dist/mcp-servers.js.map +10 -0
  36. package/dist/media.js +570 -0
  37. package/dist/media.js.map +15 -0
  38. package/dist/outbox.js +354 -0
  39. package/dist/outbox.js.map +15 -0
  40. package/dist/platform-runtime.js +73 -0
  41. package/dist/platform-runtime.js.map +12 -0
  42. package/dist/prompts.js +892 -0
  43. package/dist/prompts.js.map +15 -0
  44. package/dist/query-runtime.js +1071 -0
  45. package/dist/query-runtime.js.map +26 -0
  46. package/dist/registry.js +335 -0
  47. package/dist/registry.js.map +14 -0
  48. package/dist/rollout.js +57 -0
  49. package/dist/rollout.js.map +10 -0
  50. package/dist/runtime/cron/background-sessions.ts +119 -0
  51. package/dist/runtime/cron/context.ts +123 -0
  52. package/dist/runtime/cron/host.ts +67 -0
  53. package/dist/runtime/cron/index.ts +95 -0
  54. package/dist/runtime/cron/mcp-server.ts +556 -0
  55. package/dist/runtime/cron/module.ts +174 -0
  56. package/dist/runtime/cron/package.json +6 -0
  57. package/dist/runtime/cron/schedule.ts +211 -0
  58. package/dist/runtime/cron/scheduler.ts +444 -0
  59. package/dist/runtime/cron/scripts.ts +203 -0
  60. package/dist/runtime/cron/store.ts +1163 -0
  61. package/dist/runtime/cron/summarize.ts +115 -0
  62. package/dist/runtime/package.json +6 -0
  63. package/dist/runtime/scripts/faster-whisper-wrapper.py +87 -0
  64. package/dist/runtime/src/agents/api-topic-agent-switch.ts +179 -0
  65. package/dist/runtime/src/agents/archiver.ts +677 -0
  66. package/dist/runtime/src/agents/auth-check.ts +156 -0
  67. package/dist/runtime/src/agents/claude-notices.ts +130 -0
  68. package/dist/runtime/src/agents/claude-provider.ts +941 -0
  69. package/dist/runtime/src/agents/claude-registry.ts +117 -0
  70. package/dist/runtime/src/agents/claude-runtime-inspection.ts +43 -0
  71. package/dist/runtime/src/agents/codex-app-server.ts +138 -0
  72. package/dist/runtime/src/agents/codex-native-multi-agent.ts +360 -0
  73. package/dist/runtime/src/agents/codex-provider.ts +1193 -0
  74. package/dist/runtime/src/agents/codex-registry.ts +116 -0
  75. package/dist/runtime/src/agents/codex-tier-resolver.ts +74 -0
  76. package/dist/runtime/src/agents/codex-tree-kill.ts +54 -0
  77. package/dist/runtime/src/agents/codex-tree-manager.ts +230 -0
  78. package/dist/runtime/src/agents/codex-vault-hook-bridge.ts +240 -0
  79. package/dist/runtime/src/agents/codex-vault-hook.mjs +50 -0
  80. package/dist/runtime/src/agents/codex-windows-wrapper.ts +174 -0
  81. package/dist/runtime/src/agents/compaction-support.ts +75 -0
  82. package/dist/runtime/src/agents/compaction-tool-projection.ts +125 -0
  83. package/dist/runtime/src/agents/contracts.ts +75 -0
  84. package/dist/runtime/src/agents/deep-map.ts +13 -0
  85. package/dist/runtime/src/agents/execution-host.ts +118 -0
  86. package/dist/runtime/src/agents/explicit-agent-switch.ts +106 -0
  87. package/dist/runtime/src/agents/fixtures/claude-attachments.jsonl +2 -0
  88. package/dist/runtime/src/agents/fixtures/codex-shell.jsonl +5 -0
  89. package/dist/runtime/src/agents/fork.ts +100 -0
  90. package/dist/runtime/src/agents/hosted-agent.ts +78 -0
  91. package/dist/runtime/src/agents/idle-archiver.ts +225 -0
  92. package/dist/runtime/src/agents/idle-compact.ts +225 -0
  93. package/dist/runtime/src/agents/index.ts +225 -0
  94. package/dist/runtime/src/agents/maestro-provider.ts +246 -0
  95. package/dist/runtime/src/agents/maestro-registry.ts +189 -0
  96. package/dist/runtime/src/agents/mcp-tools/ask-user.ts +653 -0
  97. package/dist/runtime/src/agents/mcp-tools/common.ts +23 -0
  98. package/dist/runtime/src/agents/mcp-tools/inline-assets.ts +203 -0
  99. package/dist/runtime/src/agents/mcp-tools/publish-html.ts +183 -0
  100. package/dist/runtime/src/agents/mcp-tools/request-vault.ts +684 -0
  101. package/dist/runtime/src/agents/mcp-tools/self-config.ts +353 -0
  102. package/dist/runtime/src/agents/mcp-tools/spawn-subagent.ts +1349 -0
  103. package/dist/runtime/src/agents/mcp-tools/visual-compat.ts +18 -0
  104. package/dist/runtime/src/agents/mcp-tools/visuals.ts +60 -0
  105. package/dist/runtime/src/agents/memory-archive-policy.ts +54 -0
  106. package/dist/runtime/src/agents/model-catalog.ts +439 -0
  107. package/dist/runtime/src/agents/public-helpers.ts +149 -0
  108. package/dist/runtime/src/agents/registry.ts +35 -0
  109. package/dist/runtime/src/agents/rollout/claude.ts +336 -0
  110. package/dist/runtime/src/agents/rollout/codex.ts +910 -0
  111. package/dist/runtime/src/agents/rollout/index.ts +26 -0
  112. package/dist/runtime/src/agents/rollout/shared.ts +293 -0
  113. package/dist/runtime/src/agents/self-config-core.ts +704 -0
  114. package/dist/runtime/src/agents/task-events.ts +59 -0
  115. package/dist/runtime/src/agents/tool-format.ts +613 -0
  116. package/dist/runtime/src/agents/topic-agent-switch.ts +189 -0
  117. package/dist/runtime/src/agents/topic-cleanup.ts +285 -0
  118. package/dist/runtime/src/agents/vault-tool-policy.ts +36 -0
  119. package/dist/runtime/src/application/execute-external-user-turn.ts +23 -0
  120. package/dist/runtime/src/application/submit-runtime-gateway-turn.ts +484 -0
  121. package/dist/runtime/src/application/submit-user-message.ts +60 -0
  122. package/dist/runtime/src/application/switch-topic-effort.ts +48 -0
  123. package/dist/runtime/src/application/switch-topic-model.ts +79 -0
  124. package/dist/runtime/src/application/topic-service.ts +190 -0
  125. package/dist/runtime/src/application/turn-follow-ups.ts +291 -0
  126. package/dist/runtime/src/application/vault-command.ts +170 -0
  127. package/dist/runtime/src/bus.ts +409 -0
  128. package/dist/runtime/src/config-public.ts +2 -0
  129. package/dist/runtime/src/cron-host.ts +33 -0
  130. package/dist/runtime/src/cron-mcp-host.ts +5 -0
  131. package/dist/runtime/src/identifiers.ts +49 -0
  132. package/dist/runtime/src/index.ts +573 -0
  133. package/dist/runtime/src/mcp/agent-health-server.ts +8 -0
  134. package/dist/runtime/src/mcp/canonical-bridge-config.ts +84 -0
  135. package/dist/runtime/src/mcp/canonical-proxy-server.ts +308 -0
  136. package/dist/runtime/src/mcp/compaction-log-server.ts +25 -0
  137. package/dist/runtime/src/mcp/decision-server.ts +21 -0
  138. package/dist/runtime/src/mcp/dm-ipc.ts +60 -0
  139. package/dist/runtime/src/mcp/factories/agent-health.ts +394 -0
  140. package/dist/runtime/src/mcp/factories/compaction-log.ts +135 -0
  141. package/dist/runtime/src/mcp/factories/decision.ts +186 -0
  142. package/dist/runtime/src/mcp/factories/index.ts +73 -0
  143. package/dist/runtime/src/mcp/factories/session-comm.ts +184 -0
  144. package/dist/runtime/src/mcp/factories/session-history.ts +103 -0
  145. package/dist/runtime/src/mcp/factories/stdio-protection.ts +24 -0
  146. package/dist/runtime/src/mcp/factories/system-health.ts +259 -0
  147. package/dist/runtime/src/mcp/factories/task.ts +185 -0
  148. package/dist/runtime/src/mcp/factories/token-stats.ts +145 -0
  149. package/dist/runtime/src/mcp/factories/vault.ts +32 -0
  150. package/dist/runtime/src/mcp/mcp-helpers.ts +40 -0
  151. package/dist/runtime/src/mcp/peer-bridge.ts +119 -0
  152. package/dist/runtime/src/mcp/runtime-spec.ts +473 -0
  153. package/dist/runtime/src/mcp/session-comm/actor-policy.ts +160 -0
  154. package/dist/runtime/src/mcp/session-comm/bridge-ipc-config.ts +27 -0
  155. package/dist/runtime/src/mcp/session-comm/context.ts +113 -0
  156. package/dist/runtime/src/mcp/session-comm/default-host.ts +723 -0
  157. package/dist/runtime/src/mcp/session-comm/history-target.ts +89 -0
  158. package/dist/runtime/src/mcp/session-comm/history-tools.ts +113 -0
  159. package/dist/runtime/src/mcp/session-comm/hub-remote-session.ts +553 -0
  160. package/dist/runtime/src/mcp/session-comm/limits.ts +8 -0
  161. package/dist/runtime/src/mcp/session-comm/peer-forward.ts +251 -0
  162. package/dist/runtime/src/mcp/session-comm/runtime.ts +128 -0
  163. package/dist/runtime/src/mcp/session-comm/server.ts +1036 -0
  164. package/dist/runtime/src/mcp/session-comm/tell-permissions.ts +79 -0
  165. package/dist/runtime/src/mcp/session-comm/topic-catalog.ts +155 -0
  166. package/dist/runtime/src/mcp/session-comm/topic-config.ts +137 -0
  167. package/dist/runtime/src/mcp/session-comm/topics.ts +313 -0
  168. package/dist/runtime/src/mcp/session-history-limits.ts +36 -0
  169. package/dist/runtime/src/mcp/session-history-reader.ts +359 -0
  170. package/dist/runtime/src/mcp/session-history-server.ts +19 -0
  171. package/dist/runtime/src/mcp/stdio-protect.ts +7 -0
  172. package/dist/runtime/src/mcp/system-health-server.ts +5 -0
  173. package/dist/runtime/src/mcp/task-server.ts +17 -0
  174. package/dist/runtime/src/mcp/token-stats-server.ts +10 -0
  175. package/dist/runtime/src/mcp/vault-server.ts +12 -0
  176. package/dist/runtime/src/mcp/wiki-search-index.ts +359 -0
  177. package/dist/runtime/src/mcp/wiki-server.ts +2386 -0
  178. package/dist/runtime/src/mcp-runtime-host.ts +81 -0
  179. package/dist/runtime/src/media/file-events.ts +33 -0
  180. package/dist/runtime/src/media/text-extractor.ts +334 -0
  181. package/dist/runtime/src/media/video.ts +92 -0
  182. package/dist/runtime/src/node-host.ts +211 -0
  183. package/dist/runtime/src/outbox/coalescing-runner.ts +157 -0
  184. package/dist/runtime/src/outbox/file-ops.ts +267 -0
  185. package/dist/runtime/src/outbox/index.ts +26 -0
  186. package/dist/runtime/src/outbox/utils.ts +74 -0
  187. package/dist/runtime/src/platform/background-bash/context.ts +9 -0
  188. package/dist/runtime/src/platform/background-bash/manager.ts +292 -0
  189. package/dist/runtime/src/platform/background-bash/output-buffer.ts +323 -0
  190. package/dist/runtime/src/platform/config-helpers.ts +47 -0
  191. package/dist/runtime/src/platform/config.ts +618 -0
  192. package/dist/runtime/src/platform/constants.ts +30 -0
  193. package/dist/runtime/src/platform/debug-users.ts +14 -0
  194. package/dist/runtime/src/platform/delay.ts +1 -0
  195. package/dist/runtime/src/platform/error.ts +9 -0
  196. package/dist/runtime/src/platform/file-utils.ts +35 -0
  197. package/dist/runtime/src/platform/ipc.ts +55 -0
  198. package/dist/runtime/src/platform/jsonl.ts +277 -0
  199. package/dist/runtime/src/platform/lifecycle.ts +176 -0
  200. package/dist/runtime/src/platform/log-rotation.ts +45 -0
  201. package/dist/runtime/src/platform/logger.ts +42 -0
  202. package/dist/runtime/src/platform/maestro-bootstrap-env.ts +3 -0
  203. package/dist/runtime/src/platform/mcp-catalog-policy.ts +63 -0
  204. package/dist/runtime/src/platform/mcp-config.ts +1329 -0
  205. package/dist/runtime/src/platform/memoize-import.ts +26 -0
  206. package/dist/runtime/src/platform/modules.ts +145 -0
  207. package/dist/runtime/src/platform/node-plugins.ts +46 -0
  208. package/dist/runtime/src/platform/paths.ts +62 -0
  209. package/dist/runtime/src/platform/playwright/browser-processes.ts +300 -0
  210. package/dist/runtime/src/platform/playwright/capability.ts +5 -0
  211. package/dist/runtime/src/platform/playwright/headed-launch.ts +61 -0
  212. package/dist/runtime/src/platform/playwright/manager-utils.ts +128 -0
  213. package/dist/runtime/src/platform/playwright/manager.ts +1502 -0
  214. package/dist/runtime/src/platform/playwright/mcp-transport.ts +35 -0
  215. package/dist/runtime/src/platform/playwright/profile-management.ts +33 -0
  216. package/dist/runtime/src/platform/playwright/public-runtime.ts +52 -0
  217. package/dist/runtime/src/platform/playwright/transport-probe.ts +89 -0
  218. package/dist/runtime/src/platform/playwright/vault-broker.ts +261 -0
  219. package/dist/runtime/src/platform/public-runtime.ts +18 -0
  220. package/dist/runtime/src/prompts/agents/wiki-archiver.md +194 -0
  221. package/dist/runtime/src/prompts/builders.ts +696 -0
  222. package/dist/runtime/src/prompts/sessions/_shared-tools.md +38 -0
  223. package/dist/runtime/src/prompts/sessions/channel-system.md +13 -0
  224. package/dist/runtime/src/prompts/sessions/manager-system.md +34 -0
  225. package/dist/runtime/src/prompts/sessions/surfaces/cli.md +6 -0
  226. package/dist/runtime/src/prompts/sessions/surfaces/otium-manager.md +18 -0
  227. package/dist/runtime/src/prompts/sessions/surfaces/otium.md +6 -0
  228. package/dist/runtime/src/prompts/sessions/surfaces/telegram.md +5 -0
  229. package/dist/runtime/src/prompts/sessions/surfaces/terminal.md +6 -0
  230. package/dist/runtime/src/prompts/sessions/topic-system.md +9 -0
  231. package/dist/runtime/src/prompts/sessions/visual-design.md +38 -0
  232. package/dist/runtime/src/query/active-rooms.ts +514 -0
  233. package/dist/runtime/src/query/index.ts +23 -0
  234. package/dist/runtime/src/query/public-runtime.ts +28 -0
  235. package/dist/runtime/src/query/room-query-registry.ts +217 -0
  236. package/dist/runtime/src/query/session-inbox-cleanup.ts +45 -0
  237. package/dist/runtime/src/query/session-inbox-path.ts +42 -0
  238. package/dist/runtime/src/query/state.ts +116 -0
  239. package/dist/runtime/src/query/types.ts +8 -0
  240. package/dist/runtime/src/runtime/actor-topic-reach.ts +123 -0
  241. package/dist/runtime/src/runtime/actor-topic-scope.ts +255 -0
  242. package/dist/runtime/src/runtime/ask-callbacks.ts +217 -0
  243. package/dist/runtime/src/runtime/attachments.ts +149 -0
  244. package/dist/runtime/src/runtime/background-session-policy.ts +1 -0
  245. package/dist/runtime/src/runtime/background-sessions.ts +288 -0
  246. package/dist/runtime/src/runtime/bashrs-completions.ts +350 -0
  247. package/dist/runtime/src/runtime/channel-context.ts +115 -0
  248. package/dist/runtime/src/runtime/context-warning.ts +131 -0
  249. package/dist/runtime/src/runtime/cron-sessions.ts +35 -0
  250. package/dist/runtime/src/runtime/delivery-ack.ts +112 -0
  251. package/dist/runtime/src/runtime/errors.ts +70 -0
  252. package/dist/runtime/src/runtime/event-heartbeat.ts +77 -0
  253. package/dist/runtime/src/runtime/file-hooks.ts +81 -0
  254. package/dist/runtime/src/runtime/footer.ts +23 -0
  255. package/dist/runtime/src/runtime/gateway-capabilities.ts +22 -0
  256. package/dist/runtime/src/runtime/inbox.ts +1307 -0
  257. package/dist/runtime/src/runtime/playwright-turn-abort.ts +59 -0
  258. package/dist/runtime/src/runtime/public-helpers.ts +78 -0
  259. package/dist/runtime/src/runtime/remote-session-grant.ts +221 -0
  260. package/dist/runtime/src/runtime/remote-session-inbox.ts +943 -0
  261. package/dist/runtime/src/runtime/remote-session-reply-outbox.ts +168 -0
  262. package/dist/runtime/src/runtime/task-format.ts +18 -0
  263. package/dist/runtime/src/runtime/tasks.ts +53 -0
  264. package/dist/runtime/src/runtime/thread-context.ts +123 -0
  265. package/dist/runtime/src/runtime/thread-read.ts +67 -0
  266. package/dist/runtime/src/runtime/topic-config.ts +29 -0
  267. package/dist/runtime/src/runtime/turn-event-stream.ts +1051 -0
  268. package/dist/runtime/src/runtime/turn-runner.ts +2311 -0
  269. package/dist/runtime/src/runtime/turn-session.ts +116 -0
  270. package/dist/runtime/src/runtime/usage-alert.ts +51 -0
  271. package/dist/runtime/src/runtime/user-turn-envelope.ts +94 -0
  272. package/dist/runtime/src/runtime/visual-html.ts +175 -0
  273. package/dist/runtime/src/runtime/visual-store.ts +480 -0
  274. package/dist/runtime/src/runtime/visuals.ts +209 -0
  275. package/dist/runtime/src/runtime-gateway.ts +1045 -0
  276. package/dist/runtime/src/security/sanitize.ts +27 -0
  277. package/dist/runtime/src/security/sensitive-path.ts +41 -0
  278. package/dist/runtime/src/storage/activity-log.ts +167 -0
  279. package/dist/runtime/src/storage/api-messages.ts +766 -0
  280. package/dist/runtime/src/storage/api-topic-brief.ts +134 -0
  281. package/dist/runtime/src/storage/api-topic-config.ts +197 -0
  282. package/dist/runtime/src/storage/api-topics.ts +1647 -0
  283. package/dist/runtime/src/storage/app-settings.ts +50 -0
  284. package/dist/runtime/src/storage/ask-user-gates.ts +359 -0
  285. package/dist/runtime/src/storage/browser-profiles.ts +186 -0
  286. package/dist/runtime/src/storage/conversation-migration.ts +180 -0
  287. package/dist/runtime/src/storage/conversations.ts +377 -0
  288. package/dist/runtime/src/storage/decisions.ts +231 -0
  289. package/dist/runtime/src/storage/forum/agent-settings.ts +20 -0
  290. package/dist/runtime/src/storage/forum/index.ts +4 -0
  291. package/dist/runtime/src/storage/forum/repository.ts +283 -0
  292. package/dist/runtime/src/storage/forum/schema.ts +314 -0
  293. package/dist/runtime/src/storage/forum-db.ts +4 -0
  294. package/dist/runtime/src/storage/remote-session.ts +1028 -0
  295. package/dist/runtime/src/storage/runtime-events.ts +209 -0
  296. package/dist/runtime/src/storage/runtime-follow-ups.ts +212 -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 +846 -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 +591 -0
  336. package/dist/runtime/src/types.ts +418 -0
  337. package/dist/runtime/src/version.ts +1 -0
  338. package/dist/runtime/tsconfig.json +13 -0
  339. package/dist/runtime-gateway.js +514 -0
  340. package/dist/runtime-gateway.js.map +10 -0
  341. package/dist/runtime-helpers.js +1792 -0
  342. package/dist/runtime-helpers.js.map +40 -0
  343. package/dist/sqlite.js +66 -0
  344. package/dist/sqlite.js.map +10 -0
  345. package/dist/storage.js +5223 -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 +141 -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 +240 -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 +282 -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 +163 -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 +551 -0
  556. package/dist/types/packages/core/src/types.d.ts +405 -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 +848 -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,1329 @@
1
+ import { accessSync, constants as fsConstants } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { explicitAgentSwitchTargets } from "#agents/explicit-agent-switch";
5
+
6
+ import { canonicalMcpBridgeEnv } from "#mcp/canonical-bridge-config";
7
+ import {
8
+ buildHostedMcpSpec,
9
+ buildRuntimeMcpSpec,
10
+ type HostedMcpSurface,
11
+ RUNTIME_MCP_KEY,
12
+ } from "#mcp/runtime-spec";
13
+ import { peerSessionBridgeIpcEnv } from "#mcp/session-comm/bridge-ipc-config";
14
+ import { bgBashContextCapability } from "#platform/background-bash/manager";
15
+ import {
16
+ AGENT_HEALTH_SERVER,
17
+ CANONICAL_MCP_PROXY_SERVER,
18
+ DECISION_SERVER,
19
+ envText,
20
+ FALLBACK_AGENT,
21
+ resolveTopicWorkspaceDir,
22
+ SESSION_COMM_SERVER,
23
+ SESSION_HISTORY_SERVER,
24
+ SYSTEM_HEALTH_SERVER,
25
+ TASK_SERVER,
26
+ TOKEN_STATS_SERVER,
27
+ TSCONFIG_PATH,
28
+ TSX_LOADER,
29
+ VAULT_SERVER,
30
+ WIKI_SERVER,
31
+ } from "#platform/config";
32
+ import { logger } from "#platform/logger";
33
+ import {
34
+ classifyForumMcpServers,
35
+ commonRuntimeMcpPolicy,
36
+ type RuntimeMcpScope,
37
+ } from "#platform/mcp-catalog-policy";
38
+ import { browserOwnerCapability } from "#platform/playwright/capability";
39
+ import {
40
+ buildPlaywrightMcpTransport,
41
+ CODEX_BROWSER_CAPABILITY_ENV,
42
+ } from "#platform/playwright/mcp-transport";
43
+ import { actorTopicScopeMaxAgeMs, encodeActorTopicScopeArg } from "#runtime/actor-topic-scope";
44
+ import { getRegisteredCronSession } from "#runtime/cron-sessions";
45
+ import { encodeRemoteSessionGrantArg } from "#runtime/remote-session-grant";
46
+ import type { HostMcpServerSpec } from "#runtime-gateway";
47
+ import { getTopic } from "#storage/api-topics";
48
+ import type {
49
+ ActorTopicScope,
50
+ AgentKind,
51
+ AgentQueryOptions,
52
+ PeerRuntimeBridgeContext,
53
+ RemoteSessionGrant,
54
+ } from "#types";
55
+ import type { TopicDto } from "#types/api";
56
+
57
+ export type { RuntimeMcpScope } from "#platform/mcp-catalog-policy";
58
+
59
+ /**
60
+ * Build the stdio transport spec for a Otium MCP server entry.
61
+ *
62
+ * claude/maestro launch the .ts server directly with `bun run` (fast, native
63
+ * TypeScript + bun:sqlite). codex CANNOT — codex 0.135's rmcp stdio client
64
+ * fails to handshake with bun-spawned servers (initialize is dropped/raced, so
65
+ * no tools reach the model), while pure-node servers connect reliably. So for
66
+ * the `codex` agent we launch the SAME server file via node + tsx, passing the
67
+ * tsconfig explicitly (servers run with cwd ≠ PROJECT_ROOT, so tsx can't find
68
+ * it on its own) so `@/*` path aliases resolve. Per-turn agent-aware config
69
+ * means switching agents mid-topic just works: each turn re-spawns with the
70
+ * right runtime.
71
+ */
72
+ export function buildStdioMcpServer(
73
+ agent: AgentKind | undefined,
74
+ serverFile: string,
75
+ serverArgs: string[],
76
+ env?: Record<string, string>,
77
+ ): Record<string, unknown> {
78
+ if (agent === "codex") {
79
+ return {
80
+ command: "node",
81
+ args: ["--import", TSX_LOADER, serverFile, ...serverArgs],
82
+ // Merged onto codex's inherited env (not a replacement) — verified.
83
+ env: { TSX_TSCONFIG_PATH: TSCONFIG_PATH, ...env },
84
+ };
85
+ }
86
+ return {
87
+ command: "bun",
88
+ args: ["run", serverFile, ...serverArgs],
89
+ ...(env ? { env } : {}),
90
+ };
91
+ }
92
+
93
+ function useHostedBuiltinMcp(): boolean {
94
+ return envText("NEGOTIUM_BUILTIN_MCP_TRANSPORT") !== "stdio";
95
+ }
96
+
97
+ function buildBuiltinMcpServer(
98
+ surface: HostedMcpSurface,
99
+ ctx: RuntimeMcpBuildContext,
100
+ stdio: () => Record<string, unknown>,
101
+ ): Record<string, unknown> {
102
+ if (!useHostedBuiltinMcp()) return stdio();
103
+ const agent = ctx.agent ?? FALLBACK_AGENT;
104
+ return buildHostedMcpSpec(agent, surface, {
105
+ userId: ctx.userId,
106
+ ...(ctx.actorUserId ? { actorUserId: ctx.actorUserId } : {}),
107
+ ...(ctx.actorTopicScope ? { actorTopicScope: ctx.actorTopicScope } : {}),
108
+ // Only the session-comm surface addresses remote rooms; the other hosted
109
+ // tokens (and the runtime token) never carry the grant, so it costs them
110
+ // no URL budget.
111
+ ...(surface === "session-comm" && ctx.remoteSession
112
+ ? { remoteSession: ctx.remoteSession }
113
+ : {}),
114
+ topicTitle: ctx.session,
115
+ ...(ctx.topicId ? { topicId: ctx.topicId } : {}),
116
+ ...(ctx.queryId ? { queryId: ctx.queryId } : {}),
117
+ ...(ctx.wikiTopicId ? { wikiTopicId: ctx.wikiTopicId } : {}),
118
+ ...(ctx.subagentParentTopicId ? { subagentParentTopicId: ctx.subagentParentTopicId } : {}),
119
+ ...(ctx.threadRootId ? { threadRootId: ctx.threadRootId } : {}),
120
+ cwd: ctx.cwd ?? (ctx.topicId ? resolveTopicWorkspaceDir(ctx.topicId) : process.cwd()),
121
+ agent,
122
+ ...(ctx.model ? { model: ctx.model } : {}),
123
+ ...(ctx.depth !== undefined ? { depth: ctx.depth } : {}),
124
+ ...(ctx.silent !== undefined ? { silent: ctx.silent } : {}),
125
+ ...(ctx.peerBridge ? { peerBridge: ctx.peerBridge } : {}),
126
+ });
127
+ }
128
+
129
+ // --- Playwright unavailable notifier + per-turn state ---
130
+ //
131
+ // When the playwright manager fails to allocate a long-lived MCP port,
132
+ // the catalog used to fall back to a per-turn stdio chromium that ran as
133
+ // a child of the agent CLI subprocess — which meant Chromium was bound
134
+ // to the agent's process tree and died on cascade-kill. We now skip the
135
+ // browser entry entirely (the playwright entry is omitted from the
136
+ // catalog for that turn) AND surface the gap two ways:
137
+ //
138
+ // 1. `notifyPlaywrightUnavailable` — fire-and-forget callback for the host
139
+ // (telegram bot) to push an alert to the current topic. Throttled
140
+ // per (userId, topic) with a 5-minute cooldown so a flaky
141
+ // manager doesn't spam the chat. Per-process state — restart clears.
142
+ //
143
+ // 2. `consumePlaywrightUnavailable` — the system-prompt builder reads
144
+ // this flag to add an explicit "Playwright unavailable this turn"
145
+ // reminder to the agent's user message, so the model knows to
146
+ // route around browser tools instead of hallucinating a call to a
147
+ // tool that was silently removed from the schema list.
148
+
149
+ type PlaywrightUnavailableContext = {
150
+ userId: string;
151
+ topic: string | undefined;
152
+ agent: AgentKind | undefined;
153
+ };
154
+
155
+ type PlaywrightUnavailableNotifier = (ctx: PlaywrightUnavailableContext) => void;
156
+
157
+ let _playwrightUnavailableNotifier: PlaywrightUnavailableNotifier | undefined;
158
+ const _playwrightUnavailableLastNotifiedAt = new Map<string, number>();
159
+ const _PLAYWRIGHT_UNAVAILABLE_COOLDOWN_MS = 5 * 60_000;
160
+
161
+ const _playwrightUnavailableThisTurn = new Set<string>();
162
+
163
+ function _playwrightUnavailableKey(userId: string, topic: string | undefined): string {
164
+ return `${userId}:${topic ?? ""}`;
165
+ }
166
+
167
+ /**
168
+ * Register the host's "playwright unavailable" alert sink. Called once at bot
169
+ * startup. Idempotent — last writer wins.
170
+ */
171
+ export function setPlaywrightUnavailableNotifier(cb: PlaywrightUnavailableNotifier): void {
172
+ _playwrightUnavailableNotifier = cb;
173
+ }
174
+
175
+ /**
176
+ * Mark the current turn as missing long-lived Playwright and notify the host.
177
+ * The playwright catalog entry calls this when it is built without a port, but
178
+ * route-level callers can call it earlier after ensurePlaywright fails so the
179
+ * system prompt for the same turn can include the unavailable reminder.
180
+ */
181
+ export function markPlaywrightUnavailable(ctx: PlaywrightUnavailableContext): void {
182
+ _markPlaywrightUnavailable(ctx);
183
+ }
184
+
185
+ function _markPlaywrightUnavailable(ctx: PlaywrightUnavailableContext): void {
186
+ // Mark unavailable for the next system-prompt build, regardless of
187
+ // notifier presence (the model-side reminder must always fire so the
188
+ // agent doesn't try to call a missing tool).
189
+ _playwrightUnavailableThisTurn.add(_playwrightUnavailableKey(ctx.userId, ctx.topic));
190
+
191
+ if (!_playwrightUnavailableNotifier) return;
192
+ const key = _playwrightUnavailableKey(ctx.userId, ctx.topic);
193
+ const now = Date.now();
194
+ const last = _playwrightUnavailableLastNotifiedAt.get(key) ?? 0;
195
+ if (now - last < _PLAYWRIGHT_UNAVAILABLE_COOLDOWN_MS) return;
196
+ _playwrightUnavailableLastNotifiedAt.set(key, now);
197
+ try {
198
+ _playwrightUnavailableNotifier(ctx);
199
+ } catch (err) {
200
+ logger.warn({ err }, "playwright unavailable notifier threw");
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Read + clear the "playwright unavailable this turn" flag for a
206
+ * (user, group, topic). Used by the system-prompt builder right before
207
+ * the agent query starts. Single consumer pattern — calling more than
208
+ * once per turn returns `false` for the second caller (intended; the
209
+ * reminder only needs to ride one prompt).
210
+ */
211
+ export function consumePlaywrightUnavailable(userId: string, topic: string | undefined): boolean {
212
+ const key = _playwrightUnavailableKey(userId, topic);
213
+ if (!_playwrightUnavailableThisTurn.has(key)) return false;
214
+ _playwrightUnavailableThisTurn.delete(key);
215
+ return true;
216
+ }
217
+
218
+ /**
219
+ * Single source of truth for MCP server registration.
220
+ *
221
+ * Each entry declares which scopes it participates in (`dm`, `forum`, `fork`, `cron`)
222
+ * and how to build its spawn config given a context. Public helpers
223
+ * (`getDmMcpServers`, `getForumMcpServers`, `getForkMcpServers`) and the
224
+ * derived forum-name views read from this catalog plus the node-assigned
225
+ * manifest overlay installed below. Adding a built-in MCP server remains a
226
+ * one-line append here instead of touching three places.
227
+ *
228
+ * Conventions:
229
+ * - `scopes` lists every scope the server should appear in by default.
230
+ * - `forumRequired: true` keeps the server even when a forum topic
231
+ * restricts the enabled list via `configure_mcp` (forum scope only).
232
+ * - `build(ctx)` returns the raw transport config (Claude-SDK shape).
233
+ * Codex callers funnel through `toCodexMcpServers` separately.
234
+ *
235
+ * Insertion order is preserved by `Object.entries`, which determines the
236
+ * order of server names in user-facing displays.
237
+ */
238
+
239
+ export interface RuntimeMcpBuildContext {
240
+ userId: string;
241
+ /** Product actor identity when it differs from the execution principal. */
242
+ actorUserId?: string;
243
+ /** Hub-asserted rooms the product actor may reach; forwarded into signed tokens. */
244
+ actorTopicScope?: ActorTopicScope;
245
+ /** Hub-issued per-turn remote session-comm grant; session-comm only. */
246
+ remoteSession?: RemoteSessionGrant;
247
+ /** Vault namespace when credentials belong to a different principal. */
248
+ vaultUserId?: string;
249
+ /** "dm" for DM scope, topic/session name for forum/fork. */
250
+ session: string;
251
+ /** REST/WS topic id when known. Prefer for authorization/scope checks. */
252
+ topicId?: string;
253
+ /** Direct parent topic id when the current topic is a subagent room. */
254
+ subagentParentTopicId?: string;
255
+ /** REST/WS query id when known. */
256
+ queryId?: string;
257
+ /** Topic id whose wiki memory should be read/written. */
258
+ wikiTopicId?: string;
259
+ agent?: AgentKind;
260
+ cwd?: string;
261
+ model?: string;
262
+ currentUserPrompt?: string;
263
+ depth?: number;
264
+ playwrightPort?: number;
265
+ playwrightCapability?: string;
266
+ bgBashPort?: number;
267
+ autoContinue?: boolean;
268
+ visualTools?: boolean;
269
+ fileDeliveryTools?: boolean;
270
+ silent?: boolean;
271
+ /** Thread this turn answers inside; forwarded to the runtime MCP context. */
272
+ threadRootId?: string;
273
+ peerBridge?: PeerRuntimeBridgeContext;
274
+ }
275
+
276
+ export interface RuntimeMcpCatalogEntry {
277
+ scopes: readonly RuntimeMcpScope[];
278
+ /** Forum scope only: cannot be removed via the enabled whitelist. */
279
+ forumRequired?: boolean;
280
+ /**
281
+ * Returns the raw transport spec (Claude-SDK shape), or `null` to
282
+ * signal "this server is unavailable for this turn — omit it from the
283
+ * catalog entirely." Used by the playwright entry when the manager
284
+ * cannot provide a long-lived port.
285
+ */
286
+ build(ctx: RuntimeMcpBuildContext): Record<string, unknown> | null;
287
+ }
288
+
289
+ // --- Playwright transport builders ---
290
+
291
+ export { browserOwnerCapability, buildPlaywrightMcpTransport, CODEX_BROWSER_CAPABILITY_ENV };
292
+
293
+ export function browserOwnerForContext(ctx: {
294
+ userId?: string;
295
+ session?: string;
296
+ topicId?: string;
297
+ }): string | undefined {
298
+ if (ctx.topicId) return `topic:${ctx.topicId}`;
299
+ if (ctx.userId && ctx.session) return `user:${ctx.userId}:${ctx.session}`;
300
+ return undefined;
301
+ }
302
+
303
+ function longLivedHttpMcp(agent: AgentKind | undefined, port: number) {
304
+ return agent === "codex"
305
+ ? { url: `http://127.0.0.1:${port}/mcp` }
306
+ : { type: "sse" as const, url: `http://127.0.0.1:${port}/sse` };
307
+ }
308
+
309
+ // cua-rs implements Streamable HTTP only; unlike browser-rs, it does not
310
+ // expose the legacy SSE endpoint. The port is installed by the node-owned
311
+ // process manager once its singleton is ready.
312
+ let cuaRsMcpPort: number | undefined;
313
+ // cua-rs 0.8.0 requires `Authorization: Bearer` on /mcp, because loopback is not
314
+ // an authorization boundary -- any local process, a web page included, could
315
+ // otherwise drive the whole desktop. The node picks the token, hands it to the
316
+ // child as CUA_HTTP_TOKEN, and publishes it here so turns can present it. Kept
317
+ // beside the port because they are one fact: without both, the URL is useless.
318
+ let cuaRsMcpToken: string | undefined;
319
+
320
+ export function setCuaRsMcpPort(port: number | undefined, token?: string): void {
321
+ if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65_535)) {
322
+ throw new Error(`invalid cua-rs MCP port: ${port}`);
323
+ }
324
+ cuaRsMcpPort = port;
325
+ cuaRsMcpToken = port === undefined ? undefined : token;
326
+ }
327
+
328
+ function cuaRsHttpMcp(agent: AgentKind | undefined, port: number, token: string | undefined) {
329
+ const url = `http://127.0.0.1:${port}/mcp`;
330
+ // No token means an older cua-rs that does not ask for one. Sending the header
331
+ // anyway would be harmless, but omitting it keeps the config honest about what
332
+ // the running server actually requires.
333
+ const headers = token ? { Authorization: `Bearer ${token}` } : undefined;
334
+ // The shape is otherwise unchanged from before the token existed, including
335
+ // `type` for codex: only the header field is added, and only when there is a
336
+ // token to put in it. Codex spells that field `http_headers`.
337
+ const base = { type: "http" as const, url };
338
+ if (!headers) return base;
339
+ return agent === "codex" ? { ...base, http_headers: headers } : { ...base, headers };
340
+ }
341
+
342
+ function backgroundBashTransport(
343
+ agent: AgentKind | undefined,
344
+ port: number,
345
+ userId: string,
346
+ topic: string,
347
+ ) {
348
+ const capability = bgBashContextCapability(userId, topic);
349
+ const headers = {
350
+ "X-Background-Bash-User": userId,
351
+ "X-Background-Bash-Topic": topic,
352
+ "X-Background-Bash-Capability": capability,
353
+ };
354
+ if (agent === "codex") return { url: `http://127.0.0.1:${port}/mcp`, http_headers: headers };
355
+ if (agent === "maestro") {
356
+ const query = new URLSearchParams({ user: userId, topic, capability });
357
+ return { type: "sse" as const, url: `http://127.0.0.1:${port}/sse?${query}` };
358
+ }
359
+ return { type: "sse" as const, url: `http://127.0.0.1:${port}/sse`, headers };
360
+ }
361
+
362
+ // --- Catalog ---
363
+
364
+ const MCP_CATALOG: Record<string, RuntimeMcpCatalogEntry> = {
365
+ playwright: {
366
+ ...commonRuntimeMcpPolicy("playwright"),
367
+ build({ userId, session, topicId, playwrightPort, playwrightCapability, agent }) {
368
+ // Codex and Maestro use Streamable HTTP while Claude uses SSE. Both
369
+ // transports terminate at the same long-lived browser/profile server.
370
+ if (playwrightPort && playwrightCapability) {
371
+ const owner = browserOwnerForContext({ userId, session, topicId });
372
+ if (!owner) return null;
373
+ return buildPlaywrightMcpTransport(playwrightPort, owner, playwrightCapability, agent);
374
+ }
375
+ // No port available — the playwright manager could not allocate one
376
+ // for this turn. The previous behavior was to fall back to a per-turn
377
+ // stdio chromium, but that made Chromium a child of the agent CLI
378
+ // process tree, so cascade-kill on agent exit took the browser down
379
+ // with it (visible in pm2 as "Chromium died with claude"). We now
380
+ // omit the playwright entry from this turn's catalog AND fire two
381
+ // side-effects:
382
+ // 1. notify the host so it can push an alert into the current
383
+ // topic (rate-limited 5min per scope key);
384
+ // 2. mark the (user, topic) as "playwright unavailable
385
+ // this turn" so the system-prompt builder can tell the model
386
+ // explicitly, instead of letting the model hallucinate a call
387
+ // to a tool whose schema silently vanished.
388
+ _markPlaywrightUnavailable({
389
+ userId,
390
+ topic: session,
391
+ agent,
392
+ });
393
+ return null;
394
+ },
395
+ },
396
+ [RUNTIME_MCP_KEY]: {
397
+ ...commonRuntimeMcpPolicy("runtime"),
398
+ build({
399
+ userId,
400
+ actorUserId,
401
+ actorTopicScope,
402
+ session,
403
+ topicId,
404
+ queryId,
405
+ agent,
406
+ cwd,
407
+ model,
408
+ currentUserPrompt,
409
+ autoContinue,
410
+ visualTools,
411
+ fileDeliveryTools,
412
+ threadRootId,
413
+ peerBridge,
414
+ }) {
415
+ if (!topicId || !agent) return null;
416
+ const switchTargets = explicitAgentSwitchTargets(currentUserPrompt);
417
+ return buildRuntimeMcpSpec(agent, {
418
+ // Runtime tools mutate node-owned state, so authorization stays bound
419
+ // to the canonical execution principal. Keep the product-side human
420
+ // actor separately for attribution instead of replacing the identity
421
+ // that appears in this node's topic participant roster.
422
+ userId,
423
+ ...(actorUserId ? { actorUserId } : {}),
424
+ ...(actorTopicScope ? { actorTopicScope } : {}),
425
+ topicId,
426
+ topicTitle: session,
427
+ queryId,
428
+ cwd: cwd ?? resolveTopicWorkspaceDir(topicId),
429
+ agent,
430
+ model,
431
+ // Derived here, from the full prompt, so the signed token carries the
432
+ // gate's answer (bounded) instead of the prompt (unbounded); see
433
+ // `explicitAgentSwitchTargets`.
434
+ ...(switchTargets.length ? { explicitAgentSwitchTargets: switchTargets } : {}),
435
+ autoContinue,
436
+ visualTools,
437
+ fileDeliveryTools,
438
+ ...(threadRootId ? { threadRootId } : {}),
439
+ peerBridge,
440
+ });
441
+ },
442
+ },
443
+ "token-stats": {
444
+ ...commonRuntimeMcpPolicy("token-stats"),
445
+ build(ctx) {
446
+ return buildBuiltinMcpServer("token-stats", ctx, () =>
447
+ buildStdioMcpServer(ctx.agent, TOKEN_STATS_SERVER, [`--user-id=${ctx.userId}`]),
448
+ );
449
+ },
450
+ },
451
+ // Otium-owned shared task system. This is the only authoritative task/todo
452
+ // surface across claude/codex/maestro; provider-native task stores are
453
+ // blocked or ignored because they do not survive agent switches.
454
+ task: {
455
+ ...commonRuntimeMcpPolicy("task"),
456
+ build(ctx) {
457
+ const { userId, session, topicId, queryId, agent, peerBridge } = ctx;
458
+ if (peerBridge) {
459
+ if (!topicId || !queryId) return null;
460
+ const env = canonicalMcpBridgeEnv({
461
+ surface: "task",
462
+ userId,
463
+ topicId,
464
+ queryId,
465
+ peerBridge,
466
+ });
467
+ return env
468
+ ? buildStdioMcpServer(agent, CANONICAL_MCP_PROXY_SERVER, ["--surface=task"], env)
469
+ : null;
470
+ }
471
+ const args = [`--user-id=${userId}`, `--topic=${session}`];
472
+ if (topicId) args.push(`--topic-id=${topicId}`);
473
+ return buildBuiltinMcpServer("task", ctx, () =>
474
+ buildStdioMcpServer(agent, TASK_SERVER, args),
475
+ );
476
+ },
477
+ },
478
+ decision: {
479
+ ...commonRuntimeMcpPolicy("decision"),
480
+ build(ctx) {
481
+ const { userId, session, topicId, queryId, agent, model, peerBridge } = ctx;
482
+ if (peerBridge) {
483
+ if (!topicId || !queryId) return null;
484
+ const env = canonicalMcpBridgeEnv({
485
+ surface: "decision",
486
+ userId,
487
+ topicId,
488
+ queryId,
489
+ peerBridge,
490
+ });
491
+ return env
492
+ ? buildStdioMcpServer(agent, CANONICAL_MCP_PROXY_SERVER, ["--surface=decision"], env)
493
+ : null;
494
+ }
495
+ const args = [
496
+ `--user-id=${userId}`,
497
+ `--topic=${session}`,
498
+ `--agent=${agent ?? FALLBACK_AGENT}`,
499
+ ];
500
+ if (topicId) args.push(`--topic-id=${topicId}`);
501
+ if (model) args.push(`--model=${model}`);
502
+ return buildBuiltinMcpServer("decision", ctx, () =>
503
+ buildStdioMcpServer(agent, DECISION_SERVER, args),
504
+ );
505
+ },
506
+ },
507
+ "session-history": {
508
+ ...commonRuntimeMcpPolicy("session-history"),
509
+ build(ctx) {
510
+ const { userId, session, topicId, queryId, agent, peerBridge } = ctx;
511
+ if (peerBridge) {
512
+ if (!topicId || !queryId) return null;
513
+ const env = canonicalMcpBridgeEnv({
514
+ surface: "session-history",
515
+ userId,
516
+ topicId,
517
+ queryId,
518
+ peerBridge,
519
+ });
520
+ return env
521
+ ? buildStdioMcpServer(
522
+ agent,
523
+ CANONICAL_MCP_PROXY_SERVER,
524
+ ["--surface=session-history"],
525
+ env,
526
+ )
527
+ : null;
528
+ }
529
+ const args = [`--user-id=${userId}`, `--topic=${session}`];
530
+ if (topicId) args.push(`--topic-id=${topicId}`);
531
+ return buildBuiltinMcpServer("session-history", ctx, () =>
532
+ buildStdioMcpServer(agent, SESSION_HISTORY_SERVER, args),
533
+ );
534
+ },
535
+ },
536
+ "session-comm": {
537
+ // Exposed in `manager` scope as well so the General-topic manager agent
538
+ // can wake fresh-created topics via tell_session/ask_session right after
539
+ // create_topic. Without this, a newly-created topic would stay in the
540
+ // "fresh-start ready" state until the user manually visits it.
541
+ ...commonRuntimeMcpPolicy("session-comm"),
542
+ build(ctx) {
543
+ const {
544
+ userId,
545
+ actorUserId,
546
+ actorTopicScope,
547
+ remoteSession,
548
+ session,
549
+ topicId,
550
+ subagentParentTopicId,
551
+ agent,
552
+ depth = 0,
553
+ silent,
554
+ threadRootId,
555
+ peerBridge,
556
+ } = ctx;
557
+ const effectiveAgent = agent ?? FALLBACK_AGENT;
558
+ const cronSessionId = topicId
559
+ ? getRegisteredCronSession(topicId, effectiveAgent)?.sessionId
560
+ : undefined;
561
+ const args = [
562
+ `--user-id=${userId}`,
563
+ ...(actorUserId ? [`--actor-user-id=${actorUserId}`] : []),
564
+ ...(actorTopicScope
565
+ ? [
566
+ `--actor-topic-scope=${encodeActorTopicScopeArg(actorTopicScope)}`,
567
+ // The child does not inherit this process's env; hand it the
568
+ // same freshness window the hosted tools apply.
569
+ `--actor-topic-scope-max-age-ms=${actorTopicScopeMaxAgeMs()}`,
570
+ ]
571
+ : []),
572
+ ...(remoteSession
573
+ ? [`--remote-session-grant=${encodeRemoteSessionGrantArg(remoteSession)}`]
574
+ : []),
575
+ `--topic=${session}`,
576
+ ...(topicId ? [`--topic-id=${topicId}`] : []),
577
+ ...(subagentParentTopicId ? [`--subagent-parent-topic-id=${subagentParentTopicId}`] : []),
578
+ `--depth=${depth}`,
579
+ `--agent=${effectiveAgent}`,
580
+ ...(cronSessionId ? [`--cron-session-id=${cronSessionId}`] : []),
581
+ ...(silent ? ["--reply-only=true"] : []),
582
+ // Turn-scoped, like `--peer-host-query-id`: this config is rebuilt for
583
+ // every turn, so an `ask_session` raised inside a thread can record
584
+ // where its answer belongs.
585
+ ...(threadRootId ? [`--thread-root-id=${threadRootId}`] : []),
586
+ ...(peerBridge ? [`--peer-host-query-id=${peerBridge.hostQueryId}`] : []),
587
+ ];
588
+ return buildBuiltinMcpServer("session-comm", ctx, () =>
589
+ buildStdioMcpServer(
590
+ effectiveAgent,
591
+ SESSION_COMM_SERVER,
592
+ args,
593
+ peerBridge ? peerSessionBridgeIpcEnv() : undefined,
594
+ ),
595
+ );
596
+ },
597
+ },
598
+ wiki: {
599
+ ...commonRuntimeMcpPolicy("wiki"),
600
+ build(ctx) {
601
+ const { userId, session, topicId, queryId, wikiTopicId, agent, peerBridge } = ctx;
602
+ if (peerBridge) {
603
+ if (!topicId || !queryId) return null;
604
+ const env = canonicalMcpBridgeEnv({
605
+ surface: "wiki",
606
+ userId,
607
+ topicId,
608
+ queryId,
609
+ peerBridge,
610
+ });
611
+ return env
612
+ ? buildStdioMcpServer(agent, CANONICAL_MCP_PROXY_SERVER, ["--surface=wiki"], env)
613
+ : null;
614
+ }
615
+ const args = [`--user-id=${userId}`];
616
+ if (topicId) args.push(`--current-topic-id=${topicId}`);
617
+ // Prefer the REST topic id so wiki_write writes filenames and SQLite
618
+ // briefs keyed the same way the topic wiki API reads them.
619
+ const resolvedWikiTopicId =
620
+ wikiTopicId ?? topicId ?? (session !== "dm" ? session : undefined);
621
+ if (resolvedWikiTopicId) args.push(`--topic-id=${resolvedWikiTopicId}`);
622
+ args.push("--surface=wiki");
623
+ return buildBuiltinMcpServer("wiki", { ...ctx, wikiTopicId: resolvedWikiTopicId }, () =>
624
+ buildStdioMcpServer(agent, WIKI_SERVER, args),
625
+ );
626
+ },
627
+ },
628
+ skills: {
629
+ ...commonRuntimeMcpPolicy("skills"),
630
+ build(ctx) {
631
+ const { userId, topicId, agent } = ctx;
632
+ const args = [`--user-id=${userId}`, "--surface=skills"];
633
+ if (topicId) args.push(`--topic-id=${topicId}`);
634
+ return buildBuiltinMcpServer("skills", ctx, () =>
635
+ buildStdioMcpServer(agent, WIKI_SERVER, args),
636
+ );
637
+ },
638
+ },
639
+ "system-health": {
640
+ ...commonRuntimeMcpPolicy("system-health"),
641
+ build(ctx) {
642
+ return buildBuiltinMcpServer("system-health", ctx, () =>
643
+ buildStdioMcpServer(ctx.agent, SYSTEM_HEALTH_SERVER, []),
644
+ );
645
+ },
646
+ },
647
+ "background-bash": {
648
+ ...commonRuntimeMcpPolicy("background-bash"),
649
+ build({ agent, bgBashPort, userId, topicId }) {
650
+ // Key the whole pipeline by the canonical topic id: it flows through the
651
+ // capability, the request context, and the completion inbox filename
652
+ // (sessionInboxPath) so the exiting process's output is routed back to
653
+ // the exact originating topic. A title/session fallback would be encoded
654
+ // as if it were an id and the inbox worker would fail to resolve it, so
655
+ // background-bash is simply unavailable without a topic id.
656
+ if (bgBashPort === undefined || !topicId) return null;
657
+ return backgroundBashTransport(agent, bgBashPort, userId, topicId);
658
+ },
659
+ },
660
+ "agent-health": {
661
+ ...commonRuntimeMcpPolicy("agent-health"),
662
+ build(ctx) {
663
+ const { userId, agent } = ctx;
664
+ const args = [`--user-id=${userId}`];
665
+ return buildBuiltinMcpServer("agent-health", ctx, () =>
666
+ buildStdioMcpServer(agent, AGENT_HEALTH_SERVER, args),
667
+ );
668
+ },
669
+ },
670
+ vault: {
671
+ ...commonRuntimeMcpPolicy("vault"),
672
+ build(ctx) {
673
+ const { userId, vaultUserId, agent } = ctx;
674
+ // Normal turns use {{KEY}} directly in tool inputs. Keep the Vault MCP
675
+ // surface focused on key discovery; broker tools remain available from
676
+ // the public factory for compatibility but are no longer the default UX.
677
+ const args = [`--user-id=${vaultUserId ?? userId}`];
678
+ if (agent !== "codex") args.push("--list-only=true");
679
+ return buildBuiltinMcpServer("vault", { ...ctx, userId: vaultUserId ?? userId }, () =>
680
+ buildStdioMcpServer(agent, VAULT_SERVER, args),
681
+ );
682
+ },
683
+ },
684
+ // macOS desktop control, delegated to maestrojeong/cua-rs rather than
685
+ // reimplemented. The node owns one persistent Streamable HTTP process;
686
+ // turns only receive its loopback URL and must never spawn a stdio copy.
687
+ "cua-rs": {
688
+ ...commonRuntimeMcpPolicy("cua-rs"),
689
+ build({ agent }) {
690
+ return cuaRsMcpPort ? cuaRsHttpMcp(agent, cuaRsMcpPort, cuaRsMcpToken) : null;
691
+ },
692
+ },
693
+ };
694
+
695
+ /**
696
+ * Locate the `cua-rs` binary, or `null` when it is not installed.
697
+ *
698
+ * Checked in order of specificity: an explicit env override for anyone running
699
+ * a local build, then the installer's default target, then `/usr/local/bin`
700
+ * for a `--bin-dir` install. PATH is deliberately not consulted -- the server
701
+ * is spawned by a supervised host process whose PATH is not the user's shell
702
+ * PATH, so a PATH lookup would succeed in a terminal and fail under pm2.
703
+ */
704
+ export function resolveCuaRsBinary(platform: NodeJS.Platform = process.platform): string | null {
705
+ if (platform !== "darwin") return null;
706
+ const candidates = [
707
+ envText("NEGOTIUM_CUA_RS_BIN"),
708
+ join(homedir(), ".local", "bin", "cua-rs"),
709
+ "/usr/local/bin/cua-rs",
710
+ ].filter((p): p is string => Boolean(p));
711
+ for (const candidate of candidates) {
712
+ try {
713
+ accessSync(candidate, fsConstants.X_OK);
714
+ return candidate;
715
+ } catch {
716
+ // Not there, or not executable. Try the next one.
717
+ }
718
+ }
719
+ return null;
720
+ }
721
+
722
+ // --- Derived catalog views ---
723
+
724
+ export type NodeMcpEntry =
725
+ | { key: string; kind: "http"; port: number }
726
+ | {
727
+ key: string;
728
+ kind: "http-instance";
729
+ ensurePort: (instanceKey: string) => Promise<number>;
730
+ }
731
+ | { key: string; kind: "stdio"; command: string; args?: string[]; env?: Record<string, string> };
732
+
733
+ let nodeMcpEntries: NodeMcpEntry[] = [];
734
+ const resolvedNodeMcpPorts = new WeakMap<
735
+ Extract<NodeMcpEntry, { kind: "http-instance" }>,
736
+ Map<string, number>
737
+ >();
738
+
739
+ /** All forum-eligible MCP server names, in display order. */
740
+ const allForumMcpServerNames: string[] = [];
741
+ export const ALL_FORUM_MCP_SERVER_NAMES: readonly string[] = allForumMcpServerNames;
742
+
743
+ /** Forum servers that cannot be removed via the enabled whitelist. */
744
+ const requiredForumMcpServers: string[] = [];
745
+ export const REQUIRED_FORUM_MCP_SERVERS: readonly string[] = requiredForumMcpServers;
746
+
747
+ /** Forum servers that can be toggled via the enabled whitelist (not required). */
748
+ const optionalForumMcpServers: string[] = [];
749
+ export const OPTIONAL_FORUM_MCP_SERVERS: readonly string[] = optionalForumMcpServers;
750
+
751
+ function refreshForumCatalogViews(): void {
752
+ const { all, required, optional } = classifyForumMcpServers(MCP_CATALOG);
753
+ const nodeNames = nodeMcpEntries.map((entry) => entry.key);
754
+ const allWithNodeEntries = [...new Set([...all, ...nodeNames])];
755
+ const optionalWithNodeEntries = [...new Set([...optional, ...nodeNames])];
756
+ allForumMcpServerNames.splice(0, allForumMcpServerNames.length, ...allWithNodeEntries);
757
+ requiredForumMcpServers.splice(0, requiredForumMcpServers.length, ...required);
758
+ optionalForumMcpServers.splice(0, optionalForumMcpServers.length, ...optionalWithNodeEntries);
759
+ }
760
+
761
+ refreshForumCatalogViews();
762
+
763
+ /**
764
+ * Mount one MCP capability supplied by an optional node module.
765
+ *
766
+ * Registration happens once at node startup, never in the per-event hot path.
767
+ * The returned cleanup closure only removes the exact entry installed by this
768
+ * call, making module stop/restart safe.
769
+ */
770
+ export function registerRuntimeMcpServer(name: string, entry: RuntimeMcpCatalogEntry): () => void {
771
+ const key = name.trim();
772
+ if (!key || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(key)) {
773
+ throw new Error(`invalid runtime MCP server name: ${name}`);
774
+ }
775
+ if (MCP_CATALOG[key]) throw new Error(`runtime MCP server already registered: ${key}`);
776
+ MCP_CATALOG[key] = entry;
777
+ refreshForumCatalogViews();
778
+ return () => {
779
+ if (MCP_CATALOG[key] !== entry) return;
780
+ delete MCP_CATALOG[key];
781
+ refreshForumCatalogViews();
782
+ };
783
+ }
784
+
785
+ /**
786
+ * Format the active MCP config for display (used by get_mcp_config /
787
+ * get_topic_mcp / configure_mcp response).
788
+ *
789
+ * In whitelist mode the DB stores only the user-chosen optional servers;
790
+ * required servers are always active but never written to the whitelist.
791
+ * This helper surfaces that split so the model never confuses "not in
792
+ * whitelist" with "not active".
793
+ */
794
+ export function formatMcpStatus(config: {
795
+ enabled: string[] | null;
796
+ extra?: Record<string, unknown>;
797
+ }): string[] {
798
+ const extraNames = Object.keys(config.extra ?? {});
799
+
800
+ if (config.enabled === null) {
801
+ const total = ALL_FORUM_MCP_SERVER_NAMES.length + extraNames.length;
802
+ return [
803
+ `설정 방식: 기본값 (전체 활성)`,
804
+ `활성 서버 (${total}개): ${[...ALL_FORUM_MCP_SERVER_NAMES, ...extraNames].join(", ")}`,
805
+ `추가 서버: ${extraNames.length > 0 ? extraNames.join(", ") : "없음"}`,
806
+ ];
807
+ }
808
+
809
+ // whitelist mode: stored list may or may not include required servers
810
+ // (old entries might have them; new entries won't). Either way, split
811
+ // by required vs optional for display.
812
+ const availableOptional = new Set(OPTIONAL_FORUM_MCP_SERVERS);
813
+ const optionalActive = [...new Set(config.enabled)].filter((name) => availableOptional.has(name));
814
+ const total = REQUIRED_FORUM_MCP_SERVERS.length + optionalActive.length + extraNames.length;
815
+ return [
816
+ `설정 방식: whitelist`,
817
+ `필수 서버 (항상 활성, ${REQUIRED_FORUM_MCP_SERVERS.length}개): ${REQUIRED_FORUM_MCP_SERVERS.join(", ")}`,
818
+ `선택 서버 (whitelist, ${optionalActive.length}개): ${optionalActive.length > 0 ? optionalActive.join(", ") : "없음"}`,
819
+ `실제 활성 합계: ${total}개`,
820
+ `추가 서버: ${extraNames.length > 0 ? extraNames.join(", ") : "없음"}`,
821
+ ``,
822
+ `선택 가능 서버 전체 (${OPTIONAL_FORUM_MCP_SERVERS.length}개): ${OPTIONAL_FORUM_MCP_SERVERS.join(", ")}`,
823
+ ];
824
+ }
825
+
826
+ // --- Builders for each scope ---
827
+
828
+ // ── Node-assigned MCP servers (mcp-host manifest) ───────────────────
829
+ //
830
+ // The per-node MCP manifest (`negotium mcp add`) lives in @negotium/mcp-host,
831
+ // which depends on core — so core cannot read it directly. Instead the host
832
+ // process resolves the manifest at node start (ensuring long-lived http
833
+ // servers are running and have ports) and installs the result here. Entries
834
+ // then ride every eligible scope's catalog, subject to the same per-topic
835
+ // `enabled` whitelist as optional built-ins.
836
+
837
+ /** Install the node's assigned MCP servers. Last writer wins (host restart-safe). */
838
+ export function setNodeMcpServers(entries: NodeMcpEntry[]): void {
839
+ nodeMcpEntries = entries.filter((entry) => !(entry.key in MCP_CATALOG));
840
+ const dropped = entries.length - nodeMcpEntries.length;
841
+ if (dropped > 0) {
842
+ logger.warn({ dropped }, "setNodeMcpServers: entries shadowing built-in catalog keys ignored");
843
+ }
844
+ refreshForumCatalogViews();
845
+ }
846
+
847
+ export function getNodeMcpServers(): readonly NodeMcpEntry[] {
848
+ return nodeMcpEntries;
849
+ }
850
+
851
+ /** Prevent host grants from replacing node-owned MCP servers. */
852
+ export function isReservedRuntimeMcpServerName(name: string): boolean {
853
+ return Object.hasOwn(MCP_CATALOG, name) || nodeMcpEntries.some((entry) => entry.key === name);
854
+ }
855
+
856
+ /** Host MCP servers that administer the workspace; only a manager room may receive them. */
857
+ const MANAGER_ONLY_HOST_MCP_NAMES = new Set(["topic-admin"]);
858
+
859
+ /**
860
+ * Why `topic` may not receive host MCP servers named `names`, or null when it
861
+ * may. A manager room takes any of them. An ordinary room takes everything but
862
+ * the manager administration surface, so a host can scope its own tools to a
863
+ * room. A subagent room takes none.
864
+ */
865
+ export function hostMcpGrantRefusal(
866
+ topic: Pick<TopicDto, "kind" | "isSubagent">,
867
+ names: readonly string[],
868
+ ): string | null {
869
+ if (topic.kind === "manager") return null;
870
+ if (topic.isSubagent) return "hostMcpServers is not allowed for subagent topics";
871
+ const managerOnly = names.find((name) => MANAGER_ONLY_HOST_MCP_NAMES.has(name));
872
+ return managerOnly ? `${managerOnly} is only allowed for manager topics` : null;
873
+ }
874
+
875
+ function withoutManagerOnlyHostMcpServers(
876
+ hostMcpServers: Record<string, HostMcpServerSpec> | undefined,
877
+ ): Record<string, HostMcpServerSpec> | undefined {
878
+ if (!hostMcpServers) return undefined;
879
+ return Object.fromEntries(
880
+ Object.entries(hostMcpServers).filter(([name]) => !MANAGER_ONLY_HOST_MCP_NAMES.has(name)),
881
+ );
882
+ }
883
+
884
+ function mergeHostMcpServers(
885
+ base: Record<string, unknown>,
886
+ hostMcpServers: Record<string, HostMcpServerSpec> | undefined,
887
+ ): Record<string, unknown> {
888
+ if (!hostMcpServers) return base;
889
+ for (const name of Object.keys(hostMcpServers)) {
890
+ if (Object.hasOwn(base, name) || isReservedRuntimeMcpServerName(name)) {
891
+ throw new Error(`host MCP server name conflicts with node catalog: ${name}`);
892
+ }
893
+ }
894
+ return { ...base, ...hostMcpServers };
895
+ }
896
+
897
+ function buildNodeMcpSpecs(
898
+ agent: AgentKind | undefined,
899
+ filter: (name: string) => boolean,
900
+ ctx: Pick<RuntimeMcpBuildContext, "topicId" | "userId" | "session">,
901
+ ): Record<string, unknown> {
902
+ const out: Record<string, unknown> = {};
903
+ for (const entry of nodeMcpEntries) {
904
+ if (!filter(entry.key)) continue;
905
+ if (entry.kind === "http") {
906
+ out[entry.key] = longLivedHttpMcp(agent, entry.port);
907
+ continue;
908
+ }
909
+ if (entry.kind === "http-instance") {
910
+ const port = resolvedNodeMcpPorts.get(entry)?.get(nodeMcpInstanceKey(ctx));
911
+ if (port !== undefined) out[entry.key] = longLivedHttpMcp(agent, port);
912
+ continue;
913
+ }
914
+ out[entry.key] = {
915
+ command: entry.command,
916
+ args: entry.args ?? [],
917
+ ...(entry.env ? { env: entry.env } : {}),
918
+ };
919
+ }
920
+ return out;
921
+ }
922
+
923
+ function nodeMcpInstanceKey(
924
+ ctx: Pick<RuntimeMcpBuildContext, "topicId" | "userId" | "session">,
925
+ ): string {
926
+ return ctx.topicId ?? `user:${ctx.userId}:session:${ctx.session}`;
927
+ }
928
+
929
+ /**
930
+ * Lazily prepare per-topic HTTP manifest entries before a provider resolves
931
+ * its otherwise-synchronous MCP config. One failed custom server is omitted
932
+ * from that turn without taking down the rest of the runtime catalog.
933
+ */
934
+ export async function prepareNodeMcpServersForQuery(opts: AgentQueryOptions): Promise<void> {
935
+ if (
936
+ opts.toolPolicy ||
937
+ opts.sessionType === "cron" ||
938
+ nodeMcpEntries.every((entry) => entry.kind !== "http-instance")
939
+ ) {
940
+ return;
941
+ }
942
+
943
+ const forum = !["dm", "ephemeral", "manager"].includes(opts.sessionType ?? "forum");
944
+ const enabled = opts.mcpEnabled ?? null;
945
+ const instanceKey = nodeMcpInstanceKey({
946
+ topicId: opts.topicId,
947
+ userId: opts.userId || "local",
948
+ session: opts.session || "default",
949
+ });
950
+
951
+ await Promise.all(
952
+ nodeMcpEntries.map(async (entry) => {
953
+ if (entry.kind !== "http-instance") return;
954
+ if (forum && enabled !== null && !enabled.includes(entry.key)) return;
955
+ let ports = resolvedNodeMcpPorts.get(entry);
956
+ if (!ports) {
957
+ ports = new Map();
958
+ resolvedNodeMcpPorts.set(entry, ports);
959
+ }
960
+ try {
961
+ const port = await entry.ensurePort(instanceKey);
962
+ if (!Number.isInteger(port) || port < 1 || port > 65_535) {
963
+ throw new Error(`invalid port ${port}`);
964
+ }
965
+ ports.set(instanceKey, port);
966
+ } catch (err) {
967
+ ports.delete(instanceKey);
968
+ logger.warn(
969
+ { err, key: entry.key, instanceKey },
970
+ "node mcp: failed to prepare instance-scoped server",
971
+ );
972
+ }
973
+ }),
974
+ );
975
+ }
976
+
977
+ function buildScope(
978
+ scope: RuntimeMcpScope,
979
+ ctx: RuntimeMcpBuildContext,
980
+ filter: (name: string) => boolean = () => true,
981
+ ): Record<string, unknown> {
982
+ const out: Record<string, unknown> = {};
983
+ for (const [name, entry] of Object.entries(MCP_CATALOG)) {
984
+ if (!entry.scopes.includes(scope)) continue;
985
+ if (!filter(name)) continue;
986
+ // `null` from build() means "skip this server for this turn" —
987
+ // currently used by the playwright entry when no long-lived port
988
+ // is available.
989
+ const spec = entry.build(ctx);
990
+ if (spec === null) continue;
991
+ out[name] = spec;
992
+ }
993
+ // Node-assigned MCPs join every scope except cron (scheduled runs keep the
994
+ // deliberately narrow built-in set).
995
+ if (scope !== "cron") {
996
+ Object.assign(out, buildNodeMcpSpecs(ctx.agent, filter, ctx));
997
+ }
998
+ return out;
999
+ }
1000
+
1001
+ /** DM session: catalog entries with `dm` scope, no whitelist. */
1002
+ export function getDmMcpServers(opts: {
1003
+ userId: string;
1004
+ session?: string;
1005
+ topicId?: string;
1006
+ agent?: AgentKind;
1007
+ playwrightPort?: number;
1008
+ playwrightCapability?: string;
1009
+ }) {
1010
+ return buildScope("dm", {
1011
+ userId: opts.userId,
1012
+ session: opts.session ?? "dm",
1013
+ topicId: opts.topicId,
1014
+ agent: opts.agent,
1015
+ playwrightPort: opts.playwrightPort,
1016
+ playwrightCapability: opts.playwrightCapability,
1017
+ });
1018
+ }
1019
+
1020
+ /**
1021
+ * Manager session: lives in the caller's private General API topic. Owns topic CRUD,
1022
+ * invite/user admin, and cross-topic MCP toggling through `topic-admin`,
1023
+ * plus general utilities. Browser-heavy work belongs in dedicated topics, so
1024
+ * Playwright is intentionally excluded here.
1025
+ * No whitelist — manager-scope catalog entries are loaded as-is.
1026
+ */
1027
+ export function getManagerMcpServers(opts: {
1028
+ userId: string;
1029
+ actorUserId?: string;
1030
+ actorTopicScope?: ActorTopicScope;
1031
+ remoteSession?: RemoteSessionGrant;
1032
+ session?: string;
1033
+ topicId?: string;
1034
+ queryId?: string;
1035
+ wikiTopicId?: string;
1036
+ agent?: AgentKind;
1037
+ cwd?: string;
1038
+ model?: string;
1039
+ currentUserPrompt?: string;
1040
+ playwrightPort?: number;
1041
+ playwrightCapability?: string;
1042
+ autoContinue?: boolean;
1043
+ visualTools?: boolean;
1044
+ fileDeliveryTools?: boolean;
1045
+ }) {
1046
+ if (!opts.topicId) {
1047
+ throw new Error("getManagerMcpServers: private General topicId is required");
1048
+ }
1049
+ const topicId = opts.topicId;
1050
+ return buildScope("manager", {
1051
+ userId: opts.userId,
1052
+ actorUserId: opts.actorUserId,
1053
+ actorTopicScope: opts.actorTopicScope,
1054
+ remoteSession: opts.remoteSession,
1055
+ session: opts.session ?? "General",
1056
+ topicId,
1057
+ queryId: opts.queryId,
1058
+ wikiTopicId: opts.wikiTopicId ?? topicId,
1059
+ agent: opts.agent,
1060
+ cwd: opts.cwd,
1061
+ model: opts.model,
1062
+ currentUserPrompt: opts.currentUserPrompt,
1063
+ playwrightPort: opts.playwrightPort,
1064
+ playwrightCapability: opts.playwrightCapability,
1065
+ autoContinue: opts.autoContinue,
1066
+ visualTools: opts.visualTools,
1067
+ fileDeliveryTools: opts.fileDeliveryTools,
1068
+ });
1069
+ }
1070
+
1071
+ /**
1072
+ * Forum session: catalog entries with `forum` scope.
1073
+ * - `enabled === null` → all forum servers.
1074
+ * - `enabled` is an array → whitelist; required servers are always included.
1075
+ * - `extra` is merged on top, allowing one-off injections per topic.
1076
+ */
1077
+ export function getForumMcpServers(opts: {
1078
+ userId: string;
1079
+ actorUserId?: string;
1080
+ actorTopicScope?: ActorTopicScope;
1081
+ remoteSession?: RemoteSessionGrant;
1082
+ vaultUserId?: string;
1083
+ session: string;
1084
+ topicId?: string;
1085
+ subagentParentTopicId?: string;
1086
+ queryId?: string;
1087
+ wikiTopicId?: string;
1088
+ agent: AgentKind;
1089
+ cwd?: string;
1090
+ model?: string;
1091
+ currentUserPrompt?: string;
1092
+ playwrightPort?: number;
1093
+ playwrightCapability?: string;
1094
+ bgBashPort?: number;
1095
+ autoContinue?: boolean;
1096
+ visualTools?: boolean;
1097
+ fileDeliveryTools?: boolean;
1098
+ threadRootId?: string;
1099
+ depth?: number;
1100
+ enabled?: string[] | null;
1101
+ extra?: Record<string, unknown>;
1102
+ silent?: boolean;
1103
+ peerBridge?: PeerRuntimeBridgeContext;
1104
+ }) {
1105
+ const {
1106
+ userId,
1107
+ actorUserId,
1108
+ actorTopicScope,
1109
+ remoteSession,
1110
+ vaultUserId,
1111
+ session,
1112
+ topicId,
1113
+ subagentParentTopicId,
1114
+ queryId,
1115
+ wikiTopicId,
1116
+ agent,
1117
+ cwd,
1118
+ model,
1119
+ currentUserPrompt,
1120
+ playwrightPort,
1121
+ playwrightCapability,
1122
+ depth = 0,
1123
+ enabled = null,
1124
+ extra = {},
1125
+ silent = false,
1126
+ bgBashPort,
1127
+ autoContinue,
1128
+ visualTools,
1129
+ fileDeliveryTools,
1130
+ threadRootId,
1131
+ peerBridge,
1132
+ } = opts;
1133
+
1134
+ const filter = (name: string) => {
1135
+ if (silent && (name === "task" || name === "decision")) return false;
1136
+ if (enabled === null) return true;
1137
+ return (
1138
+ enabled.includes(name) || (REQUIRED_FORUM_MCP_SERVERS as readonly string[]).includes(name)
1139
+ );
1140
+ };
1141
+
1142
+ const base = buildScope(
1143
+ "forum",
1144
+ {
1145
+ userId,
1146
+ actorUserId,
1147
+ actorTopicScope,
1148
+ remoteSession,
1149
+ vaultUserId,
1150
+ session,
1151
+ topicId,
1152
+ subagentParentTopicId,
1153
+ queryId,
1154
+ wikiTopicId,
1155
+ agent,
1156
+ cwd,
1157
+ model,
1158
+ currentUserPrompt,
1159
+ depth,
1160
+ playwrightPort,
1161
+ playwrightCapability,
1162
+ bgBashPort,
1163
+ autoContinue,
1164
+ visualTools,
1165
+ fileDeliveryTools,
1166
+ threadRootId,
1167
+ silent,
1168
+ peerBridge,
1169
+ },
1170
+ filter,
1171
+ );
1172
+
1173
+ return { ...base, ...extra };
1174
+ }
1175
+
1176
+ /**
1177
+ * Cron session: scheduled background run for a concrete API topic. Keep the
1178
+ * catalog narrower than forum scope: runtime delivery, topic memory/status,
1179
+ * vault utilities and a caller-provided disposable Playwright port.
1180
+ */
1181
+ export function getCronMcpServers(opts: {
1182
+ userId: string;
1183
+ session: string;
1184
+ topicId: string;
1185
+ queryId?: string;
1186
+ wikiTopicId?: string;
1187
+ agent: AgentKind;
1188
+ cwd?: string;
1189
+ model?: string;
1190
+ currentUserPrompt?: string;
1191
+ playwrightPort?: number;
1192
+ playwrightCapability?: string;
1193
+ visualTools?: boolean;
1194
+ fileDeliveryTools?: boolean;
1195
+ }) {
1196
+ return buildScope("cron", {
1197
+ userId: opts.userId,
1198
+ session: opts.session,
1199
+ topicId: opts.topicId,
1200
+ queryId: opts.queryId,
1201
+ wikiTopicId: opts.wikiTopicId ?? opts.topicId,
1202
+ agent: opts.agent,
1203
+ cwd: opts.cwd,
1204
+ model: opts.model,
1205
+ currentUserPrompt: opts.currentUserPrompt,
1206
+ playwrightPort: opts.playwrightPort,
1207
+ playwrightCapability: opts.playwrightCapability,
1208
+ autoContinue: false,
1209
+ visualTools: opts.visualTools,
1210
+ fileDeliveryTools: opts.fileDeliveryTools,
1211
+ });
1212
+ }
1213
+
1214
+ /**
1215
+ * Pick the right MCP server bundle for an agent query. DM/ephemeral sessions
1216
+ * get the DM bundle; forum sessions get the forum bundle with full options
1217
+ * forwarded. Returned shape is the Claude-SDK shape; Codex callers funnel it
1218
+ * through their own translator (`toCodexMcpServers`).
1219
+ */
1220
+ export function getMcpServersForQuery(opts: AgentQueryOptions): Record<string, unknown> {
1221
+ if (opts.toolPolicy === "none") return {};
1222
+ if (opts.toolPolicy === "compaction-log") {
1223
+ const compactLog = opts.mcpExtra?.compact_log;
1224
+ return compactLog ? { compact_log: compactLog } : {};
1225
+ }
1226
+ if (opts.sessionType === "cron") {
1227
+ if (!opts.topicId) throw new Error("getMcpServersForQuery: cron sessionType requires topicId");
1228
+ return hideProviderIntrospectionForOtium(
1229
+ getCronMcpServers({
1230
+ userId: opts.userId || "local",
1231
+ session: opts.session || "cron",
1232
+ topicId: opts.topicId,
1233
+ queryId: opts.queryId,
1234
+ wikiTopicId: opts.wikiTopicId,
1235
+ agent: opts.agent,
1236
+ cwd: opts.cwd,
1237
+ model: opts.model,
1238
+ currentUserPrompt: opts.prompt,
1239
+ playwrightPort: opts.playwrightPort,
1240
+ playwrightCapability: opts.playwrightCapability,
1241
+ visualTools: opts.visualTools,
1242
+ fileDeliveryTools: opts.fileDeliveryTools,
1243
+ }),
1244
+ opts.topicId,
1245
+ );
1246
+ }
1247
+ if (opts.sessionType === "dm" || opts.sessionType === "ephemeral") {
1248
+ return getDmMcpServers({
1249
+ userId: opts.userId || "local",
1250
+ session: opts.session,
1251
+ topicId: opts.topicId,
1252
+ agent: opts.agent,
1253
+ playwrightPort: opts.playwrightPort,
1254
+ playwrightCapability: opts.playwrightCapability,
1255
+ });
1256
+ }
1257
+ if (opts.sessionType === "manager") {
1258
+ return hideProviderIntrospectionForOtium(
1259
+ mergeHostMcpServers(
1260
+ getManagerMcpServers({
1261
+ userId: opts.userId || "local",
1262
+ actorUserId: opts.actorUserId,
1263
+ actorTopicScope: opts.actorTopicScope,
1264
+ remoteSession: opts.remoteSession,
1265
+ session: opts.session,
1266
+ topicId: opts.topicId,
1267
+ queryId: opts.queryId,
1268
+ wikiTopicId: opts.wikiTopicId,
1269
+ agent: opts.agent,
1270
+ cwd: opts.cwd,
1271
+ model: opts.model,
1272
+ currentUserPrompt: opts.prompt,
1273
+ playwrightPort: opts.playwrightPort,
1274
+ playwrightCapability: opts.playwrightCapability,
1275
+ autoContinue: opts.autoContinue,
1276
+ visualTools: opts.visualTools,
1277
+ fileDeliveryTools: opts.fileDeliveryTools,
1278
+ }),
1279
+ opts.hostMcpServers,
1280
+ ),
1281
+ opts.topicId,
1282
+ );
1283
+ }
1284
+ return hideProviderIntrospectionForOtium(
1285
+ mergeHostMcpServers(
1286
+ getForumMcpServers({
1287
+ userId: opts.userId || "local",
1288
+ actorUserId: opts.actorUserId,
1289
+ actorTopicScope: opts.actorTopicScope,
1290
+ remoteSession: opts.remoteSession,
1291
+ vaultUserId: opts.vaultUserId,
1292
+ session: opts.session || "default",
1293
+ topicId: opts.topicId,
1294
+ subagentParentTopicId: opts.subagentParentTopicId,
1295
+ queryId: opts.queryId,
1296
+ wikiTopicId: opts.wikiTopicId,
1297
+ agent: opts.agent,
1298
+ cwd: opts.cwd,
1299
+ model: opts.model,
1300
+ currentUserPrompt: opts.prompt,
1301
+ playwrightPort: opts.playwrightPort,
1302
+ playwrightCapability: opts.playwrightCapability,
1303
+ bgBashPort: opts.bgBashPort,
1304
+ autoContinue: opts.autoContinue,
1305
+ visualTools: opts.visualTools,
1306
+ fileDeliveryTools: opts.fileDeliveryTools,
1307
+ threadRootId: opts.threadRootId,
1308
+ depth: opts.depth,
1309
+ enabled: opts.mcpEnabled,
1310
+ extra: opts.mcpExtra,
1311
+ silent: opts.silent,
1312
+ peerBridge: opts.peerBridge,
1313
+ }),
1314
+ withoutManagerOnlyHostMcpServers(opts.hostMcpServers),
1315
+ ),
1316
+ opts.topicId,
1317
+ );
1318
+ }
1319
+
1320
+ function hideProviderIntrospectionForOtium(
1321
+ servers: Record<string, unknown>,
1322
+ topicId: string | undefined,
1323
+ ): Record<string, unknown> {
1324
+ if (!topicId || getTopic(topicId)?.surface !== "otium") return servers;
1325
+ const filtered = { ...servers };
1326
+ delete filtered["agent-health"];
1327
+ delete filtered["token-stats"];
1328
+ return filtered;
1329
+ }