@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,943 @@
1
+ /**
2
+ * What the hub delivers into this node for remote session-comm
3
+ * (`POST /topics/:nodeTopicId/session-comm/inbox`): a tell, an ask (with the
4
+ * hub's reply route), an abort, or the answer to an ask this node's room
5
+ * raised. Parsing and the idempotent hand-off to the durable session inbox
6
+ * live here so the gateway route in `control.ts` only does transport.
7
+ */
8
+ import { type DeliveryParticipant, localDeliveryPrincipal } from "#mcp/session-comm/actor-policy";
9
+ import { MAX_PEER_MESSAGE_LENGTH } from "#mcp/session-comm/limits";
10
+ import { type HubRemoteReplyRoute, parseHubRemoteReplyRoute } from "#mcp/session-comm/peer-forward";
11
+ import { MAX_TELL_DEPTH } from "#platform/config";
12
+ import { logger } from "#platform/logger";
13
+ import { getTopic } from "#storage/api-topics";
14
+ import { db } from "#storage/forum-db";
15
+ import {
16
+ claimRemoteSessionInboxOwned,
17
+ completeRemoteSessionInboxClaim,
18
+ deleteExpiredRemoteSessionAsk,
19
+ deleteRemoteSessionAsk,
20
+ getRemoteSessionAsk,
21
+ getRemoteSessionInboxClaim,
22
+ listExpiredRemoteSessionInboxClaims,
23
+ listRemoteSessionAsksToExpire,
24
+ markRemoteSessionAskExpired,
25
+ type RemoteSessionAskRecord,
26
+ type RemoteSessionInboxClaimRecord,
27
+ releaseRemoteSessionInboxClaim,
28
+ remoteSessionClaimOwnerIsDead,
29
+ remoteSessionPayloadHash,
30
+ } from "#storage/remote-session";
31
+ import { enqueueSessionInbox } from "#storage/session-inbox";
32
+ import type { TopicDto } from "#types/api";
33
+
34
+ export const MAX_REMOTE_SESSION_REQUEST_ID_LENGTH = 200;
35
+ export const MAX_REMOTE_SESSION_LABEL_LENGTH = 300;
36
+
37
+ export interface RemoteSessionInboxFrom {
38
+ /** "<originNode>/<originTitle>", shown to the target as the sender. */
39
+ label: string;
40
+ /** The hub's own id of the origin room, for the hub's audit trail; opaque here. */
41
+ hubTopicId?: string;
42
+ }
43
+
44
+ export type RemoteSessionInboxDelivery =
45
+ | {
46
+ kind: "tell";
47
+ requestId: string;
48
+ from: RemoteSessionInboxFrom;
49
+ message: string;
50
+ depth: number;
51
+ }
52
+ | {
53
+ kind: "ask";
54
+ requestId: string;
55
+ from: RemoteSessionInboxFrom;
56
+ message: string;
57
+ fromDepth: number;
58
+ remoteReply: HubRemoteReplyRoute;
59
+ }
60
+ | { kind: "abort"; requestId: string }
61
+ | {
62
+ kind: "ask-reply";
63
+ requestId: string;
64
+ fromLabel: string;
65
+ replyKind: "reply" | "error";
66
+ replyText: string;
67
+ };
68
+
69
+ /** A malformed delivery, answered with its status (400 or 413). */
70
+ export class RemoteSessionInboxError extends Error {
71
+ constructor(
72
+ readonly status: number,
73
+ message: string,
74
+ ) {
75
+ super(message);
76
+ this.name = "RemoteSessionInboxError";
77
+ }
78
+ }
79
+
80
+ function text(value: unknown, name: string, max?: number): string {
81
+ if (typeof value !== "string" || !value.trim()) {
82
+ throw new RemoteSessionInboxError(400, `${name} is required`);
83
+ }
84
+ const trimmed = value.trim();
85
+ if (max !== undefined && trimmed.length > max) {
86
+ throw new RemoteSessionInboxError(400, `${name} is longer than ${max} characters`);
87
+ }
88
+ return trimmed;
89
+ }
90
+
91
+ function message(value: unknown): string {
92
+ if (typeof value !== "string" || !value.trim()) {
93
+ throw new RemoteSessionInboxError(400, "message is required");
94
+ }
95
+ if (value.length > MAX_PEER_MESSAGE_LENGTH) {
96
+ throw new RemoteSessionInboxError(
97
+ 413,
98
+ `message is ${value.length} characters; at most ${MAX_PEER_MESSAGE_LENGTH} are allowed`,
99
+ );
100
+ }
101
+ return value;
102
+ }
103
+
104
+ function depth(value: unknown, name: string, max: number): number {
105
+ if (!Number.isInteger(value) || (value as number) < 0) {
106
+ throw new RemoteSessionInboxError(400, `${name} must be a non-negative integer`);
107
+ }
108
+ if ((value as number) > max) {
109
+ throw new RemoteSessionInboxError(400, `${name} exceeds the tell depth limit (${max})`);
110
+ }
111
+ return value as number;
112
+ }
113
+
114
+ function from(value: unknown): RemoteSessionInboxFrom {
115
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
116
+ throw new RemoteSessionInboxError(400, "from must be { label, hubTopicId? }");
117
+ }
118
+ const record = value as Record<string, unknown>;
119
+ const label = text(record.label, "from.label", MAX_REMOTE_SESSION_LABEL_LENGTH);
120
+ if (record.hubTopicId !== undefined && typeof record.hubTopicId !== "string") {
121
+ throw new RemoteSessionInboxError(400, "from.hubTopicId must be a string");
122
+ }
123
+ return { label, ...(record.hubTopicId ? { hubTopicId: record.hubTopicId } : {}) };
124
+ }
125
+
126
+ /** Validate a delivery body; throws {@link RemoteSessionInboxError}. */
127
+ export function parseRemoteSessionInboxDelivery(
128
+ body: Record<string, unknown>,
129
+ ): RemoteSessionInboxDelivery {
130
+ const kind = text(body.kind, "kind");
131
+ const requestId = text(body.requestId, "requestId", MAX_REMOTE_SESSION_REQUEST_ID_LENGTH);
132
+ switch (kind) {
133
+ case "tell":
134
+ return {
135
+ kind,
136
+ requestId,
137
+ from: from(body.from),
138
+ message: message(body.message),
139
+ // The hub sends the depth the target runs at (caller + 1), already
140
+ // checked there; checked again here so a node is never made to run
141
+ // deeper than its own limit.
142
+ depth: depth(body.depth, "depth", MAX_TELL_DEPTH),
143
+ };
144
+ case "ask": {
145
+ const remoteReply = parseHubRemoteReplyRoute(body.remoteReply);
146
+ if (!remoteReply) {
147
+ throw new RemoteSessionInboxError(
148
+ 400,
149
+ "remoteReply must be { via: 'hub', hubUrl, token, nodeName, topicId, requestId }",
150
+ );
151
+ }
152
+ if (remoteReply.requestId !== requestId) {
153
+ throw new RemoteSessionInboxError(400, "remoteReply.requestId must equal requestId");
154
+ }
155
+ return {
156
+ kind,
157
+ requestId,
158
+ from: from(body.from),
159
+ message: message(body.message),
160
+ // The caller's own depth; the fork answering it runs one deeper.
161
+ fromDepth: depth(body.fromDepth, "fromDepth", MAX_TELL_DEPTH),
162
+ remoteReply,
163
+ };
164
+ }
165
+ case "abort":
166
+ return { kind, requestId };
167
+ case "ask-reply": {
168
+ const replyKind = text(body.replyKind, "replyKind");
169
+ if (replyKind !== "reply" && replyKind !== "error") {
170
+ throw new RemoteSessionInboxError(400, "replyKind must be 'reply' or 'error'");
171
+ }
172
+ if (typeof body.replyText !== "string") {
173
+ throw new RemoteSessionInboxError(400, "replyText is required");
174
+ }
175
+ return {
176
+ kind,
177
+ requestId,
178
+ fromLabel: text(body.fromLabel, "fromLabel", MAX_REMOTE_SESSION_LABEL_LENGTH),
179
+ replyKind,
180
+ replyText: body.replyText,
181
+ };
182
+ }
183
+ default:
184
+ throw new RemoteSessionInboxError(400, "kind must be one of tell, ask, abort, ask-reply");
185
+ }
186
+ }
187
+
188
+ export type RemoteSessionInboxOutcome =
189
+ | { ok: true; replayed: boolean }
190
+ | { ok: false; status: number; error: string; code?: string };
191
+
192
+ /** Answer for a duplicate that meets a live `processing` claim: come back later. */
193
+ export const REMOTE_SESSION_INBOX_IN_PROGRESS_CODE = "in_progress";
194
+
195
+ /**
196
+ * The hub asserts, in `actorUserId`, the execution principal of the person
197
+ * whose remote capability sent this delivery. The node files the inbox entry
198
+ * — and so runs the target's turn, with that principal's vault, browser
199
+ * profile and tool grants — only under that same principal: `userId` must
200
+ * equal `actorUserId`, and that principal must be a participant of the room.
201
+ * This is the remote twin of `localDeliveryPrincipal` (a session can never
202
+ * make a room run as someone else), and it holds even if the hub resolves
203
+ * `userId` to the room's owner instead of the actor (the confused deputy).
204
+ */
205
+ export const REMOTE_SESSION_REQUIRE_ACTOR_ENV = "NEGOTIUM_REMOTE_SESSION_REQUIRE_ACTOR";
206
+ /** 403: `actorUserId` absent while {@link REMOTE_SESSION_REQUIRE_ACTOR_ENV} is on. */
207
+ export const REMOTE_SESSION_ACTOR_REQUIRED_CODE = "actor_required";
208
+ /** 403: `actorUserId` differs from `userId` (or, for `ask-reply`, from the asker). */
209
+ export const REMOTE_SESSION_ACTOR_MISMATCH_CODE = "actor_mismatch";
210
+ /** 403: the asserted actor is not a participant of the target room. */
211
+ export const REMOTE_SESSION_ACTOR_NOT_PARTICIPANT_CODE = "actor_not_participant";
212
+
213
+ /**
214
+ * Whether a delivery without `actorUserId` (a hub older than this contract)
215
+ * is refused. Off by default so an upgraded node keeps working behind an old
216
+ * hub; turn it on once every hub that reaches this node sends the field.
217
+ * Read per request, so flipping it needs no restart of the route's state.
218
+ */
219
+ export function remoteSessionRequireActor(env: NodeJS.ProcessEnv = process.env): boolean {
220
+ const value = env[REMOTE_SESSION_REQUIRE_ACTOR_ENV]?.trim().toLowerCase();
221
+ return value === "1" || value === "true" || value === "yes" || value === "on";
222
+ }
223
+
224
+ export type RemoteSessionPrincipalOutcome =
225
+ | { ok: true; userId: string }
226
+ | { ok: false; status: number; error: string; code?: string };
227
+
228
+ /**
229
+ * Decide the principal a remote delivery is filed under, before anything is
230
+ * claimed or queued. `actorUserId: undefined` is the pre-contract hub: it is
231
+ * refused when `requireActor`, else it keeps the old rule (`userId` must be a
232
+ * participant; 404 otherwise, as before).
233
+ */
234
+ export function resolveRemoteSessionInboxPrincipal(input: {
235
+ userId: string;
236
+ actorUserId: string | undefined;
237
+ targetParticipants: readonly DeliveryParticipant[] | undefined;
238
+ requireActor?: boolean;
239
+ }): RemoteSessionPrincipalOutcome {
240
+ const { userId, actorUserId, targetParticipants } = input;
241
+ const requireActor = input.requireActor ?? remoteSessionRequireActor();
242
+ if (actorUserId === undefined) {
243
+ if (requireActor) {
244
+ return {
245
+ ok: false,
246
+ status: 403,
247
+ error: "actorUserId is required: this node only accepts actor-bound remote deliveries",
248
+ code: REMOTE_SESSION_ACTOR_REQUIRED_CODE,
249
+ };
250
+ }
251
+ if (!(targetParticipants ?? []).some((participant) => participant.userId === userId)) {
252
+ return { ok: false, status: 404, error: "Topic not found" };
253
+ }
254
+ return { ok: true, userId };
255
+ }
256
+ if (actorUserId !== userId) {
257
+ return {
258
+ ok: false,
259
+ status: 403,
260
+ error:
261
+ "actorUserId must equal userId: a remote session can only run a room as its own principal",
262
+ code: REMOTE_SESSION_ACTOR_MISMATCH_CODE,
263
+ };
264
+ }
265
+ const principal = localDeliveryPrincipal({ callerUserId: actorUserId, targetParticipants });
266
+ if (principal === null) {
267
+ return {
268
+ ok: false,
269
+ status: 403,
270
+ error: "actorUserId is not a participant of the target room",
271
+ code: REMOTE_SESSION_ACTOR_NOT_PARTICIPANT_CODE,
272
+ };
273
+ }
274
+ return { ok: true, userId: principal };
275
+ }
276
+
277
+ /**
278
+ * The identity a claim binds a `requestId` to: the delivery *and* the
279
+ * principal it was accepted under. Hashing the principal too means the same
280
+ * `requestId` replayed by another actor (or filed under another `userId`) is
281
+ * a `conflict`, never a `replay` of somebody else's delivery. Key order is
282
+ * fixed here, so the digest is stable.
283
+ */
284
+ export interface RemoteSessionInboxClaimIdentity {
285
+ userId: string;
286
+ /** `null`: accepted from a hub older than the actor contract (legacy rule). */
287
+ actorUserId: string | null;
288
+ delivery: RemoteSessionInboxDelivery;
289
+ }
290
+
291
+ export function remoteSessionInboxClaimHash(identity: {
292
+ userId: string;
293
+ actorUserId?: string | null;
294
+ delivery: RemoteSessionInboxDelivery;
295
+ }): string {
296
+ return remoteSessionPayloadHash({
297
+ userId: identity.userId,
298
+ actorUserId: identity.actorUserId ?? null,
299
+ delivery: identity.delivery,
300
+ });
301
+ }
302
+
303
+ /** Version tag of {@link RemoteSessionInboxEnvelope}; a payload without it is legacy. */
304
+ export const REMOTE_SESSION_INBOX_ENVELOPE_VERSION = 2;
305
+
306
+ /**
307
+ * What a `processing` claim persists (`payload_json`) so an interrupted
308
+ * delivery can be re-run: the delivery plus the principal it was verified
309
+ * under, and — for `ask-reply` — the principal of the pending ask it was
310
+ * verified against (`askUserId`). Recovery re-verifies all of it against the
311
+ * current ask row and room before delivering; a payload without this envelope
312
+ * (written by a node before the actor-bound claim) is never delivered.
313
+ */
314
+ export interface RemoteSessionInboxEnvelope extends RemoteSessionInboxClaimIdentity {
315
+ v: typeof REMOTE_SESSION_INBOX_ENVELOPE_VERSION;
316
+ askUserId?: string;
317
+ }
318
+
319
+ export function remoteSessionInboxEnvelope(input: {
320
+ userId: string;
321
+ actorUserId?: string | null;
322
+ delivery: RemoteSessionInboxDelivery;
323
+ askUserId?: string;
324
+ }): RemoteSessionInboxEnvelope {
325
+ return {
326
+ v: REMOTE_SESSION_INBOX_ENVELOPE_VERSION,
327
+ userId: input.userId,
328
+ actorUserId: input.actorUserId ?? null,
329
+ delivery: input.delivery,
330
+ ...(input.askUserId !== undefined ? { askUserId: input.askUserId } : {}),
331
+ };
332
+ }
333
+
334
+ /** A persisted envelope, or `null` for a legacy / unreadable / malformed one. */
335
+ function readRemoteSessionInboxEnvelope(payload: unknown): RemoteSessionInboxEnvelope | null {
336
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) return null;
337
+ const record = payload as Record<string, unknown>;
338
+ if (record.v !== REMOTE_SESSION_INBOX_ENVELOPE_VERSION) return null;
339
+ if (typeof record.userId !== "string" || !record.userId) return null;
340
+ if (
341
+ record.actorUserId !== null &&
342
+ (typeof record.actorUserId !== "string" || !record.actorUserId)
343
+ ) {
344
+ return null;
345
+ }
346
+ if (
347
+ record.askUserId !== undefined &&
348
+ (typeof record.askUserId !== "string" || !record.askUserId)
349
+ ) {
350
+ return null;
351
+ }
352
+ if (!record.delivery || typeof record.delivery !== "object") return null;
353
+ let delivery: RemoteSessionInboxDelivery;
354
+ try {
355
+ delivery = parseRemoteSessionInboxDelivery(record.delivery as Record<string, unknown>);
356
+ } catch {
357
+ return null;
358
+ }
359
+ return remoteSessionInboxEnvelope({
360
+ userId: record.userId,
361
+ actorUserId: record.actorUserId as string | null,
362
+ delivery,
363
+ ...(typeof record.askUserId === "string" ? { askUserId: record.askUserId } : {}),
364
+ });
365
+ }
366
+
367
+ /**
368
+ * Whether a pending ask may be answered by a delivery accepted under
369
+ * `userId`/`actorUserId`: it must belong to this room and, when the hub
370
+ * asserted an actor, to exactly that principal (`actorUserId === userId ===
371
+ * ask.userId`). Without an actor (old hub) the legacy rule stands: the route
372
+ * already required `userId` to be a participant.
373
+ */
374
+ function askReplyPrincipalRefusal(input: {
375
+ ask: RemoteSessionAskRecord;
376
+ topicId: string;
377
+ userId: string;
378
+ actorUserId: string | null;
379
+ }): Extract<RemoteSessionInboxOutcome, { ok: false }> | null {
380
+ const { ask, topicId, userId, actorUserId } = input;
381
+ if (ask.callerTopicId !== topicId) {
382
+ return { ok: false, status: 404, error: "no pending remote ask with this requestId" };
383
+ }
384
+ if (actorUserId !== null && (actorUserId !== userId || ask.userId !== actorUserId)) {
385
+ // The answer goes into the room of the principal that asked; a delivery
386
+ // asserted for anyone else is not that answer.
387
+ return {
388
+ ok: false,
389
+ status: 403,
390
+ error: "actorUserId is not the principal that raised this ask",
391
+ code: REMOTE_SESSION_ACTOR_MISMATCH_CODE,
392
+ };
393
+ }
394
+ return null;
395
+ }
396
+
397
+ /**
398
+ * One delivery at a time per `requestId` inside this process. The durable
399
+ * lease guards across processes; this guards the async window between the
400
+ * claim and its completion within one, so two identical ask-replies arriving
401
+ * together run strictly one after the other (the second then sees either a
402
+ * `completed` claim, a released one, or the ask consumed).
403
+ */
404
+ const inboxLocks = new Map<string, Promise<unknown>>();
405
+
406
+ async function withRequestLock<T>(requestId: string, run: () => Promise<T>): Promise<T> {
407
+ const previous = inboxLocks.get(requestId) ?? Promise.resolve();
408
+ const current = previous.then(run, run);
409
+ const settled = current.then(
410
+ () => undefined,
411
+ () => undefined,
412
+ );
413
+ inboxLocks.set(requestId, settled);
414
+ try {
415
+ return await current;
416
+ } finally {
417
+ if (inboxLocks.get(requestId) === settled) inboxLocks.delete(requestId);
418
+ }
419
+ }
420
+
421
+ /**
422
+ * Hand one hub delivery to the durable session inbox exactly once.
423
+ *
424
+ * The claim and the enqueue share a transaction: a retried delivery with the
425
+ * same payload is acknowledged as a replay without a second entry, the same
426
+ * `requestId` with a different payload is a conflict, and a failed enqueue
427
+ * leaves no claim behind so the hub's retry is accepted. `ask-reply` is the
428
+ * caller side: the row `recordRemoteSessionAsk` wrote when the ask went out
429
+ * says which room (and thread) the answer belongs in.
430
+ */
431
+ export async function deliverRemoteSessionInbox(args: {
432
+ topic: Pick<TopicDto, "id" | "title" | "agent">;
433
+ /** Execution principal the inbox entry is queued under (a participant). */
434
+ userId: string;
435
+ /**
436
+ * The hub-asserted actor ({@link resolveRemoteSessionInboxPrincipal}).
437
+ * When present it must equal `userId` — re-checked here so no caller of
438
+ * this function can queue an entry under a principal other than the actor —
439
+ * and an `ask-reply` must answer an ask that principal raised.
440
+ */
441
+ actorUserId?: string;
442
+ delivery: RemoteSessionInboxDelivery;
443
+ }): Promise<RemoteSessionInboxOutcome> {
444
+ const { topic, userId, actorUserId, delivery } = args;
445
+ if (actorUserId !== undefined && actorUserId !== userId) {
446
+ return {
447
+ ok: false,
448
+ status: 403,
449
+ error:
450
+ "actorUserId must equal userId: a remote session can only run a room as its own principal",
451
+ code: REMOTE_SESSION_ACTOR_MISMATCH_CODE,
452
+ };
453
+ }
454
+ // Bound to the principal too: the same requestId under another actor is a
455
+ // conflict. `legacyPayloadHash` is what a node before this contract stored.
456
+ const payloadHash = remoteSessionInboxClaimHash({ userId, actorUserId, delivery });
457
+ const legacyPayloadHash = remoteSessionPayloadHash(delivery);
458
+ const timestamp = new Date().toISOString();
459
+
460
+ if (delivery.kind === "tell" || delivery.kind === "ask") {
461
+ // The hub already judged "has AI" from its mirror; the node's own row is
462
+ // final (the two can disagree for a moment after a config change).
463
+ if (!topic.agent) {
464
+ return { ok: false, status: 409, error: `Session "${topic.title}" has no AI invited.` };
465
+ }
466
+ }
467
+
468
+ if (delivery.kind === "ask-reply") {
469
+ return withRequestLock(delivery.requestId, () =>
470
+ deliverAskReply({ topic, delivery, payloadHash, legacyPayloadHash, userId, actorUserId }),
471
+ );
472
+ }
473
+
474
+ const entry =
475
+ delivery.kind === "tell"
476
+ ? {
477
+ type: "tell" as const,
478
+ requestId: delivery.requestId,
479
+ from: delivery.from.label,
480
+ fromTitle: delivery.from.label,
481
+ message: delivery.message,
482
+ depth: delivery.depth,
483
+ timestamp,
484
+ }
485
+ : delivery.kind === "ask"
486
+ ? {
487
+ type: "ask" as const,
488
+ requestId: delivery.requestId,
489
+ from: delivery.from.label,
490
+ fromTitle: delivery.from.label,
491
+ message: delivery.message,
492
+ fromDepth: delivery.fromDepth,
493
+ remoteReply: delivery.remoteReply,
494
+ timestamp,
495
+ }
496
+ : { type: "abort" as const, timestamp };
497
+
498
+ const outcome = db.transaction((): RemoteSessionInboxOutcome => {
499
+ const { outcome: claim, owner } = claimRemoteSessionInboxOwned({
500
+ requestId: delivery.requestId,
501
+ kind: delivery.kind,
502
+ topicId: topic.id,
503
+ payloadHash,
504
+ legacyPayloadHash,
505
+ // Uniform envelope for every kind; completed in this same transaction
506
+ // (which clears it), so recovery only ever sees it for an enqueue that
507
+ // never happened — and releases it without running anything.
508
+ payload: remoteSessionInboxEnvelope({ userId, actorUserId, delivery }),
509
+ });
510
+ if (claim === "replay") return { ok: true, replayed: true };
511
+ if (claim === "conflict") {
512
+ return { ok: false, status: 409, error: "requestId is already bound to another delivery" };
513
+ }
514
+ if (claim === "in_progress") {
515
+ // Cannot happen for a synchronous claim+enqueue, but the state machine
516
+ // is uniform: a live lease is never answered as a replay.
517
+ return {
518
+ ok: false,
519
+ status: 409,
520
+ error: "this delivery is still being processed; retry shortly",
521
+ code: REMOTE_SESSION_INBOX_IN_PROGRESS_CODE,
522
+ };
523
+ }
524
+ enqueueSessionInbox({ userId, topicId: topic.id, entry });
525
+ // Same transaction as the enqueue: the claim is `completed` exactly when
526
+ // the entry is durable, never before — and only by its owner; otherwise
527
+ // the enqueue rolls back with it.
528
+ if (
529
+ !owner ||
530
+ !completeRemoteSessionInboxClaim(delivery.requestId, owner, Date.now(), { payloadHash })
531
+ ) {
532
+ throw new RemoteSessionClaimOwnershipLost(delivery.requestId);
533
+ }
534
+ return { ok: true, replayed: false };
535
+ })();
536
+ if (outcome.ok && !outcome.replayed) {
537
+ logger.info(
538
+ { topicId: topic.id, kind: delivery.kind, requestId: delivery.requestId },
539
+ "session-comm: remote delivery queued",
540
+ );
541
+ }
542
+ return outcome;
543
+ }
544
+
545
+ type AskReplyDelivery = Extract<RemoteSessionInboxDelivery, { kind: "ask-reply" }>;
546
+
547
+ /**
548
+ * The caller side of a remote ask, as one durable state machine:
549
+ *
550
+ * verify (pending ask + principal) → claim `processing` (verified envelope
551
+ * persisted) → deliver into the caller room → [same transaction] record
552
+ * written + ask row consumed + claim `completed`.
553
+ *
554
+ * The principal is checked *before* anything is persisted, and the persisted
555
+ * envelope carries the principal it was checked under, so a crash at any step
556
+ * leaves either nothing, a `processing` claim that {@link
557
+ * recoverRemoteSessionInbox} re-verifies against the ask row before re-running
558
+ * it, or a `completed` one (a replay). Nothing is deleted before the answer is
559
+ * durably in the room. A duplicate that meets a live lease is told
560
+ * `in_progress` (409) — never a false replay — and a delivery that fails
561
+ * releases the claim so the hub's retry runs it again.
562
+ */
563
+ async function deliverAskReply(args: {
564
+ topic: Pick<TopicDto, "id" | "title" | "agent">;
565
+ delivery: AskReplyDelivery;
566
+ payloadHash: string;
567
+ legacyPayloadHash: string;
568
+ userId: string;
569
+ actorUserId?: string;
570
+ now?: number;
571
+ }): Promise<RemoteSessionInboxOutcome> {
572
+ const { topic, delivery, payloadHash, legacyPayloadHash, userId } = args;
573
+ const actorUserId = args.actorUserId ?? null;
574
+ const ask = getRemoteSessionAsk(delivery.requestId);
575
+ if (!ask) {
576
+ // Nothing is waiting: a retry of a reply that already landed is a replay,
577
+ // anything else a 404/409. Read-only — no claim is written for a delivery
578
+ // that has nothing to answer.
579
+ return answerWithoutPendingAsk({ topic, delivery, payloadHash, legacyPayloadHash });
580
+ }
581
+ const refusal = askReplyPrincipalRefusal({ ask, topicId: topic.id, userId, actorUserId });
582
+ if (refusal) return refusal;
583
+ const { outcome: claim, owner } = claimRemoteSessionInboxOwned({
584
+ requestId: delivery.requestId,
585
+ kind: delivery.kind,
586
+ topicId: topic.id,
587
+ payloadHash,
588
+ legacyPayloadHash,
589
+ payload: remoteSessionInboxEnvelope({ userId, actorUserId, delivery, askUserId: ask.userId }),
590
+ now: args.now,
591
+ });
592
+ if (claim === "replay") return { ok: true, replayed: true };
593
+ if (claim === "conflict") {
594
+ return { ok: false, status: 409, error: "requestId is already bound to another delivery" };
595
+ }
596
+ if (claim === "in_progress") {
597
+ return {
598
+ ok: false,
599
+ status: 409,
600
+ error: "this reply is still being delivered; retry shortly",
601
+ code: REMOTE_SESSION_INBOX_IN_PROGRESS_CODE,
602
+ };
603
+ }
604
+ // Under the claim now: re-read the ask so the delivery answers the row the
605
+ // lease protects, and re-check it (it cannot have changed hands, but the
606
+ // check is what the envelope promises).
607
+ const held = getRemoteSessionAsk(delivery.requestId);
608
+ const heldRefusal = held
609
+ ? askReplyPrincipalRefusal({ ask: held, topicId: topic.id, userId, actorUserId })
610
+ : { ok: false as const, status: 404, error: "no pending remote ask with this requestId" };
611
+ if (!held || heldRefusal || held.userId !== ask.userId) {
612
+ releaseRemoteSessionInboxClaim(delivery.requestId, { owner: owner ?? null, payloadHash });
613
+ return (
614
+ heldRefusal ?? { ok: false, status: 404, error: "no pending remote ask with this requestId" }
615
+ );
616
+ }
617
+ return runAskReplyDelivery(held, delivery, { owner: owner!, payloadHash });
618
+ }
619
+
620
+ /** An ask-reply for which no ask is pending: replay, conflict, in-progress or 404 — never a write. */
621
+ function answerWithoutPendingAsk(args: {
622
+ topic: Pick<TopicDto, "id">;
623
+ delivery: AskReplyDelivery;
624
+ payloadHash: string;
625
+ legacyPayloadHash: string;
626
+ }): RemoteSessionInboxOutcome {
627
+ const existing = getRemoteSessionInboxClaim(args.delivery.requestId);
628
+ if (existing) {
629
+ const same =
630
+ existing.kind === args.delivery.kind &&
631
+ existing.topicId === args.topic.id &&
632
+ (existing.payloadHash === args.payloadHash ||
633
+ existing.payloadHash === args.legacyPayloadHash);
634
+ if (!same) {
635
+ return { ok: false, status: 409, error: "requestId is already bound to another delivery" };
636
+ }
637
+ if (existing.state === "completed") return { ok: true, replayed: true };
638
+ return {
639
+ ok: false,
640
+ status: 409,
641
+ error: "this reply is still being delivered; retry shortly",
642
+ code: REMOTE_SESSION_INBOX_IN_PROGRESS_CODE,
643
+ };
644
+ }
645
+ return { ok: false, status: 404, error: "no pending remote ask with this requestId" };
646
+ }
647
+
648
+ type AskReplyDeliverer = typeof import("#runtime/turn-runner").deliverAskCallbackToCaller;
649
+
650
+ let askReplyDeliverer: AskReplyDeliverer | null = null;
651
+
652
+ /** Test seam: replace the caller-room injection (to fail it, or to observe it). */
653
+ export function setRemoteSessionAskReplyDeliverer(next: AskReplyDeliverer | null): void {
654
+ askReplyDeliverer = next;
655
+ }
656
+
657
+ /** The claim changed hands mid-delivery: whatever this holder was writing is rolled back. */
658
+ class RemoteSessionClaimOwnershipLost extends Error {
659
+ constructor(requestId: string) {
660
+ super(`remote session inbox claim ${requestId} is no longer held by this delivery`);
661
+ this.name = "RemoteSessionClaimOwnershipLost";
662
+ }
663
+ }
664
+
665
+ /**
666
+ * Deliver and, in the same transaction as the room record, complete + consume.
667
+ * `claim` is the `processing` claim this delivery holds: its owner token and
668
+ * the digest it was taken under. The completion is a compare-and-set on both and runs FIRST inside the recording
669
+ * transaction: if another holder (a takeover after our lease ran out — maybe
670
+ * in another process, with the same payload digest) owns the claim now, it
671
+ * fails and the whole record rolls back, so the answer is never written twice
672
+ * and never written under someone else's claim. A failed delivery releases
673
+ * only this holder's claim instance.
674
+ */
675
+ async function runAskReplyDelivery(
676
+ ask: RemoteSessionAskRecord,
677
+ delivery: AskReplyDelivery,
678
+ claim: { owner: string; payloadHash: string },
679
+ ): Promise<RemoteSessionInboxOutcome> {
680
+ const { owner, payloadHash } = claim;
681
+ const deliverAskCallbackToCaller =
682
+ askReplyDeliverer ?? (await import("#runtime/turn-runner")).deliverAskCallbackToCaller;
683
+ let delivered = false;
684
+ let recorded = false;
685
+ let ownershipLost = false;
686
+ const onRecorded = () => {
687
+ if (!completeRemoteSessionInboxClaim(ask.requestId, owner, Date.now(), { payloadHash })) {
688
+ ownershipLost = true;
689
+ throw new RemoteSessionClaimOwnershipLost(ask.requestId);
690
+ }
691
+ deleteRemoteSessionAsk(ask.requestId);
692
+ recorded = true;
693
+ };
694
+ try {
695
+ delivered = await deliverAskCallbackToCaller(
696
+ {
697
+ requestId: ask.requestId,
698
+ callerTopicId: ask.callerTopicId,
699
+ ...(ask.callerThreadRootId ? { callerThreadRootId: ask.callerThreadRootId } : {}),
700
+ callerUserId: ask.userId,
701
+ pendingAsk: {
702
+ userId: ask.userId,
703
+ from: ask.fromKey,
704
+ to: ask.toKey,
705
+ requestId: ask.requestId,
706
+ },
707
+ },
708
+ delivery.fromLabel,
709
+ delivery.replyText,
710
+ delivery.replyKind,
711
+ { onRecorded },
712
+ );
713
+ } catch (err) {
714
+ logger.warn(
715
+ { err, requestId: ask.requestId, callerTopicId: ask.callerTopicId },
716
+ "session-comm: remote ask reply delivery threw",
717
+ );
718
+ }
719
+ if (!delivered || !recorded) {
720
+ // Nothing durable happened in the caller room (or the recording
721
+ // transaction rolled back): hand the claim back so the hub's retry (or the
722
+ // recovery pass) runs the delivery again. A compare-and-delete: if the
723
+ // answer did become durable, the claim is `completed` and survives, so the
724
+ // retry after this 500 is a replay rather than a 404.
725
+ if (
726
+ ownershipLost ||
727
+ releaseRemoteSessionInboxClaim(ask.requestId, { owner, payloadHash }) === false
728
+ ) {
729
+ logger.warn(
730
+ { requestId: ask.requestId, ownershipLost },
731
+ "session-comm: remote ask reply claim is held by another delivery; nothing recorded here",
732
+ );
733
+ }
734
+ return { ok: false, status: 500, error: "reply could not be delivered to the caller" };
735
+ }
736
+ return { ok: true, replayed: false };
737
+ }
738
+
739
+ /** The caller-facing text for an outbound ask whose fate nobody learned. */
740
+ export function remoteSessionAskNoReplyText(
741
+ ask: Pick<RemoteSessionAskRecord, "toKey" | "requestId">,
742
+ ): string {
743
+ return [
744
+ `No reply arrived for the ask to "${ask.toKey}" (request_id: ${ask.requestId}).`,
745
+ "This node was interrupted (restart or lost connection) before the hub confirmed the ask was delivered, and nothing came back within the ask timeout.",
746
+ "It may never have reached the target. Ask again if you still need an answer.",
747
+ ].join(" ");
748
+ }
749
+
750
+ /**
751
+ * Tell callers that an outbound hub ask in the `unknown` state (the hub's
752
+ * receipt was never confirmed) timed out without a reply. Each ask is moved
753
+ * `unknown` → `expired` first — refused while a late reply holds an inbox
754
+ * claim for it, and from then on invisible to the reply path — and the row
755
+ * is removed in the same transaction that records the notice. A notice that
756
+ * could not be recorded stays `expired` and is retried on the next pass.
757
+ * Idempotent; runs in the maintenance pass. Returns how many notices landed.
758
+ */
759
+ export async function expireUnknownRemoteSessionAsks(now: number = Date.now()): Promise<number> {
760
+ const due = listRemoteSessionAsksToExpire(now);
761
+ if (!due.length) return 0;
762
+ const deliverAskCallbackToCaller =
763
+ askReplyDeliverer ?? (await import("#runtime/turn-runner")).deliverAskCallbackToCaller;
764
+ let notified = 0;
765
+ for (const ask of due) {
766
+ await withRequestLock(ask.requestId, async () => {
767
+ if (ask.dispatchState === "unknown" && !markRemoteSessionAskExpired(ask.requestId)) return;
768
+ let recorded = false;
769
+ try {
770
+ await deliverAskCallbackToCaller(
771
+ {
772
+ requestId: ask.requestId,
773
+ callerTopicId: ask.callerTopicId,
774
+ ...(ask.callerThreadRootId ? { callerThreadRootId: ask.callerThreadRootId } : {}),
775
+ callerUserId: ask.userId,
776
+ },
777
+ ask.toKey,
778
+ remoteSessionAskNoReplyText(ask),
779
+ "error",
780
+ {
781
+ onRecorded: () => {
782
+ deleteExpiredRemoteSessionAsk(ask.requestId);
783
+ recorded = true;
784
+ },
785
+ },
786
+ );
787
+ } catch (err) {
788
+ logger.warn(
789
+ { err, requestId: ask.requestId, callerTopicId: ask.callerTopicId },
790
+ "session-comm: remote ask no-reply notice threw",
791
+ );
792
+ }
793
+ if (recorded) notified += 1;
794
+ });
795
+ }
796
+ return notified;
797
+ }
798
+
799
+ /**
800
+ * Why a recovered ask-reply envelope may not be delivered now, or `null`.
801
+ * Everything the live path checked is checked again against the *current*
802
+ * state: the ask row (room, and the principal it was verified against), the
803
+ * actor rule (`actorUserId === userId === ask.userId`), that principal still
804
+ * being a participant of the room, and — for an envelope accepted from an old
805
+ * hub (`actorUserId: null`) — that the node still accepts such deliveries.
806
+ */
807
+ function recoveredAskReplyRefusal(
808
+ envelope: RemoteSessionInboxEnvelope,
809
+ ask: RemoteSessionAskRecord,
810
+ topicId: string,
811
+ requireActor: boolean,
812
+ ): string | null {
813
+ if (envelope.askUserId === undefined || envelope.askUserId !== ask.userId) {
814
+ return "the envelope was not verified against this ask";
815
+ }
816
+ if (envelope.actorUserId === null && requireActor) {
817
+ return "actor-less delivery while actorUserId is required";
818
+ }
819
+ const refusal = askReplyPrincipalRefusal({
820
+ ask,
821
+ topicId,
822
+ userId: envelope.userId,
823
+ actorUserId: envelope.actorUserId,
824
+ });
825
+ if (refusal) return refusal.error;
826
+ const room = getTopic(topicId);
827
+ if (
828
+ !room ||
829
+ localDeliveryPrincipal({
830
+ callerUserId: envelope.userId,
831
+ targetParticipants: room.participants,
832
+ }) === null
833
+ ) {
834
+ return "the principal is not a participant of the caller room";
835
+ }
836
+ return null;
837
+ }
838
+
839
+ /**
840
+ * Re-run deliveries a previous process (or a hung one) left `processing`
841
+ * past their lease. Called from the periodic maintenance pass, and at startup
842
+ * with `includeLive`: a live lease is taken over then only when its holder
843
+ * process is provably dead ({@link remoteSessionClaimOwnerIsDead}) — during a
844
+ * rolling restart the previous process may still be delivering.
845
+ *
846
+ * Only an `ask-reply` is ever re-run, and only from a verified envelope
847
+ * ({@link RemoteSessionInboxEnvelope}) whose digest matches the claim and
848
+ * which re-verifies against the current ask row and room
849
+ * ({@link recoveredAskReplyRefusal}); anything else — a legacy payload
850
+ * without the principal, an unreadable one, a refused one — is dropped (the
851
+ * claim released, the ask row untouched, nothing delivered), so the hub's
852
+ * retry goes through every live check again. An ask-reply whose ask row is
853
+ * gone can only be a completed delivery whose completion did not persist
854
+ * (impossible by construction, but cheap to tolerate): it is completed.
855
+ * Claims of the other kinds complete in the same transaction as their
856
+ * enqueue, so an expired `processing` one is a claim whose enqueue never
857
+ * happened — released, so the hub's retry is accepted.
858
+ */
859
+ export async function recoverRemoteSessionInbox(
860
+ now: number = Date.now(),
861
+ options: { includeLive?: boolean; requireActor?: boolean } = {},
862
+ ): Promise<number> {
863
+ const requireActor = options.requireActor ?? remoteSessionRequireActor();
864
+ let recovered = 0;
865
+ // Every release below is a compare-and-delete on exactly the claim
866
+ // instance read here (owner token + digest + lease): the list is read once, and a hub
867
+ // retry — in this process or another one — may take a stale claim over and
868
+ // complete it while an earlier iteration awaits its delivery.
869
+ const releaseAsRead = (claim: RemoteSessionInboxClaimRecord) =>
870
+ withRequestLock(claim.requestId, async () =>
871
+ releaseRemoteSessionInboxClaim(claim.requestId, {
872
+ owner: claim.owner,
873
+ payloadHash: claim.payloadHash,
874
+ leaseUntil: claim.leaseUntil,
875
+ }),
876
+ );
877
+ for (const claim of listExpiredRemoteSessionInboxClaims(now, options)) {
878
+ // `includeLive` (startup) reaches a live lease only when its holder is
879
+ // provably dead; a live one may be a process still running next to us
880
+ // (rolling restart) and is left to its lease.
881
+ if (claim.leaseUntil > now && !remoteSessionClaimOwnerIsDead(claim.owner)) continue;
882
+ if (claim.kind !== "ask-reply") {
883
+ await releaseAsRead(claim);
884
+ continue;
885
+ }
886
+ const envelope = readRemoteSessionInboxEnvelope(claim.payload);
887
+ if (
888
+ !envelope ||
889
+ envelope.delivery.kind !== "ask-reply" ||
890
+ envelope.delivery.requestId !== claim.requestId ||
891
+ remoteSessionInboxClaimHash(envelope) !== claim.payloadHash
892
+ ) {
893
+ logger.warn(
894
+ { requestId: claim.requestId, legacy: !envelope },
895
+ "session-comm: interrupted remote ask reply has no verifiable envelope; dropping it (the hub's retry is re-checked)",
896
+ );
897
+ await releaseAsRead(claim);
898
+ continue;
899
+ }
900
+ const delivery = envelope.delivery;
901
+ const outcome = await withRequestLock(claim.requestId, async () => {
902
+ // Re-take the lease under the lock; a concurrent hub retry may have
903
+ // beaten us to it.
904
+ const { outcome: retaken, owner } = claimRemoteSessionInboxOwned({
905
+ requestId: claim.requestId,
906
+ kind: claim.kind,
907
+ topicId: claim.topicId,
908
+ payloadHash: claim.payloadHash,
909
+ payload: envelope,
910
+ now,
911
+ force: options.includeLive === true,
912
+ });
913
+ if (retaken !== "claimed" || !owner) return retaken;
914
+ const ask = getRemoteSessionAsk(claim.requestId);
915
+ if (!ask) {
916
+ completeRemoteSessionInboxClaim(claim.requestId, owner, Date.now(), {
917
+ payloadHash: claim.payloadHash,
918
+ });
919
+ return "completed-orphan";
920
+ }
921
+ const refusal = recoveredAskReplyRefusal(envelope, ask, claim.topicId, requireActor);
922
+ if (refusal) {
923
+ logger.warn(
924
+ { requestId: claim.requestId, callerTopicId: claim.topicId, reason: refusal },
925
+ "session-comm: interrupted remote ask reply failed re-verification; dropping it",
926
+ );
927
+ releaseRemoteSessionInboxClaim(claim.requestId, { owner, payloadHash: claim.payloadHash });
928
+ return "refused";
929
+ }
930
+ const result = await runAskReplyDelivery(ask, delivery, {
931
+ owner,
932
+ payloadHash: claim.payloadHash,
933
+ });
934
+ return result.ok ? "delivered" : "failed";
935
+ });
936
+ if (outcome === "delivered") recovered += 1;
937
+ logger.info(
938
+ { requestId: claim.requestId, outcome },
939
+ "session-comm: recovered interrupted remote ask reply",
940
+ );
941
+ }
942
+ return recovered;
943
+ }