@bastani/atomic 0.10.10 → 0.10.11-alpha.2

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 (402) hide show
  1. package/CHANGELOG.md +139 -0
  2. package/README.md +1 -1
  3. package/dist/_shared/dist-KOELCESV.js +2 -2
  4. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  5. package/dist/_shared/lib-4PES5P4V.js +2 -2
  6. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +11 -13
  7. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js.map +1 -1
  8. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +9 -9
  9. package/dist/_shared/mode-shared-2QJSCUM6.js +55 -18
  10. package/dist/_shared/mode-shared-2QJSCUM6.js.map +1 -1
  11. package/dist/_shared/p1a-prewarm-XIU57JHF.js +3 -3
  12. package/dist/_shared/runtime-O4KCSG4C.js +5 -5
  13. package/dist/_shared/{sdk-RRLVN7ER.js → sdk-IQMULKFU.js} +2962 -470
  14. package/dist/_shared/sdk-IQMULKFU.js.map +1 -0
  15. package/dist/_shared/session-data-AHTU7IS6.js +4 -4
  16. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  17. package/dist/_shared/settings-startup-8-DNZ2RIHM.js +1 -1
  18. package/dist/_shared/{settings-startup-4QCVCI53.js → settings-startup-HXQLSUWM.js} +8 -2
  19. package/dist/_shared/settings-startup-HXQLSUWM.js.map +1 -0
  20. package/dist/_shared/{startup-0-0-4VG2G44V.js → startup-0-0-3IXNMFM2.js} +482 -53
  21. package/dist/_shared/startup-0-0-3IXNMFM2.js.map +1 -0
  22. package/dist/_shared/{startup-0-1-XTIL65D4.js → startup-0-1-7T2IAE7J.js} +121 -251
  23. package/dist/_shared/startup-0-1-7T2IAE7J.js.map +1 -0
  24. package/dist/_shared/{startup-0-2-27OWFHV6.js → startup-0-2-5QHPCEON.js} +293 -10
  25. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -0
  26. package/dist/_shared/{startup-0-3-T4DVFYWX.js → startup-0-3-4ZYBYQNM.js} +273 -14
  27. package/dist/_shared/startup-0-3-4ZYBYQNM.js.map +1 -0
  28. package/dist/_shared/startup-0-4-ZMJV547D.js +6 -6
  29. package/dist/_shared/{startup-0-5-FD2P735I.js → startup-0-5-YDW47QX6.js} +29 -71
  30. package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -0
  31. package/dist/_shared/startup-10-0-TDQNBDDL.js +9 -9
  32. package/dist/_shared/startup-12-0-55AAXBJZ.js +4 -4
  33. package/dist/_shared/startup-14-0-MLX36RBG.js +6 -6
  34. package/dist/_shared/startup-15-0-YUKGAC63.js +34 -10
  35. package/dist/_shared/startup-15-0-YUKGAC63.js.map +1 -1
  36. package/dist/_shared/startup-15-1-4S7FLMNG.js +10 -9
  37. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  38. package/dist/_shared/startup-8-0-34CBHPZH.js +421 -84
  39. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  40. package/dist/_shared/{startup-8-1-4KANEHRA.js → startup-8-1-X32CYSXB.js} +1291 -722
  41. package/dist/_shared/startup-8-1-X32CYSXB.js.map +1 -0
  42. package/dist/_shared/storage-command-7MGXLJGZ.js +17 -9
  43. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  44. package/dist/_shared/task-reference-stream-JWMUZSJX.js +1 -1
  45. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  46. package/dist/_shared/tree-outline-MUEPK5B7.js +3 -3
  47. package/dist/builtin/intercom/CHANGELOG.md +29 -0
  48. package/dist/builtin/intercom/broker/broker.bundle.mjs +1138 -384
  49. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +103 -24
  50. package/dist/builtin/intercom/broker/multinode-router.ts +42 -21
  51. package/dist/builtin/intercom/broker/multinode-state-store.ts +22 -1
  52. package/dist/builtin/intercom/broker/open-broker-state.ts +82 -31
  53. package/dist/builtin/intercom/broker/paths.ts +8 -4
  54. package/dist/builtin/intercom/broker/released-asker-remote-replies.ts +18 -6
  55. package/dist/builtin/intercom/broker/sql-add-column.ts +4 -1
  56. package/dist/builtin/intercom/broker/sql-ended-child-queue-store.ts +65 -44
  57. package/dist/builtin/intercom/broker/sql-held-send-store.ts +11 -3
  58. package/dist/builtin/intercom/broker/sql-known-session-store.ts +24 -12
  59. package/dist/builtin/intercom/broker/sql-lease-store.ts +386 -65
  60. package/dist/builtin/intercom/broker/sql-outbox-store.ts +462 -130
  61. package/dist/builtin/intercom/broker/sql-pending-ask-store.ts +20 -9
  62. package/dist/builtin/intercom/broker/sql-released-ask-store.ts +14 -6
  63. package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +27 -11
  64. package/dist/builtin/intercom/broker/sql-schema.ts +198 -5
  65. package/dist/builtin/intercom/broker/sql-sent-message-authority.ts +97 -34
  66. package/dist/builtin/intercom/index.bundle.mjs +11 -8
  67. package/dist/builtin/intercom/package.json +1 -1
  68. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  69. package/dist/builtin/mcp/package.json +1 -1
  70. package/dist/builtin/subagents/CHANGELOG.md +18 -0
  71. package/dist/builtin/subagents/package.json +1 -1
  72. package/dist/builtin/subagents/skills/skill-creator/SKILL.md +1 -1
  73. package/dist/builtin/subagents/src/extension/index.bundle.mjs +62 -23
  74. package/dist/builtin/web-access/index.bundle.mjs +1 -1
  75. package/dist/builtin/web-access/package.json +1 -1
  76. package/dist/cli/args.js +2 -2
  77. package/dist/cli/auth-cli.code.js +6 -6
  78. package/dist/cli/auth-cli.impl.js +3 -3
  79. package/dist/cli/auth-cli.js +3 -3
  80. package/dist/cli/blueprint-command.code.js +4 -4
  81. package/dist/cli/blueprint-command.impl.js +3 -3
  82. package/dist/cli/blueprint-command.js +3 -3
  83. package/dist/cli/intercom-command.code.js +3 -3
  84. package/dist/cli/intercom-command.impl.js +3 -3
  85. package/dist/cli/intercom-command.js +3 -3
  86. package/dist/cli/list-models.code.js +2 -2
  87. package/dist/cli/list-models.impl.js +3 -3
  88. package/dist/cli/list-models.js +3 -3
  89. package/dist/cli/session-picker.code.js +2 -2
  90. package/dist/cli/session-picker.impl.js +3 -3
  91. package/dist/cli/session-picker.js +3 -3
  92. package/dist/cli/startup-ui.code.js +2 -2
  93. package/dist/cli/startup-ui.impl.js +3 -3
  94. package/dist/cli/startup-ui.js +3 -3
  95. package/dist/cli/storage-command.impl.js +3 -3
  96. package/dist/cli/storage-command.js +3 -3
  97. package/dist/cli/storage-search-session.code.js +3 -3
  98. package/dist/cli/storage-search-session.impl.js +3 -3
  99. package/dist/cli/storage-search-session.js +3 -3
  100. package/dist/cli/team-command.code.js +3 -3
  101. package/dist/cli/team-command.impl.js +3 -3
  102. package/dist/cli/team-command.js +3 -3
  103. package/dist/cli.js +2 -2
  104. package/dist/core/agent-session-methods.d.ts +3 -0
  105. package/dist/core/agent-session-methods.js.map +1 -1
  106. package/dist/core/agent-session.d.ts +1 -0
  107. package/dist/core/compaction/compactor.d.ts +2 -0
  108. package/dist/core/debug.impl.js +3 -3
  109. package/dist/core/debug.js +3 -3
  110. package/dist/core/export-html/card-projection.code.js +1 -1
  111. package/dist/core/export-html/card-projection.impl.js +3 -3
  112. package/dist/core/export-html/card-projection.js +3 -3
  113. package/dist/core/export-html/index.code.js +2 -2
  114. package/dist/core/export-html/index.impl.js +3 -3
  115. package/dist/core/export-html/index.js +3 -3
  116. package/dist/core/export-html/json-spans.impl.js +3 -3
  117. package/dist/core/export-html/json-spans.js +3 -3
  118. package/dist/core/export-html/oversized-render-inputs.code.js +2 -2
  119. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  120. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  121. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  122. package/dist/core/export-html/tool-renderer.js +3 -3
  123. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  124. package/dist/core/extensions/jiti-loader.js +3 -3
  125. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  126. package/dist/core/extensions/jiti-static-loader.js +3 -3
  127. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  128. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  129. package/dist/core/extensions/loader-host-modules.js +3 -3
  130. package/dist/core/extensions/loader-virtual-modules.js +2 -2
  131. package/dist/core/extensions/runner-context.js +4 -4
  132. package/dist/core/extensions/runner-context.js.map +1 -1
  133. package/dist/core/intercom-broker-control-host.code.js +1 -1
  134. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  135. package/dist/core/intercom-broker-control-host.js +3 -3
  136. package/dist/core/intercom-broker-control.code.js +3 -3
  137. package/dist/core/intercom-broker-control.impl.js +3 -3
  138. package/dist/core/intercom-broker-control.js +3 -3
  139. package/dist/core/model-registry.js +1 -1
  140. package/dist/core/model-resolver-defaults.d.ts +3 -2
  141. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  142. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  143. package/dist/core/package-manager-storage-adapters.js +3 -3
  144. package/dist/core/sdk.code.js +4 -5
  145. package/dist/core/sdk.impl.js +3 -3
  146. package/dist/core/sdk.js +3 -3
  147. package/dist/core/session-manager-core.d.ts +5 -2
  148. package/dist/core/session-manager-core.js +39 -23
  149. package/dist/core/session-manager-core.js.map +1 -1
  150. package/dist/core/session-manager-list.impl.js +3 -3
  151. package/dist/core/session-manager-list.js +3 -3
  152. package/dist/core/session-manager.code.js +3 -3
  153. package/dist/core/session-manager.impl.js +3 -3
  154. package/dist/core/session-manager.js +3 -3
  155. package/dist/core/session-open-markers.js +3 -0
  156. package/dist/core/session-open-markers.js.map +1 -0
  157. package/dist/core/session-storage.code.js +1 -1
  158. package/dist/core/session-storage.impl.js +3 -3
  159. package/dist/core/session-storage.js +3 -3
  160. package/dist/core/storage/added-exports.d.ts +6 -0
  161. package/dist/core/storage/added-exports.js +19 -0
  162. package/dist/core/storage/added-exports.js.map +1 -0
  163. package/dist/core/storage/database.d.ts +53 -0
  164. package/dist/core/storage/database.js.map +1 -1
  165. package/dist/core/storage/fenced-paths.d.ts +47 -0
  166. package/dist/core/storage/fenced-paths.js +53 -0
  167. package/dist/core/storage/fenced-paths.js.map +1 -1
  168. package/dist/core/storage/file-identity.js +31 -2
  169. package/dist/core/storage/file-identity.js.map +1 -1
  170. package/dist/core/storage/index.d.ts +4 -1
  171. package/dist/core/storage/index.js +5 -2
  172. package/dist/core/storage/index.js.map +1 -1
  173. package/dist/core/storage/migrations.d.ts +33 -2
  174. package/dist/core/storage/migrations.js +73 -5
  175. package/dist/core/storage/migrations.js.map +1 -1
  176. package/dist/core/storage/node-sqlite-thread.js +48 -6
  177. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  178. package/dist/core/storage/node-sqlite.js +137 -4
  179. package/dist/core/storage/node-sqlite.js.map +1 -1
  180. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  181. package/dist/core/storage/offline-snapshot-file.js +3 -3
  182. package/dist/core/storage/prefix.d.ts +3 -2
  183. package/dist/core/storage/prefix.js +23 -2
  184. package/dist/core/storage/prefix.js.map +1 -1
  185. package/dist/core/storage/provider.js +2 -2
  186. package/dist/core/storage/schema-catalog.d.ts +120 -0
  187. package/dist/core/storage/schema-catalog.js +351 -0
  188. package/dist/core/storage/schema-catalog.js.map +1 -0
  189. package/dist/core/storage/selection.js +2 -2
  190. package/dist/core/storage/session/branch-fork-source.code.js +47 -25
  191. package/dist/core/storage/session/branch-fork-source.code.js.map +1 -1
  192. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  193. package/dist/core/storage/session/branch-fork-source.js +3 -3
  194. package/dist/core/storage/session/card-view.impl.js +3 -3
  195. package/dist/core/storage/session/card-view.js +3 -3
  196. package/dist/core/storage/session/child-reader.code.js +4 -4
  197. package/dist/core/storage/session/child-reader.impl.js +3 -3
  198. package/dist/core/storage/session/child-reader.js +3 -3
  199. package/dist/core/storage/session/chunked-resume-projection.code.js +1 -1
  200. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  201. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  202. package/dist/core/storage/session/errors.js +1 -1
  203. package/dist/core/storage/session/expanded-child-details.code.js +4 -4
  204. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  205. package/dist/core/storage/session/expanded-child-details.js +3 -3
  206. package/dist/core/storage/session/fork-detach.d.ts +118 -0
  207. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  208. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  209. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  210. package/dist/core/storage/session/fork-row-index.js +3 -3
  211. package/dist/core/storage/session/fork-schema.js +53 -0
  212. package/dist/core/storage/session/fork-schema.js.map +1 -0
  213. package/dist/core/storage/session/fork-segments.d.ts +58 -0
  214. package/dist/core/storage/session/fork-staging.code.js +176 -36
  215. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  216. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  217. package/dist/core/storage/session/fork-staging.js +3 -3
  218. package/dist/core/storage/session/fork-sweep.js +61 -0
  219. package/dist/core/storage/session/fork-sweep.js.map +1 -0
  220. package/dist/core/storage/session/fork-window.code.js +4 -4
  221. package/dist/core/storage/session/fork-window.impl.js +3 -3
  222. package/dist/core/storage/session/fork-window.js +3 -3
  223. package/dist/core/storage/session/history-pages.impl.js +3 -3
  224. package/dist/core/storage/session/history-pages.js +3 -3
  225. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  226. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  227. package/dist/core/storage/session/jsonl-session-store.d.ts +37 -1
  228. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  229. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  230. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  231. package/dist/core/storage/session/memory-session-store.js +3 -3
  232. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  233. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  234. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  235. package/dist/core/storage/session/released-history-files.code.js +3 -3
  236. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  237. package/dist/core/storage/session/released-history-files.js +3 -3
  238. package/dist/core/storage/session/resident-fork-rows.code.js +1 -1
  239. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  240. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  241. package/dist/core/storage/session/session-resume.impl.js +3 -3
  242. package/dist/core/storage/session/session-resume.js +3 -3
  243. package/dist/core/storage/session/session-search-index.d.ts +5 -0
  244. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  245. package/dist/core/storage/session/snapshot-cut.js +3 -3
  246. package/dist/core/storage/session/snapshot-history.code.js +4 -4
  247. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  248. package/dist/core/storage/session/snapshot-history.js +3 -3
  249. package/dist/core/storage/session/sql-chat-records.d.ts +15 -0
  250. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  251. package/dist/core/storage/session/sql-session-store.d.ts +445 -11
  252. package/dist/core/storage/session/sql-session-store.impl.js +4 -4
  253. package/dist/core/storage/session/sql-session-store.js +4 -4
  254. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  255. package/dist/core/storage/session/tree-outline.js +3 -3
  256. package/dist/core/storage/session/tree-presentation.code.js +1 -1
  257. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  258. package/dist/core/storage/session/tree-presentation.js +3 -3
  259. package/dist/core/storage/session/types.d.ts +36 -0
  260. package/dist/core/storage/sqlite-facade.d.ts +54 -6
  261. package/dist/core/storage/sqlite-facade.js +384 -18
  262. package/dist/core/storage/sqlite-facade.js.map +1 -1
  263. package/dist/core/storage/statement-sequence.d.ts +83 -0
  264. package/dist/core/storage/statement-sequence.js +21 -0
  265. package/dist/core/storage/statement-sequence.js.map +1 -1
  266. package/dist/core/storage/storage-status.code.js +1 -1
  267. package/dist/core/storage/storage-status.impl.js +3 -3
  268. package/dist/core/storage/storage-status.js +3 -3
  269. package/dist/core/storage/team.code.js +1 -1
  270. package/dist/core/storage/team.impl.js +3 -3
  271. package/dist/core/storage/team.js +3 -3
  272. package/dist/core/structured-output/index.code.js +1 -1
  273. package/dist/core/structured-output/index.impl.js +3 -3
  274. package/dist/core/structured-output/index.js +3 -3
  275. package/dist/core/tasks/task-completion-entry.code.js +1 -1
  276. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  277. package/dist/core/tasks/task-completion-entry.js +3 -3
  278. package/dist/core/tasks/task-file-history.code.js +4 -4
  279. package/dist/core/tasks/task-file-history.impl.js +3 -3
  280. package/dist/core/tasks/task-file-history.js +3 -3
  281. package/dist/core/tasks/task-reference-archive.code.js +5 -5
  282. package/dist/core/tasks/task-reference-archive.js +3 -3
  283. package/dist/core/tasks/task-reference-identity.js +3 -3
  284. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  285. package/dist/core/tasks/task-reference-stream.js +3 -3
  286. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  287. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  288. package/dist/core/tasks/task-view-source.code.js +1 -1
  289. package/dist/core/tasks/task-view-source.impl.js +3 -3
  290. package/dist/core/tasks/task-view-source.js +3 -3
  291. package/dist/core/tools/bash.d.ts +8 -4
  292. package/dist/core/tools/history-session.d.ts +7 -0
  293. package/dist/core/tools/history-tasks.d.ts +123 -0
  294. package/dist/core/tools/kill.d.ts +5 -2
  295. package/dist/core/tools/powershell.d.ts +2 -2
  296. package/dist/core/tools/read-url.code.js +3 -3
  297. package/dist/core/tools/read-url.impl.js +3 -3
  298. package/dist/core/tools/read-url.js +3 -3
  299. package/dist/core/tools/read.d.ts +12 -2
  300. package/dist/core/tools/resource-selectors.d.ts +2 -0
  301. package/dist/core/tools/search.d.ts +12 -2
  302. package/dist/core/worktree-snapshot/blob-store.d.ts +45 -2
  303. package/dist/core/worktree-snapshot/blob-store.js +228 -60
  304. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  305. package/dist/core/worktree-snapshot/errors.code.js +3 -3
  306. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  307. package/dist/core/worktree-snapshot/errors.js +3 -3
  308. package/dist/core/worktree-snapshot/fork-snapshot-index.js +121 -0
  309. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -0
  310. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  311. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  312. package/dist/extensions/codemode/execute.code.js +3 -3
  313. package/dist/extensions/codemode/execute.impl.js +3 -3
  314. package/dist/extensions/codemode/execute.js +3 -3
  315. package/dist/extensions/codemode/renderer.code.js +2 -2
  316. package/dist/extensions/codemode/renderer.impl.js +3 -3
  317. package/dist/extensions/codemode/renderer.js +3 -3
  318. package/dist/extensions/mcp/cli.code.js +3 -3
  319. package/dist/extensions/mcp/cli.impl.js +3 -3
  320. package/dist/extensions/mcp/cli.js +3 -3
  321. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  322. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  323. package/dist/extensions/mcp/cli.lazy.js +3 -3
  324. package/dist/extensions/mcp/runtime.code.js +1 -1
  325. package/dist/extensions/mcp/runtime.impl.js +3 -3
  326. package/dist/extensions/mcp/runtime.js +3 -3
  327. package/dist/index.js +8 -8
  328. package/dist/main-first-time-setup.code.js +2 -2
  329. package/dist/main-first-time-setup.impl.js +3 -3
  330. package/dist/main-first-time-setup.js +3 -3
  331. package/dist/main.js +1 -1
  332. package/dist/modes/interactive/components/agent-panel.d.ts +1 -0
  333. package/dist/modes/interactive/components/stored-tree-view.code.js +3 -3
  334. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  335. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  336. package/dist/modes/interactive/components/task-inspector.d.ts +2 -0
  337. package/dist/modes/interactive/components/user-message-selector-archive.code.js +1 -1
  338. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  339. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  340. package/dist/modes/interactive/interactive-mode-helpers.d.ts +2 -2
  341. package/dist/modes/print-mode.js +1 -1
  342. package/dist/modes/rpc/agent-panel-bridge.d.ts +5 -0
  343. package/dist/package-manager-cli.code.js +7 -7
  344. package/dist/package-manager-cli.impl.js +3 -3
  345. package/dist/package-manager-cli.js +3 -3
  346. package/dist/rpc-entry.js +1 -1
  347. package/dist/startup-files.json +1 -1
  348. package/dist/startup-stages/0.js +1 -1
  349. package/dist/startup-stages/1.js +1 -1
  350. package/dist/startup-stages/10.js +1 -1
  351. package/dist/startup-stages/12.js +1 -1
  352. package/dist/startup-stages/2.js +9 -1
  353. package/dist/startup-stages/3.js +1 -6
  354. package/dist/startup-stages/5.js +1 -1
  355. package/dist/startup-stages/7.js +1 -1
  356. package/dist/startup-stages/8.js +2 -2
  357. package/dist/utils/startup-database-spare.code.js +3 -3
  358. package/dist/utils/startup-database-spare.impl.js +3 -3
  359. package/dist/utils/startup-database-spare.js +3 -3
  360. package/dist/utils/tools-manager.code.js +1 -1
  361. package/dist/utils/tools-manager.impl.js +3 -3
  362. package/dist/utils/tools-manager.js +3 -3
  363. package/docs/background-tasks.md +123 -23
  364. package/docs/compaction.md +18 -0
  365. package/docs/docs.json +2 -0
  366. package/docs/environment-variables.md +1 -1
  367. package/docs/getting-started/installation.md +9 -2
  368. package/docs/guides/postgres-pgbouncer.md +346 -0
  369. package/docs/guides/postgres-tuning.md +311 -0
  370. package/docs/guides/resume-on-any-machine.md +2 -2
  371. package/docs/guides.md +2 -0
  372. package/docs/index.md +1 -1
  373. package/docs/libraries/agent-core.md +1 -1
  374. package/docs/libraries/ai.md +2 -2
  375. package/docs/libraries/codemode.md +1 -1
  376. package/docs/libraries/storage-libsql.md +6 -1
  377. package/docs/libraries/storage-postgres.md +11 -6
  378. package/docs/libraries/tui.md +1 -1
  379. package/docs/libraries.md +2 -2
  380. package/docs/programmatic.md +1 -1
  381. package/docs/quickstart.md +1 -1
  382. package/docs/sdk/storage.md +1 -1
  383. package/docs/sdk/web-server.md +1 -3
  384. package/docs/sdk.md +1 -7
  385. package/docs/sessions.md +67 -2
  386. package/docs/settings.md +20 -1
  387. package/docs/skills/authoring.md +1 -1
  388. package/docs/skills.md +79 -6
  389. package/docs/storage.md +305 -14
  390. package/docs/subagents/reference.md +2 -2
  391. package/docs/subagents.md +4 -3
  392. package/docs/tools.md +44 -10
  393. package/docs/windows.md +1 -1
  394. package/package.json +9 -9
  395. package/dist/_shared/sdk-RRLVN7ER.js.map +0 -1
  396. package/dist/_shared/settings-startup-4QCVCI53.js.map +0 -1
  397. package/dist/_shared/startup-0-0-4VG2G44V.js.map +0 -1
  398. package/dist/_shared/startup-0-1-XTIL65D4.js.map +0 -1
  399. package/dist/_shared/startup-0-2-27OWFHV6.js.map +0 -1
  400. package/dist/_shared/startup-0-3-T4DVFYWX.js.map +0 -1
  401. package/dist/_shared/startup-0-5-FD2P735I.js.map +0 -1
  402. package/dist/_shared/startup-8-1-4KANEHRA.js.map +0 -1
