@bastani/atomic 0.10.10-alpha.2 → 0.10.11-alpha.1

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 (381) hide show
  1. package/CHANGELOG.md +142 -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 +8 -10
  7. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js.map +1 -1
  8. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +6 -6
  9. package/dist/_shared/mode-shared-2QJSCUM6.js +52 -15
  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 +3 -3
  13. package/dist/_shared/{sdk-RRLVN7ER.js → sdk-AVFII7NK.js} +757 -233
  14. package/dist/_shared/sdk-AVFII7NK.js.map +1 -0
  15. package/dist/_shared/session-data-AHTU7IS6.js +3 -3
  16. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  17. package/dist/_shared/{startup-0-0-4VG2G44V.js → startup-0-0-57KF6LZH.js} +94 -42
  18. package/dist/_shared/startup-0-0-57KF6LZH.js.map +1 -0
  19. package/dist/_shared/{startup-0-1-XTIL65D4.js → startup-0-1-GIY75K46.js} +75 -13
  20. package/dist/_shared/startup-0-1-GIY75K46.js.map +1 -0
  21. package/dist/_shared/startup-0-2-27OWFHV6.js +72 -7
  22. package/dist/_shared/startup-0-2-27OWFHV6.js.map +1 -1
  23. package/dist/_shared/startup-0-3-T4DVFYWX.js +4 -4
  24. package/dist/_shared/startup-0-4-ZMJV547D.js +4 -4
  25. package/dist/_shared/{startup-0-5-FD2P735I.js → startup-0-5-YDW47QX6.js} +27 -69
  26. package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -0
  27. package/dist/_shared/startup-10-0-TDQNBDDL.js +6 -6
  28. package/dist/_shared/startup-12-0-55AAXBJZ.js +3 -3
  29. package/dist/_shared/startup-14-0-MLX36RBG.js +4 -4
  30. package/dist/_shared/startup-15-0-YUKGAC63.js +31 -7
  31. package/dist/_shared/startup-15-0-YUKGAC63.js.map +1 -1
  32. package/dist/_shared/startup-15-1-4S7FLMNG.js +7 -6
  33. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  34. package/dist/_shared/startup-8-0-34CBHPZH.js +4 -4
  35. package/dist/_shared/{startup-8-1-4KANEHRA.js → startup-8-1-X32CYSXB.js} +1219 -714
  36. package/dist/_shared/startup-8-1-X32CYSXB.js.map +1 -0
  37. package/dist/_shared/storage-command-7MGXLJGZ.js +14 -8
  38. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  39. package/dist/_shared/task-reference-stream-JWMUZSJX.js +1 -1
  40. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  41. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  42. package/dist/builtin/intercom/CHANGELOG.md +24 -0
  43. package/dist/builtin/intercom/broker/broker.bundle.mjs +993 -362
  44. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +103 -24
  45. package/dist/builtin/intercom/broker/multinode-router.ts +42 -21
  46. package/dist/builtin/intercom/broker/multinode-state-store.ts +22 -1
  47. package/dist/builtin/intercom/broker/open-broker-state.ts +82 -31
  48. package/dist/builtin/intercom/broker/paths.ts +8 -4
  49. package/dist/builtin/intercom/broker/released-asker-remote-replies.ts +18 -6
  50. package/dist/builtin/intercom/broker/sql-add-column.ts +4 -1
  51. package/dist/builtin/intercom/broker/sql-ended-child-queue-store.ts +65 -44
  52. package/dist/builtin/intercom/broker/sql-held-send-store.ts +11 -3
  53. package/dist/builtin/intercom/broker/sql-known-session-store.ts +24 -12
  54. package/dist/builtin/intercom/broker/sql-lease-store.ts +375 -65
  55. package/dist/builtin/intercom/broker/sql-outbox-store.ts +270 -101
  56. package/dist/builtin/intercom/broker/sql-pending-ask-store.ts +20 -9
  57. package/dist/builtin/intercom/broker/sql-released-ask-store.ts +14 -6
  58. package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +27 -11
  59. package/dist/builtin/intercom/broker/sql-schema.ts +139 -1
  60. package/dist/builtin/intercom/broker/sql-sent-message-authority.ts +97 -34
  61. package/dist/builtin/intercom/index.bundle.mjs +11 -8
  62. package/dist/builtin/intercom/package.json +1 -1
  63. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  64. package/dist/builtin/mcp/package.json +1 -1
  65. package/dist/builtin/subagents/CHANGELOG.md +20 -0
  66. package/dist/builtin/subagents/package.json +1 -1
  67. package/dist/builtin/subagents/skills/skill-creator/SKILL.md +1 -1
  68. package/dist/builtin/subagents/src/extension/index.bundle.mjs +62 -23
  69. package/dist/builtin/web-access/CHANGELOG.md +9 -0
  70. package/dist/builtin/web-access/index.bundle.mjs +1 -1
  71. package/dist/builtin/web-access/package.json +1 -1
  72. package/dist/cli/args.js +2 -2
  73. package/dist/cli/auth-cli.code.js +4 -4
  74. package/dist/cli/auth-cli.impl.js +3 -3
  75. package/dist/cli/auth-cli.js +3 -3
  76. package/dist/cli/blueprint-command.code.js +3 -3
  77. package/dist/cli/blueprint-command.impl.js +3 -3
  78. package/dist/cli/blueprint-command.js +3 -3
  79. package/dist/cli/intercom-command.code.js +2 -2
  80. package/dist/cli/intercom-command.impl.js +3 -3
  81. package/dist/cli/intercom-command.js +3 -3
  82. package/dist/cli/list-models.code.js +2 -2
  83. package/dist/cli/list-models.impl.js +3 -3
  84. package/dist/cli/list-models.js +3 -3
  85. package/dist/cli/session-picker.code.js +1 -1
  86. package/dist/cli/session-picker.impl.js +3 -3
  87. package/dist/cli/session-picker.js +3 -3
  88. package/dist/cli/startup-ui.code.js +1 -1
  89. package/dist/cli/startup-ui.impl.js +3 -3
  90. package/dist/cli/startup-ui.js +3 -3
  91. package/dist/cli/storage-command.impl.js +3 -3
  92. package/dist/cli/storage-command.js +3 -3
  93. package/dist/cli/storage-search-session.code.js +3 -3
  94. package/dist/cli/storage-search-session.impl.js +3 -3
  95. package/dist/cli/storage-search-session.js +3 -3
  96. package/dist/cli/team-command.code.js +2 -2
  97. package/dist/cli/team-command.impl.js +3 -3
  98. package/dist/cli/team-command.js +3 -3
  99. package/dist/cli.js +2 -2
  100. package/dist/core/agent-session-methods.d.ts +3 -0
  101. package/dist/core/agent-session-methods.js.map +1 -1
  102. package/dist/core/agent-session.d.ts +1 -0
  103. package/dist/core/compaction/compactor.d.ts +2 -0
  104. package/dist/core/debug.impl.js +3 -3
  105. package/dist/core/debug.js +3 -3
  106. package/dist/core/export-html/card-projection.code.js +1 -1
  107. package/dist/core/export-html/card-projection.impl.js +3 -3
  108. package/dist/core/export-html/card-projection.js +3 -3
  109. package/dist/core/export-html/index.code.js +2 -2
  110. package/dist/core/export-html/index.impl.js +3 -3
  111. package/dist/core/export-html/index.js +3 -3
  112. package/dist/core/export-html/json-spans.impl.js +3 -3
  113. package/dist/core/export-html/json-spans.js +3 -3
  114. package/dist/core/export-html/oversized-render-inputs.code.js +1 -1
  115. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  116. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  117. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  118. package/dist/core/export-html/tool-renderer.js +3 -3
  119. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  120. package/dist/core/extensions/jiti-loader.js +3 -3
  121. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  122. package/dist/core/extensions/jiti-static-loader.js +3 -3
  123. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  124. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  125. package/dist/core/extensions/loader-host-modules.js +3 -3
  126. package/dist/core/extensions/loader-virtual-modules.js +2 -2
  127. package/dist/core/extensions/runner-context.js +3 -3
  128. package/dist/core/extensions/runner-context.js.map +1 -1
  129. package/dist/core/intercom-broker-control-host.code.js +1 -1
  130. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  131. package/dist/core/intercom-broker-control-host.js +3 -3
  132. package/dist/core/intercom-broker-control.code.js +3 -3
  133. package/dist/core/intercom-broker-control.impl.js +3 -3
  134. package/dist/core/intercom-broker-control.js +3 -3
  135. package/dist/core/model-registry.js +1 -1
  136. package/dist/core/model-resolver-defaults.d.ts +3 -2
  137. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  138. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  139. package/dist/core/package-manager-storage-adapters.js +3 -3
  140. package/dist/core/sdk.code.js +3 -4
  141. package/dist/core/sdk.impl.js +3 -3
  142. package/dist/core/sdk.js +3 -3
  143. package/dist/core/session-manager-core.d.ts +5 -2
  144. package/dist/core/session-manager-core.js +17 -13
  145. package/dist/core/session-manager-core.js.map +1 -1
  146. package/dist/core/session-manager-list.impl.js +3 -3
  147. package/dist/core/session-manager-list.js +3 -3
  148. package/dist/core/session-manager.code.js +1 -1
  149. package/dist/core/session-manager.impl.js +3 -3
  150. package/dist/core/session-manager.js +3 -3
  151. package/dist/core/session-storage.code.js +1 -1
  152. package/dist/core/session-storage.impl.js +3 -3
  153. package/dist/core/session-storage.js +3 -3
  154. package/dist/core/storage/added-exports.d.ts +6 -0
  155. package/dist/core/storage/added-exports.js +16 -0
  156. package/dist/core/storage/added-exports.js.map +1 -0
  157. package/dist/core/storage/database.d.ts +16 -0
  158. package/dist/core/storage/database.js.map +1 -1
  159. package/dist/core/storage/fenced-paths.d.ts +47 -0
  160. package/dist/core/storage/fenced-paths.js +53 -0
  161. package/dist/core/storage/fenced-paths.js.map +1 -1
  162. package/dist/core/storage/file-identity.js +31 -2
  163. package/dist/core/storage/file-identity.js.map +1 -1
  164. package/dist/core/storage/index.d.ts +3 -0
  165. package/dist/core/storage/index.js +5 -2
  166. package/dist/core/storage/index.js.map +1 -1
  167. package/dist/core/storage/migrations.d.ts +22 -0
  168. package/dist/core/storage/migrations.js +55 -0
  169. package/dist/core/storage/migrations.js.map +1 -1
  170. package/dist/core/storage/node-sqlite-thread.js +19 -6
  171. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  172. package/dist/core/storage/node-sqlite.js +53 -4
  173. package/dist/core/storage/node-sqlite.js.map +1 -1
  174. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  175. package/dist/core/storage/offline-snapshot-file.js +3 -3
  176. package/dist/core/storage/prefix.d.ts +3 -2
  177. package/dist/core/storage/prefix.js +18 -2
  178. package/dist/core/storage/prefix.js.map +1 -1
  179. package/dist/core/storage/provider.js +2 -2
  180. package/dist/core/storage/schema-catalog.d.ts +42 -0
  181. package/dist/core/storage/schema-catalog.js +141 -0
  182. package/dist/core/storage/schema-catalog.js.map +1 -0
  183. package/dist/core/storage/selection.js +2 -2
  184. package/dist/core/storage/session/branch-fork-source.code.js +41 -20
  185. package/dist/core/storage/session/branch-fork-source.code.js.map +1 -1
  186. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  187. package/dist/core/storage/session/branch-fork-source.js +3 -3
  188. package/dist/core/storage/session/card-view.impl.js +3 -3
  189. package/dist/core/storage/session/card-view.js +3 -3
  190. package/dist/core/storage/session/child-reader.code.js +3 -3
  191. package/dist/core/storage/session/child-reader.impl.js +3 -3
  192. package/dist/core/storage/session/child-reader.js +3 -3
  193. package/dist/core/storage/session/chunked-resume-projection.code.js +1 -1
  194. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  195. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  196. package/dist/core/storage/session/expanded-child-details.code.js +3 -3
  197. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  198. package/dist/core/storage/session/expanded-child-details.js +3 -3
  199. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  200. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  201. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  202. package/dist/core/storage/session/fork-row-index.js +3 -3
  203. package/dist/core/storage/session/fork-staging.code.js +176 -36
  204. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  205. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  206. package/dist/core/storage/session/fork-staging.js +3 -3
  207. package/dist/core/storage/session/fork-window.code.js +3 -3
  208. package/dist/core/storage/session/fork-window.impl.js +3 -3
  209. package/dist/core/storage/session/fork-window.js +3 -3
  210. package/dist/core/storage/session/history-pages.impl.js +3 -3
  211. package/dist/core/storage/session/history-pages.js +3 -3
  212. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  213. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  214. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  215. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  216. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  217. package/dist/core/storage/session/memory-session-store.js +3 -3
  218. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  219. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  220. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  221. package/dist/core/storage/session/released-history-files.code.js +2 -2
  222. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  223. package/dist/core/storage/session/released-history-files.js +3 -3
  224. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  225. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  226. package/dist/core/storage/session/session-resume.impl.js +3 -3
  227. package/dist/core/storage/session/session-resume.js +3 -3
  228. package/dist/core/storage/session/session-search-index.d.ts +5 -0
  229. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  230. package/dist/core/storage/session/snapshot-cut.js +3 -3
  231. package/dist/core/storage/session/snapshot-history.code.js +3 -3
  232. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  233. package/dist/core/storage/session/snapshot-history.js +3 -3
  234. package/dist/core/storage/session/sql-chat-records.d.ts +15 -0
  235. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  236. package/dist/core/storage/session/sql-session-store.d.ts +102 -5
  237. package/dist/core/storage/session/sql-session-store.impl.js +4 -4
  238. package/dist/core/storage/session/sql-session-store.js +4 -4
  239. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  240. package/dist/core/storage/session/tree-outline.js +3 -3
  241. package/dist/core/storage/session/tree-presentation.code.js +1 -1
  242. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  243. package/dist/core/storage/session/tree-presentation.js +3 -3
  244. package/dist/core/storage/session/types.d.ts +14 -0
  245. package/dist/core/storage/sqlite-facade.d.ts +37 -5
  246. package/dist/core/storage/sqlite-facade.js +351 -18
  247. package/dist/core/storage/sqlite-facade.js.map +1 -1
  248. package/dist/core/storage/statement-sequence.d.ts +83 -0
  249. package/dist/core/storage/statement-sequence.js +21 -0
  250. package/dist/core/storage/statement-sequence.js.map +1 -1
  251. package/dist/core/storage/storage-status.code.js +1 -1
  252. package/dist/core/storage/storage-status.impl.js +3 -3
  253. package/dist/core/storage/storage-status.js +3 -3
  254. package/dist/core/storage/team.code.js +1 -1
  255. package/dist/core/storage/team.impl.js +3 -3
  256. package/dist/core/storage/team.js +3 -3
  257. package/dist/core/structured-output/index.code.js +1 -1
  258. package/dist/core/structured-output/index.impl.js +3 -3
  259. package/dist/core/structured-output/index.js +3 -3
  260. package/dist/core/tasks/task-completion-entry.code.js +1 -1
  261. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  262. package/dist/core/tasks/task-completion-entry.js +3 -3
  263. package/dist/core/tasks/task-file-history.code.js +3 -3
  264. package/dist/core/tasks/task-file-history.impl.js +3 -3
  265. package/dist/core/tasks/task-file-history.js +3 -3
  266. package/dist/core/tasks/task-reference-archive.code.js +4 -4
  267. package/dist/core/tasks/task-reference-archive.js +3 -3
  268. package/dist/core/tasks/task-reference-identity.js +3 -3
  269. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  270. package/dist/core/tasks/task-reference-stream.js +3 -3
  271. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  272. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  273. package/dist/core/tasks/task-view-source.code.js +1 -1
  274. package/dist/core/tasks/task-view-source.impl.js +3 -3
  275. package/dist/core/tasks/task-view-source.js +3 -3
  276. package/dist/core/tools/bash.d.ts +8 -4
  277. package/dist/core/tools/history-session.d.ts +5 -0
  278. package/dist/core/tools/history-tasks.d.ts +123 -0
  279. package/dist/core/tools/kill.d.ts +5 -2
  280. package/dist/core/tools/powershell.d.ts +2 -2
  281. package/dist/core/tools/read-url.code.js +3 -3
  282. package/dist/core/tools/read-url.impl.js +3 -3
  283. package/dist/core/tools/read-url.js +3 -3
  284. package/dist/core/tools/read.d.ts +12 -2
  285. package/dist/core/tools/resource-selectors.d.ts +2 -0
  286. package/dist/core/tools/search.d.ts +12 -2
  287. package/dist/core/worktree-snapshot/blob-store.d.ts +14 -2
  288. package/dist/core/worktree-snapshot/blob-store.js +69 -16
  289. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  290. package/dist/core/worktree-snapshot/errors.code.js +2 -2
  291. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  292. package/dist/core/worktree-snapshot/errors.js +3 -3
  293. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  294. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  295. package/dist/extensions/codemode/execute.code.js +2 -2
  296. package/dist/extensions/codemode/execute.impl.js +3 -3
  297. package/dist/extensions/codemode/execute.js +3 -3
  298. package/dist/extensions/codemode/renderer.code.js +2 -2
  299. package/dist/extensions/codemode/renderer.impl.js +3 -3
  300. package/dist/extensions/codemode/renderer.js +3 -3
  301. package/dist/extensions/mcp/cli.code.js +3 -3
  302. package/dist/extensions/mcp/cli.impl.js +3 -3
  303. package/dist/extensions/mcp/cli.js +3 -3
  304. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  305. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  306. package/dist/extensions/mcp/cli.lazy.js +3 -3
  307. package/dist/extensions/mcp/runtime.code.js +1 -1
  308. package/dist/extensions/mcp/runtime.impl.js +3 -3
  309. package/dist/extensions/mcp/runtime.js +3 -3
  310. package/dist/index.js +5 -5
  311. package/dist/main-first-time-setup.code.js +1 -1
  312. package/dist/main-first-time-setup.impl.js +3 -3
  313. package/dist/main-first-time-setup.js +3 -3
  314. package/dist/main.js +1 -1
  315. package/dist/modes/interactive/components/agent-panel.d.ts +1 -0
  316. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  317. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  318. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  319. package/dist/modes/interactive/components/task-inspector.d.ts +2 -0
  320. package/dist/modes/interactive/components/user-message-selector-archive.code.js +1 -1
  321. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  322. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  323. package/dist/modes/interactive/interactive-mode-helpers.d.ts +2 -2
  324. package/dist/modes/print-mode.js +1 -1
  325. package/dist/modes/rpc/agent-panel-bridge.d.ts +5 -0
  326. package/dist/package-manager-cli.code.js +6 -6
  327. package/dist/package-manager-cli.impl.js +3 -3
  328. package/dist/package-manager-cli.js +3 -3
  329. package/dist/rpc-entry.js +1 -1
  330. package/dist/startup-files.json +1 -1
  331. package/dist/startup-stages/0.js +1 -1
  332. package/dist/startup-stages/1.js +1 -1
  333. package/dist/startup-stages/10.js +1 -1
  334. package/dist/startup-stages/12.js +1 -1
  335. package/dist/startup-stages/2.js +8 -1
  336. package/dist/startup-stages/3.js +1 -6
  337. package/dist/startup-stages/5.js +1 -1
  338. package/dist/startup-stages/7.js +1 -5
  339. package/dist/utils/startup-database-spare.code.js +2 -2
  340. package/dist/utils/startup-database-spare.impl.js +3 -3
  341. package/dist/utils/startup-database-spare.js +3 -3
  342. package/dist/utils/tools-manager.code.js +1 -1
  343. package/dist/utils/tools-manager.impl.js +3 -3
  344. package/dist/utils/tools-manager.js +3 -3
  345. package/docs/background-tasks.md +123 -23
  346. package/docs/compaction.md +18 -0
  347. package/docs/docs.json +2 -0
  348. package/docs/environment-variables.md +1 -1
  349. package/docs/getting-started/installation.md +9 -2
  350. package/docs/guides/postgres-pgbouncer.md +339 -0
  351. package/docs/guides/postgres-tuning.md +311 -0
  352. package/docs/guides/resume-on-any-machine.md +2 -2
  353. package/docs/guides.md +2 -0
  354. package/docs/index.md +1 -1
  355. package/docs/libraries/agent-core.md +1 -1
  356. package/docs/libraries/ai.md +2 -2
  357. package/docs/libraries/codemode.md +1 -1
  358. package/docs/libraries/storage-libsql.md +6 -1
  359. package/docs/libraries/storage-postgres.md +11 -6
  360. package/docs/libraries/tui.md +1 -1
  361. package/docs/libraries.md +2 -2
  362. package/docs/programmatic.md +1 -1
  363. package/docs/quickstart.md +1 -1
  364. package/docs/sdk/storage.md +1 -1
  365. package/docs/sdk/web-server.md +1 -3
  366. package/docs/sdk.md +1 -7
  367. package/docs/sessions.md +58 -2
  368. package/docs/settings.md +20 -1
  369. package/docs/skills/authoring.md +1 -1
  370. package/docs/skills.md +79 -6
  371. package/docs/storage.md +262 -12
  372. package/docs/subagents/reference.md +2 -2
  373. package/docs/subagents.md +4 -3
  374. package/docs/tools.md +44 -10
  375. package/docs/windows.md +1 -1
  376. package/package.json +9 -9
  377. package/dist/_shared/sdk-RRLVN7ER.js.map +0 -1
  378. package/dist/_shared/startup-0-0-4VG2G44V.js.map +0 -1
  379. package/dist/_shared/startup-0-1-XTIL65D4.js.map +0 -1
  380. package/dist/_shared/startup-0-5-FD2P735I.js.map +0 -1
  381. package/dist/_shared/startup-8-1-4KANEHRA.js.map +0 -1
