@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,8 +1,13 @@
1
+ import * as storage from "@bastani/atomic/storage";
1
2
  import {
2
3
  dialectOf,
4
+ fencedPath,
5
+ type SqliteDatabase,
3
6
  type SqliteExecutor,
4
7
  type SqliteRow,
8
+ type SqliteRunResult,
5
9
  type StorageDialect,
10
+ storageMigrationTable,
6
11
  validateStoragePrefix,
7
12
  } from "@bastani/atomic/storage";
8
13
  import type {
@@ -17,20 +22,205 @@ import type {
17
22
  LeaseSubject,
18
23
  StateStoreInvalidReason,
19
24
  } from "./multinode-state-store.js";
20
- import { ensureBrokerSchema } from "./sql-schema.js";
25
+ import { isMissingPrivilege } from "./sql-add-column.js";
26
+ import { recipientTransaction } from "./sql-outbox-store.js";
27
+ import { ensureBrokerSchema, openCatalogOf, withBrokerSchemaCatalog } from "./sql-schema.js";
21
28
 
22
29
  /** Store-clock milliseconds since the lease was renewed, never negative. */
23
30
  const age = ({ greatest, nowMs }: StorageDialect) => greatest("0", `${nowMs} - renewed_at`);
24
31
 
25
32
  /**
26
- * A read of the live leases of one kind, oldest first, that reads the clock once: PostgreSQL's moves on between two
27
- * readings, and a lease it found within the stale bound would otherwise report an age past it.
33
+ * `ensureTableFillfactor` of the storage API, which an Atomic installation older than #6560 lacks: taken from the module
34
+ * namespace, so the lease table keeps its default fillfactor there.
28
35
  */
29
- const liveLeases = (dialect: StorageDialect, table: string) =>
36
+ const fillfactorApi: Partial<Pick<typeof storage, "ensureTableFillfactor">> = storage;
37
+
38
+ /**
39
+ * The fillfactor of the lease table on PostgreSQL: a fifth of each page stays free, so a renewal's new row version
40
+ * fits on its page and stays a HOT update (#6560).
41
+ */
42
+ const LEASE_FILLFACTOR = 80;
43
+
44
+ /**
45
+ * The kind of the row whose `last_token` counts acquisitions on PostgreSQL where the order sequence is missing: see
46
+ * `nextOrder`.
47
+ */
48
+ const ACQUISITION_ORDER_KIND = "acquisition-order";
49
+
50
+ /**
51
+ * Creates the sequence first acquisitions take their order from on PostgreSQL, `<table>_order`, once per database
52
+ * (recorded as the `intercom-lease-order` schema step), starting past every order taken so far, the counter row's
53
+ * included. False where it is missing and this role may not create it: a runtime role on a database `atomic storage
54
+ * migrate` has not upgraded yet keeps the counter row (#6560).
55
+ */
56
+ async function ensureOrderSequence(
57
+ database: SqliteDatabase,
58
+ prefix: string | undefined,
59
+ table: string,
60
+ ): Promise<boolean> {
61
+ try {
62
+ await ensureBrokerSchema(database, prefix, "lease-order", async (tx) => {
63
+ await tx.exec(`CREATE SEQUENCE IF NOT EXISTS ${table}_order AS BIGINT`);
64
+ await tx.get(
65
+ `SELECT setval('${table}_order', GREATEST(
66
+ (SELECT COALESCE(MAX(first_acquired_order), 0) FROM ${table}),
67
+ (SELECT COALESCE(MAX(last_token), 0) FROM ${table} WHERE kind = '${ACQUISITION_ORDER_KIND}'),
68
+ 1
69
+ ))`,
70
+ );
71
+ });
72
+ return true;
73
+ } catch (error) {
74
+ if (isMissingPrivilege(error)) return false;
75
+ throw error;
76
+ }
77
+ }
78
+
79
+ /**
80
+ * The columns `listLiveFor` finds a send's presences by, each generated by the database from the row's key and subject,
81
+ * so the rows every broker writes, an older one's included, carry them, and each indexed (#6560). `presence_name` is
82
+ * `=` and the name in lower case when the name is ASCII, and `*` for a row the lookup reads for every target: a name
83
+ * that is not ASCII (only the JavaScript lower case a send's resolution compares is exact for it), several aliases, or
84
+ * a subject the database cannot read exactly. Every column is null on a row that is not a presence.
85
+ */
86
+ const ADDRESS_COLUMNS = ["presence_id", "presence_id_head", "presence_name", "presence_host", "presence_alias"] as const;
87
+
88
+ type AddressColumn = (typeof ADDRESS_COLUMNS)[number];
89
+
90
+ /**
91
+ * The expressions of the address columns. A subject or key is read only where its JSON text has no escape of NUL or of
92
+ * half a surrogate pair (`\ud800` to `\udfff`): PostgreSQL's `json` refuses to turn those into text, so a row an earlier
93
+ * broker wrote with one would fail every write of it and the columns' addition; on SQLite they read as bytes no target
94
+ * binds as. Such a row is marked `*`, read for every target (#6560). On SQLite a subject is read only where it is valid
95
+ * JSON. On PostgreSQL the columns are stored: a renewal that leaves their values as they were changes no indexed value,
96
+ * so it stays a HOT update.
97
+ */
98
+ function addressExpressions(dialect: StorageDialect): Record<AddressColumn, string> {
99
+ const returnPrefix = `'["return",'`;
100
+ if (dialect.name === "postgres") {
101
+ const subject = "subject_json::json";
102
+ /** Whether the column's JSON text holds an escape no `json` value can turn into text: NUL or half a surrogate pair. */
103
+ const escaped = (column: string) => `${column} ~ (chr(92) || chr(92) || 'u(0000|[dD][89a-fA-F])')`;
104
+ const readable = `kind = 'presence' AND subject_json IS NOT NULL AND NOT ${escaped("subject_json")}`;
105
+ const id = `(${subject} #>> '{session,id}')`;
106
+ const name = `(${subject} #>> '{session,name}')`;
107
+ const aliases = `(${subject} -> 'aliases')`;
108
+ const aliasCount = `CASE WHEN json_typeof(${aliases}) = 'array' THEN json_array_length(${aliases}) END`;
109
+ return {
110
+ presence_id: `CASE WHEN ${readable} THEN ${id} END`,
111
+ presence_id_head: `CASE WHEN ${readable} THEN lower(left(${id}, 8)) END`,
112
+ presence_name: `CASE WHEN kind <> 'presence' OR subject_json IS NULL THEN NULL
113
+ WHEN ${escaped("subject_json")} OR ${escaped("key")} THEN '*'
114
+ WHEN ${aliasCount} > 1 THEN '*'
115
+ WHEN ${name} IS NULL THEN NULL
116
+ WHEN ${name} ~ ('[^' || chr(1) || '-' || chr(127) || ']') THEN '*'
117
+ ELSE '=' || translate(${name}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') END`,
118
+ presence_host: `CASE WHEN kind = 'presence' AND left(key, 10) = ${returnPrefix} AND NOT ${escaped("key")}
119
+ THEN key::json ->> 1 END`,
120
+ presence_alias: `CASE WHEN ${readable} AND ${aliasCount} = 1 THEN ${subject} #>> '{aliases,0,id}' END`,
121
+ };
122
+ }
123
+ /**
124
+ * Whether the column's JSON text holds an escape of NUL or of half a surrogate pair, which SQLite reads into bytes no
125
+ * send's target binds as: such a row is read for every target, as on PostgreSQL.
126
+ */
127
+ const escaped = (column: string) =>
128
+ `(${column} GLOB '*\\u0000*' OR ${column} GLOB '*\\u[dD][89a-fA-F]*')`;
129
+ const readable = `kind = 'presence' AND json_valid(subject_json) AND NOT ${escaped("subject_json")}`;
130
+ const id = "json_extract(subject_json, '$.session.id')";
131
+ const name = "json_extract(subject_json, '$.session.name')";
132
+ const aliasCount =
133
+ "CASE WHEN json_type(subject_json, '$.aliases') = 'array' THEN json_array_length(subject_json, '$.aliases') END";
134
+ return {
135
+ presence_id: `CASE WHEN ${readable} THEN ${id} END`,
136
+ presence_id_head: `CASE WHEN ${readable} THEN lower(substr(${id}, 1, 8)) END`,
137
+ // A name with a character past ASCII, or a NUL, has more bytes than characters.
138
+ presence_name: `CASE WHEN kind <> 'presence' OR subject_json IS NULL THEN NULL
139
+ WHEN NOT json_valid(subject_json) OR ${escaped("subject_json")} OR ${escaped("key")} THEN '*'
140
+ WHEN ${aliasCount} > 1 THEN '*'
141
+ WHEN ${name} IS NULL THEN NULL
142
+ WHEN length(CAST(${name} AS BLOB)) <> length(${name}) THEN '*'
143
+ ELSE '=' || lower(${name}) END`,
144
+ presence_host: `CASE WHEN kind = 'presence' AND substr(key, 1, 10) = ${returnPrefix} AND json_valid(key)
145
+ AND NOT ${escaped("key")} THEN json_extract(key, '$[1]') END`,
146
+ presence_alias: `CASE WHEN ${readable} AND ${aliasCount} = 1 THEN json_extract(subject_json, '$.aliases[0].id') END`,
147
+ };
148
+ }
149
+
150
+ /**
151
+ * Adds the address columns and their indexes, once per database (recorded as the `intercom-lease-addresses` schema
152
+ * step). False where they are missing and this role may not add them: `listLiveFor` is then absent until `atomic
153
+ * storage migrate` adds them (#6560).
154
+ */
155
+ async function ensureAddressColumns(database: SqliteDatabase, prefix: string | undefined, table: string): Promise<boolean> {
156
+ const dialect = dialectOf(database);
157
+ const expressions = addressExpressions(dialect);
158
+ const indexes = ADDRESS_COLUMNS.map(
159
+ (column) => `CREATE INDEX IF NOT EXISTS ${table}_${column} ON ${table}(${column})`,
160
+ ).join(";\n");
161
+ // On SQLite, which records no step, the catalog an open read finds the columns and their indexes, so a current
162
+ // table costs no write transaction (#6560).
163
+ const catalog = dialect.versionedMigrations ? undefined : await openCatalogOf(database);
164
+ if (
165
+ catalog?.sqliteObjectType !== undefined &&
166
+ ADDRESS_COLUMNS.every(
167
+ (column) => catalog.hasColumn(table, column) && catalog.sqliteObjectType?.(`${table}_${column}`) === "index",
168
+ )
169
+ )
170
+ return true;
171
+ try {
172
+ await ensureBrokerSchema(database, prefix, "lease-addresses", async (tx) => {
173
+ if (dialect.name === "postgres") {
174
+ // One statement, so the table is rewritten once.
175
+ await tx.exec(
176
+ `ALTER TABLE ${table} ${ADDRESS_COLUMNS.map(
177
+ (column) =>
178
+ `ADD COLUMN IF NOT EXISTS ${column} TEXT GENERATED ALWAYS AS (${expressions[column]}) STORED`,
179
+ ).join(", ")};\n${indexes}`,
180
+ );
181
+ return;
182
+ }
183
+ // SQLite runs this on every open: `pragma_table_xinfo` lists generated columns, which `pragma_table_info` hides.
184
+ const present = new Set(
185
+ (
186
+ await tx.all<SqliteRow & { name: string }>("SELECT name FROM pragma_table_xinfo(?)", table)
187
+ ).map((row) => row.name),
188
+ );
189
+ for (const column of ADDRESS_COLUMNS)
190
+ if (!present.has(column))
191
+ await tx.exec(
192
+ `ALTER TABLE ${table} ADD COLUMN ${column} TEXT GENERATED ALWAYS AS (${expressions[column]}) VIRTUAL`,
193
+ );
194
+ await tx.exec(indexes);
195
+ });
196
+ return true;
197
+ } catch (error) {
198
+ if (isMissingPrivilege(error)) return false;
199
+ throw error;
200
+ }
201
+ }
202
+
203
+ /**
204
+ * `presence_name`'s value for the names a send to `target` compares (`target` and its trimmed form, in lower case), or
205
+ * null for one that is not ASCII, which only rows marked `*` can match.
206
+ */
207
+ function nameKey(target: string): string | null {
208
+ const lower = target.toLowerCase();
209
+ return /^[\x01-\x7f]*$/.test(lower) ? `=${lower}` : null;
210
+ }
211
+
212
+ /**
213
+ * A read of the held leases of one kind whose age compares to the bound as `comparison` does, oldest first, that reads
214
+ * the clock once: PostgreSQL's moves on between two readings, and a lease it found within the stale bound would
215
+ * otherwise report an age past it.
216
+ */
217
+ const leasesByAge = (dialect: StorageDialect, table: string, comparison: "<=" | ">=") =>
30
218
  `WITH clock AS (SELECT ${dialect.nowMs} AS now)
31
219
  SELECT kind, key, holder_id, fencing_token, subject_json, ${dialect.greatest("0", "(SELECT now FROM clock) - renewed_at")} AS age_ms
32
220
  FROM ${table} WHERE kind = ? AND holder_id IS NOT NULL
33
- AND ${dialect.greatest("0", "(SELECT now FROM clock) - renewed_at")} <= ? ORDER BY first_acquired_order`;
221
+ AND ${dialect.greatest("0", "(SELECT now FROM clock) - renewed_at")} ${comparison} ? ORDER BY first_acquired_order, key`;
222
+
223
+ const liveLeases = (dialect: StorageDialect, table: string) => leasesByAge(dialect, table, "<=");
34
224
 
35
225
  type HolderRow = SqliteRow & {
36
226
  holder_id: string | null;
@@ -48,6 +238,8 @@ type StateRow = SqliteRow & {
48
238
  age_ms: number | bigint;
49
239
  };
50
240
 
241
+ const compare = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
242
+
51
243
  const invalid = (reason: StateStoreInvalidReason): InvalidStateInput => ({ status: "invalid", reason });
52
244
 
53
245
  function keyOf(subject: LeaseSubject): LeaseKey {
@@ -69,8 +261,23 @@ function invalidKey(key: LeaseKey): InvalidStateInput | undefined {
69
261
  return invalid(key.kind === "broker" ? "empty-broker-id" : "empty-target-identity");
70
262
  }
71
263
 
264
+ /**
265
+ * Every string well formed (#6560): half a surrogate pair, which a UTF-16 slice of a longer string leaves, becomes U+FFFD,
266
+ * as a UTF-8 encoder writes it. `JSON.stringify` would write it as a lone `\ud83d` escape, which PostgreSQL's `json`
267
+ * refuses to turn into text.
268
+ */
269
+ function wellFormed(_key: string, value: unknown): unknown {
270
+ return typeof value === "string" ? value.toWellFormed() : value;
271
+ }
272
+
273
+ /** A subject as the lease table stores it, with every string well formed. */
274
+ function subjectJson(subject: LeaseSubject): string {
275
+ return JSON.stringify(subject, wellFormed);
276
+ }
277
+
72
278
  function stateFromRow(row: StateRow): LeaseState {
73
- const subject: LeaseSubject = JSON.parse(row.subject_json);
279
+ // A row an earlier broker wrote may hold half a surrogate pair: it reads as a stored one would.
280
+ const subject: LeaseSubject = JSON.parse(row.subject_json, wellFormed);
74
281
  return {
75
282
  key: keyFor(row.kind === "broker" ? "broker" : "presence", row.key),
76
283
  holderId: row.holder_id,
@@ -101,7 +308,13 @@ export async function readLiveBrokerNodes(
101
308
  }
102
309
 
103
310
  /** Opens the S1 lease store on the shared database's `<prefix>intercom_leases` table; the database stays open. */
104
- export async function openSqlBrokerLeaseStore(options: IntercomBrokerStateOptions): Promise<BrokerLeaseStore> {
311
+ export function openSqlBrokerLeaseStore(options: IntercomBrokerStateOptions): Promise<BrokerLeaseStore> {
312
+ // Its schema checks answer from one read of the catalog, shared with an open around it: a current schema costs
313
+ // no transaction and no lock, also when the store is opened on its own (#6560).
314
+ return withBrokerSchemaCatalog(options.database, options.prefix, () => openBrokerLeaseStoreInCatalog(options));
315
+ }
316
+
317
+ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions): Promise<BrokerLeaseStore> {
105
318
  const { database } = options;
106
319
  const table = `${validateStoragePrefix(options.prefix, dialectOf(database).name)}intercom_leases`;
107
320
  const dialect = dialectOf(database);
@@ -116,6 +329,16 @@ export async function openSqlBrokerLeaseStore(options: IntercomBrokerStateOption
116
329
  )
117
330
  `;
118
331
  await ensureBrokerSchema(database, options.prefix, "leases", (tx) => tx.exec(schema));
332
+ const orderSequence = `${table}_order`;
333
+ const sequenced = dialect.name === "postgres" && (await ensureOrderSequence(database, options.prefix, table));
334
+ const addressed = await ensureAddressColumns(database, options.prefix, table);
335
+ await fillfactorApi.ensureTableFillfactor?.(database, {
336
+ ledger: storageMigrationTable(options.prefix),
337
+ domain: "intercom-lease-fillfactor",
338
+ revision: 1,
339
+ table,
340
+ fillfactor: LEASE_FILLFACTOR,
341
+ });
119
342
 
120
343
  const holderOf = (executor: SqliteExecutor, key: LeaseKey) =>
121
344
  executor.get<HolderRow>(
@@ -131,6 +354,54 @@ export async function openSqlBrokerLeaseStore(options: IntercomBrokerStateOption
131
354
  invalidKey(lease.key) ?? (lease.holderId.length === 0 ? invalid("empty-holder-id") : undefined);
132
355
  const owned = `kind = ? AND key = ? AND holder_id = ? AND fencing_token = ?`;
133
356
  const ownedParams = (lease: Lease) => [lease.key.kind, keyId(lease.key), lease.holderId, lease.fencingToken];
357
+ /** In `acquire`'s upsert: the row is the acquiring holder's already. */
358
+ const mine = `${table}.holder_id = excluded.holder_id`;
359
+ /** In `acquire`'s upsert: the age of the row it found. */
360
+ const rowAge = dialect.greatest("0", `${nowMs} - ${table}.renewed_at`);
361
+ /**
362
+ * Every write decides on its own row in one guarded statement, so leases never wait for the database's serial lock,
363
+ * which a broker's renewals must not wait behind (#6560): see `fencedPath("intercom-lease")`.
364
+ */
365
+ const fenced = { concurrency: { kind: "fenced", audit: fencedPath("intercom-lease") } } as const;
366
+ /**
367
+ * The order of a key acquired for the first time. A serial database runs one acquisition at a time, so the
368
+ * largest order so far, plus one, is unique. PostgreSQL runs acquisitions beside one another, so each takes the
369
+ * next value of the order sequence, which no acquisition waits for (#6560). Where `atomic storage migrate` has not
370
+ * created it yet and this role may not, each takes the next value of a counter row, upserted by the statement
371
+ * itself, whose row lock orders them; the counter's kind is no lease's, so no lease query reads it.
372
+ */
373
+ const largestOrder = `(SELECT COALESCE(MAX(first_acquired_order), 0) FROM ${table})`;
374
+ const nextOrder = sequenced
375
+ ? { with: "", value: `nextval('${orderSequence}')` }
376
+ : dialect.name === "postgres"
377
+ ? {
378
+ with: `WITH next_order AS (
379
+ INSERT INTO ${table}(kind, key, last_token, first_acquired_order)
380
+ VALUES ('${ACQUISITION_ORDER_KIND}', '', ${largestOrder} + 1, 0)
381
+ ON CONFLICT(kind, key) DO UPDATE SET last_token = ${table}.last_token + 1
382
+ RETURNING last_token
383
+ ) `,
384
+ value: "(SELECT last_token FROM next_order)",
385
+ }
386
+ : { with: "", value: `${largestOrder} + 1` };
387
+ /** Latency-bound reads, which must not queue behind this database's writes (#6560). */
388
+ const reader = options.reader ?? database;
389
+ const clockAge = dialect.greatest("0", "(SELECT now FROM clock) - renewed_at");
390
+ /**
391
+ * `listLiveFor`'s read: each term is one indexed column's lookup, so SQLite takes the union of five index searches
392
+ * and PostgreSQL a bitmap OR of them. No `kind` term: on SQLite it would make the primary key's `kind` prefix, every
393
+ * presence, the search instead; the address columns are null on every other kind's rows.
394
+ */
395
+ const liveAddressed = `WITH clock AS (SELECT ${nowMs} AS now)
396
+ SELECT kind, key, holder_id, fencing_token, subject_json, ${clockAge} AS age_ms FROM ${table}
397
+ WHERE (presence_id IN (?, ?) OR presence_id_head = ? OR presence_name IN (?, ?, '*') OR presence_host = ?
398
+ OR presence_alias = ?)
399
+ AND holder_id IS NOT NULL AND ${clockAge} <= ? ORDER BY first_acquired_order, key`;
400
+
401
+ const listLive = async (kind: LeaseKind, staleAfterMs: number): Promise<LeaseState[]> => {
402
+ const rows = await reader.all<StateRow>(liveLeases(dialect, table), kind, staleAfterMs);
403
+ return rows.map(stateFromRow);
404
+ };
134
405
 
135
406
  return {
136
407
  async acquire(subject, holderId, staleAfterMs) {
@@ -138,50 +409,49 @@ export async function openSqlBrokerLeaseStore(options: IntercomBrokerStateOption
138
409
  const bad = invalidKey(key);
139
410
  if (bad !== undefined) return bad;
140
411
  if (holderId.length === 0) return invalid("empty-holder-id");
141
- const subjectJson = JSON.stringify(subject);
142
- return database.transaction(async (tx) => {
143
- const row = await holderOf(tx, key);
144
- if (row === undefined) {
145
- await tx.run(
146
- `INSERT INTO ${table}(kind, key, holder_id, fencing_token, last_token, subject_json, renewed_at,
147
- first_acquired_order)
148
- VALUES (?, ?, ?, 1, 1, ?, ${nowMs},
149
- (SELECT COALESCE(MAX(first_acquired_order), 0) + 1 FROM ${table}))`,
150
- key.kind,
151
- keyId(key),
152
- holderId,
153
- subjectJson,
154
- );
155
- return { status: "acquired", lease: { key, holderId, fencingToken: 1 } } as const;
156
- }
157
- if (row.holder_id === holderId) {
158
- await tx.run(
159
- `UPDATE ${table} SET subject_json = ?, renewed_at = ${nowMs} WHERE kind = ? AND key = ?`,
160
- subjectJson,
161
- key.kind,
162
- keyId(key),
163
- );
412
+ const stored = subjectJson(subject);
413
+ // #5607: a send that read the recipient's presence before this acquisition committed found it absent,
414
+ // free or stale, wrote no wake-up hint, and may still be writing its row. On PostgreSQL a presence
415
+ // acquisition therefore waits, once it committed, for every send to that recipient under way, holding the
416
+ // recipient's lock domain for an instant: the registration's first outbox scan, which follows, then finds
417
+ // their rows; a later send reads the live presence and wakes its holder (#6560).
418
+ const acquired = await database.transaction(async (tx) => {
419
+ // One guarded statement takes the lease: a new key, or a row that is free, stale or already this
420
+ // holder's; a steal gets the key's next token, a re-acquisition keeps its own. Renewals run beside it,
421
+ // so the decision is never made on an earlier read (#6560).
422
+ const taken = await tx.get<SqliteRow & { fencing_token: number | bigint }>(
423
+ `${nextOrder.with}INSERT INTO ${table}(kind, key, holder_id, fencing_token, last_token, subject_json,
424
+ renewed_at, first_acquired_order)
425
+ VALUES (?, ?, ?, 1, 1, ?, ${nowMs}, ${nextOrder.value})
426
+ ON CONFLICT(kind, key) DO UPDATE SET
427
+ fencing_token = CASE WHEN ${mine} THEN ${table}.fencing_token ELSE ${table}.last_token + 1 END,
428
+ last_token = CASE WHEN ${mine} THEN ${table}.last_token ELSE ${table}.last_token + 1 END,
429
+ holder_id = excluded.holder_id, subject_json = excluded.subject_json, renewed_at = excluded.renewed_at
430
+ WHERE ${table}.holder_id IS NULL OR ${mine} OR ${rowAge} > ?
431
+ RETURNING fencing_token`,
432
+ key.kind,
433
+ keyId(key),
434
+ holderId,
435
+ stored,
436
+ staleAfterMs,
437
+ );
438
+ if (taken !== undefined) {
164
439
  return {
165
440
  status: "acquired",
166
- lease: { key, holderId, fencingToken: Number(row.fencing_token) },
441
+ lease: { key, holderId, fencingToken: Number(taken.fencing_token) },
167
442
  } as const;
168
443
  }
169
- if (row.holder_id !== null && Number(row.age_ms) <= staleAfterMs) {
170
- return { status: "held", holderId: row.holder_id, fencingToken: Number(row.fencing_token) } as const;
171
- }
172
- const fencingToken = Number(row.last_token) + 1;
173
- await tx.run(
174
- `UPDATE ${table} SET holder_id = ?, fencing_token = ?, last_token = ?, subject_json = ?,
175
- renewed_at = ${nowMs} WHERE kind = ? AND key = ?`,
176
- holderId,
177
- fencingToken,
178
- fencingToken,
179
- subjectJson,
180
- key.kind,
181
- keyId(key),
444
+ // Held by another live holder. PostgreSQL locks the row whose guard failed until this transaction
445
+ // ends, so this reads the holder that refused it.
446
+ const row = (await holderOf(tx, key))!;
447
+ return { status: "held", holderId: row.holder_id!, fencingToken: Number(row.fencing_token) } as const;
448
+ }, fenced);
449
+ if (acquired.status === "acquired" && subject.kind === "presence" && dialect.name === "postgres")
450
+ await database.transaction(
451
+ async () => {},
452
+ recipientTransaction(database, options.prefix, subject.targetIdentity),
182
453
  );
183
- return { status: "acquired", lease: { key, holderId, fencingToken } } as const;
184
- });
454
+ return acquired;
185
455
  },
186
456
  async renew(lease, subject) {
187
457
  const bad = validLease(lease);
@@ -195,11 +465,11 @@ export async function openSqlBrokerLeaseStore(options: IntercomBrokerStateOption
195
465
  ? await tx.run(`UPDATE ${table} SET renewed_at = ${nowMs} WHERE ${owned}`, ...ownedParams(lease))
196
466
  : await tx.run(
197
467
  `UPDATE ${table} SET renewed_at = ${nowMs}, subject_json = ? WHERE ${owned}`,
198
- JSON.stringify(subject),
468
+ subjectJson(subject),
199
469
  ...ownedParams(lease),
200
470
  );
201
471
  return changes === 1 ? ({ status: "renewed" } as const) : stale(await holderOf(tx, lease.key));
202
- });
472
+ }, fenced);
203
473
  },
204
474
  async renewMany(requests) {
205
475
  if (requests.length === 0) return [];
@@ -220,21 +490,35 @@ export async function openSqlBrokerLeaseStore(options: IntercomBrokerStateOption
220
490
  }
221
491
  }
222
492
  if (validCount === 0) return results as LeaseRenewResult[];
493
+ // Rows locked in one order on every broker, so two renewals of overlapping leases never deadlock.
494
+ const order = requests
495
+ .map((request, index) => ({ index, kind: request.lease.key.kind, id: keyId(request.lease.key) }))
496
+ .filter(({ index }) => results[index] === undefined)
497
+ .sort((a, b) => compare(a.kind, b.kind) || compare(a.id, b.id))
498
+ .map(({ index }) => index);
223
499
  await database.transaction(async (tx) => {
224
- for (let i = 0; i < requests.length; i++) {
225
- if (results[i] !== undefined) continue;
500
+ // Every update is sent before any answer is awaited, in the lock order: a pipelined connection sends them
501
+ // in one round trip, and the server runs them in the order sent (#6560).
502
+ const renewals = order.map((i) => {
226
503
  const { lease, subject } = requests[i]!;
227
- const { changes } =
228
- subject === undefined
229
- ? await tx.run(`UPDATE ${table} SET renewed_at = ${nowMs} WHERE ${owned}`, ...ownedParams(lease))
230
- : await tx.run(
231
- `UPDATE ${table} SET renewed_at = ${nowMs}, subject_json = ? WHERE ${owned}`,
232
- JSON.stringify(subject),
233
- ...ownedParams(lease),
234
- );
235
- results[i] = changes === 1 ? ({ status: "renewed" } as const) : stale(await holderOf(tx, lease.key));
236
- }
237
- });
504
+ return subject === undefined
505
+ ? tx.run(`UPDATE ${table} SET renewed_at = ${nowMs} WHERE ${owned}`, ...ownedParams(lease))
506
+ : tx.run(
507
+ `UPDATE ${table} SET renewed_at = ${nowMs}, subject_json = ? WHERE ${owned}`,
508
+ subjectJson(subject),
509
+ ...ownedParams(lease),
510
+ );
511
+ });
512
+ const settled = await Promise.allSettled(renewals);
513
+ const failed = settled.find((outcome) => outcome.status === "rejected");
514
+ if (failed !== undefined) throw failed.reason;
515
+ const renewed = settled.map((outcome) => (outcome as PromiseFulfilledResult<SqliteRunResult>).value);
516
+ for (const [position, i] of order.entries())
517
+ results[i] =
518
+ renewed[position]!.changes === 1
519
+ ? ({ status: "renewed" } as const)
520
+ : stale(await holderOf(tx, requests[i]!.lease.key));
521
+ }, fenced);
238
522
  return results as LeaseRenewResult[];
239
523
  },
240
524
  async release(lease) {
@@ -247,12 +531,12 @@ export async function openSqlBrokerLeaseStore(options: IntercomBrokerStateOption
247
531
  ...ownedParams(lease),
248
532
  );
249
533
  return changes === 1 ? ({ status: "released" } as const) : stale(await holderOf(tx, lease.key));
250
- });
534
+ }, fenced);
251
535
  },
