@otium-team/negotium 0.0.0-stage → 0.23.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (572) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +329 -2
  3. package/bin/codex-sdk-window-hide.mjs +40 -0
  4. package/bin/negotium.mjs +22 -0
  5. package/dist/agent-helpers.js +23903 -0
  6. package/dist/agent-helpers.js.map +171 -0
  7. package/dist/background-bash.js +535 -0
  8. package/dist/background-bash.js.map +16 -0
  9. package/dist/browser-runtime.js +2336 -0
  10. package/dist/browser-runtime.js.map +35 -0
  11. package/dist/canonical-mcp-bridge.js +14 -0
  12. package/dist/canonical-mcp-bridge.js.map +9 -0
  13. package/dist/chunk-0fenxbe6.js +173 -0
  14. package/dist/chunk-0fenxbe6.js.map +12 -0
  15. package/dist/chunk-2mx7fq49.js +6 -0
  16. package/dist/chunk-2mx7fq49.js.map +9 -0
  17. package/dist/chunk-ad7kxsaq.js +202 -0
  18. package/dist/chunk-ad7kxsaq.js.map +9 -0
  19. package/dist/chunk-da9ad838.js +3927 -0
  20. package/dist/chunk-da9ad838.js.map +47 -0
  21. package/dist/chunk-f7p0h1gs.js +54 -0
  22. package/dist/chunk-f7p0h1gs.js.map +10 -0
  23. package/dist/chunk-jtv8yzy1.js +206 -0
  24. package/dist/chunk-jtv8yzy1.js.map +10 -0
  25. package/dist/chunk-mxxwx5mg.js +375 -0
  26. package/dist/chunk-mxxwx5mg.js.map +13 -0
  27. package/dist/cron.js +1 -0
  28. package/dist/hosted-agent.js +5919 -0
  29. package/dist/hosted-agent.js.map +62 -0
  30. package/dist/main.js +60536 -0
  31. package/dist/main.js.map +338 -0
  32. package/dist/mcp-catalog.js +39 -0
  33. package/dist/mcp-catalog.js.map +10 -0
  34. package/dist/mcp-factories.js +26572 -0
  35. package/dist/mcp-factories.js.map +181 -0
  36. package/dist/mcp-servers.js +50 -0
  37. package/dist/mcp-servers.js.map +10 -0
  38. package/dist/media.js +570 -0
  39. package/dist/media.js.map +15 -0
  40. package/dist/outbox.js +354 -0
  41. package/dist/outbox.js.map +15 -0
  42. package/dist/platform-runtime.js +73 -0
  43. package/dist/platform-runtime.js.map +12 -0
  44. package/dist/prompts.js +892 -0
  45. package/dist/prompts.js.map +15 -0
  46. package/dist/query-runtime.js +1073 -0
  47. package/dist/query-runtime.js.map +26 -0
  48. package/dist/registry.js +336 -0
  49. package/dist/registry.js.map +14 -0
  50. package/dist/rollout.js +57 -0
  51. package/dist/rollout.js.map +10 -0
  52. package/dist/runtime/cron/background-sessions.ts +119 -0
  53. package/dist/runtime/cron/context.ts +123 -0
  54. package/dist/runtime/cron/host.ts +67 -0
  55. package/dist/runtime/cron/index.ts +95 -0
  56. package/dist/runtime/cron/mcp-server.ts +556 -0
  57. package/dist/runtime/cron/module.ts +174 -0
  58. package/dist/runtime/cron/package.json +6 -0
  59. package/dist/runtime/cron/schedule.ts +211 -0
  60. package/dist/runtime/cron/scheduler.ts +444 -0
  61. package/dist/runtime/cron/scripts.ts +203 -0
  62. package/dist/runtime/cron/store.ts +1163 -0
  63. package/dist/runtime/cron/summarize.ts +115 -0
  64. package/dist/runtime/package.json +6 -0
  65. package/dist/runtime/scripts/faster-whisper-wrapper.py +87 -0
  66. package/dist/runtime/src/agents/api-topic-agent-switch.ts +179 -0
  67. package/dist/runtime/src/agents/archiver.ts +677 -0
  68. package/dist/runtime/src/agents/auth-check.ts +156 -0
  69. package/dist/runtime/src/agents/claude-notices.ts +130 -0
  70. package/dist/runtime/src/agents/claude-provider.ts +866 -0
  71. package/dist/runtime/src/agents/claude-registry.ts +117 -0
  72. package/dist/runtime/src/agents/claude-runtime-inspection.ts +43 -0
  73. package/dist/runtime/src/agents/codex-app-server.ts +138 -0
  74. package/dist/runtime/src/agents/codex-native-multi-agent.ts +360 -0
  75. package/dist/runtime/src/agents/codex-provider.ts +1193 -0
  76. package/dist/runtime/src/agents/codex-registry.ts +116 -0
  77. package/dist/runtime/src/agents/codex-tier-resolver.ts +74 -0
  78. package/dist/runtime/src/agents/codex-tree-kill.ts +54 -0
  79. package/dist/runtime/src/agents/codex-tree-manager.ts +230 -0
  80. package/dist/runtime/src/agents/codex-vault-hook-bridge.ts +240 -0
  81. package/dist/runtime/src/agents/codex-vault-hook.mjs +50 -0
  82. package/dist/runtime/src/agents/codex-windows-wrapper.ts +174 -0
  83. package/dist/runtime/src/agents/compaction-support.ts +75 -0
  84. package/dist/runtime/src/agents/compaction-tool-projection.ts +125 -0
  85. package/dist/runtime/src/agents/contracts.ts +75 -0
  86. package/dist/runtime/src/agents/deep-map.ts +13 -0
  87. package/dist/runtime/src/agents/execution-host.ts +118 -0
  88. package/dist/runtime/src/agents/explicit-agent-switch.ts +106 -0
  89. package/dist/runtime/src/agents/fixtures/claude-attachments.jsonl +2 -0
  90. package/dist/runtime/src/agents/fixtures/codex-shell.jsonl +5 -0
  91. package/dist/runtime/src/agents/fork.ts +100 -0
  92. package/dist/runtime/src/agents/hosted-agent.ts +78 -0
  93. package/dist/runtime/src/agents/idle-archiver.ts +225 -0
  94. package/dist/runtime/src/agents/idle-compact.ts +225 -0
  95. package/dist/runtime/src/agents/index.ts +225 -0
  96. package/dist/runtime/src/agents/maestro-provider.ts +246 -0
  97. package/dist/runtime/src/agents/maestro-registry.ts +189 -0
  98. package/dist/runtime/src/agents/mcp-tools/ask-user.ts +653 -0
  99. package/dist/runtime/src/agents/mcp-tools/common.ts +23 -0
  100. package/dist/runtime/src/agents/mcp-tools/inline-assets.ts +203 -0
  101. package/dist/runtime/src/agents/mcp-tools/publish-html.ts +183 -0
  102. package/dist/runtime/src/agents/mcp-tools/request-vault.ts +684 -0
  103. package/dist/runtime/src/agents/mcp-tools/self-config.ts +353 -0
  104. package/dist/runtime/src/agents/mcp-tools/spawn-subagent.ts +1349 -0
  105. package/dist/runtime/src/agents/mcp-tools/visual-compat.ts +18 -0
  106. package/dist/runtime/src/agents/mcp-tools/visuals.ts +60 -0
  107. package/dist/runtime/src/agents/memory-archive-policy.ts +54 -0
  108. package/dist/runtime/src/agents/model-catalog.ts +439 -0
  109. package/dist/runtime/src/agents/public-helpers.ts +149 -0
  110. package/dist/runtime/src/agents/registry.ts +35 -0
  111. package/dist/runtime/src/agents/rollout/claude.ts +336 -0
  112. package/dist/runtime/src/agents/rollout/codex.ts +910 -0
  113. package/dist/runtime/src/agents/rollout/index.ts +26 -0
  114. package/dist/runtime/src/agents/rollout/shared.ts +293 -0
  115. package/dist/runtime/src/agents/self-config-core.ts +704 -0
  116. package/dist/runtime/src/agents/task-events.ts +59 -0
  117. package/dist/runtime/src/agents/tool-format.ts +613 -0
  118. package/dist/runtime/src/agents/topic-agent-switch.ts +189 -0
  119. package/dist/runtime/src/agents/topic-cleanup.ts +285 -0
  120. package/dist/runtime/src/agents/vault-tool-policy.ts +36 -0
  121. package/dist/runtime/src/application/execute-external-user-turn.ts +23 -0
  122. package/dist/runtime/src/application/submit-runtime-gateway-turn.ts +420 -0
  123. package/dist/runtime/src/application/submit-user-message.ts +60 -0
  124. package/dist/runtime/src/application/switch-topic-effort.ts +48 -0
  125. package/dist/runtime/src/application/switch-topic-model.ts +79 -0
  126. package/dist/runtime/src/application/topic-service.ts +186 -0
  127. package/dist/runtime/src/application/vault-command.ts +170 -0
  128. package/dist/runtime/src/bus.ts +403 -0
  129. package/dist/runtime/src/config-public.ts +2 -0
  130. package/dist/runtime/src/cron-host.ts +33 -0
  131. package/dist/runtime/src/cron-mcp-host.ts +5 -0
  132. package/dist/runtime/src/identifiers.ts +49 -0
  133. package/dist/runtime/src/index.ts +573 -0
  134. package/dist/runtime/src/mcp/agent-health-server.ts +8 -0
  135. package/dist/runtime/src/mcp/canonical-bridge-config.ts +84 -0
  136. package/dist/runtime/src/mcp/canonical-proxy-server.ts +308 -0
  137. package/dist/runtime/src/mcp/compaction-log-server.ts +25 -0
  138. package/dist/runtime/src/mcp/decision-server.ts +21 -0
  139. package/dist/runtime/src/mcp/dm-ipc.ts +60 -0
  140. package/dist/runtime/src/mcp/factories/agent-health.ts +394 -0
  141. package/dist/runtime/src/mcp/factories/compaction-log.ts +135 -0
  142. package/dist/runtime/src/mcp/factories/decision.ts +186 -0
  143. package/dist/runtime/src/mcp/factories/index.ts +73 -0
  144. package/dist/runtime/src/mcp/factories/session-comm.ts +184 -0
  145. package/dist/runtime/src/mcp/factories/session-history.ts +103 -0
  146. package/dist/runtime/src/mcp/factories/stdio-protection.ts +24 -0
  147. package/dist/runtime/src/mcp/factories/system-health.ts +259 -0
  148. package/dist/runtime/src/mcp/factories/task.ts +185 -0
  149. package/dist/runtime/src/mcp/factories/token-stats.ts +145 -0
  150. package/dist/runtime/src/mcp/factories/vault.ts +32 -0
  151. package/dist/runtime/src/mcp/mcp-helpers.ts +40 -0
  152. package/dist/runtime/src/mcp/peer-bridge.ts +119 -0
  153. package/dist/runtime/src/mcp/runtime-spec.ts +473 -0
  154. package/dist/runtime/src/mcp/session-comm/actor-policy.ts +160 -0
  155. package/dist/runtime/src/mcp/session-comm/bridge-ipc-config.ts +27 -0
  156. package/dist/runtime/src/mcp/session-comm/context.ts +113 -0
  157. package/dist/runtime/src/mcp/session-comm/default-host.ts +723 -0
  158. package/dist/runtime/src/mcp/session-comm/history-target.ts +89 -0
  159. package/dist/runtime/src/mcp/session-comm/history-tools.ts +113 -0
  160. package/dist/runtime/src/mcp/session-comm/hub-remote-session.ts +553 -0
  161. package/dist/runtime/src/mcp/session-comm/limits.ts +8 -0
  162. package/dist/runtime/src/mcp/session-comm/peer-forward.ts +251 -0
  163. package/dist/runtime/src/mcp/session-comm/runtime.ts +128 -0
  164. package/dist/runtime/src/mcp/session-comm/server.ts +1036 -0
  165. package/dist/runtime/src/mcp/session-comm/tell-permissions.ts +79 -0
  166. package/dist/runtime/src/mcp/session-comm/topic-catalog.ts +155 -0
  167. package/dist/runtime/src/mcp/session-comm/topic-config.ts +137 -0
  168. package/dist/runtime/src/mcp/session-comm/topics.ts +313 -0
  169. package/dist/runtime/src/mcp/session-history-limits.ts +36 -0
  170. package/dist/runtime/src/mcp/session-history-reader.ts +359 -0
  171. package/dist/runtime/src/mcp/session-history-server.ts +19 -0
  172. package/dist/runtime/src/mcp/stdio-protect.ts +7 -0
  173. package/dist/runtime/src/mcp/system-health-server.ts +5 -0
  174. package/dist/runtime/src/mcp/task-server.ts +17 -0
  175. package/dist/runtime/src/mcp/token-stats-server.ts +10 -0
  176. package/dist/runtime/src/mcp/vault-server.ts +12 -0
  177. package/dist/runtime/src/mcp/wiki-search-index.ts +359 -0
  178. package/dist/runtime/src/mcp/wiki-server.ts +2386 -0
  179. package/dist/runtime/src/mcp-runtime-host.ts +81 -0
  180. package/dist/runtime/src/media/file-events.ts +33 -0
  181. package/dist/runtime/src/media/text-extractor.ts +334 -0
  182. package/dist/runtime/src/media/video.ts +92 -0
  183. package/dist/runtime/src/node-host.ts +200 -0
  184. package/dist/runtime/src/outbox/coalescing-runner.ts +157 -0
  185. package/dist/runtime/src/outbox/file-ops.ts +267 -0
  186. package/dist/runtime/src/outbox/index.ts +26 -0
  187. package/dist/runtime/src/outbox/utils.ts +74 -0
  188. package/dist/runtime/src/platform/background-bash/context.ts +9 -0
  189. package/dist/runtime/src/platform/background-bash/manager.ts +292 -0
  190. package/dist/runtime/src/platform/background-bash/output-buffer.ts +323 -0
  191. package/dist/runtime/src/platform/config-helpers.ts +47 -0
  192. package/dist/runtime/src/platform/config.ts +618 -0
  193. package/dist/runtime/src/platform/constants.ts +30 -0
  194. package/dist/runtime/src/platform/debug-users.ts +14 -0
  195. package/dist/runtime/src/platform/delay.ts +1 -0
  196. package/dist/runtime/src/platform/error.ts +9 -0
  197. package/dist/runtime/src/platform/file-utils.ts +35 -0
  198. package/dist/runtime/src/platform/ipc.ts +55 -0
  199. package/dist/runtime/src/platform/jsonl.ts +277 -0
  200. package/dist/runtime/src/platform/lifecycle.ts +176 -0
  201. package/dist/runtime/src/platform/log-rotation.ts +45 -0
  202. package/dist/runtime/src/platform/logger.ts +42 -0
  203. package/dist/runtime/src/platform/maestro-bootstrap-env.ts +3 -0
  204. package/dist/runtime/src/platform/mcp-catalog-policy.ts +63 -0
  205. package/dist/runtime/src/platform/mcp-config.ts +1329 -0
  206. package/dist/runtime/src/platform/memoize-import.ts +26 -0
  207. package/dist/runtime/src/platform/modules.ts +145 -0
  208. package/dist/runtime/src/platform/node-plugins.ts +46 -0
  209. package/dist/runtime/src/platform/paths.ts +62 -0
  210. package/dist/runtime/src/platform/playwright/browser-processes.ts +300 -0
  211. package/dist/runtime/src/platform/playwright/capability.ts +5 -0
  212. package/dist/runtime/src/platform/playwright/headed-launch.ts +61 -0
  213. package/dist/runtime/src/platform/playwright/manager-utils.ts +128 -0
  214. package/dist/runtime/src/platform/playwright/manager.ts +1502 -0
  215. package/dist/runtime/src/platform/playwright/mcp-transport.ts +35 -0
  216. package/dist/runtime/src/platform/playwright/profile-management.ts +33 -0
  217. package/dist/runtime/src/platform/playwright/public-runtime.ts +52 -0
  218. package/dist/runtime/src/platform/playwright/transport-probe.ts +89 -0
  219. package/dist/runtime/src/platform/playwright/vault-broker.ts +261 -0
  220. package/dist/runtime/src/platform/public-runtime.ts +18 -0
  221. package/dist/runtime/src/prompts/agents/wiki-archiver.md +194 -0
  222. package/dist/runtime/src/prompts/builders.ts +696 -0
  223. package/dist/runtime/src/prompts/sessions/_shared-tools.md +38 -0
  224. package/dist/runtime/src/prompts/sessions/channel-system.md +13 -0
  225. package/dist/runtime/src/prompts/sessions/manager-system.md +34 -0
  226. package/dist/runtime/src/prompts/sessions/surfaces/cli.md +6 -0
  227. package/dist/runtime/src/prompts/sessions/surfaces/otium-manager.md +18 -0
  228. package/dist/runtime/src/prompts/sessions/surfaces/otium.md +6 -0
  229. package/dist/runtime/src/prompts/sessions/surfaces/telegram.md +5 -0
  230. package/dist/runtime/src/prompts/sessions/surfaces/terminal.md +6 -0
  231. package/dist/runtime/src/prompts/sessions/topic-system.md +9 -0
  232. package/dist/runtime/src/prompts/sessions/visual-design.md +38 -0
  233. package/dist/runtime/src/query/active-rooms.ts +508 -0
  234. package/dist/runtime/src/query/index.ts +23 -0
  235. package/dist/runtime/src/query/public-runtime.ts +28 -0
  236. package/dist/runtime/src/query/room-query-registry.ts +217 -0
  237. package/dist/runtime/src/query/session-inbox-cleanup.ts +45 -0
  238. package/dist/runtime/src/query/session-inbox-path.ts +42 -0
  239. package/dist/runtime/src/query/state.ts +116 -0
  240. package/dist/runtime/src/query/types.ts +8 -0
  241. package/dist/runtime/src/runtime/actor-topic-reach.ts +123 -0
  242. package/dist/runtime/src/runtime/actor-topic-scope.ts +255 -0
  243. package/dist/runtime/src/runtime/ask-callbacks.ts +217 -0
  244. package/dist/runtime/src/runtime/attachments.ts +149 -0
  245. package/dist/runtime/src/runtime/background-session-policy.ts +1 -0
  246. package/dist/runtime/src/runtime/background-sessions.ts +288 -0
  247. package/dist/runtime/src/runtime/bashrs-completions.ts +350 -0
  248. package/dist/runtime/src/runtime/channel-context.ts +115 -0
  249. package/dist/runtime/src/runtime/context-warning.ts +131 -0
  250. package/dist/runtime/src/runtime/cron-sessions.ts +35 -0
  251. package/dist/runtime/src/runtime/delivery-ack.ts +112 -0
  252. package/dist/runtime/src/runtime/errors.ts +70 -0
  253. package/dist/runtime/src/runtime/event-heartbeat.ts +77 -0
  254. package/dist/runtime/src/runtime/file-hooks.ts +81 -0
  255. package/dist/runtime/src/runtime/footer.ts +23 -0
  256. package/dist/runtime/src/runtime/gateway-capabilities.ts +22 -0
  257. package/dist/runtime/src/runtime/inbox.ts +1307 -0
  258. package/dist/runtime/src/runtime/playwright-turn-abort.ts +59 -0
  259. package/dist/runtime/src/runtime/public-helpers.ts +78 -0
  260. package/dist/runtime/src/runtime/remote-session-grant.ts +221 -0
  261. package/dist/runtime/src/runtime/remote-session-inbox.ts +943 -0
  262. package/dist/runtime/src/runtime/remote-session-reply-outbox.ts +168 -0
  263. package/dist/runtime/src/runtime/task-format.ts +18 -0
  264. package/dist/runtime/src/runtime/tasks.ts +53 -0
  265. package/dist/runtime/src/runtime/thread-context.ts +123 -0
  266. package/dist/runtime/src/runtime/thread-read.ts +67 -0
  267. package/dist/runtime/src/runtime/topic-config.ts +29 -0
  268. package/dist/runtime/src/runtime/turn-event-stream.ts +1051 -0
  269. package/dist/runtime/src/runtime/turn-runner.ts +2284 -0
  270. package/dist/runtime/src/runtime/turn-session.ts +116 -0
  271. package/dist/runtime/src/runtime/usage-alert.ts +51 -0
  272. package/dist/runtime/src/runtime/user-turn-envelope.ts +94 -0
  273. package/dist/runtime/src/runtime/visual-html.ts +175 -0
  274. package/dist/runtime/src/runtime/visual-store.ts +480 -0
  275. package/dist/runtime/src/runtime/visuals.ts +209 -0
  276. package/dist/runtime/src/runtime-gateway.ts +848 -0
  277. package/dist/runtime/src/security/sanitize.ts +27 -0
  278. package/dist/runtime/src/security/sensitive-path.ts +41 -0
  279. package/dist/runtime/src/storage/activity-log.ts +167 -0
  280. package/dist/runtime/src/storage/api-messages.ts +766 -0
  281. package/dist/runtime/src/storage/api-topic-brief.ts +134 -0
  282. package/dist/runtime/src/storage/api-topic-config.ts +197 -0
  283. package/dist/runtime/src/storage/api-topics.ts +1647 -0
  284. package/dist/runtime/src/storage/app-settings.ts +50 -0
  285. package/dist/runtime/src/storage/ask-user-gates.ts +359 -0
  286. package/dist/runtime/src/storage/browser-profiles.ts +186 -0
  287. package/dist/runtime/src/storage/conversation-migration.ts +180 -0
  288. package/dist/runtime/src/storage/conversations.ts +377 -0
  289. package/dist/runtime/src/storage/decisions.ts +231 -0
  290. package/dist/runtime/src/storage/forum/agent-settings.ts +20 -0
  291. package/dist/runtime/src/storage/forum/index.ts +4 -0
  292. package/dist/runtime/src/storage/forum/repository.ts +283 -0
  293. package/dist/runtime/src/storage/forum/schema.ts +314 -0
  294. package/dist/runtime/src/storage/forum-db.ts +4 -0
  295. package/dist/runtime/src/storage/remote-session.ts +1028 -0
  296. package/dist/runtime/src/storage/runtime-events.ts +209 -0
  297. package/dist/runtime/src/storage/runtime-gateway-submissions.ts +132 -0
  298. package/dist/runtime/src/storage/runtime-leases.ts +190 -0
  299. package/dist/runtime/src/storage/runtime-process-leases.ts +288 -0
  300. package/dist/runtime/src/storage/runtime-topic-state.ts +181 -0
  301. package/dist/runtime/src/storage/runtime-turn-requests.ts +805 -0
  302. package/dist/runtime/src/storage/self-schedules.ts +306 -0
  303. package/dist/runtime/src/storage/session-asks.ts +468 -0
  304. package/dist/runtime/src/storage/session-inbox-signal.ts +76 -0
  305. package/dist/runtime/src/storage/session-inbox.ts +161 -0
  306. package/dist/runtime/src/storage/sqlite.ts +154 -0
  307. package/dist/runtime/src/storage/storage-contract.ts +54 -0
  308. package/dist/runtime/src/storage/storage-host.ts +336 -0
  309. package/dist/runtime/src/storage/storage-public-host.ts +16 -0
  310. package/dist/runtime/src/storage/storage-public.ts +66 -0
  311. package/dist/runtime/src/storage/tasks.ts +172 -0
  312. package/dist/runtime/src/storage/token-stats.ts +432 -0
  313. package/dist/runtime/src/storage/topic-archive-state.ts +226 -0
  314. package/dist/runtime/src/storage/topic-archive.ts +169 -0
  315. package/dist/runtime/src/storage/topic-host-mcp-grants.ts +54 -0
  316. package/dist/runtime/src/storage/topic-link-records.ts +1085 -0
  317. package/dist/runtime/src/storage/topic-settings.ts +67 -0
  318. package/dist/runtime/src/storage/topic-tool-capabilities.ts +89 -0
  319. package/dist/runtime/src/storage/topic-transcript.ts +98 -0
  320. package/dist/runtime/src/storage/vault-crypto-core.ts +65 -0
  321. package/dist/runtime/src/storage/vault-crypto.ts +31 -0
  322. package/dist/runtime/src/storage/vault-public.ts +27 -0
  323. package/dist/runtime/src/storage/vault-request-gates.ts +359 -0
  324. package/dist/runtime/src/storage/vault.ts +388 -0
  325. package/dist/runtime/src/storage/wiki-summary-names.ts +52 -0
  326. package/dist/runtime/src/storage/wiki.ts +90 -0
  327. package/dist/runtime/src/topics/claim-abort.ts +190 -0
  328. package/dist/runtime/src/topics/create.ts +192 -0
  329. package/dist/runtime/src/topics/derive.ts +600 -0
  330. package/dist/runtime/src/topics/lifecycle.ts +425 -0
  331. package/dist/runtime/src/topics/links.ts +7 -0
  332. package/dist/runtime/src/topics/personal-general.ts +91 -0
  333. package/dist/runtime/src/topics/session.ts +1041 -0
  334. package/dist/runtime/src/topics/update.ts +287 -0
  335. package/dist/runtime/src/types/api.ts +582 -0
  336. package/dist/runtime/src/types.ts +395 -0
  337. package/dist/runtime/src/version.ts +1 -0
  338. package/dist/runtime/tsconfig.json +13 -0
  339. package/dist/runtime-gateway.js +453 -0
  340. package/dist/runtime-gateway.js.map +10 -0
  341. package/dist/runtime-helpers.js +1794 -0
  342. package/dist/runtime-helpers.js.map +40 -0
  343. package/dist/sqlite.js +68 -0
  344. package/dist/sqlite.js.map +10 -0
  345. package/dist/storage.js +5194 -0
  346. package/dist/storage.js.map +47 -0
  347. package/dist/types/apps/negotium/src/mcp-servers.d.ts +20 -0
  348. package/dist/types/packages/core/src/agents/api-topic-agent-switch.d.ts +38 -0
  349. package/dist/types/packages/core/src/agents/archiver.d.ts +87 -0
  350. package/dist/types/packages/core/src/agents/auth-check.d.ts +19 -0
  351. package/dist/types/packages/core/src/agents/claude-notices.d.ts +15 -0
  352. package/dist/types/packages/core/src/agents/claude-provider.d.ts +25 -0
  353. package/dist/types/packages/core/src/agents/claude-registry.d.ts +3 -0
  354. package/dist/types/packages/core/src/agents/claude-runtime-inspection.d.ts +9 -0
  355. package/dist/types/packages/core/src/agents/codex-app-server.d.ts +13 -0
  356. package/dist/types/packages/core/src/agents/codex-native-multi-agent.d.ts +20 -0
  357. package/dist/types/packages/core/src/agents/codex-provider.d.ts +64 -0
  358. package/dist/types/packages/core/src/agents/codex-registry.d.ts +3 -0
  359. package/dist/types/packages/core/src/agents/codex-tier-resolver.d.ts +10 -0
  360. package/dist/types/packages/core/src/agents/codex-tree-kill.d.ts +13 -0
  361. package/dist/types/packages/core/src/agents/codex-tree-manager.d.ts +28 -0
  362. package/dist/types/packages/core/src/agents/codex-vault-hook-bridge.d.ts +28 -0
  363. package/dist/types/packages/core/src/agents/codex-windows-wrapper.d.ts +30 -0
  364. package/dist/types/packages/core/src/agents/compaction-support.d.ts +5 -0
  365. package/dist/types/packages/core/src/agents/compaction-tool-projection.d.ts +9 -0
  366. package/dist/types/packages/core/src/agents/contracts.d.ts +68 -0
  367. package/dist/types/packages/core/src/agents/deep-map.d.ts +2 -0
  368. package/dist/types/packages/core/src/agents/execution-host.d.ts +33 -0
  369. package/dist/types/packages/core/src/agents/explicit-agent-switch.d.ts +26 -0
  370. package/dist/types/packages/core/src/agents/fork.d.ts +50 -0
  371. package/dist/types/packages/core/src/agents/hosted-agent.d.ts +15 -0
  372. package/dist/types/packages/core/src/agents/idle-archiver.d.ts +35 -0
  373. package/dist/types/packages/core/src/agents/idle-compact.d.ts +37 -0
  374. package/dist/types/packages/core/src/agents/index.d.ts +8 -0
  375. package/dist/types/packages/core/src/agents/maestro-provider.d.ts +75 -0
  376. package/dist/types/packages/core/src/agents/maestro-registry.d.ts +3 -0
  377. package/dist/types/packages/core/src/agents/mcp-tools/ask-user.d.ts +147 -0
  378. package/dist/types/packages/core/src/agents/mcp-tools/common.d.ts +14 -0
  379. package/dist/types/packages/core/src/agents/mcp-tools/inline-assets.d.ts +24 -0
  380. package/dist/types/packages/core/src/agents/mcp-tools/publish-html.d.ts +18 -0
  381. package/dist/types/packages/core/src/agents/mcp-tools/request-vault.d.ts +124 -0
  382. package/dist/types/packages/core/src/agents/mcp-tools/self-config.d.ts +45 -0
  383. package/dist/types/packages/core/src/agents/mcp-tools/spawn-subagent.d.ts +148 -0
  384. package/dist/types/packages/core/src/agents/mcp-tools/visual-compat.d.ts +55 -0
  385. package/dist/types/packages/core/src/agents/mcp-tools/visuals.d.ts +70 -0
  386. package/dist/types/packages/core/src/agents/memory-archive-policy.d.ts +24 -0
  387. package/dist/types/packages/core/src/agents/model-catalog.d.ts +132 -0
  388. package/dist/types/packages/core/src/agents/public-helpers.d.ts +17 -0
  389. package/dist/types/packages/core/src/agents/registry.d.ts +5 -0
  390. package/dist/types/packages/core/src/agents/rollout/claude.d.ts +77 -0
  391. package/dist/types/packages/core/src/agents/rollout/codex.d.ts +119 -0
  392. package/dist/types/packages/core/src/agents/rollout/index.d.ts +6 -0
  393. package/dist/types/packages/core/src/agents/rollout/shared.d.ts +56 -0
  394. package/dist/types/packages/core/src/agents/self-config-core.d.ts +199 -0
  395. package/dist/types/packages/core/src/agents/task-events.d.ts +19 -0
  396. package/dist/types/packages/core/src/agents/tool-format.d.ts +25 -0
  397. package/dist/types/packages/core/src/agents/topic-cleanup.d.ts +83 -0
  398. package/dist/types/packages/core/src/agents/vault-tool-policy.d.ts +2 -0
  399. package/dist/types/packages/core/src/bus.d.ts +138 -0
  400. package/dist/types/packages/core/src/identifiers.d.ts +27 -0
  401. package/dist/types/packages/core/src/mcp/canonical-bridge-config.d.ts +21 -0
  402. package/dist/types/packages/core/src/mcp/factories/agent-health.d.ts +5 -0
  403. package/dist/types/packages/core/src/mcp/factories/compaction-log.d.ts +8 -0
  404. package/dist/types/packages/core/src/mcp/factories/decision.d.ts +18 -0
  405. package/dist/types/packages/core/src/mcp/factories/index.d.ts +13 -0
  406. package/dist/types/packages/core/src/mcp/factories/session-comm.d.ts +38 -0
  407. package/dist/types/packages/core/src/mcp/factories/session-history.d.ts +11 -0
  408. package/dist/types/packages/core/src/mcp/factories/stdio-protection.d.ts +10 -0
  409. package/dist/types/packages/core/src/mcp/factories/system-health.d.ts +37 -0
  410. package/dist/types/packages/core/src/mcp/factories/task.d.ts +13 -0
  411. package/dist/types/packages/core/src/mcp/factories/token-stats.d.ts +20 -0
  412. package/dist/types/packages/core/src/mcp/factories/vault.d.ts +9 -0
  413. package/dist/types/packages/core/src/mcp/mcp-helpers.d.ts +26 -0
  414. package/dist/types/packages/core/src/mcp/peer-bridge.d.ts +92 -0
  415. package/dist/types/packages/core/src/mcp/runtime-spec.d.ts +147 -0
  416. package/dist/types/packages/core/src/mcp/session-comm/actor-policy.d.ts +120 -0
  417. package/dist/types/packages/core/src/mcp/session-comm/bridge-ipc-config.d.ts +6 -0
  418. package/dist/types/packages/core/src/mcp/session-comm/context.d.ts +44 -0
  419. package/dist/types/packages/core/src/mcp/session-comm/history-tools.d.ts +31 -0
  420. package/dist/types/packages/core/src/mcp/session-comm/hub-remote-session.d.ts +149 -0
  421. package/dist/types/packages/core/src/mcp/session-comm/limits.d.ts +8 -0
  422. package/dist/types/packages/core/src/mcp/session-comm/peer-forward.d.ts +85 -0
  423. package/dist/types/packages/core/src/mcp/session-comm/tell-permissions.d.ts +29 -0
  424. package/dist/types/packages/core/src/mcp/session-comm/topic-catalog.d.ts +59 -0
  425. package/dist/types/packages/core/src/mcp/session-history-limits.d.ts +20 -0
  426. package/dist/types/packages/core/src/mcp/session-history-reader.d.ts +35 -0
  427. package/dist/types/packages/core/src/mcp/wiki-search-index.d.ts +59 -0
  428. package/dist/types/packages/core/src/mcp/wiki-server.d.ts +53 -0
  429. package/dist/types/packages/core/src/media/file-events.d.ts +14 -0
  430. package/dist/types/packages/core/src/media/text-extractor.d.ts +34 -0
  431. package/dist/types/packages/core/src/outbox/coalescing-runner.d.ts +68 -0
  432. package/dist/types/packages/core/src/outbox/file-ops.d.ts +79 -0
  433. package/dist/types/packages/core/src/outbox/index.d.ts +3 -0
  434. package/dist/types/packages/core/src/outbox/utils.d.ts +16 -0
  435. package/dist/types/packages/core/src/platform/background-bash/context.d.ts +1 -0
  436. package/dist/types/packages/core/src/platform/background-bash/manager.d.ts +34 -0
  437. package/dist/types/packages/core/src/platform/config-helpers.d.ts +20 -0
  438. package/dist/types/packages/core/src/platform/config.d.ts +178 -0
  439. package/dist/types/packages/core/src/platform/constants.d.ts +20 -0
  440. package/dist/types/packages/core/src/platform/delay.d.ts +1 -0
  441. package/dist/types/packages/core/src/platform/error.d.ts +6 -0
  442. package/dist/types/packages/core/src/platform/file-utils.d.ts +16 -0
  443. package/dist/types/packages/core/src/platform/ipc.d.ts +32 -0
  444. package/dist/types/packages/core/src/platform/jsonl.d.ts +46 -0
  445. package/dist/types/packages/core/src/platform/lifecycle.d.ts +40 -0
  446. package/dist/types/packages/core/src/platform/logger.d.ts +20 -0
  447. package/dist/types/packages/core/src/platform/maestro-bootstrap-env.d.ts +0 -0
  448. package/dist/types/packages/core/src/platform/mcp-catalog-policy.d.ts +73 -0
  449. package/dist/types/packages/core/src/platform/mcp-config.d.ts +286 -0
  450. package/dist/types/packages/core/src/platform/memoize-import.d.ts +15 -0
  451. package/dist/types/packages/core/src/platform/paths.d.ts +18 -0
  452. package/dist/types/packages/core/src/platform/playwright/browser-processes.d.ts +60 -0
  453. package/dist/types/packages/core/src/platform/playwright/capability.d.ts +1 -0
  454. package/dist/types/packages/core/src/platform/playwright/headed-launch.d.ts +13 -0
  455. package/dist/types/packages/core/src/platform/playwright/manager-utils.d.ts +34 -0
  456. package/dist/types/packages/core/src/platform/playwright/manager.d.ts +194 -0
  457. package/dist/types/packages/core/src/platform/playwright/mcp-transport.d.ts +4 -0
  458. package/dist/types/packages/core/src/platform/playwright/profile-management.d.ts +8 -0
  459. package/dist/types/packages/core/src/platform/playwright/public-runtime.d.ts +6 -0
  460. package/dist/types/packages/core/src/platform/playwright/transport-probe.d.ts +13 -0
  461. package/dist/types/packages/core/src/platform/playwright/vault-broker.d.ts +6 -0
  462. package/dist/types/packages/core/src/platform/public-runtime.d.ts +3 -0
  463. package/dist/types/packages/core/src/prompts/builders.d.ts +78 -0
  464. package/dist/types/packages/core/src/query/active-rooms.d.ts +234 -0
  465. package/dist/types/packages/core/src/query/public-runtime.d.ts +4 -0
  466. package/dist/types/packages/core/src/query/room-query-registry.d.ts +71 -0
  467. package/dist/types/packages/core/src/query/session-inbox-cleanup.d.ts +5 -0
  468. package/dist/types/packages/core/src/query/session-inbox-path.d.ts +8 -0
  469. package/dist/types/packages/core/src/query/state.d.ts +25 -0
  470. package/dist/types/packages/core/src/query/types.d.ts +6 -0
  471. package/dist/types/packages/core/src/runtime/actor-topic-reach.d.ts +63 -0
  472. package/dist/types/packages/core/src/runtime/actor-topic-scope.d.ts +127 -0
  473. package/dist/types/packages/core/src/runtime/ask-callbacks.d.ts +53 -0
  474. package/dist/types/packages/core/src/runtime/attachments.d.ts +36 -0
  475. package/dist/types/packages/core/src/runtime/background-session-policy.d.ts +1 -0
  476. package/dist/types/packages/core/src/runtime/background-sessions.d.ts +27 -0
  477. package/dist/types/packages/core/src/runtime/bashrs-completions.d.ts +50 -0
  478. package/dist/types/packages/core/src/runtime/channel-context.d.ts +13 -0
  479. package/dist/types/packages/core/src/runtime/context-warning.d.ts +46 -0
  480. package/dist/types/packages/core/src/runtime/cron-sessions.d.ts +9 -0
  481. package/dist/types/packages/core/src/runtime/errors.d.ts +6 -0
  482. package/dist/types/packages/core/src/runtime/event-heartbeat.d.ts +17 -0
  483. package/dist/types/packages/core/src/runtime/file-hooks.d.ts +38 -0
  484. package/dist/types/packages/core/src/runtime/playwright-turn-abort.d.ts +12 -0
  485. package/dist/types/packages/core/src/runtime/public-helpers.d.ts +17 -0
  486. package/dist/types/packages/core/src/runtime/remote-session-grant.d.ts +91 -0
  487. package/dist/types/packages/core/src/runtime/remote-session-inbox.d.ts +206 -0
  488. package/dist/types/packages/core/src/runtime/remote-session-reply-outbox.d.ts +37 -0
  489. package/dist/types/packages/core/src/runtime/task-format.d.ts +4 -0
  490. package/dist/types/packages/core/src/runtime/tasks.d.ts +3 -0
  491. package/dist/types/packages/core/src/runtime/thread-context.d.ts +62 -0
  492. package/dist/types/packages/core/src/runtime/topic-config.d.ts +24 -0
  493. package/dist/types/packages/core/src/runtime/turn-event-stream.d.ts +47 -0
  494. package/dist/types/packages/core/src/runtime/turn-runner.d.ts +284 -0
  495. package/dist/types/packages/core/src/runtime/turn-session.d.ts +49 -0
  496. package/dist/types/packages/core/src/runtime/usage-alert.d.ts +11 -0
  497. package/dist/types/packages/core/src/runtime/user-turn-envelope.d.ts +37 -0
  498. package/dist/types/packages/core/src/runtime/visual-html.d.ts +13 -0
  499. package/dist/types/packages/core/src/runtime/visual-store.d.ts +71 -0
  500. package/dist/types/packages/core/src/runtime/visuals.d.ts +33 -0
  501. package/dist/types/packages/core/src/runtime-gateway.d.ts +224 -0
  502. package/dist/types/packages/core/src/security/sanitize.d.ts +16 -0
  503. package/dist/types/packages/core/src/security/sensitive-path.d.ts +1 -0
  504. package/dist/types/packages/core/src/storage/activity-log.d.ts +25 -0
  505. package/dist/types/packages/core/src/storage/api-messages.d.ts +156 -0
  506. package/dist/types/packages/core/src/storage/api-topic-brief.d.ts +39 -0
  507. package/dist/types/packages/core/src/storage/api-topic-config.d.ts +23 -0
  508. package/dist/types/packages/core/src/storage/api-topics.d.ts +274 -0
  509. package/dist/types/packages/core/src/storage/app-settings.d.ts +4 -0
  510. package/dist/types/packages/core/src/storage/ask-user-gates.d.ts +65 -0
  511. package/dist/types/packages/core/src/storage/browser-profiles.d.ts +31 -0
  512. package/dist/types/packages/core/src/storage/conversations.d.ts +149 -0
  513. package/dist/types/packages/core/src/storage/decisions.d.ts +45 -0
  514. package/dist/types/packages/core/src/storage/forum/agent-settings.d.ts +3 -0
  515. package/dist/types/packages/core/src/storage/forum/index.d.ts +4 -0
  516. package/dist/types/packages/core/src/storage/forum/repository.d.ts +42 -0
  517. package/dist/types/packages/core/src/storage/forum/schema.d.ts +38 -0
  518. package/dist/types/packages/core/src/storage/forum-db.d.ts +2 -0
  519. package/dist/types/packages/core/src/storage/remote-session.d.ts +318 -0
  520. package/dist/types/packages/core/src/storage/runtime-events.d.ts +33 -0
  521. package/dist/types/packages/core/src/storage/runtime-leases.d.ts +27 -0
  522. package/dist/types/packages/core/src/storage/runtime-process-leases.d.ts +47 -0
  523. package/dist/types/packages/core/src/storage/runtime-topic-state.d.ts +39 -0
  524. package/dist/types/packages/core/src/storage/runtime-turn-requests.d.ts +138 -0
  525. package/dist/types/packages/core/src/storage/self-schedules.d.ts +54 -0
  526. package/dist/types/packages/core/src/storage/session-asks.d.ts +78 -0
  527. package/dist/types/packages/core/src/storage/session-inbox-signal.d.ts +35 -0
  528. package/dist/types/packages/core/src/storage/session-inbox.d.ts +36 -0
  529. package/dist/types/packages/core/src/storage/sqlite.d.ts +20 -0
  530. package/dist/types/packages/core/src/storage/storage-contract.d.ts +46 -0
  531. package/dist/types/packages/core/src/storage/storage-host.d.ts +41 -0
  532. package/dist/types/packages/core/src/storage/storage-public-host.d.ts +7 -0
  533. package/dist/types/packages/core/src/storage/storage-public.d.ts +45 -0
  534. package/dist/types/packages/core/src/storage/tasks.d.ts +49 -0
  535. package/dist/types/packages/core/src/storage/token-stats.d.ts +69 -0
  536. package/dist/types/packages/core/src/storage/topic-archive-state.d.ts +33 -0
  537. package/dist/types/packages/core/src/storage/topic-archive.d.ts +42 -0
  538. package/dist/types/packages/core/src/storage/topic-host-mcp-grants.d.ts +5 -0
  539. package/dist/types/packages/core/src/storage/topic-link-records.d.ts +281 -0
  540. package/dist/types/packages/core/src/storage/topic-settings.d.ts +19 -0
  541. package/dist/types/packages/core/src/storage/topic-tool-capabilities.d.ts +37 -0
  542. package/dist/types/packages/core/src/storage/topic-transcript.d.ts +38 -0
  543. package/dist/types/packages/core/src/storage/vault-crypto-core.d.ts +6 -0
  544. package/dist/types/packages/core/src/storage/vault-crypto.d.ts +12 -0
  545. package/dist/types/packages/core/src/storage/vault-public.d.ts +3 -0
  546. package/dist/types/packages/core/src/storage/vault-request-gates.d.ts +69 -0
  547. package/dist/types/packages/core/src/storage/vault.d.ts +49 -0
  548. package/dist/types/packages/core/src/storage/wiki-summary-names.d.ts +13 -0
  549. package/dist/types/packages/core/src/storage/wiki.d.ts +15 -0
  550. package/dist/types/packages/core/src/topics/derive.d.ts +83 -0
  551. package/dist/types/packages/core/src/topics/lifecycle.d.ts +75 -0
  552. package/dist/types/packages/core/src/topics/links.d.ts +2 -0
  553. package/dist/types/packages/core/src/topics/personal-general.d.ts +15 -0
  554. package/dist/types/packages/core/src/topics/session.d.ts +70 -0
  555. package/dist/types/packages/core/src/types/api.d.ts +546 -0
  556. package/dist/types/packages/core/src/types.d.ts +384 -0
  557. package/dist/types/packages/core/src/version.d.ts +1 -0
  558. package/dist/types/packages/module-cron/src/background-sessions.d.ts +2 -0
  559. package/dist/types/packages/module-cron/src/context.d.ts +15 -0
  560. package/dist/types/packages/module-cron/src/host.d.ts +23 -0
  561. package/dist/types/packages/module-cron/src/index.d.ts +14 -0
  562. package/dist/types/packages/module-cron/src/module.d.ts +13 -0
  563. package/dist/types/packages/module-cron/src/schedule.d.ts +23 -0
  564. package/dist/types/packages/module-cron/src/scheduler.d.ts +46 -0
  565. package/dist/types/packages/module-cron/src/scripts.d.ts +29 -0
  566. package/dist/types/packages/module-cron/src/store.d.ts +152 -0
  567. package/dist/types/packages/module-cron/src/summarize.d.ts +4 -0
  568. package/dist/vault.js +850 -0
  569. package/dist/vault.js.map +18 -0
  570. package/install-bash-rs.mjs +90 -0
  571. package/install-browser-rs.mjs +83 -0
  572. package/package.json +171 -4