@@ -1,11 +1,16 @@
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,
@@ -25,7 +30,7 @@ import {
25
30
  type StateStoreInvalidReason,
26
31
  } from "./multinode-state-store.js";
27
32
  import { addMissingColumns } from "./sql-add-column.js";
28
- import { ensureBrokerSchema } from "./sql-schema.js";
33
+ import { ensureBrokerSchema, withBrokerSchemaCatalog } from "./sql-schema.js";
29
34
 
30
35
  const UNDELIVERED = "state IN ('queued', 'claimed')";
31
36
 
@@ -80,15 +85,53 @@ export class OutboxWakeFailedError extends Error {
80
85
  }
81
86
  }
82
87
 
88
+ /**
89
+ * What an enqueue writes first and requires: a send's reservation of its message (#6560). `first` is written just
90
+ * before the row, in the same transaction, and the row is inserted only while `condition`, an SQL boolean expression
91
+ * with its parameters, holds; when it does not, and no row of the message is there, the enqueue reports a conflict.
92
+ */
93
+ export interface OutboxEnqueueGuard {
94
+ readonly first: SqliteStatement;
95
+ readonly condition: SqliteStatement;
96
+ }
97
+
83
98
  /** The SQL outbox, which can also enqueue inside a transaction the caller holds. */