@@ -1,21 +1,27 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import {
3
3
  dialectOf,
4
+ fencedPath,
5
+ type SqliteDatabase,
4
6
  type SqliteExecutor,
5
7
  type SqliteRow,
8
+ type SqliteStatement,
9
+ type SqliteTransactionOptions,
6
10
  type SqliteValue,
7
11
  validateStoragePrefix,
8
12
  } from "@bastani/atomic/storage";
13
+ import * as storage from "@bastani/atomic/storage";
9
14
  import {
10
15
  OUTBOX_CLAIM_STALE_AFTER_MS,
11
16
  OUTBOX_EXPIRED_REASON,
12
17
  OUTBOX_TARGET_MAX_BYTES,
13
18
  OUTBOX_TARGET_MAX_ROWS,
14
- type ClaimedOutboxRow,
15
19
  type InvalidStateInput,
16
20
  type IntercomBrokerStateOptions,
17
21
  type OutboxClaim,
22
+ type OutboxClaimResult,
18
23
  type OutboxClaimWriteRejection,
24
+ type OutboxDeliveredResult,
19
25
  type OutboxEnqueueRequest,
20
26
  type OutboxEnqueueResult,
21
27
  type OutboxFrame,
@@ -25,9 +31,13 @@ import {
25
31
  type StateStoreInvalidReason,
26
32
  } from "./multinode-state-store.js";
27
33
  import { addMissingColumns } from "./sql-add-column.js";
28
- import { ensureBrokerSchema } from "./sql-schema.js";
34
+ import { ensureBrokerSchema, withBrokerSchemaCatalog } from "./sql-schema.js";
29
35
 
30
36
  const UNDELIVERED = "state IN ('queued', 'claimed')";
37
+ /** The setting a PostgreSQL claim transaction records in that its recipient has undelivered rows, and its locks are held. */
38
+ const CLAIM_GATE = "atomic.intercom_outbox_claim";
39
+ /** The most `markDelivered` calls one transaction settles together (#6560). */
40
+ const MARK_DELIVERED_BATCH_MAX = 100;
31
41
 
32
42
  interface OutboxRecord extends SqliteRow {
33
43
  readonly sequence: SqliteValue;
@@ -80,15 +90,53 @@ export class OutboxWakeFailedError extends Error {
80
90
  }
81
91
  }
82
92
 
93
+ /**
94
+ * What an enqueue writes first and requires: a send's reservation of its message (#6560). `first` is written just
95
+ * before the row, in the same transaction, and the row is inserted only while `condition`, an SQL boolean expression
96
+ * with its parameters, holds; when it does not, and no row of the message is there, the enqueue reports a conflict.
97
+ */
98
+ export interface OutboxEnqueueGuard {
99
+ readonly first: SqliteStatement;
100
+ readonly condition: SqliteStatement;
101
+ }
102
+
83
103
  /** The SQL outbox, which can also enqueue inside a transaction the caller holds. */
84
104
  export interface SqlOutboxStore extends OutboxStore {
85
105
  /**
86
106
  * `enqueue`, as part of `executor`'s transaction: the row is written only when that transaction commits. It throws
87
107
  * `OutboxWakeFailedError` when only the optional wake-up hint failed; run the transaction again without it then.
108
+ * The transaction must hold the recipient's domain (`recipientTransaction`).
109
+ */
110
+ enqueueIn(
111
+ executor: SqliteExecutor,
112
+ request: OutboxEnqueueRequest,
113
+ guard?: OutboxEnqueueGuard,
114
+ ): Promise<OutboxEnqueueResult>;
115
+ /**
116
+ * The reads `enqueueIn` makes first for `request`, in order, for a transaction's `leading` statements: a pipelined
117
+ * connection sends them with the transaction's start instead of a round trip each (#6560).
88
118
  */
89
- enqueueIn(executor: SqliteExecutor, request: OutboxEnqueueRequest): Promise<OutboxEnqueueResult>;
119
+ enqueueLeading(request: OutboxEnqueueRequest): readonly SqliteStatement[];
120
+ }
121
+
122
+ /**
123
+ * Runs `statements` as the last calls of `executor`'s transaction: on a pipelined connection they go out with the
124
+ * commit, in one round trip; elsewhere each runs in turn as `run` runs it. The transaction's callback must make no call
125
+ * after them (#6560).
126
+ */
127
+ export async function runLast(executor: SqliteExecutor, ...statements: SqliteStatement[]): Promise<void> {
128
+ if (statements.length === 0 || finisherOf?.(executor)?.(statements) === true) return;
129
+ for (const { sql, params } of statements) await executor.run(sql, ...params);
90
130
  }
91
131
 
132
+ /**
133
+ * `transactionFinisher` of the storage module, where the copy the process loaded has it: a host whose Atomic predates it
134
+ * runs every statement in turn (#6560).
135
+ */
136
+ const finisherOf: (typeof storage)["transactionFinisher"] | undefined = (
137
+ storage as Partial<Pick<typeof storage, "transactionFinisher">>
138
+ ).transactionFinisher;
139
+
92
140
  /**
93
141
  * #5607: runs `write` for `request`, and once more for it without its wake-up hint when only that hint failed it.
94
142
  */
@@ -105,14 +153,49 @@ export async function withoutFailedWake<T>(
105
153
  }
106
154
  }