252
536
  async read(key) {
253
537
  const bad = invalidKey(key);
254
538
  if (bad !== undefined) return bad;
255
- const row = await database.get<StateRow>(
539
+ const row = await reader.get<StateRow>(
256
540
  `SELECT kind, key, holder_id, fencing_token, subject_json, ${leaseAge} AS age_ms FROM ${table}
257
541
  WHERE kind = ? AND key = ? AND holder_id IS NOT NULL`,
258
542
  key.kind,
@@ -260,8 +544,34 @@ export async function openSqlBrokerLeaseStore(options: IntercomBrokerStateOption
260
544
  );
261
545
  return row === undefined ? { status: "missing" } : { status: "found", lease: stateFromRow(row) };
262
546
  },
263
- async listLive(kind, staleAfterMs) {
264
- const rows = await database.all<StateRow>(liveLeases(dialect, table), kind, staleAfterMs);
547
+ listLive,
548
+ ...(addressed
549
+ ? {
550
+ async listLiveFor(named: string, staleAfterMs: number) {
551
+ // No statement may carry a NUL character: such a target, which no index can look up, reads every
552
+ // presence, as before.
553
+ if (named.includes("\u0000")) return listLive("presence", staleAfterMs);
554
+ // Its strings as the stored subjects' are, every one well formed, on every backend (#6560).
555
+ const target = named.toWellFormed();
556
+ const trimmed = target.trim();
557
+ const head = /^[0-9a-f]{8}$/i.test(trimmed) ? trimmed.toLowerCase() : null;
558
+ const rows = await reader.all<StateRow>(
559
+ liveAddressed,
560
+ target,
561
+ trimmed,
562
+ head,
563
+ nameKey(target),
564
+ nameKey(trimmed),
565
+ trimmed,
566
+ target,
567
+ staleAfterMs,
568
+ );
569
+ return rows.map(stateFromRow);
570
+ },
571
+ }
572
+ : {}),
573
+ async listAged(kind, minAgeMs) {
574
+ const rows = await reader.all<StateRow>(leasesByAge(dialect, table, ">="), kind, minAgeMs);
265
575
  return rows.map(stateFromRow);
266
576
  },
267
577
  async retireHolder(holderId) {