84
99
  export interface SqlOutboxStore extends OutboxStore {
85
100
  /**
86
101
  * `enqueue`, as part of `executor`'s transaction: the row is written only when that transaction commits. It throws
87
102
  * `OutboxWakeFailedError` when only the optional wake-up hint failed; run the transaction again without it then.
103
+ * The transaction must hold the recipient's domain (`recipientTransaction`).
88
104
  */
89
- enqueueIn(executor: SqliteExecutor, request: OutboxEnqueueRequest): Promise<OutboxEnqueueResult>;
105
+ enqueueIn(
106
+ executor: SqliteExecutor,
107
+ request: OutboxEnqueueRequest,
108
+ guard?: OutboxEnqueueGuard,
109
+ ): Promise<OutboxEnqueueResult>;
110
+ /**
111
+ * The reads `enqueueIn` makes first for `request`, in order, for a transaction's `leading` statements: a pipelined
112
+ * connection sends them with the transaction's start instead of a round trip each (#6560).
113
+ */
114
+ enqueueLeading(request: OutboxEnqueueRequest): readonly SqliteStatement[];
90
115
  }
91
116
 
117
+ /**
118
+ * Runs `statements` as the last calls of `executor`'s transaction: on a pipelined connection they go out with the
119
+ * commit, in one round trip; elsewhere each runs in turn as `run` runs it. The transaction's callback must make no call
120
+ * after them (#6560).
121
+ */
122
+ export async function runLast(executor: SqliteExecutor, ...statements: SqliteStatement[]): Promise<void> {
123
+ if (statements.length === 0 || finisherOf?.(executor)?.(statements) === true) return;
124
+ for (const { sql, params } of statements) await executor.run(sql, ...params);
125
+ }
126
+
127
+ /**
128
+ * `transactionFinisher` of the storage module, where the copy the process loaded has it: a host whose Atomic predates it
129
+ * runs every statement in turn (#6560).
130
+ */
131
+ const finisherOf: (typeof storage)["transactionFinisher"] | undefined = (
132
+ storage as Partial<Pick<typeof storage, "transactionFinisher">>
133
+ ).transactionFinisher;
134
+
92
135
  /**
93
136
  * #5607: runs `write` for `request`, and once more for it without its wake-up hint when only that hint failed it.
94
137
  */
