@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,2284 @@
1
+ /**
2
+ * Turn runner — executes one AI turn for a topic and streams its events.
3
+ *
4
+ * Port of otium's `api/routes/ai.ts` with the REST route table removed and the
5
+ * WsHub replaced by the channel-agnostic RuntimeBus (`#bus`). Agent execution
6
+ * remains local, while an optional peerBridge routes canonical room mutations
7
+ * back through the placement adapter.
8
+ */
9
+ import { randomUUID } from "node:crypto";
10
+ import { existsSync, mkdirSync, readdirSync, statSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ import { cleanupAgentFork, type ForkHandle } from "#agents/fork";
13
+ import { runAgent } from "#agents/index";
14
+ import {
15
+ canSpawnSubagentsFromTopic,
16
+ settleSubagentFailure,
17
+ subagentReportMode,
18
+ } from "#agents/mcp-tools/spawn-subagent";
19
+ import { getRegistryOperations } from "#agents/registry";
20
+ import { WsHub } from "#bus";
21
+ import { asTurnId, asTurnSlotKey, type TurnSlotKey } from "#identifiers";
22
+ import { ensureBgBash } from "#platform/background-bash/manager";
23
+ import { FROM_AUTO_CONTINUE } from "#platform/constants";
24
+ import { logger } from "#platform/logger";
25
+ import { consumePlaywrightUnavailable, markPlaywrightUnavailable } from "#platform/mcp-config";
26
+ import {
27
+ ensurePlaywright,
28
+ getPlaywrightCapability,
29
+ makeInstanceKey,
30
+ pinPlaywrightInstance,
31
+ unpinPlaywrightInstance,
32
+ } from "#platform/playwright/manager";
33
+ import {
34
+ buildChannelSystemPrompt,
35
+ buildManagerSystemPrompt,
36
+ buildMemoryPromptSection,
37
+ buildTopicSystemPrompt,
38
+ } from "#prompts/builders";
39
+ import {
40
+ type DeferredInject,
41
+ DeferredInjectBatcher,
42
+ decideNewQuery,
43
+ deferInject,
44
+ getRoomQuery,
45
+ interSessionQueue,
46
+ isolatedTurnRoomId,
47
+ isUserOrigin,
48
+ type RoomQueryControl,
49
+ setRoomQuery,
50
+ takeDeferredInject,
51
+ } from "#query/active-rooms";
52
+ import { writeQueryState } from "#query/state";
53
+ import { AbortReason } from "#query/types";
54
+ import { actorTopicScopeFrom } from "#runtime/actor-topic-scope";
55
+ import {
56
+ materializePromptAttachments,
57
+ promptWithAttachments,
58
+ workspaceCwdFor,
59
+ } from "#runtime/attachments";
60
+ import { buildMentionOnlyChannelPrompt } from "#runtime/channel-context";
61
+ import { classifyAgentError, stringifyError } from "#runtime/errors";
62
+ import { withTurnSilenceHeartbeat } from "#runtime/event-heartbeat";
63
+ import { trackPlaywrightTurn, untrackPlaywrightTurn } from "#runtime/playwright-turn-abort";
64
+ import { remoteSessionGrantFrom } from "#runtime/remote-session-grant";
65
+ import { getTopicConfig } from "#runtime/topic-config";
66
+ import { runTurnEventStream, type StreamAgentOutcome } from "#runtime/turn-event-stream";
67
+ import {
68
+ type AiTurnTopic,
69
+ resolveTopicTurnExecution,
70
+ resolveTopicTurnSession,
71
+ } from "#runtime/turn-session";
72
+ import {
73
+ flattenUserTurnAttachments,
74
+ legacyUserTurnEnvelope,
75
+ renderUserTurnBatch,
76
+ renderUserTurnPrompt,
77
+ type UserTurnEnvelope,
78
+ } from "#runtime/user-turn-envelope";
79
+ import { getActiveVisualForPrompt } from "#runtime/visual-store";
80
+ import { activeVisualHtmlForPrompt } from "#runtime/visuals";
81
+ import { appendApiMessage, getApiMessage } from "#storage/api-messages";
82
+ import { resolveTopicBrief } from "#storage/api-topic-brief";
83
+ import {
84
+ clearTopicSessionId,
85
+ getTopic,
86
+ getTopicMemoryOrigin,
87
+ getTopicSessionId,
88
+ } from "#storage/api-topics";
89
+ import { getGlobalAiName } from "#storage/app-settings";
90
+ import { isTopicBrowserProfileOwner } from "#storage/browser-profiles";
91
+ import { appendConversationEvent, readConversation } from "#storage/conversations";
92
+ import { db } from "#storage/forum-db";
93
+ import {
94
+ getRuntimeTurnLease,
95
+ RUNTIME_INSTANCE_ID,
96
+ requestRuntimeTurnAbort,
97
+ } from "#storage/runtime-leases";
98
+ import { getRuntimeTopicEpoch, isRuntimeTopicMaintenance } from "#storage/runtime-topic-state";
99
+ import {
100
+ claimNextRuntimeUserTurnRequest,
101
+ completeRuntimeUserTurnRequest,
102
+ getActiveRuntimeUserTurnRequest,
103
+ markRuntimeUserTurnMessagesLogged,
104
+ markRuntimeUserTurnRunning,
105
+ mergeRuntimeUserTurnRequest,
106
+ type RuntimeUserTurnExecution,
107
+ releaseRuntimeUserTurnClaim,
108
+ } from "#storage/runtime-turn-requests";
109
+ import type { PendingAskUserId } from "#storage/session-asks";
110
+ import { getTopicHostMcpGrant } from "#storage/topic-host-mcp-grants";
111
+ import { getTopicToolCapabilities } from "#storage/topic-tool-capabilities";
112
+ import { getSharedWikiDir } from "#storage/wiki";
113
+ import {
114
+ isTopicBriefFile,
115
+ isTopicSummaryFile,
116
+ wikiBriefStorageKey,
117
+ wikiSummaryFilename,
118
+ } from "#storage/wiki-summary-names";
119
+ import { getTopics } from "#topics/derive";
120
+ import type {
121
+ ActorTopicScope,
122
+ AgentKind,
123
+ EffortLevel,
124
+ PeerRuntimeBridgeContext,
125
+ RemoteSessionGrant,
126
+ UnifiedEvent,
127
+ } from "#types";
128
+ import type { MessageDto, TopicDto } from "#types/api";
129
+
130
+ // 분해된 헬퍼 모듈 재노출 — 기존 @/api/routes/ai 소비자(테스트 포함) 경로 유지
131
+ export * from "#agents/model-catalog";
132
+ export * from "#runtime/attachments";
133
+ export * from "#runtime/channel-context";
134
+ export * from "#runtime/errors";
135
+ export * from "#runtime/tasks";
136
+ export * from "#runtime/turn-session";
137
+ export { renderUserPromptBatch, renderUserTurnBatch } from "#runtime/user-turn-envelope";
138
+ export * from "#runtime/visuals";
139
+
140
+ // In-flight AI turns are tracked room-keyed (topicId → control) in
141
+ // #query/active-rooms so a new user message on a room can supersede the
142
+ // running turn (Otium abort-on-new-message). See startAiTurn / abortRoom.
143
+ const PLAYWRIGHT_UNAVAILABLE_NOTICE_COOLDOWN_MS = 5 * 60_000;
144
+ const ASK_REPLY_INJECT_BATCH_MS = 500;
145
+ const playwrightUnavailableNoticeAt = new Map<string, number>();
146
+
147
+ /** Browser and background shell tools are part of every ordinary topic. */
148
+ export function withDefaultPlaywright(configuredMcp: string[], isManager: boolean): string[] {
149
+ if (isManager) return configuredMcp;
150
+ const enabled = new Set(configuredMcp);
151
+ enabled.add("playwright");
152
+ enabled.add("background-bash");
153
+ return [...enabled];
154
+ }
155
+
156
+ export function buildTurnReminderQuery(
157
+ agent: AgentKind,
158
+ prompt: string,
159
+ reminders: string[],
160
+ ): { prompt: string; ephemeralSystemPrompt?: string } {
161
+ const reminderPrompt = reminders.join("\n\n");
162
+ if (!reminderPrompt) return { prompt };
163
+ if (agent === "maestro") return { prompt, ephemeralSystemPrompt: reminderPrompt };
164
+ return { prompt: `${prompt}\n\n${reminderPrompt}` };
165
+ }
166
+
167
+ // dequeueAll() is the merge primitive; this short gate makes the first reply
168
+ // to an idle caller wait long enough for sibling ask replies to join it.
169
+ const askReplyInjectBatcher = new DeferredInjectBatcher({
170
+ queue: interSessionQueue,
171
+ delayMs: ASK_REPLY_INJECT_BATCH_MS,
172
+ isBusy: (topicId) => Boolean(getRoomQuery(topicId)),
173
+ dispatch: (inject) => redispatchInject(inject),
174
+ });
175
+
176
+ function appendSystemMessage(topicId: string, text: string, threadRootId?: string): MessageDto {
177
+ const message: MessageDto = {
178
+ id: randomUUID(),
179
+ topicId,
180
+ authorId: "system",
181
+ text,
182
+ ...(threadRootId ? { threadRootId } : {}),
183
+ createdAt: new Date().toISOString(),
184
+ };
185
+ appendApiMessage(message, { notify: false });
186
+ WsHub.get().broadcastMessage(topicId, message);
187
+ return message;
188
+ }
189
+
190
+ function notifyPlaywrightUnavailable(topicId: string) {
191
+ const now = Date.now();
192
+ const last = playwrightUnavailableNoticeAt.get(topicId) ?? 0;
193
+ if (now - last < PLAYWRIGHT_UNAVAILABLE_NOTICE_COOLDOWN_MS) return;
194
+ playwrightUnavailableNoticeAt.set(topicId, now);
195
+ appendSystemMessage(
196
+ topicId,
197
+ "Playwright browser tools are unavailable this turn. Browser automation was removed from the tool catalog; retry shortly if browser interaction is required.",
198
+ );
199
+ WsHub.get().broadcastTopicNotice(topicId, "info", "Playwright 사용 불가");
200
+ }
201
+
202
+ function appendAskReplyMessage(
203
+ topicId: string,
204
+ text: string,
205
+ sourceLabel: string,
206
+ body: string,
207
+ kind: "reply" | "error",
208
+ agentType?: AgentKind | null,
209
+ threadRootId?: string,
210
+ ): MessageDto {
211
+ const message: MessageDto = {
212
+ id: randomUUID(),
213
+ topicId,
214
+ authorId: "ai",
215
+ text,
216
+ kind: "tell",
217
+ tellCard: {
218
+ fromLabel: sourceLabel,
219
+ label: `${kind === "error" ? "Error" : "Reply"} from ${sourceLabel}`,
220
+ message: body,
221
+ },
222
+ ...(agentType ? { agentType } : {}),
223
+ ...(threadRootId ? { threadRootId } : {}),
224
+ createdAt: new Date().toISOString(),
225
+ };
226
+ appendApiMessage(message, { notify: false });
227
+ WsHub.get().broadcastMessage(topicId, message);
228
+ return message;
229
+ }
230
+
231
+ export function resolveWikiMirrorPath(
232
+ directory: string,
233
+ preferredFilename: string,
234
+ matchesLegacyId: (filename: string) => boolean,
235
+ matchesTitle: (filename: string) => boolean,
236
+ preferExact = true,
237
+ ): string {
238
+ const preferred = join(directory, preferredFilename);
239
+ if (preferExact && existsSync(preferred)) return preferred;
240
+
241
+ let newestLegacyId: { path: string; mtimeMs: number } | null = null;
242
+ let newestTitle: { path: string; mtimeMs: number } | null = null;
243
+ try {
244
+ for (const filename of readdirSync(directory)) {
245
+ const titleMatch = matchesTitle(filename);
246
+ const legacyIdMatch = !titleMatch && matchesLegacyId(filename);
247
+ if (!titleMatch && !legacyIdMatch) continue;
248
+ const path = join(directory, filename);
249
+ const mtimeMs = statSync(path).mtimeMs;
250
+ if (titleMatch) {
251
+ if (!newestTitle || mtimeMs > newestTitle.mtimeMs) {
252
+ newestTitle = { path, mtimeMs };
253
+ }
254
+ } else if (!newestLegacyId || mtimeMs > newestLegacyId.mtimeMs) {
255
+ newestLegacyId = { path, mtimeMs };
256
+ }
257
+ }
258
+ } catch {
259
+ // The mirror is best-effort; callers can still use the SQLite brief.
260
+ }
261
+ return newestTitle?.path ?? newestLegacyId?.path ?? preferred;
262
+ }
263
+
264
+ export function resolveWikiMemoryMirror(
265
+ wikiDir: string,
266
+ topicId: string,
267
+ topicTitle: string,
268
+ ): {
269
+ briefFile: string;
270
+ hasBriefFile: boolean;
271
+ latestSummaryFile: string | null;
272
+ } {
273
+ const briefFile = resolveWikiMirrorPath(
274
+ join(wikiDir, "topic"),
275
+ `${wikiBriefStorageKey(topicTitle, topicId)}.md`,
276
+ (filename) => isTopicBriefFile(filename, topicId),
277
+ (filename) => isTopicBriefFile(filename, topicId, topicTitle),
278
+ );
279
+ const hasBriefFile = existsSync(briefFile) && statSync(briefFile).isFile();
280
+ const latestSummaryCandidate = resolveWikiMirrorPath(
281
+ join(wikiDir, "summaries"),
282
+ `__missing__-${wikiSummaryFilename("0000-00-00", topicTitle, topicId)}`,
283
+ (filename) => isTopicSummaryFile(filename, topicId),
284
+ (filename) => isTopicSummaryFile(filename, topicId, topicTitle),
285
+ false,
286
+ );
287
+ const latestSummaryFile =
288
+ existsSync(latestSummaryCandidate) && statSync(latestSummaryCandidate).isFile()
289
+ ? latestSummaryCandidate
290
+ : null;
291
+ return { briefFile, hasBriefFile, latestSummaryFile };
292
+ }
293
+
294
+ export async function streamAgentEvents(
295
+ topicId: string,
296
+ topicTitle: string,
297
+ queryId: string,
298
+ events: AsyncGenerator<UnifiedEvent>,
299
+ control: RoomQueryControl,
300
+ agentType: AgentKind,
301
+ model: string,
302
+ effort: EffortLevel | undefined,
303
+ userId: string,
304
+ retryableSessionExpired = true,
305
+ onSessionId?: (sessionId: string) => void,
306
+ execution?: {
307
+ silent?: boolean;
308
+ actorUserId?: string;
309
+ peerBridge?: PeerRuntimeBridgeContext;
310
+ sourceNode?: string;
311
+ threadRootId?: string;
312
+ },
313
+ ): Promise<StreamAgentOutcome> {
314
+ return runTurnEventStream(
315
+ topicId,
316
+ topicTitle,
317
+ queryId,
318
+ events,
319
+ control,
320
+ agentType,
321
+ model,
322
+ effort,
323
+ userId,
324
+ { appendSystemMessage, deliverAskCallbackToCaller, deliverAskError, redispatchInject },
325
+ retryableSessionExpired,
326
+ onSessionId,
327
+ execution,
328
+ );
329
+ }
330
+
331
+ /**
332
+ * Re-run a deferred session-inject after its room freed up. Re-resolves the
333
+ * topic (config/agent may have changed while queued) and dispatches through the
334
+ * same priority path — if the room got busy again, startAiTurn just re-defers.
335
+ */
336
+ function redispatchInject(inject: DeferredInject): void {
337
+ const topics = getTopics();
338
+ const topic = topics.find((t) => t.id === inject.topicId) as TopicDto | undefined;
339
+ if (!topic?.agent) {
340
+ logger.warn(
341
+ { topicId: inject.topicId, origin: inject.origin },
342
+ "ai: dropping deferred inject — topic gone or AI no longer invited",
343
+ );
344
+ try {
345
+ inject.onSettled?.({
346
+ queryId: "",
347
+ kind: "error",
348
+ error: "topic gone or AI no longer invited",
349
+ });
350
+ } catch (err) {
351
+ logger.warn({ err, topicId: inject.topicId }, "ai: deferred settlement hook failed");
352
+ }
353
+ if (inject.forkHandle) cleanupAgentFork(inject.forkHandle);
354
+ return;
355
+ }
356
+ startAiTurn({
357
+ topic: {
358
+ id: topic.id,
359
+ title: topic.title,
360
+ kind: topic.kind,
361
+ description: topic.description,
362
+ agent: topic.agent,
363
+ defaultModel: topic.defaultModel,
364
+ defaultEffort: topic.defaultEffort,
365
+ aiMode: topic.aiMode,
366
+ aiMention: topic.aiMention,
367
+ },
368
+ userId: inject.userId,
369
+ vaultUserId: inject.vaultUserId,
370
+ prompt: inject.prompt,
371
+ allowAutoContinue: false,
372
+ origin: inject.origin,
373
+ onDispatched: inject.onDispatched,
374
+ requestId: inject.requestId,
375
+ depth: inject.depth,
376
+ silent: inject.silent,
377
+ contextId: inject.contextId,
378
+ ...(inject.threadRootId ? { threadRootId: inject.threadRootId } : {}),
379
+ agentOverride: inject.agentOverride,
380
+ modelOverride: inject.modelOverride,
381
+ effortOverride: inject.effortOverride,
382
+ // Topic-owned turns carry undefined and re-resolve the newest durable
383
+ // session here; isolated/external turns carry their explicit id.
384
+ sessionId: inject.sessionId,
385
+ sessionScope: inject.sessionScope,
386
+ turnConcurrency: inject.turnConcurrency,
387
+ forkHandle: inject.forkHandle,
388
+ prepareSession: inject.prepareSession,
389
+ cwd: inject.cwd,
390
+ sessionName: inject.sessionName,
391
+ sessionType: inject.sessionType,
392
+ visualTools: inject.visualTools,
393
+ fileDeliveryTools: inject.fileDeliveryTools,
394
+ onSessionId: inject.onSessionId,
395
+ onSessionReset: inject.onSessionReset,
396
+ bridgeSessionFromHistory: inject.bridgeSessionFromHistory,
397
+ onSettled: inject.onSettled,
398
+ peerBridge: inject.peerBridge,
399
+ sourceNode: inject.sourceNode,
400
+ askReplySources: inject.askReplySources,
401
+ _runtimeEpoch: inject.runtimeEpoch,
402
+ _sessionRetried: inject._sessionRetried,
403
+ from: inject.from,
404
+ });
405
+ }
406
+
407
+ type AskPendingFileRef = {
408
+ requestId?: string;
409
+ contextId?: string;
410
+ callerTopicId?: string;
411
+ callerUserId?: string;
412
+ pendingAsk?: {
413
+ userId: PendingAskUserId;
414
+ from: string;
415
+ to: string;
416
+ requestId?: string;
417
+ };
418
+ remoteReply?: import("#mcp/session-comm/peer-forward").RemoteReplyRoute;
419
+ sourceLabel?: string;
420
+ };
421
+
422
+ async function clearPendingAskFile(
423
+ pending: AskPendingFileRef,
424
+ state?: "reply_ready" | "queued_for_caller" | "injecting_to_caller",
425
+ ): Promise<void> {
426
+ if (!pending.pendingAsk) return;
427
+ try {
428
+ const { clearPendingAsk, markPendingAskState } = await import("#storage/session-asks");
429
+ if (state) markPendingAskState({ ...pending.pendingAsk, state });
430
+ clearPendingAsk(pending.pendingAsk);
431
+ } catch (err) {
432
+ logger.warn({ err, pendingAsk: pending.pendingAsk }, "sessions: pending ask cleanup failed");
433
+ }
434
+ }
435
+
436
+ async function markPendingAskFile(
437
+ pending: AskPendingFileRef,
438
+ state: "reply_ready" | "queued_for_caller" | "injecting_to_caller",
439
+ ): Promise<void> {
440
+ if (!pending.pendingAsk) return;
441
+ try {
442
+ const { markPendingAskState } = await import("#storage/session-asks");
443
+ markPendingAskState({ ...pending.pendingAsk, state });
444
+ } catch (err) {
445
+ logger.warn(
446
+ { err, pendingAsk: pending.pendingAsk, state },
447
+ "sessions: pending ask mark failed",
448
+ );
449
+ }
450
+ }
451
+
452
+ /** Caller-side injection of an ask reply — delivers the target AI's answer (or
453
+ * error) back into the caller topic, triggering its AI when one is invited.
454
+ * `options.onRecorded` runs inside the same storage transaction as the durable
455
+ * room record (the appended reply message), so a caller that must consume its
456
+ * own bookkeeping exactly when the answer is durable can do so atomically. */
457
+ export async function deliverAskCallbackToCaller(
458
+ pending: AskPendingFileRef & {
459
+ requestId: string;
460
+ contextId?: string;
461
+ callerTopicId: string;
462
+ callerThreadRootId?: string;
463
+ callerUserId: string;
464
+ },
465
+ sourceLabel: string,
466
+ body: string,
467
+ kind: "reply" | "error",
468
+ options: { onRecorded?: () => void } = {},
469
+ ): Promise<boolean> {
470
+ if (pending.remoteReply) {
471
+ const { deliverPeerReply } = await import("#mcp/session-comm/peer-forward");
472
+ const delivered = await deliverPeerReply(pending.remoteReply, sourceLabel, body, kind);
473
+ if (delivered) options.onRecorded?.();
474
+ return delivered;
475
+ }
476
+ const callerTopic = getTopic(pending.callerTopicId);
477
+ const heading = kind === "error" ? `Error from ${sourceLabel}` : `Reply from ${sourceLabel}`;
478
+ const prompt = `[${heading}]\n\n${body}`;
479
+ const record = (agentType?: AgentKind | null) =>
480
+ db.transaction(() => {
481
+ appendAskReplyMessage(
482
+ pending.callerTopicId,
483
+ prompt,
484
+ sourceLabel,
485
+ body,
486
+ kind,
487
+ agentType ?? undefined,
488
+ pending.callerThreadRootId,
489
+ );
490
+ options.onRecorded?.();
491
+ })();
492
+
493
+ await markPendingAskFile(pending, "reply_ready");
494
+
495
+ if (!callerTopic?.agent) {
496
+ try {
497
+ record(undefined);
498
+ await clearPendingAskFile(pending);
499
+ return true;
500
+ } catch (err) {
501
+ logger.warn(
502
+ { err, requestId: pending.requestId, callerTopicId: pending.callerTopicId },
503
+ "sessions: ask callback direct delivery failed",
504
+ );
505
+ return false;
506
+ }
507
+ }
508
+
509
+ const queued = askReplyInjectBatcher.enqueue({
510
+ topicId: pending.callerTopicId,
511
+ userId: pending.callerUserId,
512
+ ...(pending.callerThreadRootId ? { threadRootId: pending.callerThreadRootId } : {}),
513
+ prompt,
514
+ origin: sourceLabel,
515
+ requestId: pending.requestId,
516
+ contextId: pending.contextId,
517
+ sessionId: getTopicSessionId(pending.callerTopicId),
518
+ askReplySources: [
519
+ { from: sourceLabel, requestId: pending.requestId, contextId: pending.contextId },
520
+ ],
521
+ onDispatched: (queryId: string) => {
522
+ void clearPendingAskFile(pending, "injecting_to_caller");
523
+ logger.info(
524
+ {
525
+ requestId: pending.requestId,
526
+ callerTopicId: pending.callerTopicId,
527
+ callerQueryId: queryId,
528
+ source: sourceLabel,
529
+ },
530
+ "sessions: batched ask callback dispatched to caller",
531
+ );
532
+ },
533
+ });
534
+
535
+ if (queued) {
536
+ // Keep individual replies visible in topic history; only the model-facing
537
+ // caller turn is coalesced into one prompt.
538
+ try {
539
+ record(callerTopic.agent);
540
+ } catch (err) {
541
+ // The durable record is what makes this answer real — it is also the
542
+ // transaction that consumes the caller's bookkeeping (`onRecorded`).
543
+ // Without it the queued entry is the answer's ONLY trace, in memory, in
544
+ // a process that just failed a write: leaving it there makes the sender's
545
+ // retry hit the dedupe branch below and settle as if the answer had
546
+ // landed, so a crash loses it for good. Drop the entry instead and fail,
547
+ // so the retry runs the whole delivery again from a clean slate.
548
+ interSessionQueue.remove(pending.callerTopicId, pending.requestId);
549
+ logger.warn(
550
+ { err, requestId: pending.requestId, callerTopicId: pending.callerTopicId },
551
+ "sessions: ask callback record failed after enqueue; queue entry withdrawn",
552
+ );
553
+ return false;
554
+ }
555
+ await markPendingAskFile(pending, "queued_for_caller");
556
+ return true;
557
+ }
558
+
559
+ // A replay can encounter the same request while its original callback is
560
+ // still queued. That request is already owned; do not append it twice.
561
+ // `onRecorded` still has to run atomically: it is an ask row deletion plus a
562
+ // claim completion, and a crash between the two would leave a completed
563
+ // claim with the ask still pending (or the reverse).
564
+ if (interSessionQueue.hasRequest(pending.callerTopicId, pending.requestId)) {
565
+ db.transaction(() => {
566
+ options.onRecorded?.();
567
+ })();
568
+ await markPendingAskFile(pending, "queued_for_caller");
569
+ return true;
570
+ }
571
+
572
+ logger.warn(
573
+ { requestId: pending.requestId, callerTopicId: pending.callerTopicId, source: sourceLabel },
574
+ "sessions: ask callback could not enter caller batch; appending direct fallback",
575
+ );
576
+ record(callerTopic.agent);
577
+ await clearPendingAskFile(pending);
578
+ return true;
579
+ }
580
+
581
+ /** Deliver an ask callback error to the caller topic (in-process, no-op if no pending ask). */
582
+ async function deliverAskError(queryId: string, sourceLabel: string, error: string) {
583
+ try {
584
+ const { resolveAskCallback } = await import("#runtime/ask-callbacks");
585
+ const pending = resolveAskCallback(queryId);
586
+ if (pending) {
587
+ const prefix = pending.timedOut ? "⚠️ [Timeout - error notification was dropped]\n\n" : "";
588
+ await deliverAskCallbackToCaller(
589
+ pending,
590
+ pending.sourceLabel ?? sourceLabel,
591
+ `${prefix}${error}`,
592
+ "error",
593
+ );
594
+ }
595
+ } catch {
596
+ // Best-effort — don't let callback failure crash the main agent loop.
597
+ }
598
+ }
599
+
600
+ export type TopicRolloutReconstruction =
601
+ | { kind: "rebuilt"; sessionId: string }
602
+ | { kind: "no-history" }
603
+ | { kind: "failed"; error: string };
604
+
605
+ export function tryReconstructTopicRollout(opts: {
606
+ topicId: string;
607
+ topicTitle: string;
608
+ userId: string;
609
+ agent: AgentKind;
610
+ sessionId: string | null | undefined;
611
+ cwd: string;
612
+ model: string;
613
+ effort?: EffortLevel;
614
+ }): TopicRolloutReconstruction {
615
+ const { topicId, topicTitle, userId, agent, sessionId, cwd, model, effort } = opts;
616
+
617
+ try {
618
+ const entries = readConversation(userId, topicTitle);
619
+ if (entries.length === 0) return { kind: "no-history" };
620
+ const result = getRegistryOperations(agent).writeRollout({
621
+ cwd,
622
+ entries,
623
+ model,
624
+ ...(effort ? { effort } : {}),
625
+ ...(sessionId ? { reuseSessionId: sessionId } : {}),
626
+ });
627
+ logger.info(
628
+ {
629
+ topicId,
630
+ agent,
631
+ sessionId: result.sessionId,
632
+ rolloutPath: result.rolloutPath,
633
+ entries: entries.length,
634
+ },
635
+ sessionId
636
+ ? "ai: session expired — rollout reconstructed from unified log"
637
+ : "ai: provider session bridged from shared conversation log",
638
+ );
639
+ return { kind: "rebuilt", sessionId: result.sessionId };
640
+ } catch (err) {
641
+ logger.warn({ err, topicId, agent, sessionId }, "ai: session reconstruct failed");
642
+ return { kind: "failed", error: stringifyError(err) };
643
+ }
644
+ }
645
+
646
+ export type SessionRetryResolution =
647
+ | { kind: "retry"; sessionId: string | null }
648
+ | { kind: "failed"; error: string };
649
+
650
+ export function resolveSessionRetry(opts: {
651
+ topicId: string;
652
+ topicTitle: string;
653
+ userId: string;
654
+ agent: AgentKind;
655
+ sessionId: string | null | undefined;
656
+ cwd: string;
657
+ silent: boolean;
658
+ model: string;
659
+ effort?: EffortLevel;
660
+ externalSessionOwner?: boolean;
661
+ onSessionReset?: () => void;
662
+ }): SessionRetryResolution {
663
+ const reconstructed = tryReconstructTopicRollout(opts);
664
+ if (reconstructed.kind === "rebuilt") {
665
+ return { kind: "retry", sessionId: reconstructed.sessionId };
666
+ }
667
+ if (reconstructed.kind === "failed") return reconstructed;
668
+ if (opts.onSessionReset) opts.onSessionReset();
669
+ else if (!opts.silent && !opts.externalSessionOwner) {
670
+ clearTopicSessionId(opts.topicId, "session-expired");
671
+ }
672
+ logger.info(
673
+ { topicId: opts.topicId, agent: opts.agent, hadSessionId: Boolean(opts.sessionId) },
674
+ "ai: session expired — retrying with fresh session",
675
+ );
676
+ return { kind: "retry", sessionId: null };
677
+ }
678
+
679
+ export interface AiTurnSettlement {
680
+ queryId: string;
681
+ kind: "completed" | "aborted" | "error";
682
+ /** Distinguishes user preemption from an explicit stop for durable owners. */
683
+ abortReason?: AbortReason;
684
+ error?: string;
685
+ }
686
+
687
+ /** Execution controls shared by direct and injected turns. */
688
+ export interface AiTurnExecutionOptions {
689
+ attachments?: string[];
690
+ /** "user" (default) for a human message; otherwise the inject source topic. */
691
+ origin?: string;
692
+ /** Product actor identity when the node executes as a shared principal. */
693
+ actorUserId?: string;
694
+ /** Host-asserted rooms the actor may reach; absent confines cross-room tools. */
695
+ actorTopicScope?: ActorTopicScope;
696
+ /** Hub-issued per-turn remote session-comm grant; absent keeps it fail-closed. */
697
+ remoteSession?: RemoteSessionGrant;
698
+ /** Origin node for transcript echo suppression. */
699
+ sourceNode?: string;
700
+ /** Answer inside this thread instead of the room's main flow (S-13). */
701
+ threadRootId?: string;
702
+ /** Fired when the turn is actually dispatched, including after a defer. */
703
+ onDispatched?: (queryId: string) => void;
704
+ /** Inter-session requestId for queue dedup (session-inject only). */
705
+ requestId?: string;
706
+ /** Nesting depth/context metadata preserved across defer/requeue. */
707
+ depth?: number;
708
+ silent?: boolean;
709
+ contextId?: string;
710
+ modelOverride?: string;
711
+ effortOverride?: EffortLevel;
712
+ sessionId?: string | null;
713
+ /** Explicitly isolate a provider conversation from the topic's durable session. */
714
+ sessionScope?: "topic" | "isolated";
715
+ /** Allow an isolated fork to run beside the topic's visible turn. Internal use only. */
716
+ turnConcurrency?: "topic" | "isolated";
717
+ forkHandle?: ForkHandle;
718
+ /** Lazily create an isolated provider session immediately before execution. */
719
+ prepareSession?: DeferredInject["prepareSession"];
720
+ cwd?: string;
721
+ /** Provider conversation namespace. Defaults to the visible topic title. */
722
+ sessionName?: string;
723
+ /** Tool/catalog scope. Defaults to manager or forum based on topic kind. */
724
+ sessionType?: "dm" | "forum" | "ephemeral" | "manager" | "cron";
725
+ /** Adapter-granted access to Otium's visual panel tools. Default-deny. */
726
+ visualTools?: boolean;
727
+ /** Adapter-granted access to chat file-delivery tools. Default-deny. */
728
+ fileDeliveryTools?: boolean;
729
+ /** Own this turn's provider session without replacing the topic's main session. */
730
+ onSessionId?: (sessionId: string) => void;
731
+ /** Clear the externally-owned provider session after recovery fails. */
732
+ onSessionReset?: () => void;
733
+ /** Bridge a fresh provider session from this namespace's shared conversation log. */
734
+ bridgeSessionFromHistory?: boolean;
735
+ /** Observe the final non-retry outcome of this turn. */
736
+ onSettled?: (result: AiTurnSettlement) => void;
737
+ /** Route user-facing runtime mutations back to a placed room's hub. */
738
+ peerBridge?: PeerRuntimeBridgeContext;
739
+ askReplySources?: DeferredInject["askReplySources"];
740
+ /** Internal source marker, e.g. FROM_AUTO_CONTINUE for config-change resumes. */
741
+ from?: string;
742
+ }
743
+
744
+ /**
745
+ * A turn that came from an adapter states its own capabilities. One that did not
746
+ * — `triggerTopicAiTurn` for tell/ask, cron, subagent reports, and config-change
747
+ * auto-continue — inherits what the room's adapter last granted. Without this a
748
+ * scheduled job or a resumed turn runs in an Otium room with no `show_html`,
749
+ * even though the panel that would render it is right there.
750
+ *
751
+ * Absence, not `false`, is what defers: an adapter that says `false` keeps
752
+ * saying no, so a host that stopped rendering a surface is not overridden by the
753
+ * grant it left behind. A room no adapter has ever granted stays default-deny.
754
+ *
755
+ * Exported so the inheritance can be asserted directly. It is the half of this
756
+ * feature that a storage test cannot reach, and the half that decides whether a
757
+ * cron job in a mapped room can draw anything.
758
+ */
759
+ export function resolveTurnToolCapabilities(
760
+ topicId: string,
761
+ params: { visualTools?: boolean; fileDeliveryTools?: boolean },
762
+ ): { visualTools: boolean; fileDeliveryTools: boolean } {
763
+ const granted =
764
+ params.visualTools === undefined || params.fileDeliveryTools === undefined
765
+ ? getTopicToolCapabilities(topicId)
766
+ : null;
767
+ return {
768
+ visualTools: params.visualTools ?? granted?.visualTools ?? false,
769
+ fileDeliveryTools: params.fileDeliveryTools ?? granted?.fileDeliveryTools ?? false,
770
+ };
771
+ }
772
+
773
+ /**
774
+ * A manager room's grant reaches only manager executions and an ordinary
775
+ * room's only forum executions, so cron/ephemeral turns cannot inherit it.
776
+ * Subagent rooms never take one.
777
+ */
778
+ export function resolveTurnHostMcpServers(
779
+ topic: Pick<TopicDto, "id" | "kind" | "isSubagent">,
780
+ sessionType?: "dm" | "forum" | "ephemeral" | "manager" | "cron",
781
+ ) {
782
+ if (topic.isSubagent) return undefined;
783
+ const ownScope = topic.kind === "manager" ? "manager" : "forum";
784
+ if ((sessionType ?? ownScope) !== ownScope) return undefined;
785
+ return getTopicHostMcpGrant(topic.id) ?? undefined;
786
+ }
787
+
788
+ export interface StartAiTurnParams extends AiTurnExecutionOptions {
789
+ topic: AiTurnTopic;
790
+ userId: string;
791
+ /** Credential namespace. Defaults to userId for backwards compatibility. */
792
+ vaultUserId?: string;
793
+ prompt: string;
794
+ allowAutoContinue: boolean;
795
+ agentOverride?: AgentKind;
796
+ /** Stable query id reserved before a cross-process handoff. Internal only. */
797
+ _queryId?: string;
798
+ /** Topic epoch captured when queued. Internal reset-fence guard only. */
799
+ _runtimeEpoch?: number;
800
+ /** Ordered user submissions already folded into prompt. Internal handoff metadata only. */
801
+ _userMessages?: UserTurnEnvelope[];
802
+ /** Newly accepted user texts not yet written to the unified conversation log. */
803
+ _conversationPrompts?: string[];
804
+ /** Number of leading _userMessages already written to the conversation log. */
805
+ _loggedUserMessageCount?: number;
806
+ /** Durable rows whose envelopes are already present in _userMessages. */
807
+ _durableRequestIds?: string[];
808
+ _sessionRetried?: boolean;
809
+ /** Internal only. Caps the empty-provider-response retry to a single attempt. */
810
+ _emptyResponseRetried?: boolean;
811
+ }
812
+
813
+ export interface TriggerTopicAiTurnOptions extends AiTurnExecutionOptions {
814
+ /** Run the injected turn without writing the inject prompt as a visible message. */
815
+ hideInjectMessage?: boolean;
816
+ /** Visible injected-message author. Execution still runs as `userId`. */
817
+ injectAuthorId?: string;
818
+ /** Structured presentation metadata for an explicit cross-session delivery. */
819
+ injectKind?: MessageDto["kind"];
820
+ injectTellCard?: MessageDto["tellCard"];
821
+ /** Identifies the subsystem that created the visible injected message. */
822
+ injectSourceAdapter?: string;
823
+ injectSourceNode?: string;
824
+ injectSourceMessageId?: string;
825
+ }
826
+
827
+ const remoteInjectWaiters = new Map<string, ReturnType<typeof setInterval>>();
828
+
829
+ /**
830
+ * Whether a new human message comes from the person a running user turn is
831
+ * answering. Only that person may steer the turn (abort it and fold the new
832
+ * message into a resumed batch); anyone else's message queues behind it. The
833
+ * comparison mirrors the durable merge rule: two turns without a recorded
834
+ * actor are one conversation, but an unrecorded actor never matches a named
835
+ * one — the conservative reading, since the alternative is folding a
836
+ * stranger's message into a turn whose author is unknown.
837
+ */
838
+ export function sameTurnActor(
839
+ runningActorUserId: string | undefined,
840
+ incomingActorUserId: string | undefined,
841
+ ): boolean {
842
+ return (runningActorUserId ?? null) === (incomingActorUserId ?? null);
843
+ }
844
+
845
+ /**
846
+ * Whether the durable request another worker holds for `topicId` belongs to
847
+ * the same actor as an incoming user turn. `ownRequestIds` are the incoming
848
+ * turn's own durable rows, which the lookup must not mistake for the remote
849
+ * turn. No visible active request means the remote turn's actor is unknown,
850
+ * which is never "the same person".
851
+ */
852
+ function remoteTurnHasSameActor(
853
+ topicId: string,
854
+ incomingActorUserId: string | undefined,
855
+ ownRequestIds: readonly string[],
856
+ ): boolean {
857
+ const active = getActiveRuntimeUserTurnRequest(topicId);
858
+ if (!active || ownRequestIds.includes(active.requestId)) return false;
859
+ return sameTurnActor(active.execution?.actorUserId, incomingActorUserId);
860
+ }
861
+
862
+ export function mergeSupersedingUserTurn(
863
+ running: Pick<RoomQueryControl, "prompt" | "userMessages" | "attachments" | "sessionId">,
864
+ incoming: { prompt: string; userMessages?: UserTurnEnvelope[]; attachments?: string[] },
865
+ ): {
866
+ prompt: string;
867
+ userMessages: UserTurnEnvelope[];
868
+ attachments?: string[];
869
+ sessionId?: string | null;
870
+ } {
871
+ const userMessages = [
872
+ ...(running.userMessages ?? [legacyUserTurnEnvelope(running.prompt, running.attachments)]),
873
+ ...(incoming.userMessages ?? [legacyUserTurnEnvelope(incoming.prompt, incoming.attachments)]),
874
+ ];
875
+ return {
876
+ prompt: renderUserTurnBatch(userMessages),
877
+ userMessages,
878
+ attachments: flattenUserTurnAttachments(userMessages),
879
+ sessionId: running.sessionId,
880
+ };
881
+ }
882
+
883
+ export function userConversationPromptsToRecord(
884
+ renderedUserPrompts: readonly string[] | undefined,
885
+ loggedUserMessageCount: number | undefined,
886
+ agentPrompt: string,
887
+ ): string[] {
888
+ return renderedUserPrompts && loggedUserMessageCount !== undefined
889
+ ? renderedUserPrompts.slice(loggedUserMessageCount)
890
+ : [agentPrompt];
891
+ }
892
+
893
+ function serializableUserTurnExecution(params: StartAiTurnParams): RuntimeUserTurnExecution {
894
+ return {
895
+ runtimeEpoch: params._runtimeEpoch ?? getRuntimeTopicEpoch(params.topic.id),
896
+ sourceRequestId: params.requestId,
897
+ actorUserId: params.actorUserId,
898
+ actorTopicScope: params.actorTopicScope,
899
+ remoteSession: params.remoteSession,
900
+ agentOverride: params.agentOverride,
901
+ modelOverride: params.modelOverride,
902
+ effortOverride: params.effortOverride,
903
+ sessionId: params.sessionId,
904
+ sessionIdSpecified: params.sessionId !== undefined,
905
+ sessionScope: params.sessionScope,
906
+ cwd: params.cwd,
907
+ sessionName: params.sessionName,
908
+ sessionType: params.sessionType,
909
+ visualTools: params.visualTools,
910
+ fileDeliveryTools: params.fileDeliveryTools,
911
+ bridgeSessionFromHistory: params.bridgeSessionFromHistory,
912
+ peerBridge: params.peerBridge,
913
+ from: params.from,
914
+ vaultUserId: params.vaultUserId,
915
+ conversationPrompts: params._conversationPrompts ??
916
+ params._userMessages?.map((message) => message.prompt) ?? [params.prompt],
917
+ loggedUserMessageCount: params._loggedUserMessageCount,
918
+ };
919
+ }
920
+
921
+ function waitToStartRemoteUserTurn(
922
+ params: StartAiTurnParams,
923
+ queryId: string,
924
+ options?: { omitRequestIds?: string[] },
925
+ ): string {
926
+ const execution = serializableUserTurnExecution(params);
927
+ const incomingUserMessages = params._userMessages ?? [
928
+ legacyUserTurnEnvelope(params.prompt, params.attachments),
929
+ ];
930
+ const merged = mergeRuntimeUserTurnRequest({
931
+ topicId: params.topic.id,
932
+ userId: params.userId,
933
+ userMessages: incomingUserMessages,
934
+ allowAutoContinue: params.allowAutoContinue,
935
+ requestId: queryId,
936
+ execution,
937
+ topicEpoch: execution.runtimeEpoch ?? getRuntimeTopicEpoch(params.topic.id),
938
+ alreadyIncludedRequestIds: params._durableRequestIds,
939
+ omitRequestIds: options?.omitRequestIds,
940
+ });
941
+ for (const supersededRequestId of merged.supersededRequestIds) {
942
+ if (supersededRequestId !== merged.requestId) {
943
+ WsHub.get().broadcastAborted(params.topic.id, supersededRequestId, "superseded");
944
+ }
945
+ }
946
+ return merged.requestId;
947
+ }
948
+
949
+ function announceQueuedUserTurn(params: StartAiTurnParams, queryId: string): void {
950
+ try {
951
+ params.onDispatched?.(queryId);
952
+ } catch (err) {
953
+ logger.warn({ err, topicId: params.topic.id, queryId }, "ai: queued dispatch hook failed");
954
+ }
955
+ if (!params.silent) WsHub.get().broadcastAiActive(params.topic.id, queryId);
956
+ }
957
+
958
+ function waitToDrainRemoteInject(topicId: string): void {
959
+ if (remoteInjectWaiters.has(topicId)) return;
960
+ const timer = setInterval(() => {
961
+ if (
962
+ getRuntimeTurnLease(topicId) ||
963
+ getRoomQuery(topicId) ||
964
+ isRuntimeTopicMaintenance(topicId)
965
+ ) {
966
+ return;
967
+ }
968
+ clearInterval(timer);
969
+ remoteInjectWaiters.delete(topicId);
970
+ const next = takeDeferredInject(topicId);
971
+ if (next) redispatchInject(next);
972
+ }, 100);
973
+ timer.unref?.();
974
+ remoteInjectWaiters.set(topicId, timer);
975
+ }
976
+
977
+ let durableTurnWorker: ReturnType<typeof setInterval> | null = null;
978
+ let durableTurnWorkerBusy = false;
979
+
980
+ async function drainOneDurableUserTurn(): Promise<void> {
981
+ if (durableTurnWorkerBusy) return;
982
+ durableTurnWorkerBusy = true;
983
+ try {
984
+ const request = claimNextRuntimeUserTurnRequest(RUNTIME_INSTANCE_ID);
985
+ if (!request) return;
986
+ const topic = getTopic(request.topicId);
987
+ if (!topic?.agent) {
988
+ completeRuntimeUserTurnRequest(request.topicId, request.requestId, RUNTIME_INSTANCE_ID);
989
+ return;
990
+ }
991
+ const execution = request.execution;
992
+ const queryId = startAiTurn({
993
+ topic,
994
+ userId: request.userId,
995
+ actorUserId: execution?.actorUserId,
996
+ actorTopicScope: actorTopicScopeFrom(execution?.actorTopicScope),
997
+ remoteSession: remoteSessionGrantFrom(execution?.remoteSession),
998
+ vaultUserId: execution?.vaultUserId,
999
+ prompt: request.prompt,
1000
+ _userMessages: request.userMessages,
1001
+ _conversationPrompts: execution?.conversationPrompts ?? [request.prompt],
1002
+ _loggedUserMessageCount:
1003
+ execution?.loggedUserMessageCount ??
1004
+ Math.max(0, request.userMessages.length - (execution?.conversationPrompts?.length ?? 1)),
1005
+ _durableRequestIds: [request.requestId],
1006
+ attachments: request.attachments,
1007
+ allowAutoContinue: request.allowAutoContinue,
1008
+ origin: "user",
1009
+ requestId: execution?.sourceRequestId,
1010
+ agentOverride: execution?.agentOverride,
1011
+ modelOverride: execution?.modelOverride,
1012
+ effortOverride: execution?.effortOverride,
1013
+ ...(execution?.sessionIdSpecified ? { sessionId: execution.sessionId } : {}),
1014
+ sessionScope: execution?.sessionScope,
1015
+ cwd: execution?.cwd,
1016
+ sessionName: execution?.sessionName,
1017
+ sessionType: execution?.sessionType,
1018
+ visualTools: execution?.visualTools,
1019
+ fileDeliveryTools: execution?.fileDeliveryTools,
1020
+ silent: execution?.silent,
1021
+ bridgeSessionFromHistory: execution?.bridgeSessionFromHistory,
1022
+ peerBridge: execution?.peerBridge,
1023
+ from: execution?.from,
1024
+ threadRootId: execution?.threadRootId,
1025
+ _queryId: request.requestId,
1026
+ _runtimeEpoch: execution?.runtimeEpoch ?? request.topicEpoch,
1027
+ onSettled: () => {
1028
+ completeRuntimeUserTurnRequest(request.topicId, request.requestId, RUNTIME_INSTANCE_ID);
1029
+ },
1030
+ });
1031
+ if (!queryId) {
1032
+ releaseRuntimeUserTurnClaim(request.topicId, request.requestId, RUNTIME_INSTANCE_ID);
1033
+ return;
1034
+ }
1035
+ markRuntimeUserTurnRunning(request.topicId, request.requestId, RUNTIME_INSTANCE_ID, queryId);
1036
+ } finally {
1037
+ durableTurnWorkerBusy = false;
1038
+ }
1039
+ }
1040
+
1041
+ /** Start a process-local claimant for durable user turns. Multiple processes
1042
+ * may run this worker; SQLite claims and topic leases choose exactly one. */
1043
+ export function startDurableTurnRequestWorker(): () => void {
1044
+ if (durableTurnWorker) return () => {};
1045
+ durableTurnWorker = setInterval(() => {
1046
+ void drainOneDurableUserTurn();
1047
+ }, 100);
1048
+ durableTurnWorker.unref?.();
1049
+ void drainOneDurableUserTurn();
1050
+ return () => {
1051
+ if (!durableTurnWorker) return;
1052
+ clearInterval(durableTurnWorker);
1053
+ durableTurnWorker = null;
1054
+ };
1055
+ }
1056
+
1057
+ /**
1058
+ * Start one AI turn for a topic: resolve agent/model/effort from
1059
+ * `config override > topic default`, run the agent, and stream events. Returns
1060
+ * the queryId.
1061
+ *
1062
+ * Caller guarantees the topic has an AI participant (agent set) —
1063
+ * people-only rooms are rejected upstream, so self-config / AI never
1064
+ * attach there.
1065
+ *
1066
+ * `allowAutoContinue`: when the AI changes this topic's config mid-turn via
1067
+ * runtime MCP, allow the runtime MCP context to enqueue ONE continue
1068
+ * turn. Follow-up turns pass false, so config changes cannot recurse.
1069
+ */
1070
+ export function startAiTurn(params: StartAiTurnParams): string | null {
1071
+ // A caller may have retained an old DTO while another surface changed the
1072
+ // topic. Durable state is authoritative at the execution boundary.
1073
+ const storedTopic = getTopic(params.topic.id);
1074
+ if (!storedTopic || (!storedTopic.agent && !params.agentOverride)) {
1075
+ if (params.forkHandle) cleanupAgentFork(params.forkHandle);
1076
+ try {
1077
+ params.onSettled?.({
1078
+ queryId: "",
1079
+ kind: "error",
1080
+ error: storedTopic ? "topic no longer has an AI agent" : "topic no longer exists",
1081
+ });
1082
+ } catch (err) {
1083
+ logger.warn({ err, topicId: params.topic.id }, "ai: rejected-turn settlement hook failed");
1084
+ }
1085
+ return null;
1086
+ }
1087
+ const topic: TopicDto = storedTopic;
1088
+ const { userId, allowAutoContinue, onDispatched } = params;
1089
+ const vaultUserId = params.vaultUserId ?? userId;
1090
+ const origin = params.origin ?? "user";
1091
+ const conversationPrompts = params._conversationPrompts ?? [params.prompt];
1092
+ let loggedUserMessageCount = params._loggedUserMessageCount;
1093
+ let durableRequestIds = params._durableRequestIds ?? [];
1094
+ let userMessages = isUserOrigin(origin)
1095
+ ? (params._userMessages ?? [legacyUserTurnEnvelope(params.prompt, params.attachments)])
1096
+ : undefined;
1097
+ let prompt = userMessages ? renderUserTurnBatch(userMessages) : params.prompt;
1098
+ let attachments = userMessages ? flattenUserTurnAttachments(userMessages) : params.attachments;
1099
+ const execution = resolveTopicTurnExecution(topic, params);
1100
+ const sessionResolution = resolveTopicTurnSession(topic, params.sessionId, {
1101
+ agentOverride: params.agentOverride,
1102
+ modelOverride: params.modelOverride,
1103
+ effortOverride: params.effortOverride,
1104
+ silent: params.silent,
1105
+ sessionScope: params.sessionScope,
1106
+ sessionName: params.sessionName,
1107
+ sessionType: params.sessionType,
1108
+ hasFork: Boolean(params.forkHandle),
1109
+ preparesSession: Boolean(params.prepareSession),
1110
+ externalSessionOwner: Boolean(params.onSessionId),
1111
+ });
1112
+ let sessionId = sessionResolution.sessionId;
1113
+ // Topic-owned sessions are deliberately re-resolved after a defer. Isolated
1114
+ // and explicit sessions retain the id supplied by their owner.
1115
+ const deferredSessionId =
1116
+ params.sessionId === undefined && !sessionResolution.isolated ? undefined : sessionId;
1117
+ const sourceNode = params.sourceNode;
1118
+ const threadRootId = params.threadRootId;
1119
+ const topicId = topic.id;
1120
+ const requestId = params.requestId;
1121
+ const depth = params.depth;
1122
+ const silent = params.silent;
1123
+ const contextId = params.contextId;
1124
+ const agentOverride = params.agentOverride;
1125
+ const modelOverride = params.modelOverride;
1126
+ const effortOverride = params.effortOverride;
1127
+ const sessionScope = params.sessionScope;
1128
+ const turnConcurrency = params.turnConcurrency ?? "topic";
1129
+ let forkHandle = params.forkHandle;
1130
+ const prepareSession = params.prepareSession;
1131
+ const cwd = params.cwd;
1132
+ const sessionName = params.sessionName ?? topic.title;
1133
+ const sessionType = params.sessionType;
1134
+ const { visualTools, fileDeliveryTools } = resolveTurnToolCapabilities(topicId, params);
1135
+ const hostMcpServers = resolveTurnHostMcpServers(topic, sessionType);
1136
+ const onSessionId = params.onSessionId;
1137
+ const onSessionReset = params.onSessionReset;
1138
+ const bridgeSessionFromHistory = params.bridgeSessionFromHistory === true;
1139
+ const onSettled = params.onSettled;
1140
+ const peerBridge = params.peerBridge;
1141
+ const askReplySources = params.askReplySources;
1142
+ const sessionRetried = params._sessionRetried === true;
1143
+ const emptyResponseRetried = params._emptyResponseRetried === true;
1144
+ const queryId = asTurnId(params._queryId ?? randomUUID());
1145
+ const roomId: TurnSlotKey =
1146
+ turnConcurrency === "isolated" ? isolatedTurnRoomId(topicId, queryId) : asTurnSlotKey(topicId);
1147
+ const currentRuntimeEpoch = getRuntimeTopicEpoch(topic.id);
1148
+ const runtimeEpoch = params._runtimeEpoch ?? currentRuntimeEpoch;
1149
+ if (params._runtimeEpoch !== undefined && params._runtimeEpoch !== currentRuntimeEpoch) {
1150
+ if (params.forkHandle) cleanupAgentFork(params.forkHandle);
1151
+ if (!params.silent && params._queryId) {
1152
+ WsHub.get().broadcastAborted(topic.id, params._queryId, "stopped");
1153
+ }
1154
+ try {
1155
+ params.onSettled?.({ queryId, kind: "aborted", abortReason: AbortReason.External });
1156
+ } catch (err) {
1157
+ logger.warn({ err, topicId: topic.id, queryId }, "ai: stale-turn settlement hook failed");
1158
+ }
1159
+ logger.info(
1160
+ { topicId: topic.id, queryId, queuedEpoch: params._runtimeEpoch, currentRuntimeEpoch },
1161
+ "ai: dropped work queued before topic reset",
1162
+ );
1163
+ return null;
1164
+ }
1165
+
1166
+ const deferCurrentTurn = (): boolean => {
1167
+ const queued = deferInject({
1168
+ topicId,
1169
+ runtimeEpoch,
1170
+ userId,
1171
+ vaultUserId,
1172
+ prompt,
1173
+ origin,
1174
+ sourceNode,
1175
+ requestId,
1176
+ depth,
1177
+ silent,
1178
+ contextId,
1179
+ agentOverride,
1180
+ modelOverride,
1181
+ effortOverride,
1182
+ sessionId: deferredSessionId,
1183
+ sessionScope,
1184
+ turnConcurrency,
1185
+ forkHandle,
1186
+ prepareSession,
1187
+ cwd,
1188
+ sessionName,
1189
+ sessionType,
1190
+ visualTools,
1191
+ fileDeliveryTools,
1192
+ onSessionId,
1193
+ onSessionReset,
1194
+ bridgeSessionFromHistory,
1195
+ onSettled,
1196
+ peerBridge,
1197
+ askReplySources,
1198
+ _sessionRetried: sessionRetried,
1199
+ onDispatched,
1200
+ from: params.from,
1201
+ });
1202
+ if (!queued && forkHandle) cleanupAgentFork(forkHandle);
1203
+ return queued;
1204
+ };
1205
+
1206
+ const rejectIsolatedTurnBeforeDispatch = (error: string): null => {
1207
+ if (forkHandle) cleanupAgentFork(forkHandle);
1208
+ try {
1209
+ onSettled?.({ queryId: "", kind: "error", error });
1210
+ } catch (err) {
1211
+ logger.warn({ err, topicId, queryId }, "ai: isolated-turn rejection hook failed");
1212
+ }
1213
+ return null;
1214
+ };
1215
+
1216
+ if (turnConcurrency === "isolated" && isRuntimeTopicMaintenance(topicId)) {
1217
+ return rejectIsolatedTurnBeforeDispatch("target topic is being reset or deleted");
1218
+ }
1219
+
1220
+ // Abort-on-new-message priority is scoped to the runtime room. Normal turns
1221
+ // share the topic room; a read-only ask fork owns a private room and can run
1222
+ // immediately beside the target topic's visible user turn.
1223
+ const decision = decideNewQuery(roomId, origin);
1224
+ if (decision.action === "defer") {
1225
+ if (turnConcurrency === "isolated") {
1226
+ return rejectIsolatedTurnBeforeDispatch("isolated turn slot is already occupied");
1227
+ }
1228
+ deferCurrentTurn();
1229
+ logger.info({ topicId, origin }, "ai: session-inject deferred behind running turn");
1230
+ return null;
1231
+ }
1232
+ if (decision.action === "remote-defer") {
1233
+ if (turnConcurrency === "isolated") {
1234
+ return rejectIsolatedTurnBeforeDispatch(
1235
+ "isolated turn slot is owned by another runtime process",
1236
+ );
1237
+ }
1238
+ if (deferCurrentTurn()) waitToDrainRemoteInject(topicId);
1239
+ logger.info(
1240
+ { topicId, origin, remoteQueryId: decision.running.queryId },
1241
+ "ai: session-inject deferred behind a turn owned by another process",
1242
+ );
1243
+ return null;
1244
+ }
1245
+ if (decision.action === "remote-abort-wait") {
1246
+ // Only the same person's follow-up steers the turn the other process is
1247
+ // running; anyone else's message just waits for the lease to be released.
1248
+ if (remoteTurnHasSameActor(topicId, params.actorUserId, durableRequestIds)) {
1249
+ requestRuntimeTurnAbort(topicId, "internal");
1250
+ }
1251
+ const queuedQueryId = waitToStartRemoteUserTurn(
1252
+ {
1253
+ ...params,
1254
+ topic,
1255
+ prompt,
1256
+ attachments,
1257
+ sessionId,
1258
+ _userMessages: userMessages,
1259
+ _conversationPrompts: conversationPrompts,
1260
+ _loggedUserMessageCount: loggedUserMessageCount,
1261
+ _runtimeEpoch: runtimeEpoch,
1262
+ },
1263
+ queryId,
1264
+ );
1265
+ announceQueuedUserTurn({ ...params, topic }, queuedQueryId);
1266
+ logger.info(
1267
+ { topicId, queryId: queuedQueryId, remoteQueryId: decision.running.queryId },
1268
+ "ai: user turn waiting for another process to release the topic lease",
1269
+ );
1270
+ return queuedQueryId;
1271
+ }
1272
+ if (decision.action === "abort-replace") {
1273
+ const running = decision.running;
1274
+ // Another person's running answer is not this message's to interrupt. The
1275
+ // message keeps its own durable row (the merge never folds across actors)
1276
+ // and the worker claims it once the running turn releases the room. A
1277
+ // running session-inject is still preempted by any human message.
1278
+ if (isUserOrigin(running.origin) && !sameTurnActor(running.actorUserId, params.actorUserId)) {
1279
+ const queuedQueryId = waitToStartRemoteUserTurn(
1280
+ {
1281
+ ...params,
1282
+ topic,
1283
+ prompt,
1284
+ attachments,
1285
+ sessionId,
1286
+ _userMessages: userMessages,
1287
+ _conversationPrompts: conversationPrompts,
1288
+ _loggedUserMessageCount: loggedUserMessageCount,
1289
+ _durableRequestIds: durableRequestIds,
1290
+ _runtimeEpoch: runtimeEpoch,
1291
+ },
1292
+ queryId,
1293
+ );
1294
+ announceQueuedUserTurn({ ...params, topic }, queuedQueryId);
1295
+ logger.info(
1296
+ { topicId, queryId: queuedQueryId, runningQueryId: running.queryId },
1297
+ "ai: user turn from another actor queued behind the running turn",
1298
+ );
1299
+ return queuedQueryId;
1300
+ }
1301
+ let omitRequestIds: string[] | undefined;
1302
+ if (isUserOrigin(running.origin)) {
1303
+ if (running.providerTurnContentObserved && running.sessionId) {
1304
+ // The native rollout already contains the interrupted user turn and
1305
+ // any partial assistant/tool history. Send only the new envelope after
1306
+ // the old provider process has exited; replaying the prior prompt makes
1307
+ // the model restart the work and can race two writers on one rollout.
1308
+ sessionId = running.sessionId;
1309
+ omitRequestIds = running.durableRequestIds;
1310
+ } else {
1311
+ const merged = mergeSupersedingUserTurn(running, { prompt, userMessages, attachments });
1312
+ userMessages = merged.userMessages;
1313
+ prompt = merged.prompt;
1314
+ attachments = merged.attachments;
1315
+ // No provider session was observed, so replay from the pre-turn base.
1316
+ sessionId = merged.sessionId;
1317
+ loggedUserMessageCount = running.userMessages?.length ?? 1;
1318
+ durableRequestIds = [
1319
+ ...new Set([...(running.durableRequestIds ?? []), ...durableRequestIds]),
1320
+ ];
1321
+ }
1322
+ }
1323
+ // The preempted turn was itself a session-inject → re-queue it so the
1324
+ // inter-session work isn't lost; it resumes after the user's turn.
1325
+ if (running.injectParams) {
1326
+ const runningInject = running.injectParams;
1327
+ // A silent ask fork may already contain a partially-consumed provider
1328
+ // rollout. Requeue only its recipe, never that mutable rollout; the old
1329
+ // turn's finally block owns cleanup and the replay prepares a fresh fork.
1330
+ const requeuedInject = prepareInjectReplayAfterUserPreemption(runningInject);
1331
+ const queued = deferInject(requeuedInject);
1332
+ running.injectRequeued = queued;
1333
+ if (queued && runningInject.prepareSession) {
1334
+ // The queued copy retained requestId, so detach it from the dying
1335
+ // control. The async preparation may still publish an old fork after
1336
+ // this abort; finally must clean that fork instead of mistaking it for
1337
+ // the queued replay's resource.
1338
+ running.injectParams = { ...runningInject, requestId: undefined };
1339
+ } else if (!queued && runningInject.forkHandle) {
1340
+ cleanupAgentFork(runningInject.forkHandle);
1341
+ running.injectParams = {
1342
+ ...runningInject,
1343
+ forkHandle: undefined,
1344
+ sessionId: undefined,
1345
+ };
1346
+ }
1347
+ }
1348
+ running.abortReason = AbortReason.Internal;
1349
+ running.abortController.abort();
1350
+ logger.info(
1351
+ { topicId, supersededQueryId: running.queryId, supersededOrigin: running.origin },
1352
+ "ai: new user message superseded running turn",
1353
+ );
1354
+ // Do not synchronously start another provider against the same native
1355
+ // session while the aborted process is still flushing its rollout. The
1356
+ // durable worker can claim this replacement only after the old room lease
1357
+ // is released in streamAgentEvents' finally block.
1358
+ const queuedQueryId = waitToStartRemoteUserTurn(
1359
+ {
1360
+ ...params,
1361
+ topic,
1362
+ prompt,
1363
+ attachments,
1364
+ sessionId,
1365
+ _userMessages: userMessages,
1366
+ _conversationPrompts: conversationPrompts,
1367
+ _loggedUserMessageCount: loggedUserMessageCount,
1368
+ _durableRequestIds: durableRequestIds,
1369
+ _runtimeEpoch: runtimeEpoch,
1370
+ },
1371
+ queryId,
1372
+ { omitRequestIds },
1373
+ );
1374
+ announceQueuedUserTurn({ ...params, topic }, queuedQueryId);
1375
+ return queuedQueryId;
1376
+ }
1377
+
1378
+ const abortController = new AbortController();
1379
+ const control: RoomQueryControl = {
1380
+ topicId,
1381
+ roomId,
1382
+ queryId,
1383
+ origin,
1384
+ prompt,
1385
+ userMessages,
1386
+ ...(isUserOrigin(origin) && params.actorUserId !== undefined
1387
+ ? { actorUserId: params.actorUserId }
1388
+ : {}),
1389
+ durableRequestIds,
1390
+ attachments,
1391
+ sessionId,
1392
+ abortController,
1393
+ abortReason: AbortReason.None,
1394
+ // Preserve enough to re-queue this turn if a later user message preempts it.
1395
+ injectParams: isUserOrigin(origin)
1396
+ ? undefined
1397
+ : {
1398
+ topicId,
1399
+ runtimeEpoch,
1400
+ userId,
1401
+ vaultUserId,
1402
+ prompt,
1403
+ origin,
1404
+ requestId,
1405
+ depth,
1406
+ silent,
1407
+ contextId,
1408
+ agentOverride,
1409
+ modelOverride,
1410
+ effortOverride,
1411
+ sessionId: deferredSessionId,
1412
+ sessionScope,
1413
+ turnConcurrency,
1414
+ forkHandle,
1415
+ prepareSession,
1416
+ cwd,
1417
+ sessionName,
1418
+ sessionType,
1419
+ visualTools,
1420
+ fileDeliveryTools,
1421
+ onSessionId,
1422
+ onSessionReset,
1423
+ bridgeSessionFromHistory,
1424
+ onSettled,
1425
+ peerBridge,
1426
+ askReplySources,
1427
+ _sessionRetried: sessionRetried,
1428
+ onDispatched,
1429
+ from: params.from,
1430
+ },
1431
+ };
1432
+ if (!setRoomQuery(control)) {
1433
+ // Another process won the lease between the decision and the atomic claim.
1434
+ // Preserve the same user-priority behavior and retry after that owner
1435
+ // releases (or its heartbeat expires).
1436
+ if (turnConcurrency === "isolated") {
1437
+ return rejectIsolatedTurnBeforeDispatch("failed to claim isolated turn slot");
1438
+ }
1439
+ if (isUserOrigin(origin)) {
1440
+ if (remoteTurnHasSameActor(topicId, params.actorUserId, durableRequestIds)) {
1441
+ requestRuntimeTurnAbort(topicId, "internal");
1442
+ }
1443
+ const queuedQueryId = waitToStartRemoteUserTurn(
1444
+ {
1445
+ ...params,
1446
+ topic,
1447
+ prompt,
1448
+ attachments,
1449
+ sessionId,
1450
+ _userMessages: userMessages,
1451
+ _conversationPrompts: conversationPrompts,
1452
+ _loggedUserMessageCount: loggedUserMessageCount,
1453
+ _durableRequestIds: durableRequestIds,
1454
+ _runtimeEpoch: runtimeEpoch,
1455
+ },
1456
+ queryId,
1457
+ );
1458
+ announceQueuedUserTurn({ ...params, topic }, queuedQueryId);
1459
+ return queuedQueryId;
1460
+ } else if (deferCurrentTurn()) {
1461
+ waitToDrainRemoteInject(topicId);
1462
+ }
1463
+ return null;
1464
+ }
1465
+ if (turnConcurrency === "topic") {
1466
+ try {
1467
+ writeQueryState(userId, topic.id, topic.title, prompt);
1468
+ } catch (err) {
1469
+ logger.warn({ err, topicId, userId }, "ai: failed to write active query state");
1470
+ }
1471
+ }
1472
+ try {
1473
+ onDispatched?.(queryId);
1474
+ } catch (err) {
1475
+ // Module/adapter observers are outside the turn's trust boundary. A broken
1476
+ // observer must not leave the room occupied without starting its provider.
1477
+ logger.warn({ err, topicId, queryId }, "ai: dispatch hook failed");
1478
+ }
1479
+
1480
+ // Priority: config override > topic default. (Per-message slash overrides
1481
+ // were removed — switching is config-only now.) Cross-agent-stale models are
1482
+ // dropped to the agent's default by resolveModelForAgent.
1483
+ const override = getTopicConfig(topicId);
1484
+ const agentKind = execution.agent;
1485
+ const resolvedModel = execution.model;
1486
+ const resolvedEffort = execution.effort;
1487
+
1488
+ const workspaceCwd = cwd ?? workspaceCwdFor(topicId);
1489
+ mkdirSync(workspaceCwd, { recursive: true });
1490
+ let historyBridgeError: string | undefined;
1491
+ if (bridgeSessionFromHistory && !sessionId) {
1492
+ const bridge = tryReconstructTopicRollout({
1493
+ topicId,
1494
+ topicTitle: sessionName,
1495
+ userId,
1496
+ agent: agentKind,
1497
+ sessionId: null,
1498
+ cwd: workspaceCwd,
1499
+ model: resolvedModel,
1500
+ ...(resolvedEffort ? { effort: resolvedEffort } : {}),
1501
+ });
1502
+ if (bridge.kind === "rebuilt") {
1503
+ sessionId = bridge.sessionId;
1504
+ control.sessionId = bridge.sessionId;
1505
+ if (control.injectParams) control.injectParams.sessionId = bridge.sessionId;
1506
+ try {
1507
+ onSessionId?.(bridge.sessionId);
1508
+ } catch (err) {
1509
+ logger.warn(
1510
+ { err, topicId, queryId, agent: agentKind },
1511
+ "ai: isolated session owner rejected bridged provider session id",
1512
+ );
1513
+ }
1514
+ } else if (bridge.kind === "failed") {
1515
+ historyBridgeError =
1516
+ "Conversation history could not be encoded into a provider session; no fresh session was started.";
1517
+ }
1518
+ }
1519
+ const messageAttachmentGroups = userMessages?.map((message, index) =>
1520
+ materializePromptAttachments(topicId, `${queryId}-${index}`, message.attachments),
1521
+ );
1522
+ const promptAttachments =
1523
+ messageAttachmentGroups?.flat() ?? materializePromptAttachments(topicId, queryId, attachments);
1524
+ const promptWithFiles = userMessages
1525
+ ? renderUserTurnBatch(
1526
+ userMessages.map((message, index) => ({
1527
+ ...message,
1528
+ prompt: promptWithAttachments(message.prompt, messageAttachmentGroups?.[index] ?? []),
1529
+ })),
1530
+ )
1531
+ : promptWithAttachments(prompt, promptAttachments);
1532
+ const renderedUserPrompts = userMessages
1533
+ ? userMessages.map((message, index) =>
1534
+ renderUserTurnPrompt({
1535
+ ...message,
1536
+ prompt: promptWithAttachments(message.prompt, messageAttachmentGroups?.[index] ?? []),
1537
+ }),
1538
+ )
1539
+ : undefined;
1540
+ const agentPrompt =
1541
+ topic.aiMode === "mention" && isUserOrigin(origin) && !silent
1542
+ ? buildMentionOnlyChannelPrompt({
1543
+ topicId,
1544
+ userId,
1545
+ prompt,
1546
+ promptWithFiles,
1547
+ hasSession: Boolean(sessionId),
1548
+ })
1549
+ : promptWithFiles;
1550
+
1551
+ logger.info(
1552
+ {
1553
+ queryId,
1554
+ topicId,
1555
+ resolvedAgent: agentKind,
1556
+ resolvedModel,
1557
+ resolvedEffort,
1558
+ origin,
1559
+ silent: Boolean(silent),
1560
+ requestId,
1561
+ depth,
1562
+ resumeSessionId: sessionId ? sessionId.slice(0, 8) : null,
1563
+ freshSession: !sessionId,
1564
+ autoContinue: allowAutoContinue,
1565
+ attachmentCount: attachments?.length ?? 0,
1566
+ materializedAttachmentCount: promptAttachments.length,
1567
+ },
1568
+ "ai: dispatching query",
1569
+ );
1570
+
1571
+ const aiLabel = getGlobalAiName();
1572
+
1573
+ // R2: inject shared topic brief into system prompt for AI-invited topic turns.
1574
+ // In-memory process can read SQLite synchronously — zero latency for hot path.
1575
+ const topicRecord = getTopic(topicId);
1576
+ const systemPromptOpts = {
1577
+ aiLabel,
1578
+ topicTitle: topic.title,
1579
+ workspaceCwd,
1580
+ agentKind,
1581
+ surface: topicRecord?.surface ?? topic.surface,
1582
+ currentModel: resolvedModel,
1583
+ currentEffort: resolvedEffort,
1584
+ description: topic.description,
1585
+ canSpawnSubagents: peerBridge?.canSpawnSubagents ?? canSpawnSubagentsFromTopic(topicId),
1586
+ canStageSubagents: !peerBridge && canSpawnSubagentsFromTopic(topicId),
1587
+ subagentParentTitle:
1588
+ topicRecord?.isSubagent && topicRecord.parentTopicId
1589
+ ? getTopic(topicRecord.parentTopicId)?.title
1590
+ : undefined,
1591
+ subagentReportMode: topicRecord?.isSubagent ? subagentReportMode(topicId) : undefined,
1592
+ visualTools,
1593
+ fileDeliveryTools,
1594
+ };
1595
+ const isManager = topicRecord?.kind === "manager";
1596
+ const isMentionOnlyChannel = topic.aiMode === "mention" && !isManager;
1597
+ let systemPrompt = isManager
1598
+ ? buildManagerSystemPrompt(systemPromptOpts)
1599
+ : isMentionOnlyChannel
1600
+ ? buildChannelSystemPrompt(systemPromptOpts)
1601
+ : buildTopicSystemPrompt(systemPromptOpts);
1602
+ const memoryTopic =
1603
+ isMentionOnlyChannel || isManager || topic.memoryKey
1604
+ ? topic
1605
+ : (getTopicMemoryOrigin(topicId) ?? topic);
1606
+ const memoryTitle = memoryTopic.memoryKey?.trim() || memoryTopic.title;
1607
+ if (!isMentionOnlyChannel) {
1608
+ let hasMemoryArchive = false;
1609
+ try {
1610
+ const resolvedBrief = resolveTopicBrief(memoryTopic.id, memoryTitle);
1611
+ // #General is the workspace memory hub: its brief is the rolling digest the
1612
+ // archiver accumulates across ALL archived topics, and its files live in the
1613
+ // SHARED wiki root (getSharedWikiDir), not this topic's per-room workspace.
1614
+ const wikiDir = getSharedWikiDir();
1615
+ const { latestSummaryFile } = resolveWikiMemoryMirror(wikiDir, memoryTopic.id, memoryTitle);
1616
+ hasMemoryArchive = Boolean(resolvedBrief?.brief.latestSummaryMd || latestSummaryFile);
1617
+ } catch (err) {
1618
+ // Brief fetch failure is non-fatal — don't block the turn.
1619
+ logger.warn({ topicId, err }, "ai: failed to inject topic brief");
1620
+ }
1621
+ systemPrompt += buildMemoryPromptSection({
1622
+ topicTitle: topic.title,
1623
+ ...(memoryTopic.memoryKey ? { memoryKey: memoryTopic.memoryKey } : {}),
1624
+ hasArchive: hasMemoryArchive,
1625
+ isManager,
1626
+ });
1627
+ }
1628
+ const activeVisual = visualTools ? getActiveVisualForPrompt(topicId, userId) : null;
1629
+ if (activeVisual) {
1630
+ const label = activeVisual.title ? `"${activeVisual.title}"` : `#${activeVisual.index}`;
1631
+ const promptVisual = activeVisualHtmlForPrompt(activeVisual.content);
1632
+ const visualContentLabel =
1633
+ activeVisual.fence === "html"
1634
+ ? "HTML"
1635
+ : activeVisual.fence === "mermaid"
1636
+ ? "Mermaid source"
1637
+ : "visual content";
1638
+ systemPrompt += [
1639
+ "",
1640
+ "",
1641
+ "## Active Visual Panel",
1642
+ `The user is currently viewing a ${activeVisual.kind} visual ${label} (${activeVisual.index} of ${activeVisual.total}) in the side panel.`,
1643
+ "Its current source/content is shown below when available. Reference or modify it directly when the user asks to update the visual:",
1644
+ ...(promptVisual.omittedChars > 0
1645
+ ? [
1646
+ `The ${visualContentLabel} is truncated for prompt size; ${promptVisual.omittedChars} characters from the middle are omitted.`,
1647
+ ]
1648
+ : []),
1649
+ `\`\`\`${activeVisual.fence}`,
1650
+ promptVisual.html,
1651
+ "```",
1652
+ ].join("\n");
1653
+ }
1654
+
1655
+ /**
1656
+ * Per-turn `<system-reminder>` blocks kept out of the stable system prompt.
1657
+ *
1658
+ * These facts flip between turns on the same model — whether the browser MCP
1659
+ * came up, whether this turn is an auto-resume. A prompt cache invalidates
1660
+ * from the first diverging byte, so putting them in the system prompt means
1661
+ * every flip re-reads the entire prompt: measured against the live DeepSeek
1662
+ * API, one flip at turn 15 of a 20-turn conversation cost 17,852 uncached
1663
+ * tokens (hit=0) versus 1,215 with the reminder on the user turn — 40% more
1664
+ * uncached tokens across the run. Claude/Codex receive them at the user prompt
1665
+ * tail. Maestro projects them onto its invocation-start user wire message via
1666
+ * `ephemeralSystemPrompt`, fixed across that invocation's tool iterations.
1667
+ *
1668
+ * Applied after the conversation log is written, so a reminder never becomes
1669
+ * part of the recorded user message (it would then persist into synthesized
1670
+ * rollouts and defeat the point).
1671
+ */
1672
+ const turnReminders: string[] = [];
1673
+
1674
+ if (params.from === FROM_AUTO_CONTINUE) {
1675
+ turnReminders.push(
1676
+ "<system-reminder>이 턴은 설정 자동 조정(effort/model/agent) 후 자동 재개된 턴이다. effort/model/agent 난이도 재평가 및 설정 변경 없이 즉시 작업을 시작할 것.</system-reminder>",
1677
+ );
1678
+ }
1679
+
1680
+ if (!silent && !sessionRetried) {
1681
+ const promptsToRecord = userConversationPromptsToRecord(
1682
+ renderedUserPrompts,
1683
+ loggedUserMessageCount,
1684
+ agentPrompt,
1685
+ );
1686
+ const consecutiveBatchSize =
1687
+ userMessages && userMessages.length > 1 ? userMessages.length : undefined;
1688
+ const firstPromptIndex = loggedUserMessageCount ?? 0;
1689
+ for (const [index, content] of promptsToRecord.entries()) {
1690
+ const appended = appendConversationEvent(userId, sessionName, agentKind, {
1691
+ type: "user_message",
1692
+ content,
1693
+ ...(consecutiveBatchSize
1694
+ ? {
1695
+ consecutiveBatchSize,
1696
+ consecutiveBatchIndex: firstPromptIndex + index,
1697
+ }
1698
+ : {}),
1699
+ });
1700
+ if (!appended) break;
1701
+ loggedUserMessageCount = firstPromptIndex + index + 1;
1702
+ markRuntimeUserTurnMessagesLogged(
1703
+ topicId,
1704
+ queryId,
1705
+ RUNTIME_INSTANCE_ID,
1706
+ userMessages?.slice(0, loggedUserMessageCount) ?? [],
1707
+ );
1708
+ }
1709
+ }
1710
+
1711
+ // Wrap runAgent in a lazy async generator so we can `await ensurePlaywright`
1712
+ // at the moment streaming starts (startAiTurn itself is sync — it returns the
1713
+ // queryId immediately and streams in the background). Bring up a long-lived
1714
+ // Playwright and Background Bash MCPs for every non-manager topic. Without
1715
+ // a live `playwrightPort`,
1716
+ // mcp-config omits the
1717
+ // playwright entry entirely, so the agent connects but sees NO browser tools
1718
+ // — the "playwright active but tools missing" bug. The host must allocate
1719
+ // the port before building MCP config. Named browser profiles still control
1720
+ // which topics share a Chromium process and login state. Non-fatal.
1721
+ const configuredMcp = override?.mcp ?? [];
1722
+ const enabledMcp = withDefaultPlaywright(configuredMcp, isManager);
1723
+ const playwrightRequested = !isManager && enabledMcp.includes("playwright");
1724
+ const browserProfileOwner = isTopicBrowserProfileOwner(topic.id, userId);
1725
+ const wantsPlaywright = playwrightRequested && browserProfileOwner;
1726
+ const turnMcpEnabled = browserProfileOwner
1727
+ ? enabledMcp
1728
+ : enabledMcp.filter((name) => name !== "playwright");
1729
+ const wantsBgBash = !isManager && enabledMcp.includes("background-bash");
1730
+ async function* runWithPlaywright(): AsyncGenerator<UnifiedEvent> {
1731
+ if (historyBridgeError) {
1732
+ yield { type: "error", content: historyBridgeError };
1733
+ return;
1734
+ }
1735
+ if (prepareSession && !sessionId) {
1736
+ if (abortController.signal.aborted) return;
1737
+ try {
1738
+ const prepared = await prepareSession();
1739
+ sessionId = prepared.forkId;
1740
+ forkHandle = prepared;
1741
+ control.sessionId = prepared.forkId;
1742
+ if (control.injectParams) {
1743
+ control.injectParams.sessionId = prepared.forkId;
1744
+ control.injectParams.forkHandle = prepared;
1745
+ }
1746
+ } catch (err) {
1747
+ throw new Error(`failed to prepare isolated session: ${stringifyError(err)}`);
1748
+ }
1749
+ if (abortController.signal.aborted) return;
1750
+ }
1751
+ let playwrightPort: number | undefined;
1752
+ let playwrightCapability: string | undefined;
1753
+ let playwrightInstanceKey: string | undefined;
1754
+ let bgBashPort: number | undefined;
1755
+ if (wantsPlaywright) {
1756
+ try {
1757
+ playwrightInstanceKey = makeInstanceKey(userId, topic.id);
1758
+ // Pin before ensurePlaywright's asynchronous health check so an idle
1759
+ // sweep cannot evict the instance between validation and turn setup.
1760
+ pinPlaywrightInstance(playwrightInstanceKey);
1761
+ playwrightPort = await ensurePlaywright(userId, topic.id);
1762
+ playwrightCapability = getPlaywrightCapability(playwrightInstanceKey);
1763
+ if (!playwrightCapability) {
1764
+ throw new Error("browser MCP capability was not registered");
1765
+ }
1766
+ trackPlaywrightTurn(playwrightInstanceKey, control);
1767
+ } catch (err) {
1768
+ logger.warn(
1769
+ { topicId, err },
1770
+ "ai: ensurePlaywright failed — proceeding without browser tools",
1771
+ );
1772
+ markPlaywrightUnavailable({
1773
+ userId,
1774
+ topic: topic.title,
1775
+ agent: agentKind,
1776
+ });
1777
+ if (!silent) notifyPlaywrightUnavailable(topicId);
1778
+ }
1779
+ }
1780
+ if (wantsBgBash) {
1781
+ try {
1782
+ bgBashPort = await ensureBgBash(userId, topic.id);
1783
+ } catch (err) {
1784
+ logger.warn(
1785
+ { topicId, err },
1786
+ "ai: ensureBgBash failed — proceeding without background bash tools",
1787
+ );
1788
+ // Say so in the turn. Losing the tool silently makes the model plan
1789
+ // around a capability it does not have, and the operator only finds
1790
+ // out by reading server logs.
1791
+ turnReminders.push(
1792
+ "<system-reminder>Background bash tools are UNAVAILABLE this turn. The `background_bash_*` tools could not be prepared, most often because the bash-rs binary is not installed on this host. Do not attempt to call them; run short commands in the foreground instead, and tell the user if the work genuinely needs a background job.</system-reminder>",
1793
+ );
1794
+ }
1795
+ }
1796
+ if (playwrightRequested && !browserProfileOwner) {
1797
+ turnReminders.push(
1798
+ "<system-reminder>Browser tools are unavailable in this turn because browser profiles are private to the topic owner. Do not attempt browser calls or ask to reuse the owner's login state.</system-reminder>",
1799
+ );
1800
+ }
1801
+ if (consumePlaywrightUnavailable(userId, topic.title)) {
1802
+ turnReminders.push(
1803
+ "<system-reminder>Playwright browser tools are UNAVAILABLE this turn. The `mcp__playwright__*` tools have been removed from this turn's catalog because the long-lived browser MCP could not be prepared. Do not attempt to call browser tools. If browser interaction is required, ask the user to retry shortly or use a non-browser alternative.</system-reminder>",
1804
+ );
1805
+ }
1806
+ // Build this after conversation recording: transient runtime facts must be
1807
+ // supplied again by the host on a later external turn, never resumed from
1808
+ // Negotium's canonical conversation state.
1809
+ const reminderQuery = buildTurnReminderQuery(agentKind, agentPrompt, turnReminders);
1810
+
1811
+ try {
1812
+ yield* runAgent({
1813
+ agent: agentKind,
1814
+ ...reminderQuery,
1815
+ attachments: promptAttachments,
1816
+ cwd: workspaceCwd,
1817
+ systemPrompt,
1818
+ sessionId,
1819
+ userId,
1820
+ actorUserId: params.actorUserId,
1821
+ actorTopicScope: params.actorTopicScope,
1822
+ remoteSession: params.remoteSession,
1823
+ vaultUserId,
1824
+ session: sessionName,
1825
+ sessionType: sessionType ?? (isManager ? "manager" : "forum"),
1826
+ abortController,
1827
+ model: resolvedModel,
1828
+ effort: resolvedEffort,
1829
+ depth,
1830
+ silent,
1831
+ // Default OFF: with no override a topic loads only the REQUIRED servers (no
1832
+ // optional ones). Optional servers are opt-in per topic via the settings UI
1833
+ // / #General set_topic_mcp. `[]` = required-only; getForumMcpServers reserves
1834
+ // `null`/`undefined` for "all optional", which Otium no longer defaults to.
1835
+ mcpEnabled: turnMcpEnabled,
1836
+ playwrightPort,
1837
+ playwrightCapability,
1838
+ bgBashPort,
1839
+ topicId,
1840
+ subagentParentTopicId:
1841
+ topicRecord?.isSubagent && topicRecord.parentTopicId
1842
+ ? topicRecord.parentTopicId
1843
+ : undefined,
1844
+ queryId,
1845
+ wikiTopicId: memoryTopic.id,
1846
+ autoContinue: allowAutoContinue && !silent,
1847
+ visualTools,
1848
+ fileDeliveryTools,
1849
+ hostMcpServers,
1850
+ // Turn-scoped, so the runtime MCP this turn connects to can answer
1851
+ // "which thread am I in" without the model having to know the id.
1852
+ ...(threadRootId ? { threadRootId } : {}),
1853
+ peerBridge,
1854
+ });
1855
+ } finally {
1856
+ if (playwrightInstanceKey) {
1857
+ untrackPlaywrightTurn(playwrightInstanceKey, control);
1858
+ unpinPlaywrightInstance(playwrightInstanceKey);
1859
+ }
1860
+ }
1861
+ }
1862
+ // Provider streams can stay silent while reasoning, starting MCPs, or
1863
+ // waiting on a long tool. Otium covers Claude thinking signals; this
1864
+ // channel-neutral fallback keeps every Negotium host alive for all agents.
1865
+ const providerEvents = runWithPlaywright();
1866
+ const events = silent ? providerEvents : withTurnSilenceHeartbeat(providerEvents);
1867
+
1868
+ // Let UI show typing indicator while AI works (including tool calls / thinking).
1869
+ if (!silent) {
1870
+ WsHub.get().broadcastTyping(topicId, "ai");
1871
+ // Carry the queryId so clients can bind typing/tool UI to turns they did
1872
+ // not initiate (subagent task turns, session injects, other participants).
1873
+ WsHub.get().broadcastAiActive(topicId, queryId);
1874
+ }
1875
+
1876
+ streamAgentEvents(
1877
+ topicId,
1878
+ topic.title,
1879
+ queryId,
1880
+ events,
1881
+ control,
1882
+ agentKind,
1883
+ resolvedModel,
1884
+ resolvedEffort,
1885
+ userId,
1886
+ !sessionRetried,
1887
+ onSessionId,
1888
+ {
1889
+ silent,
1890
+ actorUserId: params.actorUserId,
1891
+ peerBridge,
1892
+ sourceNode,
1893
+ ...(threadRootId ? { threadRootId } : {}),
1894
+ },
1895
+ )
1896
+ .then(async (streamOutcome) => {
1897
+ let outcome = streamOutcome;
1898
+ if (outcome.kind === "session-expired") {
1899
+ const retry = resolveSessionRetry({
1900
+ topicId,
1901
+ topicTitle: sessionName,
1902
+ userId,
1903
+ agent: agentKind,
1904
+ sessionId,
1905
+ cwd: workspaceCwd,
1906
+ silent: Boolean(silent),
1907
+ model: resolvedModel,
1908
+ ...(resolvedEffort ? { effort: resolvedEffort } : {}),
1909
+ externalSessionOwner: Boolean(onSessionId),
1910
+ onSessionReset,
1911
+ });
1912
+ if (retry.kind === "failed") {
1913
+ outcome = {
1914
+ kind: "provider-error",
1915
+ error:
1916
+ "Provider session expired and conversation history could not be rebuilt; the existing session was preserved for retry.",
1917
+ };
1918
+ } else {
1919
+ // No terminal event, and the same queryId carries over (see the
1920
+ // `_queryId` note on the empty-response retry below): this is one
1921
+ // logical turn recovering internally, not a turn that ended.
1922
+ const retrySessionId = retry.sessionId;
1923
+ logger.info(
1924
+ {
1925
+ topicId,
1926
+ queryId,
1927
+ agent: agentKind,
1928
+ retrySessionId: retrySessionId ? retrySessionId.slice(0, 8) : null,
1929
+ },
1930
+ "ai: retrying query after session expiry",
1931
+ );
1932
+ if (!retrySessionId && prepareSession && forkHandle) {
1933
+ // The retry will invoke the recipe and mint a different rollout.
1934
+ // The expired fork is no longer in use after stream cleanup.
1935
+ cleanupAgentFork(forkHandle);
1936
+ forkHandle = undefined;
1937
+ }
1938
+ startAiTurn({
1939
+ topic,
1940
+ userId,
1941
+ actorUserId: params.actorUserId,
1942
+ actorTopicScope: params.actorTopicScope,
1943
+ remoteSession: params.remoteSession,
1944
+ vaultUserId,
1945
+ prompt,
1946
+ _userMessages: userMessages,
1947
+ _conversationPrompts: conversationPrompts,
1948
+ _loggedUserMessageCount: loggedUserMessageCount,
1949
+ _durableRequestIds: durableRequestIds,
1950
+ attachments,
1951
+ allowAutoContinue,
1952
+ origin,
1953
+ onDispatched,
1954
+ requestId,
1955
+ depth,
1956
+ silent,
1957
+ contextId,
1958
+ agentOverride,
1959
+ modelOverride,
1960
+ effortOverride,
1961
+ sessionId: retrySessionId,
1962
+ sessionScope,
1963
+ turnConcurrency,
1964
+ forkHandle,
1965
+ // Keep the recipe so a later user preemption can replay from a
1966
+ // clean snapshot. A non-empty retrySessionId suppresses immediate
1967
+ // preparation in runWithPlaywright.
1968
+ prepareSession,
1969
+ cwd,
1970
+ sessionName,
1971
+ sessionType,
1972
+ visualTools,
1973
+ fileDeliveryTools,
1974
+ onSessionId,
1975
+ onSessionReset,
1976
+ bridgeSessionFromHistory,
1977
+ onSettled,
1978
+ peerBridge,
1979
+ askReplySources,
1980
+ _runtimeEpoch: runtimeEpoch,
1981
+ _sessionRetried: true,
1982
+ _queryId: queryId,
1983
+ });
1984
+ return;
1985
+ }
1986
+ }
1987
+
1988
+ if (outcome.kind === "empty-response") {
1989
+ if (emptyResponseRetried) {
1990
+ // Already retried once and still got nothing back — stop masking it
1991
+ // and report a normal provider failure.
1992
+ outcome = { kind: "provider-error", error: outcome.error };
1993
+ } else {
1994
+ // Observed cause: a queued background-task notification flushes into
1995
+ // the CLI session at the same instant this turn is dispatched, and
1996
+ // the CLI self-interrupts within ~1-2s with a zero-usage "success".
1997
+ // A same-session retry has reliably produced a real reply in every
1998
+ // case seen so far, so retry once before surfacing a failure.
1999
+ // Deliberately NO terminal event here, and the retry keeps this
2000
+ // queryId. An internal retry is invisible bookkeeping: the turn the
2001
+ // caller asked for is still running. Emitting `ai_aborted` made a
2002
+ // host treat the turn as over — the hub revokes the turn's remote
2003
+ // session-comm capability on any terminal event for its queryId, so
2004
+ // the retried attempt found its own remote tools answering 401 —
2005
+ // and a fresh queryId would leave the original one with no terminal
2006
+ // event at all, stranding that capability for its whole ceiling.
2007
+ logger.info(
2008
+ { topicId, queryId, agent: agentKind },
2009
+ "ai: retrying query after empty provider response",
2010
+ );
2011
+ startAiTurn({
2012
+ topic,
2013
+ userId,
2014
+ actorUserId: params.actorUserId,
2015
+ actorTopicScope: params.actorTopicScope,
2016
+ remoteSession: params.remoteSession,
2017
+ vaultUserId,
2018
+ prompt,
2019
+ _userMessages: userMessages,
2020
+ _conversationPrompts: conversationPrompts,
2021
+ _loggedUserMessageCount: loggedUserMessageCount,
2022
+ _durableRequestIds: durableRequestIds,
2023
+ attachments,
2024
+ allowAutoContinue,
2025
+ origin,
2026
+ onDispatched,
2027
+ requestId,
2028
+ depth,
2029
+ silent,
2030
+ contextId,
2031
+ agentOverride,
2032
+ modelOverride,
2033
+ effortOverride,
2034
+ sessionId,
2035
+ sessionScope,
2036
+ turnConcurrency,
2037
+ forkHandle,
2038
+ prepareSession,
2039
+ cwd,
2040
+ sessionName,
2041
+ sessionType,
2042
+ visualTools,
2043
+ fileDeliveryTools,
2044
+ onSessionId,
2045
+ onSessionReset,
2046
+ bridgeSessionFromHistory,
2047
+ onSettled,
2048
+ peerBridge,
2049
+ askReplySources,
2050
+ _runtimeEpoch: runtimeEpoch,
2051
+ _sessionRetried: sessionRetried,
2052
+ _emptyResponseRetried: true,
2053
+ _queryId: queryId,
2054
+ });
2055
+ return;
2056
+ }
2057
+ }
2058
+
2059
+ if (outcome.kind === "budget-capped") {
2060
+ const error = "The job reached its cost limit";
2061
+ if (!silent) {
2062
+ appendSystemMessage(
2063
+ topicId,
2064
+ "여기까지 완료했어요. 비용 예산 한도에 도달해 작업을 멈췄습니다.",
2065
+ threadRootId,
2066
+ );
2067
+ WsHub.get().broadcastDone(
2068
+ topicId,
2069
+ queryId,
2070
+ outcome.usage
2071
+ ? {
2072
+ input: outcome.usage.inputTokens,
2073
+ output: outcome.usage.outputTokens,
2074
+ cachedInput: outcome.usage.cacheReadInputTokens,
2075
+ context: outcome.usage.contextTokens,
2076
+ contextWindow: outcome.usage.contextWindow,
2077
+ }
2078
+ : undefined,
2079
+ { agent: agentKind, model: resolvedModel, budgetReason: outcome.reason },
2080
+ );
2081
+ WsHub.get().broadcastTopicNotice(topicId, "warning", "예산 한도 도달");
2082
+ }
2083
+ // Visible ask_session turns run on the target session too, so the
2084
+ // caller must hear about the cap regardless of `silent`.
2085
+ await deliverAskError(queryId, topic.title, error);
2086
+ await settleSubagentFailure(queryId, error);
2087
+ try {
2088
+ onSettled?.({ queryId, kind: "error", error });
2089
+ } catch (err) {
2090
+ logger.warn({ err, topicId, queryId }, "ai: turn settlement hook failed");
2091
+ }
2092
+ return;
2093
+ }
2094
+
2095
+ if (outcome.kind === "provider-error") {
2096
+ if (!silent) {
2097
+ // Provider failures are user-visible, but Otium does not automatically
2098
+ // switch the topic to another provider. Users may register multiple
2099
+ // providers and explicitly change this topic with /model.
2100
+ appendSystemMessage(
2101
+ topicId,
2102
+ `${classifyAgentError(outcome.error, agentKind)}\n\n다른 등록된 모델을 쓰려면 /model <model>로 바꾼 뒤 다시 보내세요.`,
2103
+ threadRootId,
2104
+ );
2105
+ WsHub.get().broadcastError(topicId, queryId, outcome.error);
2106
+ WsHub.get().broadcastTopicNotice(topicId, "error", "응답 실패");
2107
+ }
2108
+ await deliverAskError(queryId, topic.title, outcome.error);
2109
+ await settleSubagentFailure(queryId, classifyAgentError(outcome.error, agentKind));
2110
+ try {
2111
+ onSettled?.({ queryId, kind: "error", error: outcome.error });
2112
+ } catch (err) {
2113
+ logger.warn({ err, topicId, queryId }, "ai: turn settlement hook failed");
2114
+ }
2115
+ return;
2116
+ }
2117
+ const requeuedAfterUserPreemption = wasLocallyRequeuedAfterUserPreemption(
2118
+ outcome.kind,
2119
+ control,
2120
+ );
2121
+ if (requeuedAfterUserPreemption) return;
2122
+ try {
2123
+ onSettled?.({
2124
+ queryId,
2125
+ kind: outcome.kind === "aborted" ? "aborted" : "completed",
2126
+ ...(outcome.kind === "aborted" ? { abortReason: control.abortReason } : {}),
2127
+ });
2128
+ } catch (err) {
2129
+ logger.warn({ err, topicId, queryId }, "ai: turn settlement hook failed");
2130
+ }
2131
+ })
2132
+ .catch(async (err) => {
2133
+ const error = err instanceof Error ? err.message : "Agent process crashed";
2134
+ logger.warn(
2135
+ { err, topicId, queryId, agent: agentKind, model: resolvedModel, silent },
2136
+ "ai: background stream task failed",
2137
+ );
2138
+ if (!silent) {
2139
+ WsHub.get().broadcastError(topicId, queryId, error);
2140
+ WsHub.get().broadcastTopicNotice(topicId, "error", "응답 실패");
2141
+ }
2142
+ await deliverAskError(queryId, topic.title, error);
2143
+ await settleSubagentFailure(queryId, classifyAgentError(error, agentKind));
2144
+ try {
2145
+ onSettled?.({
2146
+ queryId,
2147
+ kind: "error",
2148
+ error,
2149
+ });
2150
+ } catch (hookErr) {
2151
+ logger.warn({ err: hookErr, topicId, queryId }, "ai: turn settlement hook failed");
2152
+ }
2153
+ });
2154
+
2155
+ return queryId;
2156
+ }
2157
+
2158
+ export function wasLocallyRequeuedAfterUserPreemption(
2159
+ outcomeKind: StreamAgentOutcome["kind"],
2160
+ control: Pick<RoomQueryControl, "abortReason" | "injectParams" | "injectRequeued">,
2161
+ ): boolean {
2162
+ return (
2163
+ outcomeKind === "aborted" &&
2164
+ control.abortReason === AbortReason.Internal &&
2165
+ Boolean(control.injectParams) &&
2166
+ control.injectRequeued === true
2167
+ );
2168
+ }
2169
+
2170
+ /**
2171
+ * Prepare an injected turn for replay after a user preempts it. An eager ask
2172
+ * can carry both its first fork and a regeneration recipe; only the recipe is
2173
+ * safe to retain once the provider may have partially consumed that fork.
2174
+ */
2175
+ export function prepareInjectReplayAfterUserPreemption(
2176
+ runningInject: DeferredInject,
2177
+ ): DeferredInject {
2178
+ return runningInject.prepareSession
2179
+ ? { ...runningInject, sessionId: undefined, forkHandle: undefined }
2180
+ : runningInject;
2181
+ }
2182
+
2183
+ /**
2184
+ * Programmatic AI turn trigger — used by session-comm (tell/ask) and any
2185
+ * internal consumer that needs to inject a prompt into a topic's AI pipeline.
2186
+ *
2187
+ * Returns the queryId so callers can track the result, or null if the topic
2188
+ * has no AI participant (AI not invited).
2189
+ */
2190
+ export function triggerTopicAiTurn(
2191
+ topicId: string,
2192
+ userId: string,
2193
+ prompt: string,
2194
+ agentType?: AgentKind,
2195
+ opts?: TriggerTopicAiTurnOptions,
2196
+ ): string | null {
2197
+ const topics = getTopics();
2198
+ const topic = topics.find((t) => t.id === topicId) as TopicDto | undefined;
2199
+ if (!topic?.agent) return null;
2200
+
2201
+ const topicCfg: AiTurnTopic = {
2202
+ id: topic.id,
2203
+ title: topic.title,
2204
+ kind: topic.kind,
2205
+ description: topic.description,
2206
+ agent: topic.agent,
2207
+ defaultModel: topic.defaultModel,
2208
+ defaultEffort: topic.defaultEffort,
2209
+ aiMode: topic.aiMode,
2210
+ aiMention: topic.aiMention,
2211
+ };
2212
+ const execution = resolveTopicTurnExecution(topicCfg, {
2213
+ agentOverride: agentType,
2214
+ modelOverride: opts?.modelOverride,
2215
+ effortOverride: opts?.effortOverride,
2216
+ });
2217
+
2218
+ if (!opts?.silent && !opts?.hideInjectMessage) {
2219
+ // Show the injected message in the receiving topic immediately, decoupled
2220
+ // from when the AI turn actually runs — the turn may be deferred behind a
2221
+ // running user turn, but participants should see the inject arrive now.
2222
+ const now = new Date().toISOString();
2223
+ const injectMsg: MessageDto = {
2224
+ id: opts?.requestId ? `tell-${opts.requestId}` : `tell-${randomUUID()}`,
2225
+ topicId,
2226
+ authorId: opts?.injectAuthorId ?? userId,
2227
+ sourceAdapter: opts?.injectSourceAdapter,
2228
+ sourceNode: opts?.injectSourceNode,
2229
+ sourceMessageId: opts?.injectSourceMessageId,
2230
+ authorName: execution.agent,
2231
+ text: prompt,
2232
+ agentType: execution.agent,
2233
+ model: execution.model,
2234
+ kind: opts?.injectKind,
2235
+ tellCard: opts?.injectTellCard,
2236
+ createdAt: now,
2237
+ };
2238
+ try {
2239
+ appendApiMessage(injectMsg);
2240
+ WsHub.get().broadcastMessage(topicId, injectMsg);
2241
+ } catch (error) {
2242
+ // Session-inbox rows are replayed after an interrupted worker. A stable
2243
+ // request-derived id makes the visible handoff converge on one message.
2244
+ if (!opts?.requestId || !getApiMessage(topicId, injectMsg.id)) throw error;
2245
+ }
2246
+ }
2247
+
2248
+ // Dispatch (or defer) the AI turn. origin != "user" → never preempts a
2249
+ // running user turn; the user keeps priority (Otium inter-session rule).
2250
+ return startAiTurn({
2251
+ topic: topicCfg,
2252
+ userId,
2253
+ prompt,
2254
+ attachments: opts?.attachments,
2255
+ allowAutoContinue: false,
2256
+ origin: opts?.origin ?? `inject:${agentType ?? topic.agent ?? "session"}`,
2257
+ onDispatched: opts?.onDispatched,
2258
+ requestId: opts?.requestId,
2259
+ depth: opts?.depth,
2260
+ silent: opts?.silent,
2261
+ contextId: opts?.contextId,
2262
+ agentOverride: agentType,
2263
+ modelOverride: opts?.modelOverride,
2264
+ effortOverride: opts?.effortOverride,
2265
+ sessionId: opts?.sessionId,
2266
+ sessionScope: opts?.sessionScope,
2267
+ turnConcurrency: opts?.turnConcurrency,
2268
+ forkHandle: opts?.forkHandle,
2269
+ prepareSession: opts?.prepareSession,
2270
+ cwd: opts?.cwd,
2271
+ sessionName: opts?.sessionName,
2272
+ sessionType: opts?.sessionType,
2273
+ visualTools: opts?.visualTools,
2274
+ fileDeliveryTools: opts?.fileDeliveryTools,
2275
+ onSessionId: opts?.onSessionId,
2276
+ onSessionReset: opts?.onSessionReset,
2277
+ bridgeSessionFromHistory: opts?.bridgeSessionFromHistory,
2278
+ onSettled: opts?.onSettled,
2279
+ peerBridge: opts?.peerBridge,
2280
+ sourceNode: opts?.injectSourceNode,
2281
+ askReplySources: opts?.askReplySources,
2282
+ from: opts?.from,
2283
+ });
2284
+ }