107
155
 
156
+ /**
157
+ * The lock domain of one recipient's sends, `<outbox>:<recipient>`: a send reserves its message and queues its row in
158
+ * one transaction of it (`reserveAndEnqueue`, `enqueue`), so sends to one recipient run one at a time, and commit their
159
+ * rows in the order of their sequence, and a send's checks of that recipient's queue (its size budget) hold until it
160
+ * commits. Sends to other recipients, claims and every write of one row run beside them (#6560).
161
+ */
162
+ export function recipientTransaction(
163
+ database: SqliteDatabase,
164
+ prefix: string | undefined,
165
+ targetIdentity: string,
166
+ ): SqliteTransactionOptions {
167
+ const outbox = `${validateStoragePrefix(prefix, dialectOf(database).name)}intercom_outbox`;
168
+ return { concurrency: { kind: "serial", domain: `${outbox}:${targetIdentity}` } };
169
+ }
170
+
171
+ /**
172
+ * A transaction of the outbox or the sent-message table that takes no lock domain: each of its writes decides on the
173
+ * rows it locks itself (`fencedPath("intercom-outbox-row")`). It still waits for and excludes the database-wide
174
+ * transactions an older broker runs on these tables (#6560).
175
+ */
176
+ export function rowTransaction(): SqliteTransactionOptions {
177
+ return { concurrency: { kind: "fenced", audit: fencedPath("intercom-outbox-row"), excludesSerial: true } };
178
+ }
179
+
108
180
  /**
109
181
  * S2 outbox on the shared storage adapter's database, in `<prefix>intercom_outbox`. Every read-modify-write runs in
110
- * one `BEGIN IMMEDIATE` transaction, and every age is measured on the database clock.
182
+ * one `BEGIN IMMEDIATE` transaction, and every age is measured on the database clock. On a database whose transactions
183
+ * run concurrently (PostgreSQL), an enqueue holds its recipient's domain (`recipientTransaction`); a claim holds its
184
+ * recipient's claim domain and locks the recipient's rows in sequence order, and every write of a claimed row is one
185
+ * statement guarded by its claim token (`rowTransaction`), so no write waits for another recipient's (#6560).
111
186
  */