@@ -105,14 +148,49 @@ export async function withoutFailedWake<T>(
105
148
  }
106
149
  }
107
150
 
151
+ /**
152
+ * The lock domain of one recipient's sends, `<outbox>:<recipient>`: a send reserves its message and queues its row in
153
+ * one transaction of it (`reserveAndEnqueue`, `enqueue`), so sends to one recipient run one at a time, and commit their
154
+ * rows in the order of their sequence, and a send's checks of that recipient's queue (its size budget) hold until it
155
+ * commits. Sends to other recipients, claims and every write of one row run beside them (#6560).
156
+ */
157
+ export function recipientTransaction(
158
+ database: SqliteDatabase,
159
+ prefix: string | undefined,
160
+ targetIdentity: string,
161
+ ): SqliteTransactionOptions {
162
+ const outbox = `${validateStoragePrefix(prefix, dialectOf(database).name)}intercom_outbox`;
163
+ return { concurrency: { kind: "serial", domain: `${outbox}:${targetIdentity}` } };
164
+ }
165
+
166
+ /**
167
+ * A transaction of the outbox or the sent-message table that takes no lock domain: each of its writes decides on the
168
+ * rows it locks itself (`fencedPath("intercom-outbox-row")`). It still waits for and excludes the database-wide
169
+ * transactions an older broker runs on these tables (#6560).
170
+ */
171
+ export function rowTransaction(): SqliteTransactionOptions {
172
+ return { concurrency: { kind: "fenced", audit: fencedPath("intercom-outbox-row"), excludesSerial: true } };
173
+ }
174
+
108
175
  /**
109
176
  * 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.
177
+ * one `BEGIN IMMEDIATE` transaction, and every age is measured on the database clock. On a database whose transactions
178
+ * run concurrently (PostgreSQL), an enqueue holds its recipient's domain (`recipientTransaction`); a claim locks the
179
+ * recipient's rows in sequence order and every write of a claimed row is one statement guarded by its claim token
180
+ * (`rowTransaction`), so no write waits for another recipient's (#6560).
111
181
  */