@@ -0,0 +1,1307 @@
1
+ /**
2
+ * Session-inbox consumer — claims SQLite-backed inter-session messages and
3
+ * dispatches ask/tell/abort in the runtime process. Legacy JSONL files remain
4
+ * readable during rolling upgrades.
5
+ *
6
+ * Architecture:
7
+ * MCP tools / adapters → enqueueSessionInbox → shared WAL SQLite
8
+ * Runtime host → claimSessionInboxBatch → process entries
9
+ *
10
+ * Both converge on `triggerTopicAiTurn` from the turn runner.
11
+ *
12
+ * Port of otium's `query/session-inbox.ts` with every peer/placement branch
13
+ * removed (placed rooms, peer inject dispatch, remote ask replies): this node
14
+ * runs every turn locally, so asks route only to local caller topics.
15
+ */
16
+
17
+ import { createHash, randomUUID } from "node:crypto";
18
+ import { readdirSync, statSync, writeFileSync } from "node:fs";
19
+ import { join } from "node:path";
20
+ import type { ForkHandle } from "#agents/fork";
21
+ import { WsHub } from "#bus";
22
+ import { deliverPeerReply, type RemoteReplyRoute } from "#mcp/session-comm/peer-forward";
23
+ import { type CoalescingRunner, createCoalescingRunner } from "#outbox/coalescing-runner";
24
+ import { deleteProcessingFile, drainOutboxFile, parseOutboxLine } from "#outbox/file-ops";
25
+ import { watchDir } from "#outbox/utils";
26
+ import { SESSION_INBOX_DIR } from "#platform/config";
27
+ import { FROM_AUTO_CONTINUE, FROM_SELF_SCHEDULE } from "#platform/constants";
28
+ import { appendJsonlEntry, readJsonlLines } from "#platform/jsonl";
29
+ import { logger } from "#platform/logger";
30
+ import {
31
+ topicIdFromScheduledSessionInboxFileName,
32
+ topicIdFromSessionInboxFileName,
33
+ } from "#query/session-inbox-path";
34
+ import { AbortReason } from "#query/types";
35
+ import { getRegisteredCronSession } from "#runtime/cron-sessions";
36
+ import { appendApiMessage, getApiMessage } from "#storage/api-messages";
37
+ import { getTopicSessionId, type TopicNameLookupScope } from "#storage/api-topics";
38
+ import type { ConversationEntry } from "#storage/conversations";
39
+ import { RUNTIME_INSTANCE_ID } from "#storage/runtime-leases";
40
+ import {
41
+ acquireRuntimeProcessLease,
42
+ PROCESS_LEASE_HEARTBEAT_MS,
43
+ type RuntimeProcessLeaseHandle,
44
+ } from "#storage/runtime-process-leases";
45
+ import {
46
+ claimNextDueSelfSchedule,
47
+ completeSelfSchedule,
48
+ heartbeatSelfScheduleClaim,
49
+ markSelfScheduleRunning,
50
+ releaseSelfScheduleClaim,
51
+ } from "#storage/self-schedules";
52
+ import { clearPendingAsk } from "#storage/session-asks";
53
+ import {
54
+ claimSessionInboxBatch,
55
+ completeSessionInboxBatch,
56
+ enqueueSessionInbox,
57
+ listPendingSessionInboxTopics,
58
+ recoverSessionInboxClaims,
59
+ releaseSessionInboxBatch,
60
+ } from "#storage/session-inbox";
61
+ import { subscribeSessionInboxWrite } from "#storage/session-inbox-signal";
62
+ import type { AgentKind } from "#types";
63
+ import type { MessageDto, TopicSurface } from "#types/api";
64
+
65
+ // ── Entry types (match MCP server.ts write format) ──────────────────
66
+
67
+ type SessionInboxEntry =
68
+ | { type: "abort"; timestamp: string }
69
+ | {
70
+ type: "ask";
71
+ requestId: string;
72
+ from: string;
73
+ fromTitle?: string;
74
+ fromTopicId?: string;
75
+ /**
76
+ * Thread in the *caller's* room that this ask was raised from.
77
+ *
78
+ * Optional and additive, like `contextId`/`fromDepth` beside it: entries
79
+ * written before this field are replayed unchanged and simply answer in
80
+ * the channel, which is the old behaviour.
81
+ */
82
+ fromThreadRootId?: string;
83
+ message: string;
84
+ contextId?: string;
85
+ fromDepth?: number;
86
+ target?: "main" | "cron";
87
+ remoteReply?: RemoteReplyRoute;
88
+ timestamp: string;
89
+ }
90
+ | {
91
+ type: "tell";
92
+ from: string;
93
+ fromTitle?: string;
94
+ fromTopicId?: string;
95
+ message: string;
96
+ depth: number;
97
+ requestId?: string;
98
+ silent?: boolean;
99
+ timestamp: string;
100
+ };
101
+
102
+ interface PendingAskScope {
103
+ userId: string;
104
+ }
105
+
106
+ interface AskForkPlanOptions {
107
+ entries: ConversationEntry[];
108
+ forkNative?: () => Promise<ForkHandle>;
109
+ prepareSession?: () => Promise<ForkHandle>;
110
+ synthesize: (entries: ConversationEntry[]) => ForkHandle | Promise<ForkHandle>;
111
+ onNativeForkError?: (error: unknown) => void;
112
+ }
113
+
114
+ export interface AskForkPlan {
115
+ forkHandle: ForkHandle;
116
+ /** Rebuild from the inbox-consumption snapshot, never from mutable provider state. */
117
+ prepareSession: () => Promise<ForkHandle>;
118
+ }
119
+
120
+ export function normalizeAskTarget(target: unknown): "main" | "cron" | null {
121
+ if (target === undefined || target === "main") return "main";
122
+ return target === "cron" ? "cron" : null;
123
+ }
124
+
125
+ /**
126
+ * Every ask now runs as a normal turn on the target's own session
127
+ * (tell_session-style, visible in the target) instead of on a fork. Codex
128
+ * scopes its prompt cache to the thread, so a fork's first request never
129
+ * reused the parent's cache and every ask paid full input price; running on
130
+ * the target session keeps the cache warm.
131
+ *
132
+ * Cron asks (2026-10-20) dropped the fork too, trading it for
133
+ * `turnConcurrency: "isolated"` so the ask doesn't queue behind the topic's
134
+ * main visible turn. This does NOT serialize against a scheduled cron run
135
+ * landing on the identical session at the same moment — the fork used to
136
+ * sidestep that by mutating a private copy instead of the shared session.
137
+ * Treat a corrupted/interleaved cron rollout as a known residual risk until
138
+ * the cron scheduler itself gets a per-session lock.
139
+ */
140
+ export function askRunsOnTargetSession(_target: "main" | "cron"): boolean {
141
+ return true;
142
+ }
143
+
144
+ export function resolveAskParentSessionId(
145
+ topicId: string,
146
+ agent: AgentKind,
147
+ target: "main" | "cron" = "main",
148
+ ): string | null {
149
+ if (target === "cron") {
150
+ return getRegisteredCronSession(topicId, agent)?.sessionId ?? null;
151
+ }
152
+ return getTopicSessionId(topicId);
153
+ }
154
+
155
+ /**
156
+ * Create the first ask fork eagerly while retaining a replay recipe over the
157
+ * exact provider-neutral history observed when the inbox entry was consumed.
158
+ * Every replay receives its own clone so rollout writers cannot mutate the
159
+ * snapshot shared by a later retry.
160
+ */
161
+ export async function createAskForkPlan(options: AskForkPlanOptions): Promise<AskForkPlan> {
162
+ const snapshot = structuredClone(options.entries);
163
+ const prepareSession =
164
+ options.prepareSession ??
165
+ (async (): Promise<ForkHandle> => options.synthesize(structuredClone(snapshot)));
166
+
167
+ let forkHandle: ForkHandle | undefined;
168
+ if (options.forkNative) {
169
+ try {
170
+ forkHandle = await options.forkNative();
171
+ } catch (error) {
172
+ options.onNativeForkError?.(error);
173
+ }
174
+ }
175
+ forkHandle ??= await options.synthesize(structuredClone(snapshot));
176
+ return { forkHandle, prepareSession };
177
+ }
178
+
179
+ type ScheduledSessionInboxEntry = Extract<SessionInboxEntry, { type: "tell" }> & {
180
+ deliverAt: string;
181
+ };
182
+
183
+ function scheduledEntryDeliveryTime(value: unknown): number | null {
184
+ if (!value || typeof value !== "object") return null;
185
+ const entry = value as Partial<ScheduledSessionInboxEntry>;
186
+ const deliverAt = typeof entry.deliverAt === "string" ? Date.parse(entry.deliverAt) : Number.NaN;
187
+ if (
188
+ entry.type !== "tell" ||
189
+ entry.from !== FROM_SELF_SCHEDULE ||
190
+ typeof entry.message !== "string" ||
191
+ !entry.message ||
192
+ typeof entry.requestId !== "string" ||
193
+ !entry.requestId ||
194
+ !Number.isFinite(deliverAt)
195
+ ) {
196
+ return null;
197
+ }
198
+ return deliverAt;
199
+ }
200
+
201
+ /**
202
+ * Avoid claiming and rewriting a future-only schedule file. Rewriting emits
203
+ * fs.watch events which would otherwise self-trigger a flush loop until the
204
+ * earliest entry becomes due — the trigger runner rate-limits that loop to
205
+ * `SESSION_INBOX_COALESCE_MS` but there is no reason to spin at all. A
206
+ * concurrent append is safe: it emits its own watch event and the fallback
207
+ * poll covers missed notifications.
208
+ */
209
+ function scheduledFileNeedsClaim(filePath: string, nowMs: number): boolean {
210
+ try {
211
+ return readJsonlLines(filePath).some((line) => {
212
+ try {
213
+ const deliverAt = scheduledEntryDeliveryTime(JSON.parse(line));
214
+ return deliverAt === null || deliverAt <= nowMs;
215
+ } catch {
216
+ return true;
217
+ }
218
+ });
219
+ } catch {
220
+ // The file may have moved between readdir and this preflight. Let the
221
+ // atomic claim path decide whether anything remains to process.
222
+ return true;
223
+ }
224
+ }
225
+
226
+ function pendingAskScope(userId: string): PendingAskScope {
227
+ return { userId };
228
+ }
229
+
230
+ function clearPendingAskForEntry(
231
+ scope: PendingAskScope,
232
+ entry: Extract<SessionInboxEntry, { type: "ask" }>,
233
+ topicName: string,
234
+ reason: string,
235
+ ): void {
236
+ if (entry.remoteReply) return;
237
+ if (!entry.from) return;
238
+ const cleared = clearPendingAsk({
239
+ userId: scope.userId,
240
+ from: entry.from,
241
+ to: topicName,
242
+ requestId: entry.requestId,
243
+ });
244
+ logger.info(
245
+ { from: entry.from, to: topicName, requestId: entry.requestId, cleared, reason },
246
+ "session-inbox: pending ask cleared",
247
+ );
248
+ }
249
+
250
+ function entryFromLabel(entry: { from: string; fromTitle?: string }): string {
251
+ return entry.fromTitle?.trim() || entry.from;
252
+ }
253
+
254
+ /**
255
+ * Where an inbox entry's by-name fallback is allowed to look.
256
+ *
257
+ * `"unscoped"` reproduces pre-S-7 behaviour and is only returned for entries
258
+ * with no `fromTopicId` at all — legacy writers, and every `abort` entry,
259
+ * whose format carries no sender identity. Refusing those would drop traffic
260
+ * that has always worked.
261
+ *
262
+ * A `fromTopicId` that resolves to nothing is different: the sender existed
263
+ * and is gone (deleted mid-exchange), so falling back to an unscoped name
264
+ * lookup is exactly how a reply lands in a same-named room on another
265
+ * surface. That case returns `"deny"` and the caller drops the entry.
266
+ */
267
+ type CallerScope = { kind: "unscoped" } | { kind: "deny" } | { kind: "surface"; on: TopicSurface };
268
+
269
+ function callerScope(
270
+ entry: SessionInboxEntry,
271
+ getTopic: (id: string) => { surface?: string | null } | null,
272
+ ): CallerScope {
273
+ const fromTopicId = "fromTopicId" in entry ? entry.fromTopicId : undefined;
274
+ if (!fromTopicId) return { kind: "unscoped" };
275
+ const surface = getTopic(fromTopicId)?.surface;
276
+ return surface ? { kind: "surface", on: surface as TopicSurface } : { kind: "deny" };
277
+ }
278
+
279
+ /** `getTopicByNameForUser` scope for a caller scope, or null when it must not run. */
280
+ function scopeToLookupOpts(scope: CallerScope): TopicNameLookupScope | null {
281
+ if (scope.kind === "deny") return null;
282
+ return scope.kind === "surface" ? { surface: scope.on } : { scope: "all" };
283
+ }
284
+
285
+ async function resolveEntryCallerTopic(
286
+ scope: PendingAskScope,
287
+ entry: Extract<SessionInboxEntry, { type: "ask" }>,
288
+ ) {
289
+ const { getTopic, getTopicByNameForUser } = await import("#storage/api-topics");
290
+ if (entry.fromTopicId) {
291
+ const byId = getTopic(entry.fromTopicId);
292
+ if (byId?.participants.some((p) => p.userId === scope.userId)) return byId;
293
+ }
294
+ // Same reasoning as the target lookup: resolve the caller inside its own
295
+ // surface so a same-named topic elsewhere cannot receive the reply. A sender
296
+ // id that no longer resolves denies the fallback outright — that is the
297
+ // deleted-caller case, where an unscoped name match is most likely to be the
298
+ // wrong room rather than the right one.
299
+ const opts = scopeToLookupOpts(callerScope(entry, getTopic));
300
+ if (!opts) return null;
301
+ return getTopicByNameForUser(entry.from, String(scope.userId), opts);
302
+ }
303
+
304
+ export function notifyCallerTopic(
305
+ callerTopicId: string,
306
+ targetLabel: string,
307
+ message: string,
308
+ label = `Reply from ${targetLabel}`,
309
+ threadRootId?: string,
310
+ ): void {
311
+ const msg: MessageDto = {
312
+ id: randomUUID(),
313
+ topicId: callerTopicId,
314
+ authorId: "system",
315
+ text: `[<- ${targetLabel}]\n${message}`,
316
+ kind: "tell",
317
+ tellCard: {
318
+ fromLabel: targetLabel,
319
+ label,
320
+ message,
321
+ },
322
+ ...(threadRootId ? { threadRootId } : {}),
323
+ createdAt: new Date().toISOString(),
324
+ };
325
+ appendApiMessage(msg, { notify: false });
326
+ WsHub.get().broadcastMessage(callerTopicId, msg);
327
+ }
328
+
329
+ function persistVisibleAskMessage(args: {
330
+ callerTopicId: string;
331
+ callerUserId: string;
332
+ targetLabel: string;
333
+ requestId: string;
334
+ message: string;
335
+ /** Thread the ask was raised from, so the question card stays beside it. */
336
+ threadRootId?: string;
337
+ }): void {
338
+ const msg: MessageDto = {
339
+ id: `ask-${args.requestId}-sent`,
340
+ topicId: args.callerTopicId,
341
+ authorId: args.callerUserId,
342
+ text: `[Ask to **${args.targetLabel}**]\n\n${args.message}`,
343
+ kind: "tell",
344
+ tellCard: {
345
+ fromLabel: args.targetLabel,
346
+ label: `Ask to ${args.targetLabel}`,
347
+ message: args.message,
348
+ },
349
+ // The outgoing question belongs where it was asked. Its answer is already
350
+ // placed there; leaving the question in the channel splits one exchange
351
+ // across two conversations.
352
+ ...(args.threadRootId ? { threadRootId: args.threadRootId } : {}),
353
+ createdAt: new Date().toISOString(),
354
+ };
355
+ try {
356
+ appendApiMessage(msg, { notify: false });
357
+ WsHub.get().broadcastMessage(args.callerTopicId, msg);
358
+ } catch (error) {
359
+ // Inbox files are at-least-once. The stable request-derived id makes a
360
+ // replay successful without duplicating the visible card.
361
+ if (!getApiMessage(args.callerTopicId, msg.id)) throw error;
362
+ }
363
+ }
364
+
365
+ async function notifyAskDrop(
366
+ scope: PendingAskScope,
367
+ entry: Extract<SessionInboxEntry, { type: "ask" }>,
368
+ targetLabel: string,
369
+ message: string,
370
+ ): Promise<void> {
371
+ if (!entry.from) return;
372
+ const callerTopic = await resolveEntryCallerTopic(scope, entry);
373
+ if (!callerTopic) {
374
+ logger.warn(
375
+ { from: entry.from, to: targetLabel, requestId: entry.requestId },
376
+ "session-inbox: failed to notify ask caller — caller topic not found",
377
+ );
378
+ return;
379
+ }
380
+ try {
381
+ notifyCallerTopic(
382
+ callerTopic.id,
383
+ targetLabel,
384
+ message,
385
+ `Error from ${targetLabel}`,
386
+ entry.fromThreadRootId,
387
+ );
388
+ } catch (err) {
389
+ logger.warn(
390
+ { err, from: entry.from, to: targetLabel, requestId: entry.requestId },
391
+ "session-inbox: failed to notify ask caller",
392
+ );
393
+ }
394
+ }
395
+
396
+ function stableLegacyRequestId(prefix: string, parts: Array<string | number | undefined>): string {
397
+ const hash = createHash("sha256")
398
+ .update(parts.map((part) => String(part ?? "")).join("\0"))
399
+ .digest("hex")
400
+ .slice(0, 16);
401
+ return `${prefix}-${hash}`;
402
+ }
403
+
404
+ // ── Per-topic worker mutex ──────────────────────────────────────────
405
+
406
+ /**
407
+ * Key: `${userId}/${topicName}`. While a worker is draining a topic's inbox,
408
+ * the dispatcher skips it — same-topic entries must be serial to preserve
409
+ * order and avoid `drainOutboxFile` rename races.
410
+ */
411
+ const topicWorkerBusy = new Set<string>();
412
+
413
+ // ── Dispatcher ──────────────────────────────────────────────────────
414
+
415
+ /**
416
+ * Scan all user inbox dirs and kick a worker per topic. Returns immediately
417
+ * — workers run in the background.
418
+ *
419
+ * Triggered by the enqueue wake signal, fs.watch on the rolling-upgrade JSONL
420
+ * files, and a fallback poll — all coalesced by one `CoalescingRunner`.
421
+ */
422
+ export async function flushSessionInbox() {
423
+ await dispatchDueSelfSchedules();
424
+ // Upgrade compatibility: schedules written by versions before the SQLite
425
+ // manager remain consumable from their legacy `.schedule` sidecars.
426
+ sweepScheduledSessionInbox();
427
+
428
+ for (const pending of listPendingSessionInboxTopics()) {
429
+ const topicKey = `${pending.userId}/id:${pending.topicId}`;
430
+ if (topicWorkerBusy.has(topicKey)) continue;
431
+ topicWorkerBusy.add(topicKey);
432
+ processQueuedTopicInbox({ ...pending, topicKey })
433
+ .catch((e) => logger.error({ err: e, topicKey }, "session-inbox: SQLite worker crashed"))
434
+ .finally(() => topicWorkerBusy.delete(topicKey));
435
+ }
436
+
437
+ // Continue draining JSONL written by an older process during rolling upgrades.
438
+ let userDirs: string[];
439
+ try {
440
+ userDirs = readdirSync(SESSION_INBOX_DIR);
441
+ } catch {
442
+ // Dir doesn't exist yet — nothing to drain.
443
+ return;
444
+ }
445
+
446
+ for (const uid of userDirs) {
447
+ const userInboxDir = join(SESSION_INBOX_DIR, uid);
448
+ let entries: string[];
449
+ try {
450
+ entries = readdirSync(userInboxDir);
451
+ } catch {
452
+ continue;
453
+ }
454
+
455
+ for (const entry of entries) {
456
+ const entryPath = join(userInboxDir, entry);
457
+
458
+ let isDir = false;
459
+ try {
460
+ isDir = statSync(entryPath).isDirectory();
461
+ } catch {
462
+ continue;
463
+ }
464
+
465
+ if (!isDir && entry.endsWith(".jsonl")) {
466
+ // New files are keyed by an encoded canonical topic id. Keep reading
467
+ // legacy title-keyed files during rolling upgrades.
468
+ const topicId = topicIdFromSessionInboxFileName(entry);
469
+ const topicName = topicId ? "" : entry.replace(/\.jsonl$/, "");
470
+ const topicKey = `${uid}/${topicId ? `id:${topicId}` : topicName}`;
471
+ if (topicWorkerBusy.has(topicKey)) continue;
472
+
473
+ topicWorkerBusy.add(topicKey);
474
+ processLegacyTopicInbox({ topicKey, filePath: entryPath, userId: uid, topicId, topicName })
475
+ .catch((e) => logger.error({ err: e, topicKey }, "session-inbox: topic worker crashed"))
476
+ .finally(() => topicWorkerBusy.delete(topicKey));
477
+ }
478
+ }
479
+ }
480
+ }
481
+
482
+ type SelfScheduleTurnTrigger = typeof import("#runtime/turn-runner").triggerTopicAiTurn;
483
+
484
+ /**
485
+ * Claim and start due DB-backed self-schedules. A busy-topic race is removed
486
+ * from the process-local defer queue and returned to durable pending state;
487
+ * interrupted runs are retried after the topic is idle again.
488
+ */
489
+ export async function dispatchDueSelfSchedules(
490
+ nowMs = Date.now(),
491
+ triggerOverride?: SelfScheduleTurnTrigger,
492
+ ): Promise<number> {
493
+ const trigger = triggerOverride ?? (await import("#runtime/turn-runner")).triggerTopicAiTurn;
494
+ const { cancelDeferredInject } = await import("#query/active-rooms");
495
+ const { getTopic } = await import("#storage/api-topics");
496
+ const ownerId = `${RUNTIME_INSTANCE_ID}:self-schedule`;
497
+ let started = 0;
498
+
499
+ // Bound one sweep so a corrupt/hostile database cannot monopolize the inbox
500
+ // worker. The fallback poll picks up any remaining due topics.
501
+ for (let index = 0; index < 100; index++) {
502
+ const schedule = claimNextDueSelfSchedule(ownerId, nowMs);
503
+ if (!schedule) break;
504
+ const topic = getTopic(schedule.topicId);
505
+ if (
506
+ !topic?.agent ||
507
+ !topic.participants.some((participant) => participant.userId === schedule.userId)
508
+ ) {
509
+ completeSelfSchedule(schedule.id, ownerId);
510
+ logger.warn(
511
+ { scheduleId: schedule.id, topicId: schedule.topicId, userId: schedule.userId },
512
+ "self-schedule: target topic unavailable, dropping",
513
+ );
514
+ continue;
515
+ }
516
+
517
+ let settled = false;
518
+ let claimHeartbeat: ReturnType<typeof setInterval> | null = null;
519
+ const stopClaimHeartbeat = () => {
520
+ if (!claimHeartbeat) return;
521
+ clearInterval(claimHeartbeat);
522
+ claimHeartbeat = null;
523
+ };
524
+ const fromLabel = "Scheduled self";
525
+ const queryId = trigger(
526
+ topic.id,
527
+ schedule.userId,
528
+ `[Tell from **${fromLabel}**]\n\n${schedule.message}`,
529
+ topic.agent,
530
+ {
531
+ origin: fromLabel,
532
+ requestId: schedule.id,
533
+ depth: 0,
534
+ from: fromLabel,
535
+ injectAuthorId: "system",
536
+ injectSourceAdapter: "self-schedule",
537
+ injectKind: "tell",
538
+ injectTellCard: {
539
+ fromLabel,
540
+ message: schedule.message,
541
+ },
542
+ onSettled: (result) => {
543
+ settled = true;
544
+ stopClaimHeartbeat();
545
+ if (result.kind === "aborted" && result.abortReason === AbortReason.Internal) {
546
+ // User preemption requeues injects in memory. Remove that copy and
547
+ // restore the durable schedule instead; a newer pending schedule
548
+ // created by this run wins if one already exists.
549
+ cancelDeferredInject(topic.id, schedule.id);
550
+ releaseSelfScheduleClaim(schedule.id, ownerId);
551
+ return;
552
+ }
553
+ completeSelfSchedule(schedule.id, ownerId);
554
+ },
555
+ },
556
+ );
557
+
558
+ if (!queryId) {
559
+ if (!settled) {
560
+ // The room became busy between the DB idle check and turn claim.
561
+ cancelDeferredInject(topic.id, schedule.id);
562
+ releaseSelfScheduleClaim(schedule.id, ownerId);
563
+ }
564
+ // Avoid immediately reclaiming the same overdue schedule in this sweep.
565
+ break;
566
+ }
567
+ if (markSelfScheduleRunning(schedule.id, ownerId, queryId) && !settled) {
568
+ claimHeartbeat = setInterval(() => {
569
+ if (heartbeatSelfScheduleClaim(schedule.id, ownerId)) return;
570
+ stopClaimHeartbeat();
571
+ }, 1_000);
572
+ claimHeartbeat.unref?.();
573
+ }
574
+ started++;
575
+ }
576
+ return started;
577
+ }
578
+
579
+ /**
580
+ * Promote due schedule_self sidecars into the normal session inbox. Files are
581
+ * atomically claimed with the same crash-recovery primitive as every outbox;
582
+ * future entries are appended back and due entries retain their requestId.
583
+ */
584
+ export function sweepScheduledSessionInbox(nowMs = Date.now()): void {
585
+ let userDirs: string[];
586
+ try {
587
+ userDirs = readdirSync(SESSION_INBOX_DIR);
588
+ } catch {
589
+ return;
590
+ }
591
+
592
+ for (const userId of userDirs) {
593
+ const userInboxDir = join(SESSION_INBOX_DIR, userId);
594
+ let files: string[];
595
+ try {
596
+ files = readdirSync(userInboxDir);
597
+ } catch {
598
+ continue;
599
+ }
600
+ const scheduledFiles = new Set(
601
+ files
602
+ .filter((file) => file.endsWith(".schedule") || file.endsWith(".schedule.processing"))
603
+ .map((file) =>
604
+ file.endsWith(".processing") ? file.slice(0, -".processing".length) : file,
605
+ ),
606
+ );
607
+
608
+ for (const file of scheduledFiles) {
609
+ const topicId = topicIdFromScheduledSessionInboxFileName(file);
610
+ if (!topicId) continue;
611
+ const schedulePath = join(userInboxDir, file);
612
+ const hasProcessingClaim = files.includes(`${file}.processing`);
613
+ if (!hasProcessingClaim && !scheduledFileNeedsClaim(schedulePath, nowMs)) continue;
614
+ const drained = drainOutboxFile(schedulePath, "self-schedule");
615
+ if (!drained) continue;
616
+ const pending: ScheduledSessionInboxEntry[] = [];
617
+ const due: ScheduledSessionInboxEntry[] = [];
618
+
619
+ for (const line of drained.lines) {
620
+ const entry = parseOutboxLine<ScheduledSessionInboxEntry>(line, "self-schedule");
621
+ const deliverAt = scheduledEntryDeliveryTime(entry);
622
+ if (!entry || deliverAt === null) {
623
+ logger.warn({ userId, topicId }, "self-schedule: invalid entry dropped");
624
+ continue;
625
+ }
626
+ (deliverAt <= nowMs ? due : pending).push(entry);
627
+ }
628
+
629
+ // A contended append can throw. Promotion is not atomic across entries,
630
+ // so record exactly which ones still need doing: retaining the whole
631
+ // claim would re-promote entries already delivered, and `seenRequestIds`
632
+ // only dedupes within a single drained batch — once the durable turn row
633
+ // completes, the same requestId runs a second time.
634
+ const unfinished: ScheduledSessionInboxEntry[] = [];
635
+ let failure: unknown;
636
+
637
+ for (const entry of due) {
638
+ if (failure) {
639
+ unfinished.push(entry);
640
+ continue;
641
+ }
642
+ const { deliverAt: _deliverAt, ...liveEntry } = entry;
643
+ try {
644
+ enqueueSessionInbox({
645
+ userId,
646
+ topicId,
647
+ id: `scheduled:${entry.requestId}`,
648
+ entry: liveEntry,
649
+ });
650
+ } catch (err) {
651
+ failure = err;
652
+ unfinished.push(entry);
653
+ }
654
+ }
655
+ for (const entry of pending) {
656
+ if (failure) {
657
+ unfinished.push(entry);
658
+ continue;
659
+ }
660
+ try {
661
+ appendJsonlEntry(schedulePath, entry);
662
+ } catch (err) {
663
+ failure = err;
664
+ unfinished.push(entry);
665
+ }
666
+ }
667
+
668
+ if (failure) {
669
+ logger.error(
670
+ {
671
+ err: failure,
672
+ userId,
673
+ topicId,
674
+ unfinished: unfinished.length,
675
+ total: due.length + pending.length,
676
+ },
677
+ "self-schedule: promotion interrupted; retaining only the unpromoted entries",
678
+ );
679
+ try {
680
+ // Rewrite the claim we own so the next drain merges back only what
681
+ // was not delivered. Not an append, so it needs no append lock.
682
+ writeFileSync(
683
+ drained.processingPath,
684
+ `${unfinished.map((entry) => JSON.stringify(entry)).join("\n")}\n`,
685
+ );
686
+ } catch (rewriteErr) {
687
+ // Could not narrow the claim; keep all of it. Recovery then re-runs
688
+ // already-promoted entries, which is worse than losing none.
689
+ logger.error(
690
+ { err: rewriteErr, userId, topicId },
691
+ "self-schedule: could not rewrite the claim; recovery may duplicate entries",
692
+ );
693
+ }
694
+ continue;
695
+ }
696
+ deleteProcessingFile(drained.processingPath, "self-schedule", drained.lines.length);
697
+
698
+ if (due.length > 0) {
699
+ logger.info({ userId, topicId, count: due.length }, "self-schedule: due entries promoted");
700
+ }
701
+ }
702
+ }
703
+ }
704
+
705
+ // ── Topic worker ────────────────────────────────────────────────────
706
+
707
+ async function processInboxLines(args: {
708
+ topicKey: string;
709
+ sourcePath: string;
710
+ userId: string;
711
+ topicId: string | null;
712
+ topicName: string;
713
+ lines: string[];
714
+ }) {
715
+ // Lazy-import to avoid circular deps at module-load time.
716
+ const { getTopic, getTopicByNameForUser } = await import("#storage/api-topics");
717
+ const { topicKey, sourcePath, userId, topicId, topicName, lines } = args;
718
+ const scope = pendingAskScope(userId);
719
+ const seenRequestIds = new Set<string>();
720
+
721
+ for (const line of lines) {
722
+ const raw = parseOutboxLine<Record<string, unknown>>(line, "session-inbox");
723
+ if (!raw) continue;
724
+
725
+ // Normalize: Otium legacy compat (command/type-less → tell/ask).
726
+ let entry: SessionInboxEntry;
727
+ if (raw.type === "abort") {
728
+ entry = raw as SessionInboxEntry;
729
+ } else if (raw.command || raw.type === "command" || raw.type === "tell") {
730
+ entry = { ...raw, type: "tell" } as SessionInboxEntry;
731
+ } else {
732
+ entry = { ...raw, type: "ask" } as SessionInboxEntry;
733
+ }
734
+
735
+ if (!topicId && !topicName) {
736
+ logger.error({ sourcePath, topicKey }, "session-inbox: could not extract topic name");
737
+ continue;
738
+ }
739
+
740
+ // ── abort ──────────────────────────────────────────────────
741
+ if (entry.type === "abort") {
742
+ await handleAbortEntry(userId, topicName, topicId, entry.timestamp);
743
+ continue;
744
+ }
745
+
746
+ // ── validate from/message ──────────────────────────────────
747
+ if (!entry.from || !entry.message) {
748
+ logger.error({ entry }, "session-inbox: missing from/message, dropping");
749
+ // MCP writer clears its own pending ask on write failure;
750
+ // the inbox consumer only drops the entry.
751
+ if (entry.type === "ask") {
752
+ clearPendingAskForEntry(scope, entry, topicName, "invalid-entry");
753
+ logger.warn({ from: entry.from, to: topicName }, "session-inbox: dropping invalid ask");
754
+ await notifyAskDrop(scope, entry, topicName, "(error: invalid ask entry)");
755
+ }
756
+ continue;
757
+ }
758
+
759
+ if (entry.requestId) {
760
+ if (seenRequestIds.has(entry.requestId)) {
761
+ logger.info(
762
+ { topicKey, topicName, requestId: entry.requestId, from: entry.from },
763
+ "session-inbox: duplicate requestId in drained batch, skipping",
764
+ );
765
+ continue;
766
+ }
767
+ seenRequestIds.add(entry.requestId);
768
+ }
769
+
770
+ // Look up the target topic.
771
+ //
772
+ // The by-NAME fallback must stay inside the caller's surface (S-7).
773
+ // Names are only unique per surface since S-3, so an unscoped lookup can
774
+ // resolve `General` on `terminal` for a message sent from `telegram`.
775
+ // The session-target catalog already refuses to *offer* a cross-surface
776
+ // target, so this is the second line of defence for entries that name a
777
+ // topic directly — including ones written before the catalog was scoped.
778
+ // With no `fromTopicId` (legacy entries) the caller's surface is unknown
779
+ // and the lookup stays as it was rather than dropping the message; a
780
+ // `fromTopicId` that no longer resolves denies the fallback instead.
781
+ const byId = topicId ? getTopic(topicId) : null;
782
+ const nameLookupOpts = scopeToLookupOpts(callerScope(entry, getTopic));
783
+ const topic = topicId
784
+ ? byId?.participants.some((participant) => participant.userId === userId)
785
+ ? byId
786
+ : null
787
+ : nameLookupOpts && getTopicByNameForUser(topicName, userId, nameLookupOpts);
788
+ if (!topic) {
789
+ logger.warn({ topicName, from: entry.from }, "session-inbox: topic not found, dropping");
790
+ if (entry.type === "ask") {
791
+ clearPendingAskForEntry(scope, entry, topicName, "target-topic-not-found");
792
+ await notifyAskDrop(
793
+ scope,
794
+ entry,
795
+ topicName,
796
+ `(error: target topic "${topicName}" was not found)`,
797
+ );
798
+ }
799
+ continue;
800
+ }
801
+
802
+ // The AI-enabled check: topics without agent can't run AI turns.
803
+ const isAiEnabled = Boolean(topic.agent?.trim());
804
+
805
+ // ── tell ───────────────────────────────────────────────────
806
+ if (entry.type === "tell") {
807
+ await handleTellEntry(topic, topic.title, entry, isAiEnabled, scope);
808
+ continue;
809
+ }
810
+
811
+ // ── ask ────────────────────────────────────────────────────
812
+ if (entry.type === "ask") {
813
+ await handleAskEntry(topic, topic.title, entry, isAiEnabled, scope);
814
+ }
815
+ }
816
+ }
817
+
818
+ async function processLegacyTopicInbox(args: {
819
+ topicKey: string;
820
+ filePath: string;
821
+ userId: string;
822
+ topicId: string | null;
823
+ topicName: string;
824
+ }) {
825
+ while (true) {
826
+ const drained = drainOutboxFile(args.filePath, "session-inbox");
827
+ if (!drained) return;
828
+ await processInboxLines({
829
+ ...args,
830
+ sourcePath: args.filePath,
831
+ lines: drained.lines,
832
+ });
833
+ // At-least-once compatibility: a crash leaves the file claim for replay.
834
+ deleteProcessingFile(drained.processingPath, "session-inbox", drained.lines.length);
835
+ }
836
+ }
837
+
838
+ async function processQueuedTopicInbox(args: {
839
+ topicKey: string;
840
+ userId: string;
841
+ topicId: string;
842
+ }): Promise<void> {
843
+ const ownerId = `${RUNTIME_INSTANCE_ID}:session-inbox:${randomUUID()}`;
844
+ while (true) {
845
+ const rows = claimSessionInboxBatch({ ...args, ownerId });
846
+ if (rows.length === 0) return;
847
+ try {
848
+ await processInboxLines({
849
+ ...args,
850
+ topicName: "",
851
+ sourcePath: "sqlite:session_inbox",
852
+ lines: rows.map((row) => row.payload),
853
+ });
854
+ completeSessionInboxBatch(
855
+ rows.map((row) => row.id),
856
+ ownerId,
857
+ );
858
+ } catch (error) {
859
+ releaseSessionInboxBatch(
860
+ rows.map((row) => row.id),
861
+ ownerId,
862
+ );
863
+ throw error;
864
+ }
865
+ }
866
+ }
867
+
868
+ // ── Entry handlers ──────────────────────────────────────────────────
869
+
870
+ async function handleAbortEntry(
871
+ userId: string,
872
+ topicName: string,
873
+ topicId: string | null,
874
+ issuedAt?: string,
875
+ ) {
876
+ const { getTopic, getTopicByNameForUser } = await import("#storage/api-topics");
877
+ const byId = topicId ? getTopic(topicId) : null;
878
+ // KNOWN GAP: this by-name fallback cannot be surface-scoped the way the
879
+ // tell/ask one is. An `abort` entry is `{ type, timestamp }` — the format
880
+ // carries no sender identity at all, and every current writer omits one
881
+ // (mcp/session-comm/server.ts, default-host.ts). So there is nothing to
882
+ // derive a caller surface from, and scoping would have to invent one.
883
+ //
884
+ // The exposure is narrow but real: reaching this line at all needs an entry
885
+ // with no `topicId`, which only legacy title-keyed inboxes produce, and the
886
+ // worst outcome is aborting a same-named topic's turn on another surface.
887
+ // Closing it properly means adding sender identity to the abort entry format
888
+ // and is a wire-format change, not a call-site fix — deliberately left out
889
+ // of this change rather than papered over with a scope that is always empty.
890
+ // `scope: "all"` states that here instead of leaving it to a default.
891
+ const topic = topicId
892
+ ? byId?.participants.some((participant) => participant.userId === userId)
893
+ ? byId
894
+ : null
895
+ : getTopicByNameForUser(topicName, userId, { scope: "all" });
896
+ if (!topic) {
897
+ logger.warn({ topicName }, "session-inbox: abort for unknown topic, skipping");
898
+ return;
899
+ }
900
+
901
+ const { abortRoom, getRoomQuery, interSessionQueue } = await import("#query/active-rooms");
902
+
903
+ // The user's intent at abort time also covers work still waiting in the
904
+ // defer queue — otherwise the "aborted" room immediately restarts.
905
+ interSessionQueue.drop(topic.id);
906
+
907
+ // Stale-abort guard: the inbox is at-least-once, so an abort entry can be
908
+ // consumed AFTER a newer turn already claimed the room. Only abort turns
909
+ // that started before the abort was issued (60s skew allowance).
910
+ const issuedMs = issuedAt ? Date.parse(issuedAt) : Number.NaN;
911
+ const running = getRoomQuery(topic.id);
912
+ if (running?.startedAt && Number.isFinite(issuedMs) && running.startedAt > issuedMs + 60_000) {
913
+ logger.info(
914
+ { topicName, topicId: topic.id, startedAt: running.startedAt, issuedMs },
915
+ "session-inbox: stale abort ignored — turn started after abort was issued",
916
+ );
917
+ return;
918
+ }
919
+
920
+ // Abort the running query via the room-keyed registry (B from active-rooms.ts).
921
+ const aborted = abortRoom(topic.id);
922
+ logger.info({ topicName, topicId: topic.id, aborted }, "session-inbox: abort processed");
923
+ }
924
+
925
+ async function handleTellEntry(
926
+ topic: { id: string; title: string; agent?: string | null },
927
+ topicName: string,
928
+ entry: Extract<SessionInboxEntry, { type: "tell" }>,
929
+ isAiEnabled: boolean,
930
+ scope: PendingAskScope,
931
+ ) {
932
+ const { triggerTopicAiTurn } = await import("#runtime/turn-runner");
933
+ const fromLabel = entryFromLabel(entry);
934
+ const requestId =
935
+ entry.requestId ??
936
+ stableLegacyRequestId("legacy-tell", [topicName, entry.from, entry.message, entry.timestamp]);
937
+
938
+ if (!isAiEnabled) {
939
+ // AI-enabled targets are persisted by triggerTopicAiTurn below. Human-only
940
+ // targets still need a visible DB message even though no AI turn runs. A
941
+ // request-derived id makes crash replay converge on the same row.
942
+ const msgId = `tell-${requestId}`;
943
+ const now = new Date().toISOString();
944
+ const text = `[from ${fromLabel}]\n${entry.message}`;
945
+
946
+ try {
947
+ appendApiMessage({
948
+ id: msgId,
949
+ topicId: topic.id,
950
+ authorId: "system",
951
+ sourceAdapter: "session-comm",
952
+ text,
953
+ kind: "tell",
954
+ tellCard: {
955
+ fromLabel,
956
+ fromTopicId: entry.fromTopicId,
957
+ message: entry.message,
958
+ },
959
+ createdAt: now,
960
+ });
961
+ } catch (e) {
962
+ logger.error({ err: e, topicName }, "session-inbox: failed to persist tell message");
963
+ }
964
+ }
965
+
966
+ // Trigger AI turn (defers behind a running user turn via B's abort-on-new-message).
967
+ if (isAiEnabled) {
968
+ const isAutoContinue = entry.from === FROM_AUTO_CONTINUE;
969
+ const isHiddenContinue = isAutoContinue;
970
+ triggerTopicAiTurn(
971
+ topic.id,
972
+ String(scope.userId),
973
+ isHiddenContinue ? entry.message : `[Tell from **${fromLabel}**]\n\n${entry.message}`,
974
+ (topic.agent ?? undefined) as Parameters<typeof triggerTopicAiTurn>[3],
975
+ {
976
+ origin: fromLabel,
977
+ requestId,
978
+ depth: entry.depth,
979
+ from: fromLabel,
980
+ hideInjectMessage: isHiddenContinue,
981
+ injectAuthorId: "system",
982
+ injectSourceAdapter: "session-comm",
983
+ injectKind: "tell",
984
+ injectTellCard: {
985
+ fromLabel,
986
+ fromTopicId: entry.fromTopicId,
987
+ message: entry.message,
988
+ },
989
+ },
990
+ );
991
+ }
992
+
993
+ logger.info(
994
+ { topicName, from: entry.from, fromLabel, aiEnabled: isAiEnabled },
995
+ "session-inbox: tell delivered",
996
+ );
997
+ }
998
+
999
+ async function handleAskEntry(
1000
+ topic: { id: string; title: string; agent?: string | null },
1001
+ topicName: string,
1002
+ entry: Extract<SessionInboxEntry, { type: "ask" }>,
1003
+ isAiEnabled: boolean,
1004
+ scope: PendingAskScope,
1005
+ ) {
1006
+ const { triggerTopicAiTurn } = await import("#runtime/turn-runner");
1007
+ const { registerAskCallback } = await import("#runtime/ask-callbacks");
1008
+ const fromLabel = entryFromLabel(entry);
1009
+ const remoteReply = entry.remoteReply;
1010
+ const askTarget = normalizeAskTarget(entry.target);
1011
+ if (!askTarget) {
1012
+ clearPendingAskForEntry(scope, entry, topicName, "invalid-target");
1013
+ if (remoteReply) {
1014
+ await deliverPeerReply(remoteReply, topicName, "(error: invalid ask target)", "error");
1015
+ } else {
1016
+ await notifyAskDrop(scope, entry, topicName, "(error: invalid ask target)");
1017
+ }
1018
+ return;
1019
+ }
1020
+ const targetLabel = askTarget === "cron" ? `${topic.title}:cron` : topic.title;
1021
+
1022
+ // Build the prompt with read-only instruction (mirrors Otium).
1023
+ const prompt =
1024
+ askTarget === "cron"
1025
+ ? `[ASK from ${fromLabel} -> ${targetLabel}]\n${entry.message}\n\n이건 ${fromLabel}이 이 토픽의 크론 세션에 묻는 질문입니다 (READ-only).\n크론 작업이 수집하고 처리한 정보를 바탕으로 답변하세요.\n출력 내용은 자동으로 "${fromLabel}" 세션에 돌아갑니다.`
1026
+ : `[ASK from ${fromLabel}]\n${entry.message}\n\n이건 ${fromLabel}이 당신의 context를 참조하려는 요청입니다 (READ-only).\n가지고 있는 정보를 그대로 공유하세요.\n출력 내용은 자동으로 "${fromLabel}" 세션에 돌아갑니다.`;
1027
+
1028
+ if (!isAiEnabled) {
1029
+ logger.warn({ topicName, from: entry.from }, "session-inbox: ask to non-AI topic, dropping");
1030
+ clearPendingAskForEntry(scope, entry, topicName, "target-ai-disabled");
1031
+ if (remoteReply) {
1032
+ await deliverPeerReply(
1033
+ remoteReply,
1034
+ topic.title,
1035
+ `(error: target topic "${topicName}" has no AI)`,
1036
+ "error",
1037
+ );
1038
+ } else {
1039
+ await notifyAskDrop(
1040
+ scope,
1041
+ entry,
1042
+ topicName,
1043
+ `(error: target topic "${topicName}" has no AI)`,
1044
+ );
1045
+ }
1046
+ return;
1047
+ }
1048
+
1049
+ // Register the ask reply callback so the AI's response routes back to the caller.
1050
+ // requestId is pre-generated by the MCP writer — we use it as-is.
1051
+ const requestId = entry.requestId;
1052
+
1053
+ // Look up the caller topic to route the reply back.
1054
+ const callerTopic = remoteReply ? null : await resolveEntryCallerTopic(scope, entry);
1055
+ const callerTopicId = remoteReply?.topicId ?? callerTopic?.id;
1056
+ if (!requestId || !callerTopicId) {
1057
+ clearPendingAskForEntry(scope, entry, topicName, "caller-topic-not-found");
1058
+ logger.warn(
1059
+ { topicName, from: entry.from, fromTopicId: entry.fromTopicId, requestId, callerTopicId },
1060
+ "session-inbox: ask cannot be routed back, dropping",
1061
+ );
1062
+ return;
1063
+ }
1064
+
1065
+ if (!remoteReply) {
1066
+ persistVisibleAskMessage({
1067
+ callerTopicId,
1068
+ callerUserId: String(scope.userId),
1069
+ targetLabel,
1070
+ requestId,
1071
+ message: entry.message,
1072
+ ...(entry.fromThreadRootId ? { threadRootId: entry.fromThreadRootId } : {}),
1073
+ });
1074
+ }
1075
+
1076
+ const { getTopic } = await import("#storage/api-topics");
1077
+ const fullTopic = getTopic(topic.id);
1078
+ const agentOverride = (fullTopic?.agent ?? topic.agent ?? undefined) as AgentKind | undefined;
1079
+ if (!agentOverride) {
1080
+ clearPendingAskForEntry(scope, entry, topicName, "target-agent-missing");
1081
+ await notifyAskDrop(scope, entry, topicName, "(error: target topic has no agent)");
1082
+ return;
1083
+ }
1084
+
1085
+ // Every ask runs as a normal turn on the target's own session (see
1086
+ // askRunsOnTargetSession above), so no fork/model/effort resolution is
1087
+ // needed here — triggerTopicAiTurn below resolves those itself, same as
1088
+ // a regular tell_session.
1089
+ const cronSession =
1090
+ askTarget === "cron" ? getRegisteredCronSession(topic.id, agentOverride) : null;
1091
+ const parentSessionId =
1092
+ askTarget === "cron" ? (cronSession?.sessionId ?? null) : getTopicSessionId(topic.id);
1093
+ if (askTarget === "cron" && !parentSessionId) {
1094
+ clearPendingAskForEntry(scope, entry, topicName, "cron-session-missing");
1095
+ const message = "(error: cron 작업이 최소 한 번 실행되어야 합니다)";
1096
+ if (remoteReply) {
1097
+ await deliverPeerReply(remoteReply, targetLabel, message, "error");
1098
+ } else {
1099
+ await notifyAskDrop(scope, entry, targetLabel, message);
1100
+ }
1101
+ return;
1102
+ }
1103
+
1104
+ const onSettled = (result: { queryId?: string; kind: string; error?: string }) => {
1105
+ if (result.queryId || result.kind !== "error") return;
1106
+ clearPendingAskForEntry(scope, entry, topicName, "target-unavailable-before-dispatch");
1107
+ const message = `(error: ${result.error ?? "target topic became unavailable before dispatch"})`;
1108
+ if (remoteReply) {
1109
+ void deliverPeerReply(remoteReply, targetLabel, message, "error");
1110
+ } else {
1111
+ void notifyAskDrop(scope, entry, targetLabel, message);
1112
+ }
1113
+ };
1114
+ const onDispatched = (queryId: string) => {
1115
+ registerAskCallback({
1116
+ requestId,
1117
+ contextId: entry.contextId,
1118
+ callerTopicId,
1119
+ ...(entry.fromThreadRootId ? { callerThreadRootId: entry.fromThreadRootId } : {}),
1120
+ callerUserId: String(scope.userId),
1121
+ targetQueryId: queryId,
1122
+ createdAt: Date.now(),
1123
+ ...(remoteReply
1124
+ ? { remoteReply }
1125
+ : {
1126
+ pendingAsk: {
1127
+ userId: scope.userId,
1128
+ from: entry.from,
1129
+ to: topicName,
1130
+ requestId,
1131
+ },
1132
+ }),
1133
+ sourceLabel: targetLabel,
1134
+ });
1135
+ };
1136
+
1137
+ if (askRunsOnTargetSession(askTarget)) {
1138
+ triggerTopicAiTurn(topic.id, String(scope.userId), prompt, agentOverride, {
1139
+ origin: entry.from,
1140
+ requestId,
1141
+ contextId: entry.contextId,
1142
+ depth: (entry.fromDepth ?? 0) + 1,
1143
+ from: fromLabel,
1144
+ injectAuthorId: "system",
1145
+ injectSourceAdapter: "session-comm",
1146
+ injectKind: "tell",
1147
+ injectTellCard: {
1148
+ fromLabel,
1149
+ fromTopicId: entry.fromTopicId,
1150
+ label: `Ask from ${fromLabel}`,
1151
+ message: entry.message,
1152
+ },
1153
+ // cron: target the cron session explicitly and run it isolated from
1154
+ // the topic's main visible turn (no fork — see askRunsOnTargetSession's
1155
+ // doc comment for the residual concurrency tradeoff). main: default to
1156
+ // the topic's own session/turn slot, same as tell_session.
1157
+ ...(askTarget === "cron"
1158
+ ? {
1159
+ sessionId: parentSessionId,
1160
+ sessionScope: "isolated" as const,
1161
+ turnConcurrency: "isolated" as const,
1162
+ }
1163
+ : {}),
1164
+ onSettled,
1165
+ onDispatched,
1166
+ });
1167
+ logger.info(
1168
+ { topicName, from: entry.from, requestId, callerTopicId, agent: agentOverride },
1169
+ "session-inbox: ask delivered to target session",
1170
+ );
1171
+ return;
1172
+ }
1173
+
1174
+ // Every ask now runs on the target's own session (see
1175
+ // askRunsOnTargetSession above) — the fork-and-copy path this used to
1176
+ // fall through to for ask_cron was removed 2026-10-20. createAskForkPlan
1177
+ // itself is kept (still exported + unit-tested) in case a future caller
1178
+ // needs a true read-only copy again.
1179
+ }
1180
+
1181
+ // ── Bootstrap ───────────────────────────────────────────────────────
1182
+
1183
+ let watcher: ReturnType<typeof watchDir> | null = null;
1184
+ let fallbackTimer: ReturnType<typeof setInterval> | null = null;
1185
+ let inboxRunner: CoalescingRunner | null = null;
1186
+ let unsubscribeWakeSignal: (() => void) | null = null;
1187
+ let leadershipTimer: ReturnType<typeof setInterval> | null = null;
1188
+ let workerLease: RuntimeProcessLeaseHandle | null = null;
1189
+ let workerStarted = false;
1190
+
1191
+ const SESSION_INBOX_PROCESS_ROLE = "worker:session-inbox";
1192
+
1193
+ /**
1194
+ * Trigger design (see `#outbox/coalescing-runner` for the invariant).
1195
+ *
1196
+ * enqueueSessionInbox ─► wake signal ─┐
1197
+ * legacy JSONL write ─► fs.watch ─────┼─► runner.trigger() ─► flushSessionInbox()
1198
+ * fallback poll ──────────────────────┘ (leading edge, ≥100ms apart)
1199
+ *
1200
+ * Every source funnels into one runner that can only ever pull a run *earlier*.
1201
+ * No source can starve another, so the poll interval and the coalescing window
1202
+ * are now independent knobs instead of a landmine.
1203
+ *
1204
+ * Regression history: the trigger used to be a 200ms trailing debounce fed by a
1205
+ * 100ms poll (b919a2e). Each tick re-armed the debounce before it could fire,
1206
+ * so `flushSessionInbox()` never ran again after boot and every local
1207
+ * tell_session/ask_session hung. `coalescing-runner.test.ts` replays exactly
1208
+ * that timing against these constants.
1209
+ */
1210
+
1211
+ /** Upper bound on trigger→flush latency, and the floor on flush start spacing. */
1212
+ export const SESSION_INBOX_COALESCE_MS = 100;
1213
+ /** Safety net for a missed fs.watch event or a wake signal from a dead writer. */
1214
+ export const SESSION_INBOX_POLL_MS = 1_000;
1215
+ /** With no watcher the poll carries all cross-process latency, so tighten it. */
1216
+ export const SESSION_INBOX_POLL_WITHOUT_WATCH_MS = 250;
1217
+
1218
+ function stopLeaderResources(): void {
1219
+ if (watcher) {
1220
+ watcher.close();
1221
+ watcher = null;
1222
+ }
1223
+ if (fallbackTimer) {
1224
+ clearInterval(fallbackTimer);
1225
+ fallbackTimer = null;
1226
+ }
1227
+ if (unsubscribeWakeSignal) {
1228
+ unsubscribeWakeSignal();
1229
+ unsubscribeWakeSignal = null;
1230
+ }
1231
+ inboxRunner?.stop();
1232
+ inboxRunner = null;
1233
+ }
1234
+
1235
+ function tryBecomeSessionInboxLeader(): void {
1236
+ if (!workerStarted || workerLease) return;
1237
+
1238
+ let acquired: RuntimeProcessLeaseHandle | null = null;
1239
+ acquired = acquireRuntimeProcessLease(SESSION_INBOX_PROCESS_ROLE, {
1240
+ onLost: () => {
1241
+ if (workerLease !== acquired) return;
1242
+ workerLease = null;
1243
+ stopLeaderResources();
1244
+ logger.warn("session-inbox: worker leadership lost");
1245
+ },
1246
+ });
1247
+ if (!acquired) return;
1248
+
1249
+ workerLease = acquired;
1250
+ const recovered = recoverSessionInboxClaims();
1251
+ if (recovered > 0) {
1252
+ logger.warn({ recovered }, "session-inbox: recovered interrupted SQLite claims");
1253
+ }
1254
+ // Recreated per leadership term: a fresh runner cannot inherit a stale timer
1255
+ // from a previous term, and `stopLeaderResources` disarms the old one first.
1256
+ const runner = createCoalescingRunner({
1257
+ run: flushSessionInbox,
1258
+ label: "session-inbox",
1259
+ minIntervalMs: SESSION_INBOX_COALESCE_MS,
1260
+ });
1261
+ inboxRunner = runner;
1262
+ watcher = watchDir(SESSION_INBOX_DIR, () => runner.trigger());
1263
+ unsubscribeWakeSignal = subscribeSessionInboxWrite(() => runner.trigger());
1264
+ const pollMs = watcher ? SESSION_INBOX_POLL_MS : SESSION_INBOX_POLL_WITHOUT_WATCH_MS;
1265
+ fallbackTimer = setInterval(() => runner.trigger(), pollMs);
1266
+ fallbackTimer.unref?.();
1267
+
1268
+ logger.info(
1269
+ {
1270
+ dir: SESSION_INBOX_DIR,
1271
+ role: SESSION_INBOX_PROCESS_ROLE,
1272
+ pollMs,
1273
+ watching: Boolean(watcher),
1274
+ },
1275
+ "session-inbox: worker leadership acquired",
1276
+ );
1277
+ // Drain entries written before this leader started, bypassing the rate limit.
1278
+ void runner.runNow();
1279
+ }
1280
+
1281
+ /**
1282
+ * Join the session-inbox worker election. Exactly one runtime process watches
1283
+ * and drains the shared inbox; contenders take over when its process lease is
1284
+ * released, expires, or belongs to a dead PID.
1285
+ * Returns a cleanup function for graceful shutdown.
1286
+ */
1287
+ export function startSessionInboxWorker(): () => void {
1288
+ if (workerStarted) return () => {};
1289
+ workerStarted = true;
1290
+
1291
+ tryBecomeSessionInboxLeader();
1292
+ leadershipTimer = setInterval(tryBecomeSessionInboxLeader, PROCESS_LEASE_HEARTBEAT_MS);
1293
+ leadershipTimer.unref?.();
1294
+
1295
+ return () => {
1296
+ if (!workerStarted) return;
1297
+ workerStarted = false;
1298
+ if (leadershipTimer) {
1299
+ clearInterval(leadershipTimer);
1300
+ leadershipTimer = null;
1301
+ }
1302
+ stopLeaderResources();
1303
+ workerLease?.stop();
1304
+ workerLease = null;
1305
+ logger.info("session-inbox: worker stopped");
1306
+ };
1307
+ }