@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,1028 @@
1
+ /**
2
+ * Durable state for hub-routed remote session-comm (the `node/topic` branch
3
+ * of `tell_session` / `ask_session` / `abort_session` on the `otium` surface).
4
+ *
5
+ * Three small tables, all keyed by the hub's per-call `requestId`:
6
+ *
7
+ * - `remote_session_inbox_claims` — idempotency for what the hub delivers into
8
+ * this node (`POST /topics/:id/session-comm/inbox`). A claim is a small state
9
+ * machine: `processing` (held under a lease while the delivery is being
10
+ * handed off) → `completed`. Only a `completed` claim answers a retried
11
+ * delivery with a replay; a duplicate that meets a `processing` claim is told
12
+ * to come back (`in_progress`), and a `processing` claim whose lease expired
13
+ * (the process died mid-delivery) is taken over and re-run. The same id with
14
+ * a different payload is a conflict.
15
+ * - `remote_session_asks` — the caller side of a remote `ask_session`: which
16
+ * room asked, so the hub's `ask-reply` delivery can be routed back into it
17
+ * after this process restarted.
18
+ * - `remote_session_reply_outbox` — the target side of a remote ask: the
19
+ * answer waiting to be posted to the hub with its one-shot reply token,
20
+ * retried until the hub acknowledges it or the pending-ask TTL passes.
21
+ */
22
+ import { createHash, randomUUID } from "node:crypto";
23
+ import { db } from "#storage/forum-db";
24
+ import { PENDING_ASK_TTL_MS, releasePendingAsk } from "#storage/session-asks";
25
+ import { registerStorageSchemaInitializer } from "#storage/storage-host";
26
+
27
+ const REMOTE_SESSION_TABLES_SQL = `
28
+ CREATE TABLE IF NOT EXISTS remote_session_inbox_claims (
29
+ request_id TEXT PRIMARY KEY,
30
+ kind TEXT NOT NULL,
31
+ topic_id TEXT NOT NULL,
32
+ payload_hash TEXT NOT NULL,
33
+ created_at INTEGER NOT NULL
34
+ );
35
+ CREATE INDEX IF NOT EXISTS idx_remote_session_inbox_claims_created
36
+ ON remote_session_inbox_claims(created_at);
37
+ CREATE TABLE IF NOT EXISTS remote_session_asks (
38
+ request_id TEXT PRIMARY KEY,
39
+ caller_topic_id TEXT NOT NULL,
40
+ user_id TEXT NOT NULL,
41
+ from_key TEXT NOT NULL,
42
+ to_key TEXT NOT NULL,
43
+ caller_thread_root_id TEXT,
44
+ created_at INTEGER NOT NULL
45
+ );
46
+ CREATE INDEX IF NOT EXISTS idx_remote_session_asks_caller
47
+ ON remote_session_asks(caller_topic_id);
48
+ CREATE TABLE IF NOT EXISTS remote_session_reply_outbox (
49
+ request_id TEXT PRIMARY KEY,
50
+ hub_url TEXT NOT NULL,
51
+ token TEXT NOT NULL,
52
+ kind TEXT NOT NULL CHECK (kind IN ('reply', 'error')),
53
+ reply_text TEXT NOT NULL,
54
+ from_label TEXT NOT NULL,
55
+ created_at INTEGER NOT NULL,
56
+ attempts INTEGER NOT NULL DEFAULT 0,
57
+ next_attempt_at INTEGER NOT NULL DEFAULT 0,
58
+ last_error TEXT
59
+ );
60
+ `;
61
+
62
+ /**
63
+ * Columns added after their table existed (guarded: `[table, column, DDL]`).
64
+ * Claim state machine: a claim is `processing` under a lease until its
65
+ * delivery is durably recorded, then `completed`; `payload_json` keeps what a
66
+ * `processing` ask-reply must deliver so an expired lease can be re-run after
67
+ * a restart. `owner_token` is the opaque per-claim ownership token (see
68
+ * `claimRemoteSessionInboxOwned`), NULL only on claims written before it
69
+ * existed. `dispatch_state` is the outbound ask state (see
70
+ * `RemoteSessionAskDispatchState`); rows that predate the column may or may
71
+ * not have reached the hub: `dispatched` (reconciled to `unknown`).
72
+ */
73
+ const REMOTE_SESSION_ADDED_COLUMNS: ReadonlyArray<readonly [string, string, string]> = [
74
+ [
75
+ "remote_session_inbox_claims",
76
+ "state",
77
+ "ALTER TABLE remote_session_inbox_claims ADD COLUMN state TEXT NOT NULL DEFAULT 'completed'",
78
+ ],
79
+ [
80
+ "remote_session_inbox_claims",
81
+ "lease_until",
82
+ "ALTER TABLE remote_session_inbox_claims ADD COLUMN lease_until INTEGER NOT NULL DEFAULT 0",
83
+ ],
84
+ [
85
+ "remote_session_inbox_claims",
86
+ "payload_json",
87
+ "ALTER TABLE remote_session_inbox_claims ADD COLUMN payload_json TEXT",
88
+ ],
89
+ [
90
+ "remote_session_inbox_claims",
91
+ "owner_token",
92
+ "ALTER TABLE remote_session_inbox_claims ADD COLUMN owner_token TEXT",
93
+ ],
94
+ [
95
+ "remote_session_asks",
96
+ "dispatch_state",
97
+ "ALTER TABLE remote_session_asks ADD COLUMN dispatch_state TEXT NOT NULL DEFAULT 'dispatched'",
98
+ ],
99
+ ];
100
+
101
+ const REMOTE_SESSION_SCHEMA_OBJECTS = [
102
+ "remote_session_inbox_claims",
103
+ "idx_remote_session_inbox_claims_created",
104
+ "remote_session_asks",
105
+ "idx_remote_session_asks_caller",
106
+ "remote_session_reply_outbox",
107
+ ];
108
+
109
+ type RemoteSessionSchemaDatabase = Parameters<
110
+ Parameters<typeof registerStorageSchemaInitializer>[0]
111
+ >[0];
112
+
113
+ function remoteSessionColumns(database: RemoteSessionSchemaDatabase, table: string): Set<string> {
114
+ const rows = database.query(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>;
115
+ return new Set(rows.map((row) => row.name));
116
+ }
117
+
118
+ /** Read-only: every table, index and added column is present. */
119
+ function remoteSessionSchemaIsCurrent(database: RemoteSessionSchemaDatabase): boolean {
120
+ const names = new Set(
121
+ (
122
+ database
123
+ .query("SELECT name FROM sqlite_master WHERE type IN ('table','index')")
124
+ .all() as Array<{ name: string }>
125
+ ).map((row) => row.name),
126
+ );
127
+ if (!REMOTE_SESSION_SCHEMA_OBJECTS.every((name) => names.has(name))) return false;
128
+ const columns = new Map<string, Set<string>>();
129
+ return REMOTE_SESSION_ADDED_COLUMNS.every(([table, column]) => {
130
+ let known = columns.get(table);
131
+ if (!known) {
132
+ known = remoteSessionColumns(database, table);
133
+ columns.set(table, known);
134
+ }
135
+ return known.has(column);
136
+ });
137
+ }
138
+
139
+ /**
140
+ * Idempotent and all-or-nothing. A current schema is detected read-only, so a
141
+ * normal boot never takes the write lock. Otherwise the tables and every
142
+ * missing column are added in one `BEGIN IMMEDIATE`: concurrent boots
143
+ * serialize, and the loser re-reads the columns under the lock instead of
144
+ * racing an `ALTER` (which used to be swallowed together with any other
145
+ * error, e.g. SQLITE_BUSY, leaving a process without the column).
146
+ */
147
+ export function initializeRemoteSessionSchema(database: RemoteSessionSchemaDatabase): void {
148
+ if (remoteSessionSchemaIsCurrent(database)) return;
149
+ const migrate = database.transaction(() => {
150
+ database.exec(REMOTE_SESSION_TABLES_SQL);
151
+ const columns = new Map<string, Set<string>>();
152
+ for (const [table, column, ddl] of REMOTE_SESSION_ADDED_COLUMNS) {
153
+ let known = columns.get(table);
154
+ if (!known) {
155
+ known = remoteSessionColumns(database, table);
156
+ columns.set(table, known);
157
+ }
158
+ if (known.has(column)) continue;
159
+ database.exec(ddl);
160
+ known.add(column);
161
+ }
162
+ });
163
+ if (migrate.immediate) migrate.immediate();
164
+ else migrate();
165
+ }
166
+
167
+ registerStorageSchemaInitializer(initializeRemoteSessionSchema, 36);
168
+
169
+ /** Claims older than this are forgotten; the hub never retries a call this late. */
170
+ export const REMOTE_SESSION_INBOX_CLAIM_TTL_MS = 24 * 60 * 60 * 1000;
171
+ /** A reply the hub has not acknowledged by then is dropped: the caller's pending ask has timed out. */
172
+ export const REMOTE_SESSION_REPLY_OUTBOX_TTL_MS = PENDING_ASK_TTL_MS;
173
+ /** Poll cadence of the reply outbox worker; individual rows back off (see {@link remoteSessionRetryDelayMs}). */
174
+ export const REMOTE_SESSION_REPLY_RETRY_MS = 5_000;
175
+ /** Backoff ladder for a reply the hub did not accept: 5, 10, 20, 30 s (cap), with jitter. */
176
+ export const REMOTE_SESSION_REPLY_BACKOFF_BASE_MS = 5_000;
177
+ export const REMOTE_SESSION_REPLY_BACKOFF_MAX_MS = 30_000;
178
+ /**
179
+ * How long a `processing` claim is held before another delivery (a hub retry
180
+ * or the maintenance pass) may take it over. Longer than any single delivery
181
+ * attempt, so a live process is never raced by its own retry.
182
+ */
183
+ export const REMOTE_SESSION_INBOX_CLAIM_LEASE_MS = 60_000;
184
+
185
+ export type RemoteSessionInboxKind = "tell" | "ask" | "abort" | "ask-reply";
186
+ export type RemoteSessionInboxClaimState = "processing" | "completed";
187
+ /**
188
+ * `claimed`: this caller now holds the `processing` lease (fresh, or taken
189
+ * over from an expired one). `replay`: a `completed` claim with the same
190
+ * payload. `in_progress`: another delivery holds a live lease. `conflict`:
191
+ * the id is bound to a different payload/kind/room.
192
+ */
193
+ export type RemoteSessionInboxClaimOutcome = "claimed" | "replay" | "in_progress" | "conflict";
194
+
195
+ /**
196
+ * Delay before retry number `attempts` (1-based: the first retry after the
197
+ * immediate attempt is `attempts = 1`): 5, 10, 20, 30 s and 30 s thereafter,
198
+ * each with ±20 % jitter from `random` (injectable for deterministic tests).
199
+ */
200
+ export function remoteSessionRetryDelayMs(
201
+ attempts: number,
202
+ random: () => number = Math.random,
203
+ ): number {
204
+ const step = Math.max(0, Math.floor(attempts) - 1);
205
+ const base = Math.min(
206
+ REMOTE_SESSION_REPLY_BACKOFF_BASE_MS * 2 ** step,
207
+ REMOTE_SESSION_REPLY_BACKOFF_MAX_MS,
208
+ );
209
+ const jitter = 0.8 + 0.4 * Math.min(1, Math.max(0, random()));
210
+ return Math.round(base * jitter);
211
+ }
212
+
213
+ /**
214
+ * Stable digest of a value. The inbox hashes its actor-bound claim identity
215
+ * (`remoteSessionInboxClaimIdentity` in `#runtime/remote-session-inbox`), so
216
+ * a retried delivery is recognised as one only under the same principal.
217
+ */
218
+ export function remoteSessionPayloadHash(payload: unknown): string {
219
+ return createHash("sha256").update(JSON.stringify(payload)).digest("hex");
220
+ }
221
+
222
+ interface InboxClaimRow {
223
+ kind: string;
224
+ topic_id: string;
225
+ payload_hash: string;
226
+ state: RemoteSessionInboxClaimState;
227
+ lease_until: number | bigint;
228
+ payload_json: string | null;
229
+ owner_token: string | null;
230
+ created_at: number | bigint;
231
+ }
232
+
233
+ export interface RemoteSessionInboxClaimRecord {
234
+ requestId: string;
235
+ kind: RemoteSessionInboxKind;
236
+ topicId: string;
237
+ payloadHash: string;
238
+ state: RemoteSessionInboxClaimState;
239
+ leaseUntil: number;
240
+ payload: unknown;
241
+ createdAt: number;
242
+ /** Who holds the claim right now (`null`: written before tokens existed). */
243
+ owner: string | null;
244
+ }
245
+
246
+ /** This process's incarnation; tells a reused pid apart from a live owner. */
247
+ const CLAIM_PROCESS_INSTANCE = randomUUID();
248
+
249
+ /**
250
+ * A fresh, unique claim-ownership token: `<pid>.<process instance>.<nonce>`.
251
+ * Every claim and every takeover mints a new one, so two holders of the same
252
+ * payload digest (a stalled process and the one that took its lease over,
253
+ * possibly in another process) never share an identity.
254
+ */
255
+ function mintRemoteSessionClaimOwner(): string {
256
+ return `${process.pid}.${CLAIM_PROCESS_INSTANCE}.${randomUUID()}`;
257
+ }
258
+
259
+ /**
260
+ * `true` only when the process that holds `owner` is provably gone: our own
261
+ * pid under another incarnation (the pid was reused after a restart), or a
262
+ * pid the OS reports as nonexistent. A live process, a pid we may not signal,
263
+ * an unparseable or legacy (`null`) token are all "maybe alive".
264
+ */
265
+ export function remoteSessionClaimOwnerIsDead(owner: string | null): boolean {
266
+ if (!owner) return false;
267
+ const [pidText, instance] = owner.split(".");
268
+ const pid = Number(pidText);
269
+ if (!Number.isSafeInteger(pid) || pid <= 0 || !instance) return false;
270
+ if (pid === process.pid) return instance !== CLAIM_PROCESS_INSTANCE;
271
+ try {
272
+ process.kill(pid, 0);
273
+ return false;
274
+ } catch (err) {
275
+ return (err as NodeJS.ErrnoException).code === "ESRCH";
276
+ }
277
+ }
278
+
279
+ export interface RemoteSessionInboxClaimResult {
280
+ outcome: RemoteSessionInboxClaimOutcome;
281
+ /** Set exactly when `outcome` is `claimed`: the token release/complete must present. */
282
+ owner?: string;
283
+ }
284
+
285
+ /**
286
+ * Claim one hub delivery as `processing` under a lease. For tell/ask/abort
287
+ * the caller completes it in the same transaction as the enqueue; for an
288
+ * ask-reply it stays `processing` — with `payload` persisted — until the
289
+ * answer is durably in the caller's room, or is released so the hub's retry
290
+ * runs the delivery again.
291
+ */
292
+ export function claimRemoteSessionInboxOwned(args: {
293
+ requestId: string;
294
+ kind: RemoteSessionInboxKind;
295
+ topicId: string;
296
+ payloadHash: string;
297
+ /** Persisted while `processing` so an interrupted delivery can be re-run. */
298
+ payload?: unknown;
299
+ now?: number;
300
+ leaseMs?: number;
301
+ /**
302
+ * Take over even a live lease — but only one whose owner process is
303
+ * provably dead ({@link remoteSessionClaimOwnerIsDead}); a live or unknown
304
+ * owner is still `in_progress`. Used by the startup recovery pass.
305
+ */
306
+ force?: boolean;
307
+ /**
308
+ * The digest a node before the actor-bound hash would have stored for this
309
+ * delivery (payload only, no principal). A claim bearing it was written by
310
+ * that version: `completed` answers a replay (no side effect), `processing`
311
+ * is taken over and re-bound to `payloadHash`/`payload` — the caller has
312
+ * already verified the principal of the delivery it is re-running.
313
+ */
314
+ legacyPayloadHash?: string;
315
+ }): RemoteSessionInboxClaimResult {
316
+ const now = args.now ?? Date.now();
317
+ const leaseUntil = now + (args.leaseMs ?? REMOTE_SESSION_INBOX_CLAIM_LEASE_MS);
318
+ const payloadJson = args.payload === undefined ? null : JSON.stringify(args.payload);
319
+ const owner = mintRemoteSessionClaimOwner();
320
+ return db.transaction((): RemoteSessionInboxClaimResult => {
321
+ const inserted = db
322
+ .query(
323
+ `INSERT OR IGNORE INTO remote_session_inbox_claims
324
+ (request_id, kind, topic_id, payload_hash, created_at, state, lease_until, payload_json,
325
+ owner_token)
326
+ VALUES (?, ?, ?, ?, ?, 'processing', ?, ?, ?)`,
327
+ )
328
+ .run(
329
+ args.requestId,
330
+ args.kind,
331
+ args.topicId,
332
+ args.payloadHash,
333
+ now,
334
+ leaseUntil,
335
+ payloadJson,
336
+ owner,
337
+ );
338
+ if (Number(inserted.changes ?? 0) === 1) return { outcome: "claimed", owner };
339
+ const existing = db
340
+ .query<InboxClaimRow, [string]>(
341
+ "SELECT * FROM remote_session_inbox_claims WHERE request_id = ?",
342
+ )
343
+ .get(args.requestId);
344
+ const legacy =
345
+ args.legacyPayloadHash !== undefined && existing?.payload_hash === args.legacyPayloadHash;
346
+ if (
347
+ !existing ||
348
+ existing.kind !== args.kind ||
349
+ existing.topic_id !== args.topicId ||
350
+ (existing.payload_hash !== args.payloadHash && !legacy)
351
+ ) {
352
+ return { outcome: "conflict" };
353
+ }
354
+ if (existing.state === "completed") return { outcome: "replay" };
355
+ const leaseLive = Number(existing.lease_until) > now;
356
+ if (leaseLive && !(args.force && remoteSessionClaimOwnerIsDead(existing.owner_token))) {
357
+ return { outcome: "in_progress" };
358
+ }
359
+ // The previous holder died (or hung past its lease): take the claim over
360
+ // under a NEW owner token, so the previous holder's late release or
361
+ // completion (same digest, maybe another process) no longer matches.
362
+ // A legacy claim is re-bound to the actor-bound digest and envelope, so
363
+ // recovery never meets it again in its unverifiable form.
364
+ const taken = db
365
+ .query(
366
+ `UPDATE remote_session_inbox_claims
367
+ SET lease_until = ?, payload_json = COALESCE(?, payload_json), payload_hash = ?,
368
+ owner_token = ?
369
+ WHERE request_id = ? AND state = 'processing' AND owner_token IS ?`,
370
+ )
371
+ .run(leaseUntil, payloadJson, args.payloadHash, owner, args.requestId, existing.owner_token);
372
+ return Number(taken.changes ?? 0) === 1
373
+ ? { outcome: "claimed", owner }
374
+ : { outcome: "in_progress" };
375
+ })();
376
+ }
377
+
378
+ /** {@link claimRemoteSessionInboxOwned} without the token (inspection and tests). */
379
+ export function claimRemoteSessionInbox(
380
+ args: Parameters<typeof claimRemoteSessionInboxOwned>[0],
381
+ ): RemoteSessionInboxClaimOutcome {
382
+ return claimRemoteSessionInboxOwned(args).outcome;
383
+ }
384
+
385
+ /**
386
+ * The delivery is durably recorded: replays may now be acknowledged.
387
+ * Compare-and-set on (requestId, `processing`, owner token — and the payload
388
+ * digest when given): `false` means
389
+ * the caller no longer owns the claim (taken over, completed or released by
390
+ * someone else) and must not record anything — run it inside the recording
391
+ * transaction and abort that transaction on `false`.
392
+ */
393
+ export function completeRemoteSessionInboxClaim(
394
+ requestId: string,
395
+ owner: string,
396
+ now: number = Date.now(),
397
+ expected: { payloadHash?: string } = {},
398
+ ): boolean {
399
+ const result = db
400
+ .query(
401
+ `UPDATE remote_session_inbox_claims
402
+ SET state = 'completed', lease_until = ?, payload_json = NULL
403
+ WHERE request_id = ? AND state = 'processing' AND owner_token = ?
404
+ AND (? IS NULL OR payload_hash = ?)`,
405
+ )
406
+ .run(now, requestId, owner, expected.payloadHash ?? null, expected.payloadHash ?? null);
407
+ return Number(result.changes ?? 0) === 1;
408
+ }
409
+
410
+ export function getRemoteSessionInboxClaim(
411
+ requestId: string,
412
+ ): RemoteSessionInboxClaimRecord | null {
413
+ const row = db
414
+ .query<InboxClaimRow & { request_id: string }, [string]>(
415
+ "SELECT * FROM remote_session_inbox_claims WHERE request_id = ?",
416
+ )
417
+ .get(requestId);
418
+ return row ? toClaimRecord(row) : null;
419
+ }
420
+
421
+ function toClaimRecord(row: InboxClaimRow & { request_id: string }): RemoteSessionInboxClaimRecord {
422
+ let payload: unknown = null;
423
+ if (row.payload_json) {
424
+ try {
425
+ payload = JSON.parse(row.payload_json);
426
+ } catch {
427
+ payload = null;
428
+ }
429
+ }
430
+ return {
431
+ requestId: row.request_id,
432
+ kind: row.kind as RemoteSessionInboxKind,
433
+ topicId: row.topic_id,
434
+ payloadHash: row.payload_hash,
435
+ state: row.state,
436
+ leaseUntil: Number(row.lease_until),
437
+ payload,
438
+ createdAt: Number(row.created_at),
439
+ owner: row.owner_token ?? null,
440
+ };
441
+ }
442
+
443
+ /** `processing` claims whose lease ran out: deliveries a dead process left behind. */
444
+ export function listExpiredRemoteSessionInboxClaims(
445
+ now: number = Date.now(),
446
+ options: { includeLive?: boolean } = {},
447
+ ): RemoteSessionInboxClaimRecord[] {
448
+ return db
449
+ .query<InboxClaimRow & { request_id: string }, [number]>(
450
+ `SELECT * FROM remote_session_inbox_claims
451
+ WHERE state = 'processing' AND lease_until <= ?
452
+ ORDER BY created_at ASC`,
453
+ )
454
+ .all(options.includeLive ? Number.MAX_SAFE_INTEGER : now)
455
+ .map(toClaimRecord);
456
+ }
457
+
458
+ /**
459
+ * Hand a `processing` claim back so the hub's retry runs the delivery again.
460
+ *
461
+ * A compare-and-delete on (requestId, `processing`, owner token, payload
462
+ * digest and — when given — the exact lease): only the claim instance the
463
+ * caller holds — or, for recovery, exactly the one it read — is deleted. A claim that was meanwhile completed, or taken over by
464
+ * another holder (even with the same payload digest, even in another
465
+ * process), carries a different state or token and is never deleted: losing
466
+ * it would turn the hub's next retry into a 404 (an ask-reply whose answer
467
+ * already landed) or a second enqueue (tell/ask/abort).
468
+ */
469
+ export function releaseRemoteSessionInboxClaim(
470
+ requestId: string,
471
+ expected: { owner: string | null; payloadHash: string; leaseUntil?: number },
472
+ ): boolean {
473
+ const result = db
474
+ .query(
475
+ `DELETE FROM remote_session_inbox_claims
476
+ WHERE request_id = ? AND state = 'processing' AND owner_token IS ? AND payload_hash = ?
477
+ AND (? IS NULL OR lease_until = ?)`,
478
+ )
479
+ .run(
480
+ requestId,
481
+ expected.owner,
482
+ expected.payloadHash,
483
+ expected.leaseUntil ?? null,
484
+ expected.leaseUntil ?? null,
485
+ );
486
+ return Number(result.changes ?? 0) === 1;
487
+ }
488
+
489
+ export function purgeRemoteSessionInboxClaims(now: number = Date.now()): number {
490
+ const result = db
491
+ .query("DELETE FROM remote_session_inbox_claims WHERE created_at < ?")
492
+ .run(now - REMOTE_SESSION_INBOX_CLAIM_TTL_MS);
493
+ return Number(result.changes ?? 0);
494
+ }
495
+
496
+ export interface RemoteSessionAskRecord {
497
+ requestId: string;
498
+ callerTopicId: string;
499
+ userId: string;
500
+ fromKey: string;
501
+ toKey: string;
502
+ callerThreadRootId?: string;
503
+ createdAt: number;
504
+ /** Where the outbound ask stands; see {@link RemoteSessionAskDispatchState}. */
505
+ dispatchState?: RemoteSessionAskDispatchState;
506
+ }
507
+
508
+ interface RemoteSessionAskRow {
509
+ request_id: string;
510
+ caller_topic_id: string;
511
+ user_id: string;
512
+ from_key: string;
513
+ to_key: string;
514
+ caller_thread_root_id: string | null;
515
+ created_at: number | bigint;
516
+ dispatch_state: RemoteSessionAskDispatchState;
517
+ }
518
+
519
+ function toAskRecord(row: RemoteSessionAskRow): RemoteSessionAskRecord {
520
+ return {
521
+ requestId: row.request_id,
522
+ callerTopicId: row.caller_topic_id,
523
+ userId: row.user_id,
524
+ fromKey: row.from_key,
525
+ toKey: row.to_key,
526
+ ...(row.caller_thread_root_id ? { callerThreadRootId: row.caller_thread_root_id } : {}),
527
+ createdAt: Number(row.created_at),
528
+ dispatchState: row.dispatch_state,
529
+ };
530
+ }
531
+
532
+ /**
533
+ * One state machine for the outbound hub ask: the durable row *and* the
534
+ * caller's pending marker (a file) it may hold. Invariant: the row is never
535
+ * deleted while its marker may still exist — the marker is released first
536
+ * (requestId-scoped, idempotent: {@link releasePendingAsk}) and the row goes
537
+ * only once that succeeded, so a marker is always findable through its row.
538
+ *
539
+ * - `prepared`: row written, marker maybe; the hub has certainly not been called.
540
+ * - `dispatched`: the hub call is in flight (or its process died during it, or
541
+ * it ended "uncertain"); the hub may hold the ask. Row + marker.
542
+ * - `sent`: the hub acknowledged the ask. Row + marker until the reply lands
543
+ * (the reply path consumes both) or the TTL passes.
544
+ * - `abandoned`: no reply can come (the hub refused, or registration failed)
545
+ * but the marker could not be released yet; reconciliation retries.
546
+ * - `unknown`: a `dispatched` ask whose outcome nobody will learn (the hub
547
+ * call's grant is per-turn, so neither an idempotent resend nor a hub status
548
+ * query is possible after the fact). Marker released so the room can ask
549
+ * again; row kept so a late reply is still routed; at the TTL the caller is
550
+ * told no reply arrived.
551
+ * - `expired`: an `unknown` ask whose "no reply arrived" notice is being
552
+ * delivered; invisible to the reply path, removed with the notice's record.
553
+ *
554
+ * prepared ─marker─▶ dispatched ─hub ok─▶ sent ─reply/TTL─▶ ∅
555
+ * │ │ └─hub refused─▶ abandoned ─release─▶ ∅
556
+ * └─fail/grace─▶ release ─▶ ∅ (or abandoned)
557
+ * └─crash/uncertain + grace ─release─▶ unknown ─reply─▶ ∅
558
+ * └─TTL─▶ expired ─notice─▶ ∅
559
+ */
560
+ export type RemoteSessionAskDispatchState =
561
+ | "prepared"
562
+ | "dispatched"
563
+ | "sent"
564
+ | "abandoned"
565
+ | "unknown"
566
+ | "expired";
567
+
568
+ /**
569
+ * A `prepared` row older than this belongs to a process that died between
570
+ * writing it and calling the hub: prepare → marker → dispatched is
571
+ * synchronous, so a live one is never this old.
572
+ */
573
+ export const REMOTE_SESSION_ASK_PREPARE_GRACE_MS = 60_000;
574
+ /**
575
+ * A `dispatched` row older than this is not waiting on a live hub call: one
576
+ * `hubRemoteAsk` is bounded by 3 attempts × 15 s (+ backoff), so the caller
577
+ * has long since either confirmed it (`sent`) or given up on knowing.
578
+ */
579
+ export const REMOTE_SESSION_ASK_DISPATCH_GRACE_MS = 2 * 60_000;
580
+
581
+ /** Remember an outbound remote ask before the hub is asked to forward it. */
582
+ export function recordRemoteSessionAsk(
583
+ args: Omit<RemoteSessionAskRecord, "createdAt" | "dispatchState"> & {
584
+ createdAt?: number;
585
+ /** Defaults to `sent` (an ask the hub holds); the hub-ask path passes `prepared`. */
586
+ dispatchState?: RemoteSessionAskDispatchState;
587
+ },
588
+ ): void {
589
+ db.query(
590
+ `INSERT INTO remote_session_asks
591
+ (request_id, caller_topic_id, user_id, from_key, to_key, caller_thread_root_id, created_at,
592
+ dispatch_state)
593
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
594
+ ON CONFLICT(request_id) DO UPDATE SET
595
+ caller_topic_id = excluded.caller_topic_id,
596
+ user_id = excluded.user_id,
597
+ from_key = excluded.from_key,
598
+ to_key = excluded.to_key,
599
+ caller_thread_root_id = excluded.caller_thread_root_id,
600
+ created_at = excluded.created_at,
601
+ dispatch_state = excluded.dispatch_state`,
602
+ ).run(
603
+ args.requestId,
604
+ args.callerTopicId,
605
+ args.userId,
606
+ args.fromKey,
607
+ args.toKey,
608
+ args.callerThreadRootId ?? null,
609
+ args.createdAt ?? Date.now(),
610
+ args.dispatchState ?? "sent",
611
+ );
612
+ }
613
+
614
+ /** Compare-and-set of the dispatch state; `false` if the row is not in `from`. */
615
+ function moveRemoteSessionAsk(
616
+ requestId: string,
617
+ from: RemoteSessionAskDispatchState,
618
+ to: RemoteSessionAskDispatchState,
619
+ ): boolean {
620
+ const result = db
621
+ .query(
622
+ "UPDATE remote_session_asks SET dispatch_state = ? WHERE request_id = ? AND dispatch_state = ?",
623
+ )
624
+ .run(to, requestId, from);
625
+ return Number(result.changes ?? 0) === 1;
626
+ }
627
+
628
+ /** Compare-and-delete: drop the row only if it is still in `state`. */
629
+ function deleteRemoteSessionAskInState(
630
+ requestId: string,
631
+ state: RemoteSessionAskDispatchState,
632
+ ): boolean {
633
+ const result = db
634
+ .query("DELETE FROM remote_session_asks WHERE request_id = ? AND dispatch_state = ?")
635
+ .run(requestId, state);
636
+ return Number(result.changes ?? 0) === 1;
637
+ }
638
+
639
+ /** The hub call is about to be made: from now on the hub may hold the ask. */
640
+ export function markRemoteSessionAskDispatched(requestId: string): boolean {
641
+ return moveRemoteSessionAsk(requestId, "prepared", "dispatched");
642
+ }
643
+
644
+ /**
645
+ * The hub acknowledged the ask. Best effort: a row left `dispatched` (this
646
+ * write failed, or the reply already consumed the row) is still correct —
647
+ * reconciliation merely treats it as `unknown` after the grace.
648
+ */
649
+ export function markRemoteSessionAskSent(requestId: string): boolean {
650
+ try {
651
+ return moveRemoteSessionAsk(requestId, "dispatched", "sent");
652
+ } catch {
653
+ return false;
654
+ }
655
+ }
656
+
657
+ /** `true` when no marker of this ask remains; a throw counts as "still held". */
658
+ function tryRelease(release: () => boolean): boolean {
659
+ try {
660
+ return release() === true;
661
+ } catch {
662
+ return false;
663
+ }
664
+ }
665
+
666
+ /**
667
+ * Drop the row only once its marker is released; otherwise park it as
668
+ * `abandoned` (from `state`) so reconciliation retries the release. If even
669
+ * that write fails the row keeps `state`, which reconciliation also covers.
670
+ */
671
+ function retireRemoteSessionAsk(
672
+ requestId: string,
673
+ state: RemoteSessionAskDispatchState,
674
+ release: () => boolean,
675
+ ): void {
676
+ try {
677
+ if (tryRelease(release)) deleteRemoteSessionAskInState(requestId, state);
678
+ else if (state !== "abandoned") moveRemoteSessionAsk(requestId, state, "abandoned");
679
+ } catch {
680
+ // Row left as it was: reconciliation retries from that state.
681
+ }
682
+ }
683
+
684
+ /**
685
+ * Register an outbound hub ask: durable caller row (`prepared`), then the
686
+ * caller's pending marker, then `dispatched` — only after this returns `ok`
687
+ * may the hub be called. A failure retires what was written without ever
688
+ * orphaning the marker: the row is deleted only after `releaseMarker`
689
+ * confirmed the marker is gone, else it stays (`abandoned`/`prepared`) for
690
+ * {@link reconcileRemoteSessionAsks}. `pending` means another ask to that
691
+ * room is outstanding (its marker is not ours and is never touched).
692
+ */
693
+ export function beginRemoteSessionAsk(
694
+ args: Omit<RemoteSessionAskRecord, "createdAt" | "dispatchState"> & {
695
+ createMarker: () => boolean;
696
+ /** RequestId-scoped, idempotent: `true` once no marker of this ask remains. */
697
+ releaseMarker: () => boolean;
698
+ },
699
+ ): "ok" | "pending" {
700
+ const { createMarker, releaseMarker, ...record } = args;
701
+ recordRemoteSessionAsk({ ...record, dispatchState: "prepared" });
702
+ let created: boolean;
703
+ try {
704
+ created = createMarker();
705
+ } catch (err) {
706
+ // A throwing create may still have left a (partial) marker file.
707
+ retireRemoteSessionAsk(record.requestId, "prepared", releaseMarker);
708
+ throw err;
709
+ }
710
+ if (!created) {
711
+ // The slot belongs to another ask: its marker is never touched.
712
+ retireRemoteSessionAsk(record.requestId, "prepared", () => true);
713
+ return "pending";
714
+ }
715
+ try {
716
+ if (!markRemoteSessionAskDispatched(record.requestId)) {
717
+ throw new Error("remote session ask row vanished before dispatch");
718
+ }
719
+ } catch (err) {
720
+ retireRemoteSessionAsk(record.requestId, "prepared", releaseMarker);
721
+ throw err;
722
+ }
723
+ return "ok";
724
+ }
725
+
726
+ /**
727
+ * The hub definitively refused a `dispatched` ask (nothing was forwarded):
728
+ * release the marker, then drop the row — or keep it `abandoned` until the
729
+ * release succeeds.
730
+ */
731
+ export function abandonRemoteSessionAsk(requestId: string, releaseMarker: () => boolean): void {
732
+ retireRemoteSessionAsk(requestId, "dispatched", releaseMarker);
733
+ }
734
+
735
+ function releaseRowMarker(row: RemoteSessionAskRow): boolean {
736
+ return tryRelease(() =>
737
+ releasePendingAsk({
738
+ userId: row.user_id,
739
+ from: row.from_key,
740
+ to: row.to_key,
741
+ requestId: row.request_id,
742
+ }),
743
+ );
744
+ }
745
+
746
+ /**
747
+ * Durable recovery of the outbound-ask state machine; runs in the
748
+ * maintenance pass (at startup and then periodically). Idempotent.
749
+ *
750
+ * - `abandoned` (any age) and `prepared` past {@link REMOTE_SESSION_ASK_PREPARE_GRACE_MS}
751
+ * (the hub was never called): release the marker, then drop the row.
752
+ * - `dispatched` past {@link REMOTE_SESSION_ASK_DISPATCH_GRACE_MS} (the
753
+ * process died around the hub call, or the call ended uncertain): release
754
+ * the marker so the room can ask again, then mark the row `unknown`.
755
+ *
756
+ * A failed release leaves the row as it was, so the next pass retries; past
757
+ * the ask TTL the marker is stale (it no longer blocks a new ask and is
758
+ * swept on read), so the row moves on regardless.
759
+ */
760
+ export function reconcileRemoteSessionAsks(
761
+ now: number = Date.now(),
762
+ opts: { prepareGraceMs?: number; dispatchGraceMs?: number } = {},
763
+ ): { removed: number; unknown: number } {
764
+ const prepareCutoff = now - (opts.prepareGraceMs ?? REMOTE_SESSION_ASK_PREPARE_GRACE_MS);
765
+ const dispatchCutoff = now - (opts.dispatchGraceMs ?? REMOTE_SESSION_ASK_DISPATCH_GRACE_MS);
766
+ const ttlCutoff = now - PENDING_ASK_TTL_MS;
767
+ const rows = db
768
+ .query<RemoteSessionAskRow, [number, number]>(
769
+ `SELECT * FROM remote_session_asks
770
+ WHERE dispatch_state = 'abandoned'
771
+ OR (dispatch_state = 'prepared' AND created_at <= ?)
772
+ OR (dispatch_state = 'dispatched' AND created_at <= ?)`,
773
+ )
774
+ .all(prepareCutoff, dispatchCutoff);
775
+ let removed = 0;
776
+ let unknown = 0;
777
+ for (const row of rows) {
778
+ const released = releaseRowMarker(row) || Number(row.created_at) < ttlCutoff;
779
+ if (!released) continue;
780
+ if (row.dispatch_state === "dispatched") {
781
+ if (moveRemoteSessionAsk(row.request_id, "dispatched", "unknown")) unknown += 1;
782
+ } else if (deleteRemoteSessionAskInState(row.request_id, row.dispatch_state)) {
783
+ removed += 1;
784
+ }
785
+ }
786
+ return { removed, unknown };
787
+ }
788
+
789
+ /**
790
+ * Asks whose caller must now be told that no reply arrived: `unknown` past
791
+ * the ask TTL, and `expired` ones whose notice did not land yet.
792
+ */
793
+ export function listRemoteSessionAsksToExpire(now: number = Date.now()): RemoteSessionAskRecord[] {
794
+ return db
795
+ .query<RemoteSessionAskRow, [number]>(
796
+ `SELECT * FROM remote_session_asks
797
+ WHERE dispatch_state = 'expired' OR (dispatch_state = 'unknown' AND created_at < ?)
798
+ ORDER BY created_at`,
799
+ )
800
+ .all(now - PENDING_ASK_TTL_MS)
801
+ .map(toAskRecord);
802
+ }
803
+
804
+ /**
805
+ * `unknown` → `expired`, unless a late reply is being delivered right now
806
+ * (it holds an inbox claim for the same requestId): that reply wins.
807
+ * From here on the reply path no longer sees the row.
808
+ */
809
+ export function markRemoteSessionAskExpired(requestId: string): boolean {
810
+ const result = db
811
+ .query(
812
+ `UPDATE remote_session_asks SET dispatch_state = 'expired'
813
+ WHERE request_id = ? AND dispatch_state = 'unknown'
814
+ AND NOT EXISTS (
815
+ SELECT 1 FROM remote_session_inbox_claims
816
+ WHERE request_id = ? AND kind = 'ask-reply' AND state = 'processing'
817
+ )`,
818
+ )
819
+ .run(requestId, requestId);
820
+ return Number(result.changes ?? 0) === 1;
821
+ }
822
+
823
+ /** The "no reply arrived" notice is durable: the `expired` row goes with it. */
824
+ export function deleteExpiredRemoteSessionAsk(requestId: string): boolean {
825
+ return deleteRemoteSessionAskInState(requestId, "expired");
826
+ }
827
+
828
+ /** The ask a reply may still answer (an `expired` one no longer can). */
829
+ export function getRemoteSessionAsk(requestId: string): RemoteSessionAskRecord | null {
830
+ const row = db
831
+ .query<RemoteSessionAskRow, [string]>(
832
+ "SELECT * FROM remote_session_asks WHERE request_id = ? AND dispatch_state <> 'expired'",
833
+ )
834
+ .get(requestId);
835
+ return row ? toAskRecord(row) : null;
836
+ }
837
+
838
+ export function deleteRemoteSessionAsk(requestId: string): boolean {
839
+ const result = db.query("DELETE FROM remote_session_asks WHERE request_id = ?").run(requestId);
840
+ return Number(result.changes ?? 0) === 1;
841
+ }
842
+
843
+ /** Consume the caller record exactly once: the row is gone after this returns it. */
844
+ export function takeRemoteSessionAsk(requestId: string): RemoteSessionAskRecord | null {
845
+ return db.transaction(() => {
846
+ const record = getRemoteSessionAsk(requestId);
847
+ if (record) deleteRemoteSessionAsk(requestId);
848
+ return record;
849
+ })();
850
+ }
851
+
852
+ export function deleteRemoteSessionAsksForTopic(callerTopicId: string): number {
853
+ const result = db
854
+ .query("DELETE FROM remote_session_asks WHERE caller_topic_id = ?")
855
+ .run(callerTopicId);
856
+ return Number(result.changes ?? 0);
857
+ }
858
+
859
+ /**
860
+ * Forget asks past the TTL. Only states whose marker is settled go at the TTL
861
+ * (`sent`: the marker is stale by then); the others are walked through
862
+ * {@link reconcileRemoteSessionAsks} and the expiry notice first. Anything
863
+ * still here at twice the TTL is dropped unconditionally (a caller room that
864
+ * can no longer take the notice must not pin the row forever).
865
+ */
866
+ export function purgeStaleRemoteSessionAsks(now: number = Date.now()): number {
867
+ const result = db
868
+ .query(
869
+ `DELETE FROM remote_session_asks
870
+ WHERE (dispatch_state = 'sent' AND created_at < ?) OR created_at < ?`,
871
+ )
872
+ .run(now - PENDING_ASK_TTL_MS, now - 2 * PENDING_ASK_TTL_MS);
873
+ return Number(result.changes ?? 0);
874
+ }
875
+
876
+ export interface RemoteSessionReplyOutboxEntry {
877
+ requestId: string;
878
+ hubUrl: string;
879
+ token: string;
880
+ kind: "reply" | "error";
881
+ replyText: string;
882
+ fromLabel: string;
883
+ createdAt: number;
884
+ attempts: number;
885
+ nextAttemptAt: number;
886
+ lastError?: string;
887
+ }
888
+
889
+ interface RemoteSessionReplyOutboxRow {
890
+ request_id: string;
891
+ hub_url: string;
892
+ token: string;
893
+ kind: "reply" | "error";
894
+ reply_text: string;
895
+ from_label: string;
896
+ created_at: number | bigint;
897
+ attempts: number | bigint;
898
+ next_attempt_at: number | bigint;
899
+ last_error: string | null;
900
+ }
901
+
902
+ function toOutboxEntry(row: RemoteSessionReplyOutboxRow): RemoteSessionReplyOutboxEntry {
903
+ return {
904
+ requestId: row.request_id,
905
+ hubUrl: row.hub_url,
906
+ token: row.token,
907
+ kind: row.kind,
908
+ replyText: row.reply_text,
909
+ fromLabel: row.from_label,
910
+ createdAt: Number(row.created_at),
911
+ attempts: Number(row.attempts),
912
+ nextAttemptAt: Number(row.next_attempt_at),
913
+ ...(row.last_error ? { lastError: row.last_error } : {}),
914
+ };
915
+ }
916
+
917
+ /**
918
+ * Queue an answer for the hub. One row per ask: a second answer for the same
919
+ * request (a retry after a partial failure) replaces the first, which is what
920
+ * the hub's one-shot reply token would enforce anyway.
921
+ */
922
+ export function upsertRemoteSessionReplyOutbox(args: {
923
+ requestId: string;
924
+ hubUrl: string;
925
+ token: string;
926
+ kind: "reply" | "error";
927
+ replyText: string;
928
+ fromLabel: string;
929
+ createdAt?: number;
930
+ }): void {
931
+ db.query(
932
+ `INSERT INTO remote_session_reply_outbox
933
+ (request_id, hub_url, token, kind, reply_text, from_label, created_at, attempts, next_attempt_at, last_error)
934
+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, 0, NULL)
935
+ ON CONFLICT(request_id) DO UPDATE SET
936
+ hub_url = excluded.hub_url,
937
+ token = excluded.token,
938
+ kind = excluded.kind,
939
+ reply_text = excluded.reply_text,
940
+ from_label = excluded.from_label,
941
+ attempts = 0,
942
+ next_attempt_at = 0,
943
+ last_error = NULL`,
944
+ ).run(
945
+ args.requestId,
946
+ args.hubUrl,
947
+ args.token,
948
+ args.kind,
949
+ args.replyText,
950
+ args.fromLabel,
951
+ args.createdAt ?? Date.now(),
952
+ );
953
+ }
954
+
955
+ export function listRemoteSessionReplyOutbox(
956
+ args: { now?: number; limit?: number; due?: boolean } = {},
957
+ ): RemoteSessionReplyOutboxEntry[] {
958
+ const now = args.now ?? Date.now();
959
+ const rows =
960
+ args.due === false
961
+ ? db
962
+ .query<RemoteSessionReplyOutboxRow, [number]>(
963
+ "SELECT * FROM remote_session_reply_outbox ORDER BY created_at LIMIT ?",
964
+ )
965
+ .all(args.limit ?? 100)
966
+ : db
967
+ .query<RemoteSessionReplyOutboxRow, [number, number]>(
968
+ `SELECT * FROM remote_session_reply_outbox
969
+ WHERE next_attempt_at <= ?
970
+ ORDER BY created_at LIMIT ?`,
971
+ )
972
+ .all(now, args.limit ?? 100);
973
+ return rows.map(toOutboxEntry);
974
+ }
975
+
976
+ export function deleteRemoteSessionReplyOutbox(requestId: string): boolean {
977
+ const result = db
978
+ .query("DELETE FROM remote_session_reply_outbox WHERE request_id = ?")
979
+ .run(requestId);
980
+ return Number(result.changes ?? 0) === 1;
981
+ }
982
+
983
+ /**
984
+ * Record a failed attempt and schedule the next one on the backoff ladder
985
+ * (5, 10, 20, 30 s cap, jittered) — the immediate first attempt is
986
+ * `attempts = 0`, so the first deferral waits ≈5 s. `retryMs` pins the delay.
987
+ */
988
+ export function deferRemoteSessionReplyOutbox(args: {
989
+ requestId: string;
990
+ error: string;
991
+ now?: number;
992
+ retryMs?: number;
993
+ random?: () => number;
994
+ }): void {
995
+ const now = args.now ?? Date.now();
996
+ db.transaction(() => {
997
+ const row = db
998
+ .query<{ attempts: number | bigint }, [string]>(
999
+ "SELECT attempts FROM remote_session_reply_outbox WHERE request_id = ?",
1000
+ )
1001
+ .get(args.requestId);
1002
+ if (!row) return;
1003
+ const attempts = Number(row.attempts) + 1;
1004
+ const delay = args.retryMs ?? remoteSessionRetryDelayMs(attempts, args.random);
1005
+ db.query(
1006
+ `UPDATE remote_session_reply_outbox
1007
+ SET attempts = ?, next_attempt_at = ?, last_error = ?
1008
+ WHERE request_id = ?`,
1009
+ ).run(attempts, now + delay, args.error.slice(0, 500), args.requestId);
1010
+ })();
1011
+ }
1012
+
1013
+ /** Drop answers nobody is waiting for any more. Returns what was dropped, for the log. */
1014
+ export function purgeExpiredRemoteSessionReplyOutbox(
1015
+ now: number = Date.now(),
1016
+ ): RemoteSessionReplyOutboxEntry[] {
1017
+ const cutoff = now - REMOTE_SESSION_REPLY_OUTBOX_TTL_MS;
1018
+ const expired = db
1019
+ .query<RemoteSessionReplyOutboxRow, [number]>(
1020
+ "SELECT * FROM remote_session_reply_outbox WHERE created_at < ?",
1021
+ )
1022
+ .all(cutoff)
1023
+ .map(toOutboxEntry);
1024
+ if (expired.length) {
1025
+ db.query("DELETE FROM remote_session_reply_outbox WHERE created_at < ?").run(cutoff);
1026
+ }
1027
+ return expired;
1028
+ }