112
- export async function openSqlOutboxStore(options: IntercomBrokerStateOptions): Promise<SqlOutboxStore> {
182
+ export function openSqlOutboxStore(options: IntercomBrokerStateOptions): Promise<SqlOutboxStore> {
183
+ // Its schema checks answer from one read of the catalog, shared with an open around it: a current schema costs
184
+ // no transaction and no lock, also when the store is opened on its own (#6560).
185
+ return withBrokerSchemaCatalog(options.database, options.prefix, () => openOutboxStoreInCatalog(options));
186
+ }
187
+
188
+ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Promise<SqlOutboxStore> {
113
189
  const { database } = options;
114
190
  const table = `${validateStoragePrefix(options.prefix, dialectOf(database).name)}intercom_outbox`;
115
- const { types, nowMs, greatest, name: dialect } = dialectOf(database);
191
+ const { types, nowMs, greatest, lockClause, name: dialect } = dialectOf(database);
192
+ /** Claims, claim writes and expiry: each decides on the rows it locks (#6560). */
193
+ const fenced = rowTransaction();
116
194
  const ageSince = (column: string) => greatest("0", `${nowMs} - ${column}`);
117
195
  // In a serial transaction, so brokers opening a new store at once take turns creating it (#5054).
118
196
  const schema = `
@@ -148,70 +226,86 @@ export async function openSqlOutboxStore(options: IntercomBrokerStateOptions): P
148
226
  claim_attempts, claimant_id, claim_token, failure_reason,
149
227
  CASE WHEN claim_renewed_at IS NULL THEN NULL ELSE ${ageSince("claim_renewed_at")} END AS claim_age,
150
228
  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);
229
+ const selectStatement = (messageId: string): SqliteStatement => ({
230
+ sql: `SELECT ${columns} FROM ${table} WHERE message_id = ?`,
231
+ params: [messageId],
232
+ });
233
+ const select = (executor: SqliteExecutor, messageId: string) => {
234
+ const { sql, params } = selectStatement(messageId);
235
+ return executor.get<OutboxRecord>(sql, ...params);
236
+ };
153
237
  // #5607: the lease store's table, whose presence leases name the broker hosting a recipient, and the wake-up bus's
154
238
  // hint log. The broker opens both before it enqueues anything.
155
239
  const leases = `${validateStoragePrefix(options.prefix, dialectOf(database).name)}intercom_leases`;
156
240
  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
- );
241
+ const allUndeliveredStatement = (targetIdentity: string): SqliteStatement => ({
242
+ sql: `SELECT ${columns} FROM ${table} WHERE target_identity = ? AND ${UNDELIVERED} ORDER BY sequence`,
243
+ params: [targetIdentity],
244
+ });
245
+ const undelivered = (executor: SqliteExecutor, targetIdentity: string, limit?: number) => {
246
+ if (limit === undefined) {
247
+ const { sql, params } = allUndeliveredStatement(targetIdentity);
248
+ return executor.all<OutboxRecord>(sql, ...params);
249
+ }
250
+ return executor.all<OutboxRecord>(
251
+ `SELECT ${columns} FROM ${table} WHERE target_identity = ? AND ${UNDELIVERED} ORDER BY sequence LIMIT ?`,
252
+ targetIdentity,
253
+ limit,
254
+ );
255
+ };
168
256
  const isLive = (record: OutboxRecord, staleAfterMs: number): boolean =>
169
257
  record.claim_age !== null && Number(record.claim_age) <= staleAfterMs;
170
258
 
171
- /** Runs `write` only for the row's current claim; every other case is reported as the contract requires. */
259
+ /**
260
+ * Applies `assignments` (with their parameters) to the row only while `claim` is its current claim: one UPDATE whose
261
+ * WHERE names the claim, so the decision is made on the row's lock and its newest version, never on an earlier read.
262
+ * The update is the transaction's first statement, sent with its start; only when it changed nothing is the row read,
263
+ * to report why (#6560).
264
+ */
172
265
  const withClaim = <Result>(
173
266
  claim: OutboxClaim,
174
- write: (executor: SqliteExecutor) => Promise<Result>,
267
+ assignments: string,
268
+ params: readonly SqliteValue[],
269
+ answer: (written: OutboxRecord) => Result,
175
270
  ): Promise<Result | OutboxClaimWriteRejection> => {
176
271
  if (claim.messageId.length === 0) return Promise.resolve(invalid("empty-message-id"));
177
272
  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) {
273
+ const write: SqliteStatement = {
274
+ sql: `UPDATE ${table} SET ${assignments}
275
+ WHERE message_id = ? AND claim_token = ? AND claimant_id = ? AND state = 'claimed'
276
+ RETURNING ${columns}`,
277
+ params: [...params, claim.messageId, claim.token, claim.claimantId],
278
+ };
279
+ return database.transaction(
280
+ async (executor) => {
281
+ const written = await executor.get<OutboxRecord>(write.sql, ...write.params);
282
+ if (written !== undefined) return answer(written);
283
+ const record = await select(executor, claim.messageId);
284
+ if (record === undefined) return { status: "unknown" } as const;
285
+ if (isSettled(record)) return { status: "settled", row: toRow(record) } as const;
183
286
  return { status: "stale" } as const;
184
- }
185
- return write(executor);
186
- });
187
- };
188
-
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,
287
+ },
288
+ { ...fenced, leading: [write] },
202
289
  );
203
- return toRow((await select(executor, messageId))!);
204
290
  };
205
291
 
292
+ const settled = `failure_reason = ?, settled_at = ${nowMs},
293
+ claimant_id = NULL, claim_token = NULL, claim_renewed_at = NULL, saving_at = NULL`;
294
+
206
295
  /**
207
296
  * #4896: the recipient's undelivered rows and their frame bytes, read from `<table>_target_bytes` alone. Only rows an
208
297
  * older broker wrote, without `frame_bytes`, are measured from their frames.
209
298
  */
299
+ const sizedTotalsStatement = (targetIdentity: string): SqliteStatement => ({
300
+ sql: `SELECT COUNT(*) AS row_count, COALESCE(SUM(frame_bytes), 0) AS byte_count, COUNT(*) - COUNT(frame_bytes) AS unsized
301
+ FROM ${table} WHERE target_identity = ? AND ${UNDELIVERED}`,
302
+ params: [targetIdentity],
303
+ });
210
304
  const queuedTotals = async (executor: SqliteExecutor, targetIdentity: string) => {
305
+ const totals = sizedTotalsStatement(targetIdentity);
211
306
  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,
307
+ totals.sql,
308
+ ...totals.params,
215
309
  ))!;
216
310
  const unsized =
217
311
  Number(sized.unsized) === 0
@@ -226,7 +320,11 @@ export async function openSqlOutboxStore(options: IntercomBrokerStateOptions): P
226
320
  return { rows: Number(sized.row_count), bytes: Number(sized.byte_count) + unsized };
227
321
  };
228
322
 
229
- const enqueueIn = async (executor: SqliteExecutor, request: OutboxEnqueueRequest): Promise<OutboxEnqueueResult> => {
323
+ const enqueueIn = async (
324
+ executor: SqliteExecutor,
325
+ request: OutboxEnqueueRequest,
326
+ guard?: OutboxEnqueueGuard,
327
+ ): Promise<OutboxEnqueueResult> => {
230
328
  if (request.targetIdentity.length === 0) return invalid("empty-target-identity");
231
329
  if (request.originBrokerId.length === 0) return invalid("empty-broker-id");
232
330
  const messageId = request.frame.message.id;
@@ -246,38 +344,82 @@ export async function openSqlOutboxStore(options: IntercomBrokerStateOptions): P
246
344
  ) {
247
345
  return { status: "full", limit: OUTBOX_TARGET_MAX_ROWS, byteLimit: OUTBOX_TARGET_MAX_BYTES } as const;
248
346
  }
347
+ // Inserted only while the guard holds, and never over a row of the message that another recipient's send, in a
348
+ // domain of its own, queued meanwhile: the unique message id makes that send's row, once it commits, the answer
349
+ // (#6560). The guard's first write and the insert go out together.
350
+ const condition = guard?.condition;
249
351
  const insert = `INSERT INTO ${table}(message_id, target_identity, origin_broker_id, digest, frame_json, state, queued_at,
250
352
  frame_bytes)
251
- VALUES (?, ?, ?, ?, ?, 'queued', ${nowMs}, ?)`;
252
- const values = [messageId, request.targetIdentity, request.originBrokerId, request.digest, frameJson, frameBytes];
353
+ SELECT ?, ?, ?, ?, ?, 'queued', ${nowMs}, CAST(? AS ${types.int})
354
+ WHERE ${condition === undefined ? "1 = 1" : condition.sql}
355
+ ON CONFLICT(message_id) DO NOTHING`;
356
+ const values = [
357
+ messageId,
358
+ request.targetIdentity,
359
+ request.originBrokerId,
360
+ request.digest,
361
+ frameJson,
362
+ frameBytes,
363
+ ...(condition?.params ?? []),
364
+ ];
365
+ const first = guard === undefined ? undefined : executor.run(guard.first.sql, ...guard.first.params);
366
+ first?.catch(() => {});
367
+ // The insert goes out behind the guard's write without waiting for its answer only on a pipelined transaction's
368
+ // own handle, which sends calls in the order they are made; any other executor, a wrapper included, may run a
369
+ // later call first, so the write is answered before the insert is made.
370
+ if (finisherOf?.(executor) === undefined) await first;
371
+ /** The answer of the insert, once the guard's write, sent before it, succeeded. */
372
+ const after = async <T>(inserting: Promise<T>): Promise<T> => {
373
+ inserting.catch(() => {});
374
+ await first;
375
+ return inserting;
376
+ };
377
+ /** Nothing was inserted: the message's row, which another send queued, or the guard's refusal. */
378
+ const notInserted = async (): Promise<OutboxEnqueueResult> => {
379
+ const queued = await select(executor, messageId);
380
+ if (queued !== undefined && queued.digest === request.digest)
381
+ return { status: "duplicate", row: toRow(queued) } as const;
382
+ return { status: "conflict", messageId } as const;
383
+ };
253
384
  if (request.wakeHostWithinMs === undefined) {
254
- await executor.run(insert, ...values);
255
- return { status: "inserted", row: toRow((await select(executor, messageId))!) } as const;
385
+ // The row comes back from its insert, in the same round trip (#6560).
386
+ const row = await after(executor.get<OutboxRecord>(`${insert} RETURNING ${columns}`, ...values));
387
+ return row === undefined ? notInserted() : ({ status: "inserted", row: toRow(row) } as const);
256
388
  }
257
389
  // #5607: the row comes back from its insert, with the broker holding the recipient's live presence, read in this
258
390
  // transaction: a presence lease committed before it is seen here; one committed after it was written after this row,
259
391
  // 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}, (
392
+ // its wake-up hint, in this transaction too. On PostgreSQL leases are acquired beside this transaction
393
+ // (#6560), so the read locks the lease: an acquisition under way commits first and is seen, and a later one
394
+ // waits for this row.
395
+ const inserted = await after(
396
+ executor.get<OutboxRecord & { readonly presence_holder: string | null }>(
397
+ `${insert} RETURNING ${columns}, (
263
398
  SELECT presence.holder_id FROM ${leases} presence
264
399
  WHERE presence.kind = 'presence' AND presence.key = ? AND presence.holder_id IS NOT NULL
265
- AND ${greatest("0", `${nowMs} - presence.renewed_at`)} <= ?
400
+ AND ${greatest("0", `${nowMs} - presence.renewed_at`)} <= ?${lockClause("share")}
266
401
  ) AS presence_holder`,
267
- ...values,
268
- request.targetIdentity,
269
- request.wakeHostWithinMs,
270
- ))!;
402
+ ...values,
403
+ request.targetIdentity,
404
+ request.wakeHostWithinMs,
405
+ ),
406
+ );
407
+ if (inserted === undefined) return notInserted();
271
408
  const host = inserted.presence_holder;