112
- export async function openSqlOutboxStore(options: IntercomBrokerStateOptions): Promise<SqlOutboxStore> {
187
+ export function openSqlOutboxStore(options: IntercomBrokerStateOptions): Promise<SqlOutboxStore> {
188
+ // Its schema checks answer from one read of the catalog, shared with an open around it: a current schema costs
189
+ // no transaction and no lock, also when the store is opened on its own (#6560).
190
+ return withBrokerSchemaCatalog(options.database, options.prefix, () => openOutboxStoreInCatalog(options));
191
+ }
192
+
193
+ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Promise<SqlOutboxStore> {
113
194
  const { database } = options;
114
195
  const table = `${validateStoragePrefix(options.prefix, dialectOf(database).name)}intercom_outbox`;
115
- const { types, nowMs, greatest, name: dialect } = dialectOf(database);
196
+ const { types, nowMs, greatest, lockClause, name: dialect } = dialectOf(database);
197
+ /** Claim writes and expiry: each decides on the rows it locks (#6560). */
198
+ const fenced = rowTransaction();
116
199
  const ageSince = (column: string) => greatest("0", `${nowMs} - ${column}`);
117
200
  // In a serial transaction, so brokers opening a new store at once take turns creating it (#5054).
118
201
  const schema = `
@@ -148,70 +231,167 @@ export async function openSqlOutboxStore(options: IntercomBrokerStateOptions): P
148
231
  claim_attempts, claimant_id, claim_token, failure_reason,
149
232
  CASE WHEN claim_renewed_at IS NULL THEN NULL ELSE ${ageSince("claim_renewed_at")} END AS claim_age,
150
233
  CASE WHEN saving_at IS NULL THEN NULL ELSE ${ageSince("saving_at")} END AS saving_age`;
151
- const select = (executor: SqliteExecutor, messageId: string) =>
152
- executor.get<OutboxRecord>(`SELECT ${columns} FROM ${table} WHERE message_id = ?`, messageId);
234
+ const selectStatement = (messageId: string): SqliteStatement => ({
235
+ sql: `SELECT ${columns} FROM ${table} WHERE message_id = ?`,
236
+ params: [messageId],
237
+ });
238
+ const select = (executor: SqliteExecutor, messageId: string) => {
239
+ const { sql, params } = selectStatement(messageId);
240
+ return executor.get<OutboxRecord>(sql, ...params);
241
+ };
153
242
  // #5607: the lease store's table, whose presence leases name the broker hosting a recipient, and the wake-up bus's
154
243
  // hint log. The broker opens both before it enqueues anything.
155
244
  const leases = `${validateStoragePrefix(options.prefix, dialectOf(database).name)}intercom_leases`;
156
245
  const wakeups = `${validateStoragePrefix(options.prefix, dialectOf(database).name)}intercom_wakeups`;
157
- const undelivered = (executor: SqliteExecutor, targetIdentity: string, limit?: number) =>
158
- limit === undefined
159
- ? executor.all<OutboxRecord>(
160
- `SELECT ${columns} FROM ${table} WHERE target_identity = ? AND ${UNDELIVERED} ORDER BY sequence`,
161
- targetIdentity,
162
- )
163
- : executor.all<OutboxRecord>(
164
- `SELECT ${columns} FROM ${table} WHERE target_identity = ? AND ${UNDELIVERED} ORDER BY sequence LIMIT ?`,
165
- targetIdentity,
166
- limit,
167
- );
168
- const isLive = (record: OutboxRecord, staleAfterMs: number): boolean =>
169
- record.claim_age !== null && Number(record.claim_age) <= staleAfterMs;
246
+ const allUndeliveredStatement = (targetIdentity: string): SqliteStatement => ({
247
+ sql: `SELECT ${columns} FROM ${table} WHERE target_identity = ? AND ${UNDELIVERED} ORDER BY sequence`,
248
+ params: [targetIdentity],
249
+ });
250
+ const undelivered = (executor: SqliteExecutor, targetIdentity: string, limit?: number) => {
251
+ if (limit === undefined) {
252
+ const { sql, params } = allUndeliveredStatement(targetIdentity);
253
+ return executor.all<OutboxRecord>(sql, ...params);
254
+ }
255
+ return executor.all<OutboxRecord>(
256
+ `SELECT ${columns} FROM ${table} WHERE target_identity = ? AND ${UNDELIVERED} ORDER BY sequence LIMIT ?`,
257
+ targetIdentity,
258
+ limit,
259
+ );
260
+ };
170
261
 
171
- /** Runs `write` only for the row's current claim; every other case is reported as the contract requires. */
262
+ /**
263
+ * Applies `assignments` (with their parameters) to the row only while `claim` is its current claim: one UPDATE whose
264
+ * WHERE names the claim, so the decision is made on the row's lock and its newest version, never on an earlier read.
265
+ * The update is the transaction's first statement, sent with its start; only when it changed nothing is the row read,
266
+ * to report why (#6560).
267
+ */
172
268
  const withClaim = <Result>(
173
269
  claim: OutboxClaim,
174
- write: (executor: SqliteExecutor) => Promise<Result>,
270
+ assignments: string,
271
+ params: readonly SqliteValue[],
272
+ answer: (written: OutboxRecord) => Result,
175
273
  ): Promise<Result | OutboxClaimWriteRejection> => {
176
274
  if (claim.messageId.length === 0) return Promise.resolve(invalid("empty-message-id"));
177
275
  if (claim.claimantId.length === 0) return Promise.resolve(invalid("empty-claimant-id"));
178
- return database.transaction(async (executor) => {
179
- const record = await select(executor, claim.messageId);
180
- if (record === undefined) return { status: "unknown" } as const;
181
- if (isSettled(record)) return { status: "settled", row: toRow(record) } as const;
182
- if (record.claim_token !== claim.token || record.claimant_id !== claim.claimantId) {
276
+ const write: SqliteStatement = {
277
+ sql: `UPDATE ${table} SET ${assignments}
278
+ WHERE message_id = ? AND claim_token = ? AND claimant_id = ? AND state = 'claimed'
279
+ RETURNING ${columns}`,
280
+ params: [...params, claim.messageId, claim.token, claim.claimantId],
281
+ };
282
+ return database.transaction(
283
+ async (executor) => {
284
+ const written = await executor.get<OutboxRecord>(write.sql, ...write.params);
285
+ if (written !== undefined) return answer(written);
286
+ const record = await select(executor, claim.messageId);
287
+ if (record === undefined) return { status: "unknown" } as const;
288
+ if (isSettled(record)) return { status: "settled", row: toRow(record) } as const;
183
289
  return { status: "stale" } as const;
184
- }
185
- return write(executor);
186
- });
290
+ },
291
+ { ...fenced, leading: [write] },
292
+ );
187
293
  };
188
294
 
189
- const settle = async (
190
- executor: SqliteExecutor,
191
- messageId: string,
192
- state: "delivered" | "failed",
193
- reason: string | null,
194
- ): Promise<OutboxRow> => {
195
- await executor.run(
196
- `UPDATE ${table} SET state = ?, failure_reason = ?, settled_at = ${nowMs},
197
- claimant_id = NULL, claim_token = NULL, claim_renewed_at = NULL, saving_at = NULL
198
- WHERE message_id = ?`,
199
- state,
200
- reason === null ? null : JSON.stringify(reason),
201
- messageId,
295
+ const settled = `failure_reason = ?, settled_at = ${nowMs},
296
+ claimant_id = NULL, claim_token = NULL, claim_renewed_at = NULL, saving_at = NULL`;
297
+
298
+ /**
299
+ * Settles each of `claims`, of distinct rows, as delivered, in one transaction: one UPDATE, sent with its start, that
300
+ * locks their rows in sequence order, as a claim locks a recipient's rows, and changes those whose claim is still
301
+ * current. Only when it changed fewer rows than it was given are the others read, to report why (#6560).
302
+ */
303
+ const markDeliveredTogether = (claims: readonly OutboxClaim[]): Promise<OutboxDeliveredResult[]> => {
304
+ const current = claims.map(() => "(message_id = ? AND claim_token = ? AND claimant_id = ?)").join(" OR ");
305
+ const keys = claims.flatMap((claim) => [claim.messageId, claim.token, claim.claimantId]);
306
+ const write: SqliteStatement = {
307
+ sql: `UPDATE ${table} SET state = 'delivered', ${settled}
308
+ WHERE message_id IN (
309
+ SELECT message_id FROM ${table} WHERE state = 'claimed' AND (${current})
310
+ ORDER BY sequence${lockClause("update")}
311
+ ) AND state = 'claimed' AND (${current})
312
+ RETURNING ${columns}`,
313
+ params: [null, ...keys, ...keys],
314
+ };
315
+ return database.transaction(
316
+ async (executor) => {
317
+ const written = new Map(
318
+ (await executor.all<OutboxRecord>(write.sql, ...write.params)).map((record) => [record.message_id, record]),
319
+ );
320
+ const others = claims.filter((claim) => !written.has(claim.messageId));
321
+ const found =
322
+ others.length === 0
323
+ ? new Map<string, OutboxRecord>()
324
+ : new Map(
325
+ (
326
+ await executor.all<OutboxRecord>(
327
+ `SELECT ${columns} FROM ${table} WHERE message_id IN (${others.map(() => "?").join(", ")})`,
328
+ ...others.map((claim) => claim.messageId),
329
+ )
330
+ ).map((record) => [record.message_id, record]),
331
+ );
332
+ return claims.map((claim): OutboxDeliveredResult => {
333
+ const delivered = written.get(claim.messageId);
334
+ if (delivered !== undefined) return { status: "delivered", row: toRow(delivered) };
335
+ const record = found.get(claim.messageId);
336
+ if (record === undefined) return { status: "unknown" };
337
+ if (isSettled(record)) return { status: "settled", row: toRow(record) };
338
+ return { status: "stale" };
339
+ });
340
+ },
341
+ { ...fenced, leading: [write] },
202
342
  );
203
- return toRow((await select(executor, messageId))!);
343
+ };
344
+
345
+ /**
346
+ * The `markDelivered` calls waiting for the transaction that settles them, in the order they were made. On PostgreSQL
347
+ * the calls made while one transaction settles others go together in the next, whose round trips they share, rather
348
+ * than two round trips each: one transaction at a time, so each commits after every call made before it (#6560).
349
+ */
350
+ const deliveries: {
351
+ readonly claim: OutboxClaim;
352
+ readonly resolve: (result: OutboxDeliveredResult) => void;
353
+ readonly reject: (error: unknown) => void;
354
+ }[] = [];
355
+ let delivering = false;
356
+ const deliverQueued = async () => {
357
+ // Calls made in the same turn as the first go with it.
358
+ await undefined;
359
+ while (deliveries.length > 0) {
360
+ // The calls in order, up to one that names a row already in the batch: it goes in the next, so it finds the row as
361
+ // the call before it left it.
362
+ const rows = new Set<string>();
363
+ let count = 0;
364
+ while (
365
+ count < deliveries.length &&
366
+ count < MARK_DELIVERED_BATCH_MAX &&
367
+ !rows.has(deliveries[count]!.claim.messageId)
368
+ )
369
+ rows.add(deliveries[count++]!.claim.messageId);
370
+ const batch = deliveries.splice(0, count);
371
+ try {
372
+ const results = await markDeliveredTogether(batch.map(({ claim }) => claim));
373
+ batch.forEach(({ resolve }, index) => resolve(results[index]!));
374
+ } catch (error) {
375
+ for (const { reject } of batch) reject(error);
376
+ }
377
+ }
378
+ delivering = false;
204
379
  };
205
380
 
206
381
  /**
207
382
  * #4896: the recipient's undelivered rows and their frame bytes, read from `<table>_target_bytes` alone. Only rows an
208
383
  * older broker wrote, without `frame_bytes`, are measured from their frames.
209
384
  */
385
+ const sizedTotalsStatement = (targetIdentity: string): SqliteStatement => ({
386
+ sql: `SELECT COUNT(*) AS row_count, COALESCE(SUM(frame_bytes), 0) AS byte_count, COUNT(*) - COUNT(frame_bytes) AS unsized
387
+ FROM ${table} WHERE target_identity = ? AND ${UNDELIVERED}`,
388
+ params: [targetIdentity],
389
+ });
210
390
  const queuedTotals = async (executor: SqliteExecutor, targetIdentity: string) => {
391
+ const totals = sizedTotalsStatement(targetIdentity);
211
392
  const sized = (await executor.get<{ row_count: SqliteValue; byte_count: SqliteValue; unsized: SqliteValue }>(
212
- `SELECT COUNT(*) AS row_count, COALESCE(SUM(frame_bytes), 0) AS byte_count, COUNT(*) - COUNT(frame_bytes) AS unsized
213
- FROM ${table} WHERE target_identity = ? AND ${UNDELIVERED}`,
214
- targetIdentity,
393
+ totals.sql,
394
+ ...totals.params,
215
395
  ))!;
216
396
  const unsized =
217
397
  Number(sized.unsized) === 0
@@ -226,7 +406,11 @@ export async function openSqlOutboxStore(options: IntercomBrokerStateOptions): P
226
406
  return { rows: Number(sized.row_count), bytes: Number(sized.byte_count) + unsized };
227
407
  };
228
408
 
229
- const enqueueIn = async (executor: SqliteExecutor, request: OutboxEnqueueRequest): Promise<OutboxEnqueueResult> => {
409
+ const enqueueIn = async (
410
+ executor: SqliteExecutor,
411
+ request: OutboxEnqueueRequest,
412
+ guard?: OutboxEnqueueGuard,
413
+ ): Promise<OutboxEnqueueResult> => {
230
414
  if (request.targetIdentity.length === 0) return invalid("empty-target-identity");
231
415
  if (request.originBrokerId.length === 0) return invalid("empty-broker-id");
232
416
  const messageId = request.frame.message.id;
@@ -246,38 +430,82 @@ export async function openSqlOutboxStore(options: IntercomBrokerStateOptions): P
246
430
  ) {
247
431
  return { status: "full", limit: OUTBOX_TARGET_MAX_ROWS, byteLimit: OUTBOX_TARGET_MAX_BYTES } as const;
248
432
  }
433
+ // Inserted only while the guard holds, and never over a row of the message that another recipient's send, in a
434
+ // domain of its own, queued meanwhile: the unique message id makes that send's row, once it commits, the answer
435
+ // (#6560). The guard's first write and the insert go out together.
436
+ const condition = guard?.condition;
249
437
  const insert = `INSERT INTO ${table}(message_id, target_identity, origin_broker_id, digest, frame_json, state, queued_at,
250
438
  frame_bytes)
251
- VALUES (?, ?, ?, ?, ?, 'queued', ${nowMs}, ?)`;
252
- const values = [messageId, request.targetIdentity, request.originBrokerId, request.digest, frameJson, frameBytes];
439
+ SELECT ?, ?, ?, ?, ?, 'queued', ${nowMs}, CAST(? AS ${types.int})
440
+ WHERE ${condition === undefined ? "1 = 1" : condition.sql}
441
+ ON CONFLICT(message_id) DO NOTHING`;
442
+ const values = [
443
+ messageId,
444
+ request.targetIdentity,
445
+ request.originBrokerId,
446
+ request.digest,
447
+ frameJson,
448
+ frameBytes,
449
+ ...(condition?.params ?? []),
450
+ ];
451
+ const first = guard === undefined ? undefined : executor.run(guard.first.sql, ...guard.first.params);
452
+ first?.catch(() => {});
453
+ // The insert goes out behind the guard's write without waiting for its answer only on a pipelined transaction's
454
+ // own handle, which sends calls in the order they are made; any other executor, a wrapper included, may run a
455
+ // later call first, so the write is answered before the insert is made.
456
+ if (finisherOf?.(executor) === undefined) await first;
457
+ /** The answer of the insert, once the guard's write, sent before it, succeeded. */
458
+ const after = async <T>(inserting: Promise<T>): Promise<T> => {
459
+ inserting.catch(() => {});
460
+ await first;
461
+ return inserting;
462
+ };
463
+ /** Nothing was inserted: the message's row, which another send queued, or the guard's refusal. */
464
+ const notInserted = async (): Promise<OutboxEnqueueResult> => {
465
+ const queued = await select(executor, messageId);
466
+ if (queued !== undefined && queued.digest === request.digest)
467
+ return { status: "duplicate", row: toRow(queued) } as const;
468
+ return { status: "conflict", messageId } as const;
469
+ };
253
470
  if (request.wakeHostWithinMs === undefined) {
254
- await executor.run(insert, ...values);
255
- return { status: "inserted", row: toRow((await select(executor, messageId))!) } as const;
471
+ // The row comes back from its insert, in the same round trip (#6560).
472
+ const row = await after(executor.get<OutboxRecord>(`${insert} RETURNING ${columns}`, ...values));
473
+ return row === undefined ? notInserted() : ({ status: "inserted", row: toRow(row) } as const);
256
474
  }
257
475
  // #5607: the row comes back from its insert, with the broker holding the recipient's live presence, read in this
258
476
  // transaction: a presence lease committed before it is seen here; one committed after it was written after this row,
259
477
  // and the registration that wrote it looks for the row next. Only when there is one does a second statement write
260
- // its wake-up hint, in this transaction too.
261
- const inserted = (await executor.get<OutboxRecord & { readonly presence_holder: string | null }>(
262
- `${insert} RETURNING ${columns}, (
478
+ // its wake-up hint, in this transaction too. On PostgreSQL leases are acquired beside this transaction
479
+ // (#6560), so the read locks the lease: an acquisition under way commits first and is seen, and a later one
480
+ // waits for this row.
481
+ const inserted = await after(
482
+ executor.get<OutboxRecord & { readonly presence_holder: string | null }>(
483
+ `${insert} RETURNING ${columns}, (
263
484
  SELECT presence.holder_id FROM ${leases} presence
264
485
  WHERE presence.kind = 'presence' AND presence.key = ? AND presence.holder_id IS NOT NULL
265
- AND ${greatest("0", `${nowMs} - presence.renewed_at`)} <= ?
486
+ AND ${greatest("0", `${nowMs} - presence.renewed_at`)} <= ?${lockClause("share")}
266
487
  ) AS presence_holder`,
267
- ...values,
268
- request.targetIdentity,
269
- request.wakeHostWithinMs,
270
- ))!;
488
+ ...values,
489
+ request.targetIdentity,
490
+ request.wakeHostWithinMs,
491
+ ),
492
+ );
493
+ if (inserted === undefined) return notInserted();
271
494
  const host = inserted.presence_holder;
272
495
  if (host !== null) {
273
496
  const hint = async () => {
274
- // PostgreSQL: never wait behind another session's lock on the hint log; such a hint goes without.
497
+ // PostgreSQL: never wait behind another session's lock on the hint log; such a hint goes without. The hint
498
+ // is a new row, so it needs no lock domain of its own (#6560): see `fencedPath("intercom-wakeup-hint")`.
275
499
  if (dialect === "postgres") await executor.run(`LOCK TABLE ${wakeups} IN ROW EXCLUSIVE MODE NOWAIT`);
276
500
  await executor.run(
277
501
  `INSERT INTO ${wakeups}(broker_id, reason, version, created_at) VALUES (?, 'outbox', ?, ${nowMs})`,
278
502
  host,
279
503
  Number(inserted.sequence),
280
504
  );
505
+ // Notified when it commits, as the wake-up bus's own hints are, so the host does not wait for its backup
506
+ // poll (#6560).
507
+ const notify = database.notifications?.notify(wakeups, host);
508
+ if (notify !== undefined) await executor.run(notify.sql, ...notify.params);
281
509
  };
282
510
  await hint().catch((cause: unknown) => {
283
511
  throw new OutboxWakeFailedError(cause);
@@ -286,109 +514,206 @@ export async function openSqlOutboxStore(options: IntercomBrokerStateOptions): P
286
514
  return { status: "inserted", row: toRow(inserted), ...(host === null ? {} : { woke: host }) } as const;
287
515
  };
288
516
 
517
+ const enqueueLeading = (request: OutboxEnqueueRequest): readonly SqliteStatement[] => [
518
+ selectStatement(request.frame.message.id),
519
+ ...(request.owed === true ? [] : [sizedTotalsStatement(request.targetIdentity)]),
520
+ ];
521
+
289
522
  return {
290
523
  enqueueIn,
524
+ enqueueLeading,
291
525
  async enqueue(request) {
292
526
  if (request.targetIdentity.length === 0) return invalid("empty-target-identity");
293
527
  if (request.originBrokerId.length === 0) return invalid("empty-broker-id");
294
528
  if (request.frame.message.id.length === 0) return invalid("empty-message-id");
295
529
  return withoutFailedWake(request, (attempt) =>
296
- database.transaction((executor) => enqueueIn(executor, attempt)),
530
+ database.transaction((executor) => enqueueIn(executor, attempt), {
531
+ ...recipientTransaction(database, options.prefix, attempt.targetIdentity),
532
+ leading: enqueueLeading(attempt),
533
+ }),
297
534
  );
298
535
  },
299
536
 
300
537
  async claim(request) {
301
538
  if (request.claimantId.length === 0) return invalid("empty-claimant-id");
302
539
  if (request.targetIdentity.length === 0) return invalid("empty-target-identity");
303
- // Fast read-only index check so empty scans (such as fan-out wake-up polls across idle sessions) never take a
304
- // SQLite write lock. Linearizable: if a row commits after this snapshot, its enqueue writes a new wake-up hint.
305
- const pending = await database.get(
306
- `SELECT 1 AS present FROM ${table} WHERE target_identity = ? AND ${UNDELIVERED} LIMIT 1`,
307
- request.targetIdentity,
308
- );
309
- if (pending === undefined) return { status: "claimed", rows: [] } as const;
310
- return database.transaction(async (executor) => {
311
- const records = await undelivered(executor, request.targetIdentity);
312
- const other = records.find(
313
- (record) =>
314
- record.state === "claimed" &&
315
- record.claimant_id !== request.claimantId &&
316
- isLive(record, request.staleAfterMs),
317
- );
318
- if (other?.claimant_id) return { status: "held", claimantId: other.claimant_id } as const;
319
- const rows: ClaimedOutboxRow[] = [];
320
- for (const record of records) {
321
- if (record.state === "claimed" && isLive(record, request.staleAfterMs)) continue;
322
- const token = randomUUID();
323
- await executor.run(
324
- `UPDATE ${table} SET state = 'claimed', claim_attempts = claim_attempts + 1, claimant_id = ?,
325
- claim_token = ?, claim_renewed_at = ${nowMs}, saving_at = NULL
326
- WHERE message_id = ?`,
327
- request.claimantId,
328
- token,
329
- record.message_id,
330
- );
331
- const row = toRow((await select(executor, record.message_id))!);
332
- rows.push({
333
- row,
334
- claim: { messageId: row.messageId, claimantId: request.claimantId, token, attempt: row.claimAttempts },
335
- });
336
- }
337
- return { status: "claimed", rows } as const;
540
+ const { claimantId, targetIdentity, staleAfterMs } = request;
541
+ // Each row's token: this claim's, with the row's sequence, so every claimed row has a token of its own.
542
+ const token = randomUUID();
543
+ const claimed = (records: readonly OutboxRecord[]): OutboxClaimResult => ({
544
+ status: "claimed",
545
+ rows: [...records]
546
+ .sort((first, second) => Number(first.sequence) - Number(second.sequence))
547
+ .map((record) => {
548
+ const row = toRow(record);
549
+ const claim = { messageId: row.messageId, claimantId, token: String(record.claim_token), attempt: row.claimAttempts };
550
+ return { row, claim };
551
+ }),
338
552
  });
553
+ const claiming = `state = 'claimed', claim_attempts = claim_attempts + 1, claimant_id = ?,
554
+ claim_token = ? || ':' || CAST(sequence AS TEXT), claim_renewed_at = ${nowMs}, saving_at = NULL`;
555
+ if (dialect === "postgres") {
556
+ // A read and one claim statement, sent with the transaction's start and its commit: one round trip whether or not
557
+ // there is anything to claim (#6560). The claim statement locks the recipient's undelivered rows in sequence order, as every write of several rows
558
+ // locks them, and reads them in their newest versions, so a renewal or settlement of one waits for this claim, or
559
+ // this claim for it. It does not skip a locked row (SKIP LOCKED): an earlier row passed over could be handed out
560
+ // after a later one, and another claimant's live claim would go unseen. Another claimant's live claim holds
561
+ // every row; otherwise each row not live is claimed, and the claimant's own live claims stay in flight.
562
+ // The recipient's claims take turns: the lock domain `<outbox>_claims:<recipient>` is taken before the statement
563
+ // takes its snapshot. The statement sees only rows its snapshot holds, so without it a claim made meanwhile of a
564
+ // row queued meanwhile went unseen: this claim could take over a claimant's older row it was late to renew while
565
+ // that claimant held a newer one, and two brokers would hand out one recipient's messages at once, the newer
566
+ // possibly first. Sends, settlements and other recipients' claims do not take it.
567
+ // Only a recipient with undelivered rows needs the lock. A read sent first, `waiting`, takes it, with the
568
+ // database's lock shared, only when it finds such a row, so the common empty poll takes no lock at all. The read
569
+ // records what it found in a setting of the transaction, and the claim statement locks and claims rows only when
570
+ // the read found some: every claim acts under the lock, with a snapshot taken after it. A row queued after the
571
+ // read waits for the next claim, which its send's wake-up hint brings. An older driver takes the locks with the
572
+ // transaction's start instead, which is just as correct.
573
+ // While it waits for the locks, `waiting` holds the table's share lock. A broker that adds a column to the table
574
+ // under the database's lock at that moment ends one of the two with a deadlock error; a claim that fails so is
575
+ // taken again at the next scan, as after any failed claim.
576
+ const waiting: SqliteStatement = {
577
+ sql: `SELECT set_config('${CLAIM_GATE}', 'locked', true) AS waiting
578
+ WHERE EXISTS (SELECT 1 FROM ${table} WHERE target_identity = ? AND ${UNDELIVERED})`,
579
+ params: [targetIdentity],
580
+ };
581
+ const statement: SqliteStatement = {
582
+ sql: `WITH locked AS MATERIALIZED (
583
+ SELECT message_id, sequence, state, claimant_id, claim_renewed_at FROM ${table}
584
+ WHERE target_identity = ? AND ${UNDELIVERED}
585
+ AND current_setting('${CLAIM_GATE}', true) = 'locked'
586
+ ORDER BY sequence${lockClause("update")}
587
+ ), live AS MATERIALIZED (
588
+ SELECT message_id, sequence, claimant_id FROM locked
589
+ WHERE state = 'claimed' AND claim_renewed_at IS NOT NULL AND ${ageSince("claim_renewed_at")} <= ?
590
+ ), holder AS MATERIALIZED (
591
+ SELECT claimant_id FROM live WHERE claimant_id <> ? ORDER BY sequence LIMIT 1
592
+ ), claimed AS (
593
+ UPDATE ${table} SET ${claiming}
594
+ WHERE message_id IN (SELECT message_id FROM locked)
595
+ AND message_id NOT IN (SELECT message_id FROM live)
596
+ AND NOT EXISTS (SELECT 1 FROM holder)
597
+ RETURNING ${columns}
598
+ )
599
+ SELECT claimed.*, (SELECT claimant_id FROM holder) AS holder
600
+ FROM (SELECT 1) AS answer LEFT JOIN claimed ON TRUE`,
601
+ params: [targetIdentity, staleAfterMs, claimantId, claimantId, token],
602
+ };
603
+ return database.transaction(
604
+ async (executor) => {
605
+ await executor.all(waiting.sql, ...waiting.params);
606
+ const records = await executor.all<OutboxRecord & { readonly holder: string | null }>(
607
+ statement.sql,
608
+ ...statement.params,
609
+ );
610
+ const holder = records[0]?.holder ?? null;
611
+ if (holder !== null) return { status: "held", claimantId: holder } as const;
612
+ return claimed(records.filter((record) => record.message_id !== null));
613
+ },
614
+ {
615
+ concurrency: { kind: "serial", domain: `${table}_claims:${targetIdentity}` },
616
+ leading: [waiting, statement],
617
+ leadingOnly: true,
618
+ lockIfLeadingFinds: true,
619
+ },
620
+ );
621
+ }
622
+ // SQLite and libSQL: a write statement takes the database's write lock even when it changes nothing, so a read
623
+ // decides first, without it, whether there is anything to claim: empty scans (such as fan-out wake-up polls across
624
+ // idle sessions) cost one read. Linearizable: if a row commits after this snapshot, its enqueue writes a new
625
+ // wake-up hint. The same read answers a claim another claimant holds, or one of only the claimant's own rows in
626
+ // flight. Otherwise one statement claims the rows, deciding again on what it changes (#6560).
627
+ const live = (alias: string) =>
628
+ `${alias}.state = 'claimed' AND ${alias}.claim_renewed_at IS NOT NULL
629
+ AND ${ageSince(`${alias}.claim_renewed_at`)} <= ?`;
630
+ const heldBy = `SELECT live.claimant_id FROM ${table} live
631
+ WHERE live.target_identity = ? AND ${live("live")} AND live.claimant_id <> ?`;
632
+ const probe = () =>
633
+ database.get<{ holder: string | null; claimable: SqliteValue }>(
634
+ `SELECT (${heldBy} ORDER BY live.sequence LIMIT 1) AS holder, EXISTS (
635
+ SELECT 1 FROM ${table} pending WHERE pending.target_identity = ?
636
+ AND pending.${UNDELIVERED} AND NOT (${live("pending")})
637
+ ) AS claimable`,
638
+ targetIdentity,
639
+ staleAfterMs,
640
+ claimantId,
641
+ targetIdentity,
642
+ staleAfterMs,
643
+ );
644
+ const found = await probe();
645
+ if (found !== undefined && found.holder !== null) return { status: "held", claimantId: found.holder } as const;
646
+ if (Number(found?.claimable ?? 0) === 0) return { status: "claimed", rows: [] } as const;
647
+ const records = await database.all<OutboxRecord>(
648
+ `UPDATE ${table} SET ${claiming}
649
+ WHERE target_identity = ? AND ${UNDELIVERED} AND NOT (${live(table)}) AND NOT EXISTS (${heldBy})
650
+ RETURNING ${columns}`,
651
+ claimantId,
652
+ token,
653
+ targetIdentity,
654
+ staleAfterMs,
655
+ targetIdentity,
656
+ staleAfterMs,
657
+ claimantId,
658
+ );
659
+ if (records.length > 0) return claimed(records);
660
+ // Another claimant took the rows since the read, or they were settled: only then is the holder read again.
661
+ const again = await probe();
662
+ return again !== undefined && again.holder !== null
663
+ ? ({ status: "held", claimantId: again.holder } as const)
664
+ : ({ status: "claimed", rows: [] } as const);
339
665
  },
340
666
 
341
667
  renewClaim(claim) {
342
- return withClaim(claim, async (executor) => {
343
- await executor.run(
344
- `UPDATE ${table} SET claim_renewed_at = ${nowMs} WHERE message_id = ?`,
345
- claim.messageId,
346
- );
347
- return { status: "renewed" } as const;
348
- });
668
+ return withClaim(claim, `claim_renewed_at = ${nowMs}`, [], () => ({ status: "renewed" }) as const);
349
669
  },
350
670
 
351
671
  reportSaving(claim) {
352
- return withClaim(claim, async (executor) => {
353
- await executor.run(`UPDATE ${table} SET saving_at = ${nowMs} WHERE message_id = ?`, claim.messageId);
354
- return { status: "renewed" } as const;
355
- });
672
+ return withClaim(claim, `saving_at = ${nowMs}`, [], () => ({ status: "renewed" }) as const);
356
673
  },
357
674
 
358
675
  releaseClaim(claim, options) {
359
676
  const attempts = options?.unwritten === true ? `, claim_attempts = ${greatest("0", "claim_attempts - 1")}` : "";
360
- return withClaim(claim, async (executor) => {
361
- await executor.run(
362
- `UPDATE ${table} SET state = 'queued', claimant_id = NULL, claim_token = NULL, claim_renewed_at = NULL,
363
- saving_at = NULL${attempts}
364
- WHERE message_id = ?`,
365
- claim.messageId,
366
- );
367
- return { status: "released" } as const;
368
- });
677
+ return withClaim(
678
+ claim,
679
+ `state = 'queued', claimant_id = NULL, claim_token = NULL, claim_renewed_at = NULL, saving_at = NULL${attempts}`,
680
+ [],
681
+ () => ({ status: "released" }) as const,
682
+ );
369
683
  },
370
684
 
371
685
  async releaseClaimsOf(claimantId) {
686
+ // Its rows locked in sequence order, as a claim locks them, so the two never wait for each other (#6560).
372
687
  const { changes } = await database.run(
373
688
  `UPDATE ${table} SET state = 'queued', claimant_id = NULL, claim_token = NULL, claim_renewed_at = NULL,
374
689
  saving_at = NULL
375
- WHERE state = 'claimed' AND claimant_id = ?`,
690
+ WHERE message_id IN (
691
+ SELECT message_id FROM ${table} WHERE state = 'claimed' AND claimant_id = ?
692
+ ORDER BY sequence${lockClause("update")}
693
+ )`,
376
694
  claimantId,
377
695
  );
378
696
  return changes;
379
697
  },
380
698
 
381
699
  markDelivered(claim) {
382
- return withClaim(claim, async (executor) => ({
383
- status: "delivered" as const,
384
- row: await settle(executor, claim.messageId, "delivered", null),
385
- }));
700
+ if (dialect !== "postgres" || claim.messageId.length === 0 || claim.claimantId.length === 0)
701
+ return withClaim(claim, `state = 'delivered', ${settled}`, [null], (written) => ({
702
+ status: "delivered" as const,
703
+ row: toRow(written),
704
+ }));
705
+ return new Promise<OutboxDeliveredResult>((resolve, reject) => {
706
+ deliveries.push({ claim, resolve, reject });
707
+ if (delivering) return;
708
+ delivering = true;
709
+ void deliverQueued();
710
+ });
386
711
  },
387
712
 
388
713
  markFailed(claim, reason) {
389
- return withClaim(claim, async (executor) => ({
714
+ return withClaim(claim, `state = 'failed', ${settled}`, [JSON.stringify(reason)], (written) => ({
390
715
  status: "failed" as const,
391
- row: await settle(executor, claim.messageId, "failed", reason),
716
+ row: toRow(written),
392
717
  }));
393
718
  },
394
719
 
@@ -422,19 +747,26 @@ export async function openSqlOutboxStore(options: IntercomBrokerStateOptions): P
422
747
 
423
748
  async prune(settledOlderThanMs, queuedOlderThanMs) {
424
749
  if (queuedOlderThanMs !== undefined) {
750
+ // Every recipient's rows, each locked in sequence order and decided on in its newest version, as a claim
751
+ // locks them: a renewal that commits first keeps its row, and expiry waits for no lock domain (#6560).
752
+ const lockedWhere = (where: string) =>
753
+ `message_id IN (SELECT message_id FROM ${table} WHERE ${where} ORDER BY sequence${lockClause("update")})`;
425
754
  await database.transaction(async (executor) => {
426
755
  // A row an older broker queued has no time: its retention starts now.
427
- await executor.run(`UPDATE ${table} SET queued_at = ${nowMs} WHERE queued_at IS NULL AND ${UNDELIVERED}`);
428
756
  await executor.run(
429
- `UPDATE ${table} SET state = 'failed', failure_reason = ?, settled_at = ${nowMs},
430
- claimant_id = NULL, claim_token = NULL, claim_renewed_at = NULL, saving_at = NULL
431
- WHERE ${UNDELIVERED} AND ${ageSince("queued_at")} > ?
757
+ `UPDATE ${table} SET queued_at = ${nowMs} WHERE ${lockedWhere(`queued_at IS NULL AND ${UNDELIVERED}`)}`,
758
+ );
759
+ await executor.run(
760
+ `UPDATE ${table} SET state = 'failed', ${settled}
761
+ WHERE ${lockedWhere(
762
+ `${UNDELIVERED} AND ${ageSince("queued_at")} > ?
432
763
  AND (claim_renewed_at IS NULL OR ${ageSince("claim_renewed_at")} > ?)`,
764
+ )}`,
433
765
  JSON.stringify(OUTBOX_EXPIRED_REASON),
434
766
  queuedOlderThanMs,
435
767
  OUTBOX_CLAIM_STALE_AFTER_MS,
436
768
  );
437
- });
769
+ }, fenced);
438
770
  }
439
771
  const result = await database.run(
440
772
  `DELETE FROM ${table}