@otium-team/negotium 0.0.0-stage → 0.23.13

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