272
409
  if (host !== null) {
273
410
  const hint = async () => {
274
- // PostgreSQL: never wait behind another session's lock on the hint log; such a hint goes without.
411
+ // PostgreSQL: never wait behind another session's lock on the hint log; such a hint goes without. The hint
412
+ // is a new row, so it needs no lock domain of its own (#6560): see `fencedPath("intercom-wakeup-hint")`.
275
413
  if (dialect === "postgres") await executor.run(`LOCK TABLE ${wakeups} IN ROW EXCLUSIVE MODE NOWAIT`);
276
414
  await executor.run(
277
415
  `INSERT INTO ${wakeups}(broker_id, reason, version, created_at) VALUES (?, 'outbox', ?, ${nowMs})`,
278
416
  host,
279
417
  Number(inserted.sequence),
280
418
  );
419
+ // Notified when it commits, as the wake-up bus's own hints are, so the host does not wait for its backup
420
+ // poll (#6560).
421
+ const notify = database.notifications?.notify(wakeups, host);
422
+ if (notify !== undefined) await executor.run(notify.sql, ...notify.params);
281
423
  };
282
424
  await hint().catch((cause: unknown) => {
283
425
  throw new OutboxWakeFailedError(cause);
@@ -286,14 +428,23 @@ export async function openSqlOutboxStore(options: IntercomBrokerStateOptions): P
286
428
  return { status: "inserted", row: toRow(inserted), ...(host === null ? {} : { woke: host }) } as const;
287
429
  };
288
430
 
431
+ const enqueueLeading = (request: OutboxEnqueueRequest): readonly SqliteStatement[] => [
432
+ selectStatement(request.frame.message.id),
433
+ ...(request.owed === true ? [] : [sizedTotalsStatement(request.targetIdentity)]),
434
+ ];
435
+
289
436
  return {
290
437
  enqueueIn,
438
+ enqueueLeading,
291
439
  async enqueue(request) {
292
440
  if (request.targetIdentity.length === 0) return invalid("empty-target-identity");
293
441
  if (request.originBrokerId.length === 0) return invalid("empty-broker-id");
294
442
  if (request.frame.message.id.length === 0) return invalid("empty-message-id");
295
443
  return withoutFailedWake(request, (attempt) =>
296
- database.transaction((executor) => enqueueIn(executor, attempt)),
444
+ database.transaction((executor) => enqueueIn(executor, attempt), {
445
+ ...recipientTransaction(database, options.prefix, attempt.targetIdentity),
446
+ leading: enqueueLeading(attempt),
447
+ }),
297
448
  );
298
449
  },
299
450
 
@@ -307,8 +458,17 @@ export async function openSqlOutboxStore(options: IntercomBrokerStateOptions): P
307
458
  request.targetIdentity,
308
459
  );
309
460
  if (pending === undefined) return { status: "claimed", rows: [] } as const;
461
+ // The recipient's rows are locked in sequence order, as every write of several rows locks them, and read in
462
+ // their newest versions: a renewal or settlement of one waits for this claim, or this claim for it, so what it
463
+ // decides on stays true until it commits (#6560). It does not skip a locked row (SKIP LOCKED): an earlier row
464
+ // passed over could be handed out after a later one, and another claimant's live claim would go unseen.
465
+ const locking: SqliteStatement = {
466
+ sql: `SELECT ${columns} FROM ${table} WHERE target_identity = ? AND ${UNDELIVERED}
467
+ ORDER BY sequence${lockClause("update")}`,
468
+ params: [request.targetIdentity],
469
+ };
310
470
  return database.transaction(async (executor) => {
311
- const records = await undelivered(executor, request.targetIdentity);
471
+ const records = await executor.all<OutboxRecord>(locking.sql, ...locking.params);
312
472
  const other = records.find(
313
473
  (record) =>
314
474
  record.state === "claimed" &&
@@ -317,78 +477,80 @@ export async function openSqlOutboxStore(options: IntercomBrokerStateOptions): P
317
477
  );
318
478
  if (other?.claimant_id) return { status: "held", claimantId: other.claimant_id } as const;
319
479
  const rows: ClaimedOutboxRow[] = [];
480
+ const claims: SqliteStatement[] = [];
320
481
  for (const record of records) {
321
482
  if (record.state === "claimed" && isLive(record, request.staleAfterMs)) continue;
322
483
  const token = randomUUID();
323
- await executor.run(
324
- `UPDATE ${table} SET state = 'claimed', claim_attempts = claim_attempts + 1, claimant_id = ?,
484
+ claims.push({
485
+ sql: `UPDATE ${table} SET state = 'claimed', claim_attempts = claim_attempts + 1, claimant_id = ?,
325
486
  claim_token = ?, claim_renewed_at = ${nowMs}, saving_at = NULL
326
487
  WHERE message_id = ?`,
327
- request.claimantId,
328
- token,
329
- record.message_id,
330
- );
331
- const row = toRow((await select(executor, record.message_id))!);
488
+ params: [request.claimantId, token, record.message_id],
489
+ });
490
+ // The row as the update leaves it: this transaction holds its lock (#6560).
491
+ const row = toRow({
492
+ ...record,
493
+ state: "claimed",
494
+ claim_attempts: Number(record.claim_attempts) + 1,
495
+ claimant_id: request.claimantId,
496
+ claim_token: token,
497
+ claim_age: 0,
498
+ saving_age: null,
499
+ });
332
500
  rows.push({
333
501
  row,
334
502
  claim: { messageId: row.messageId, claimantId: request.claimantId, token, attempt: row.claimAttempts },
335
503
  });
336
504
  }
505
+ // Sent with the commit: one round trip for the claim's reads, one for its writes (#6560).
506
+ await runLast(executor, ...claims);
337
507
  return { status: "claimed", rows } as const;
338
- });
508
+ }, { ...fenced, leading: [locking] });
339
509
  },
340
510
 
341
511
  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
- });
512
+ return withClaim(claim, `claim_renewed_at = ${nowMs}`, [], () => ({ status: "renewed" }) as const);
349
513
  },
350
514
 
351
515
  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
- });
516
+ return withClaim(claim, `saving_at = ${nowMs}`, [], () => ({ status: "renewed" }) as const);
356
517
  },
357
518
 
358
519
  releaseClaim(claim, options) {
359
520
  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
- });
521
+ return withClaim(
522
+ claim,
523
+ `state = 'queued', claimant_id = NULL, claim_token = NULL, claim_renewed_at = NULL, saving_at = NULL${attempts}`,
524
+ [],
525
+ () => ({ status: "released" }) as const,
526
+ );
369
527
  },
370
528
 
371
529
  async releaseClaimsOf(claimantId) {
530
+ // Its rows locked in sequence order, as a claim locks them, so the two never wait for each other (#6560).
372
531
  const { changes } = await database.run(
373
532
  `UPDATE ${table} SET state = 'queued', claimant_id = NULL, claim_token = NULL, claim_renewed_at = NULL,
374
533
  saving_at = NULL
375
- WHERE state = 'claimed' AND claimant_id = ?`,
534
+ WHERE message_id IN (
535
+ SELECT message_id FROM ${table} WHERE state = 'claimed' AND claimant_id = ?
536
+ ORDER BY sequence${lockClause("update")}
537
+ )`,
376
538
  claimantId,
377
539
  );
378
540
  return changes;
379
541
  },
380
542
 
381
543
  markDelivered(claim) {
382
- return withClaim(claim, async (executor) => ({
544
+ return withClaim(claim, `state = 'delivered', ${settled}`, [null], (written) => ({
383
545
  status: "delivered" as const,
384
- row: await settle(executor, claim.messageId, "delivered", null),
546
+ row: toRow(written),
385
547
  }));
386
548
  },
387
549
 
388
550
  markFailed(claim, reason) {
389
- return withClaim(claim, async (executor) => ({
551
+ return withClaim(claim, `state = 'failed', ${settled}`, [JSON.stringify(reason)], (written) => ({
390
552
  status: "failed" as const,
391
- row: await settle(executor, claim.messageId, "failed", reason),
553
+ row: toRow(written),
392
554
  }));
393
555
  },
394
556
 
@@ -422,19 +584,26 @@ export async function openSqlOutboxStore(options: IntercomBrokerStateOptions): P
422
584
 
423
585
  async prune(settledOlderThanMs, queuedOlderThanMs) {
424
586
  if (queuedOlderThanMs !== undefined) {
587
+ // Every recipient's rows, each locked in sequence order and decided on in its newest version, as a claim
588
+ // locks them: a renewal that commits first keeps its row, and expiry waits for no lock domain (#6560).
589
+ const lockedWhere = (where: string) =>
590
+ `message_id IN (SELECT message_id FROM ${table} WHERE ${where} ORDER BY sequence${lockClause("update")})`;
425
591
  await database.transaction(async (executor) => {
426
592
  // 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
593
  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")} > ?
594
+ `UPDATE ${table} SET queued_at = ${nowMs} WHERE ${lockedWhere(`queued_at IS NULL AND ${UNDELIVERED}`)}`,
595
+ );
596
+ await executor.run(
597
+ `UPDATE ${table} SET state = 'failed', ${settled}
598
+ WHERE ${lockedWhere(
599
+ `${UNDELIVERED} AND ${ageSince("queued_at")} > ?
432
600
  AND (claim_renewed_at IS NULL OR ${ageSince("claim_renewed_at")} > ?)`,
601
+ )}`,
433
602
  JSON.stringify(OUTBOX_EXPIRED_REASON),
434
603
  queuedOlderThanMs,
435
604
  OUTBOX_CLAIM_STALE_AFTER_MS,
436
605
  );
437
- });
606
+ }, fenced);
438
607
  }
439
608
  const result = await database.run(
440
609
  `DELETE FROM ${table}
@@ -19,7 +19,7 @@ import type {
19
19
  } from "./multinode-state-store.js";
20
20
  import { SETTLED_ASK_RETENTION_MS } from "./multinode-state-store.js";
21
21
  import { addMissingColumns } from "./sql-add-column.js";
22
- import { ensureBrokerSchema } from "./sql-schema.js";
22
+ import { ensureBrokerSchema, withBrokerSchemaCatalog } from "./sql-schema.js";
23
23
 
24
24
  type AskRow = SqliteRow & { sender_session_id: string; target_session_id: string; message_id: string };
25
25
 
@@ -49,12 +49,23 @@ function invalidRoute(route: ReplyRoute): InvalidStateInput | undefined {
49
49
  }
50
50
 
51
51
  /** S3: `PendingAskStore` on the shared storage adapter's database, table `<prefix>intercom_pending_asks`. */
52
- export async function openSqlPendingAskStore({
52
+ export function openSqlPendingAskStore(options: IntercomBrokerStateOptions): Promise<PendingAskStore> {
53
+ // Its schema checks answer from one read of the catalog, shared with an open around it: a current schema costs
54
+ // no transaction and no lock, also when the store is opened on its own (#6560).
55
+ return withBrokerSchemaCatalog(options.database, options.prefix, () => openPendingAskStoreInCatalog(options));
56
+ }
57
+
58
+ async function openPendingAskStoreInCatalog({
53
59
  database,
54
60
  prefix,
55
61
  }: IntercomBrokerStateOptions): Promise<PendingAskStore> {
56
62
  const table = `${validateStoragePrefix(prefix, dialectOf(database).name)}intercom_pending_asks`;
57
63
  const { types, nowMs, greatest } = dialectOf(database);
64
+ /**
65
+ * Its transactions read and write this table and the settled asks alone, which no other store touches, so they
66
+ * exclude one another, not every writer of the database (#6560).
67
+ */
68
+ const serial = { concurrency: { kind: "serial", domain: table } } as const;
58
69
  await ensureBrokerSchema(database, prefix, "pending-asks", (tx) =>
59
70
  tx.exec(`
60
71
  CREATE TABLE IF NOT EXISTS ${table}(
@@ -112,7 +123,7 @@ export async function openSqlPendingAskStore({
112
123
  ...params,
113
124
  );
114
125
  return changes === 0 ? ({ status: "duplicate" } as const) : ({ status: "recorded" } as const);
115
- });
126
+ }, serial);
116
127
  },
117
128
  async matchesReply(route): Promise<PendingAskMatchResult> {
118
129
  const bad = invalidRoute(route);
@@ -132,7 +143,7 @@ export async function openSqlPendingAskStore({
132
143
  );
133
144
  await tx.run(`DELETE FROM ${settled} WHERE settled_at < ${nowMs} - ?`, SETTLED_ASK_RETENTION_MS);
134
145
  return changes === 0 ? ({ status: "no-match" } as const) : ({ status: "cleared" } as const);
135
- });
146
+ }, serial);
136
147
  },
137
148
  async isSettled(route): Promise<boolean> {
138
149
  if (invalidRoute(route) !== undefined) return false;
@@ -177,7 +188,7 @@ export async function openSqlPendingAskStore({
177
188
  );
178
189
  await tx.run(`DELETE FROM ${table} WHERE target_session_id = ?`, targetSessionId);
179
190
  return taken;
180
- });
191
+ }, serial);
181
192
  return { status: "taken", asks: rows.map(toAsk) };
182
193
  },
183
194
  async listForTarget(targetSessionId): Promise<PendingAskListResult> {
@@ -220,7 +231,7 @@ export async function openSqlPendingAskStore({
220
231
  ...parked.params,
221
232
  );
222
233
  return found;
223
- });
234
+ }, serial);
224
235
  return {
225
236
  status: "rebound",
226
237
  asks: rows.map((row) => ({
@@ -241,7 +252,7 @@ export async function openSqlPendingAskStore({
241
252
  );
242
253
  await tx.run(`DELETE FROM ${table} WHERE ${parked.where}`, ...parked.params);
243
254
  return taken;
244
- });
255
+ }, serial);
245
256
  return { status: "taken", asks: rows.map(toAsk) };
246
257
  },
247
258
  async listParked(ownerSessionId, reservationKey): Promise<PendingAskListResult> {
@@ -292,7 +303,7 @@ export async function openSqlPendingAskStore({
292
303
  if (Number(changes) === 1) marked.push(row);
293
304
  }
294
305
  return marked;
295
- });
306
+ }, serial);
296
307
  return { status: "listed", asks: rows.map(toAsk) };
297
308
  },
298
309
  async unmarkEnded(route): Promise<PendingAskMarkResult> {
@@ -318,7 +329,7 @@ export async function openSqlPendingAskStore({
318
329
  WHERE ${where} AND replied IS NULL AND ended_at IS NOT NULL ORDER BY "order"`,
319
330
  ...params,
320
331
  );
321
- });
332
+ }, serial);
322
333
  return { status: "listed", asks: rows.map(toAsk) };
323
334
  }
324
335
  }