@bastani/atomic 0.10.10 → 0.10.11-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (402) hide show
  1. package/CHANGELOG.md +139 -0
  2. package/README.md +1 -1
  3. package/dist/_shared/dist-KOELCESV.js +2 -2
  4. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  5. package/dist/_shared/lib-4PES5P4V.js +2 -2
  6. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +11 -13
  7. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js.map +1 -1
  8. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +9 -9
  9. package/dist/_shared/mode-shared-2QJSCUM6.js +55 -18
  10. package/dist/_shared/mode-shared-2QJSCUM6.js.map +1 -1
  11. package/dist/_shared/p1a-prewarm-XIU57JHF.js +3 -3
  12. package/dist/_shared/runtime-O4KCSG4C.js +5 -5
  13. package/dist/_shared/{sdk-RRLVN7ER.js → sdk-IQMULKFU.js} +2962 -470
  14. package/dist/_shared/sdk-IQMULKFU.js.map +1 -0
  15. package/dist/_shared/session-data-AHTU7IS6.js +4 -4
  16. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  17. package/dist/_shared/settings-startup-8-DNZ2RIHM.js +1 -1
  18. package/dist/_shared/{settings-startup-4QCVCI53.js → settings-startup-HXQLSUWM.js} +8 -2
  19. package/dist/_shared/settings-startup-HXQLSUWM.js.map +1 -0
  20. package/dist/_shared/{startup-0-0-4VG2G44V.js → startup-0-0-3IXNMFM2.js} +482 -53
  21. package/dist/_shared/startup-0-0-3IXNMFM2.js.map +1 -0
  22. package/dist/_shared/{startup-0-1-XTIL65D4.js → startup-0-1-7T2IAE7J.js} +121 -251
  23. package/dist/_shared/startup-0-1-7T2IAE7J.js.map +1 -0
  24. package/dist/_shared/{startup-0-2-27OWFHV6.js → startup-0-2-5QHPCEON.js} +293 -10
  25. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -0
  26. package/dist/_shared/{startup-0-3-T4DVFYWX.js → startup-0-3-4ZYBYQNM.js} +273 -14
  27. package/dist/_shared/startup-0-3-4ZYBYQNM.js.map +1 -0
  28. package/dist/_shared/startup-0-4-ZMJV547D.js +6 -6
  29. package/dist/_shared/{startup-0-5-FD2P735I.js → startup-0-5-YDW47QX6.js} +29 -71
  30. package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -0
  31. package/dist/_shared/startup-10-0-TDQNBDDL.js +9 -9
  32. package/dist/_shared/startup-12-0-55AAXBJZ.js +4 -4
  33. package/dist/_shared/startup-14-0-MLX36RBG.js +6 -6
  34. package/dist/_shared/startup-15-0-YUKGAC63.js +34 -10
  35. package/dist/_shared/startup-15-0-YUKGAC63.js.map +1 -1
  36. package/dist/_shared/startup-15-1-4S7FLMNG.js +10 -9
  37. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  38. package/dist/_shared/startup-8-0-34CBHPZH.js +421 -84
  39. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  40. package/dist/_shared/{startup-8-1-4KANEHRA.js → startup-8-1-X32CYSXB.js} +1291 -722
  41. package/dist/_shared/startup-8-1-X32CYSXB.js.map +1 -0
  42. package/dist/_shared/storage-command-7MGXLJGZ.js +17 -9
  43. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  44. package/dist/_shared/task-reference-stream-JWMUZSJX.js +1 -1
  45. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  46. package/dist/_shared/tree-outline-MUEPK5B7.js +3 -3
  47. package/dist/builtin/intercom/CHANGELOG.md +29 -0
  48. package/dist/builtin/intercom/broker/broker.bundle.mjs +1138 -384
  49. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +103 -24
  50. package/dist/builtin/intercom/broker/multinode-router.ts +42 -21
  51. package/dist/builtin/intercom/broker/multinode-state-store.ts +22 -1
  52. package/dist/builtin/intercom/broker/open-broker-state.ts +82 -31
  53. package/dist/builtin/intercom/broker/paths.ts +8 -4
  54. package/dist/builtin/intercom/broker/released-asker-remote-replies.ts +18 -6
  55. package/dist/builtin/intercom/broker/sql-add-column.ts +4 -1
  56. package/dist/builtin/intercom/broker/sql-ended-child-queue-store.ts +65 -44
  57. package/dist/builtin/intercom/broker/sql-held-send-store.ts +11 -3
  58. package/dist/builtin/intercom/broker/sql-known-session-store.ts +24 -12
  59. package/dist/builtin/intercom/broker/sql-lease-store.ts +386 -65
  60. package/dist/builtin/intercom/broker/sql-outbox-store.ts +462 -130
  61. package/dist/builtin/intercom/broker/sql-pending-ask-store.ts +20 -9
  62. package/dist/builtin/intercom/broker/sql-released-ask-store.ts +14 -6
  63. package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +27 -11
  64. package/dist/builtin/intercom/broker/sql-schema.ts +198 -5
  65. package/dist/builtin/intercom/broker/sql-sent-message-authority.ts +97 -34
  66. package/dist/builtin/intercom/index.bundle.mjs +11 -8
  67. package/dist/builtin/intercom/package.json +1 -1
  68. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  69. package/dist/builtin/mcp/package.json +1 -1
  70. package/dist/builtin/subagents/CHANGELOG.md +18 -0
  71. package/dist/builtin/subagents/package.json +1 -1
  72. package/dist/builtin/subagents/skills/skill-creator/SKILL.md +1 -1
  73. package/dist/builtin/subagents/src/extension/index.bundle.mjs +62 -23
  74. package/dist/builtin/web-access/index.bundle.mjs +1 -1
  75. package/dist/builtin/web-access/package.json +1 -1
  76. package/dist/cli/args.js +2 -2
  77. package/dist/cli/auth-cli.code.js +6 -6
  78. package/dist/cli/auth-cli.impl.js +3 -3
  79. package/dist/cli/auth-cli.js +3 -3
  80. package/dist/cli/blueprint-command.code.js +4 -4
  81. package/dist/cli/blueprint-command.impl.js +3 -3
  82. package/dist/cli/blueprint-command.js +3 -3
  83. package/dist/cli/intercom-command.code.js +3 -3
  84. package/dist/cli/intercom-command.impl.js +3 -3
  85. package/dist/cli/intercom-command.js +3 -3
  86. package/dist/cli/list-models.code.js +2 -2
  87. package/dist/cli/list-models.impl.js +3 -3
  88. package/dist/cli/list-models.js +3 -3
  89. package/dist/cli/session-picker.code.js +2 -2
  90. package/dist/cli/session-picker.impl.js +3 -3
  91. package/dist/cli/session-picker.js +3 -3
  92. package/dist/cli/startup-ui.code.js +2 -2
  93. package/dist/cli/startup-ui.impl.js +3 -3
  94. package/dist/cli/startup-ui.js +3 -3
  95. package/dist/cli/storage-command.impl.js +3 -3
  96. package/dist/cli/storage-command.js +3 -3
  97. package/dist/cli/storage-search-session.code.js +3 -3
  98. package/dist/cli/storage-search-session.impl.js +3 -3
  99. package/dist/cli/storage-search-session.js +3 -3
  100. package/dist/cli/team-command.code.js +3 -3
  101. package/dist/cli/team-command.impl.js +3 -3
  102. package/dist/cli/team-command.js +3 -3
  103. package/dist/cli.js +2 -2
  104. package/dist/core/agent-session-methods.d.ts +3 -0
  105. package/dist/core/agent-session-methods.js.map +1 -1
  106. package/dist/core/agent-session.d.ts +1 -0
  107. package/dist/core/compaction/compactor.d.ts +2 -0
  108. package/dist/core/debug.impl.js +3 -3
  109. package/dist/core/debug.js +3 -3
  110. package/dist/core/export-html/card-projection.code.js +1 -1
  111. package/dist/core/export-html/card-projection.impl.js +3 -3
  112. package/dist/core/export-html/card-projection.js +3 -3
  113. package/dist/core/export-html/index.code.js +2 -2
  114. package/dist/core/export-html/index.impl.js +3 -3
  115. package/dist/core/export-html/index.js +3 -3
  116. package/dist/core/export-html/json-spans.impl.js +3 -3
  117. package/dist/core/export-html/json-spans.js +3 -3
  118. package/dist/core/export-html/oversized-render-inputs.code.js +2 -2
  119. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  120. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  121. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  122. package/dist/core/export-html/tool-renderer.js +3 -3
  123. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  124. package/dist/core/extensions/jiti-loader.js +3 -3
  125. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  126. package/dist/core/extensions/jiti-static-loader.js +3 -3
  127. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  128. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  129. package/dist/core/extensions/loader-host-modules.js +3 -3
  130. package/dist/core/extensions/loader-virtual-modules.js +2 -2
  131. package/dist/core/extensions/runner-context.js +4 -4
  132. package/dist/core/extensions/runner-context.js.map +1 -1
  133. package/dist/core/intercom-broker-control-host.code.js +1 -1
  134. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  135. package/dist/core/intercom-broker-control-host.js +3 -3
  136. package/dist/core/intercom-broker-control.code.js +3 -3
  137. package/dist/core/intercom-broker-control.impl.js +3 -3
  138. package/dist/core/intercom-broker-control.js +3 -3
  139. package/dist/core/model-registry.js +1 -1
  140. package/dist/core/model-resolver-defaults.d.ts +3 -2
  141. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  142. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  143. package/dist/core/package-manager-storage-adapters.js +3 -3
  144. package/dist/core/sdk.code.js +4 -5
  145. package/dist/core/sdk.impl.js +3 -3
  146. package/dist/core/sdk.js +3 -3
  147. package/dist/core/session-manager-core.d.ts +5 -2
  148. package/dist/core/session-manager-core.js +39 -23
  149. package/dist/core/session-manager-core.js.map +1 -1
  150. package/dist/core/session-manager-list.impl.js +3 -3
  151. package/dist/core/session-manager-list.js +3 -3
  152. package/dist/core/session-manager.code.js +3 -3
  153. package/dist/core/session-manager.impl.js +3 -3
  154. package/dist/core/session-manager.js +3 -3
  155. package/dist/core/session-open-markers.js +3 -0
  156. package/dist/core/session-open-markers.js.map +1 -0
  157. package/dist/core/session-storage.code.js +1 -1
  158. package/dist/core/session-storage.impl.js +3 -3
  159. package/dist/core/session-storage.js +3 -3
  160. package/dist/core/storage/added-exports.d.ts +6 -0
  161. package/dist/core/storage/added-exports.js +19 -0
  162. package/dist/core/storage/added-exports.js.map +1 -0
  163. package/dist/core/storage/database.d.ts +53 -0
  164. package/dist/core/storage/database.js.map +1 -1
  165. package/dist/core/storage/fenced-paths.d.ts +47 -0
  166. package/dist/core/storage/fenced-paths.js +53 -0
  167. package/dist/core/storage/fenced-paths.js.map +1 -1
  168. package/dist/core/storage/file-identity.js +31 -2
  169. package/dist/core/storage/file-identity.js.map +1 -1
  170. package/dist/core/storage/index.d.ts +4 -1
  171. package/dist/core/storage/index.js +5 -2
  172. package/dist/core/storage/index.js.map +1 -1
  173. package/dist/core/storage/migrations.d.ts +33 -2
  174. package/dist/core/storage/migrations.js +73 -5
  175. package/dist/core/storage/migrations.js.map +1 -1
  176. package/dist/core/storage/node-sqlite-thread.js +48 -6
  177. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  178. package/dist/core/storage/node-sqlite.js +137 -4
  179. package/dist/core/storage/node-sqlite.js.map +1 -1
  180. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  181. package/dist/core/storage/offline-snapshot-file.js +3 -3
  182. package/dist/core/storage/prefix.d.ts +3 -2
  183. package/dist/core/storage/prefix.js +23 -2
  184. package/dist/core/storage/prefix.js.map +1 -1
  185. package/dist/core/storage/provider.js +2 -2
  186. package/dist/core/storage/schema-catalog.d.ts +120 -0
  187. package/dist/core/storage/schema-catalog.js +351 -0
  188. package/dist/core/storage/schema-catalog.js.map +1 -0
  189. package/dist/core/storage/selection.js +2 -2
  190. package/dist/core/storage/session/branch-fork-source.code.js +47 -25
  191. package/dist/core/storage/session/branch-fork-source.code.js.map +1 -1
  192. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  193. package/dist/core/storage/session/branch-fork-source.js +3 -3
  194. package/dist/core/storage/session/card-view.impl.js +3 -3
  195. package/dist/core/storage/session/card-view.js +3 -3
  196. package/dist/core/storage/session/child-reader.code.js +4 -4
  197. package/dist/core/storage/session/child-reader.impl.js +3 -3
  198. package/dist/core/storage/session/child-reader.js +3 -3
  199. package/dist/core/storage/session/chunked-resume-projection.code.js +1 -1
  200. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  201. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  202. package/dist/core/storage/session/errors.js +1 -1
  203. package/dist/core/storage/session/expanded-child-details.code.js +4 -4
  204. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  205. package/dist/core/storage/session/expanded-child-details.js +3 -3
  206. package/dist/core/storage/session/fork-detach.d.ts +118 -0
  207. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  208. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  209. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  210. package/dist/core/storage/session/fork-row-index.js +3 -3
  211. package/dist/core/storage/session/fork-schema.js +53 -0
  212. package/dist/core/storage/session/fork-schema.js.map +1 -0
  213. package/dist/core/storage/session/fork-segments.d.ts +58 -0
  214. package/dist/core/storage/session/fork-staging.code.js +176 -36
  215. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  216. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  217. package/dist/core/storage/session/fork-staging.js +3 -3
  218. package/dist/core/storage/session/fork-sweep.js +61 -0
  219. package/dist/core/storage/session/fork-sweep.js.map +1 -0
  220. package/dist/core/storage/session/fork-window.code.js +4 -4
  221. package/dist/core/storage/session/fork-window.impl.js +3 -3
  222. package/dist/core/storage/session/fork-window.js +3 -3
  223. package/dist/core/storage/session/history-pages.impl.js +3 -3
  224. package/dist/core/storage/session/history-pages.js +3 -3
  225. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  226. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  227. package/dist/core/storage/session/jsonl-session-store.d.ts +37 -1
  228. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  229. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  230. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  231. package/dist/core/storage/session/memory-session-store.js +3 -3
  232. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  233. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  234. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  235. package/dist/core/storage/session/released-history-files.code.js +3 -3
  236. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  237. package/dist/core/storage/session/released-history-files.js +3 -3
  238. package/dist/core/storage/session/resident-fork-rows.code.js +1 -1
  239. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  240. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  241. package/dist/core/storage/session/session-resume.impl.js +3 -3
  242. package/dist/core/storage/session/session-resume.js +3 -3
  243. package/dist/core/storage/session/session-search-index.d.ts +5 -0
  244. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  245. package/dist/core/storage/session/snapshot-cut.js +3 -3
  246. package/dist/core/storage/session/snapshot-history.code.js +4 -4
  247. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  248. package/dist/core/storage/session/snapshot-history.js +3 -3
  249. package/dist/core/storage/session/sql-chat-records.d.ts +15 -0
  250. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  251. package/dist/core/storage/session/sql-session-store.d.ts +445 -11
  252. package/dist/core/storage/session/sql-session-store.impl.js +4 -4
  253. package/dist/core/storage/session/sql-session-store.js +4 -4
  254. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  255. package/dist/core/storage/session/tree-outline.js +3 -3
  256. package/dist/core/storage/session/tree-presentation.code.js +1 -1
  257. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  258. package/dist/core/storage/session/tree-presentation.js +3 -3
  259. package/dist/core/storage/session/types.d.ts +36 -0
  260. package/dist/core/storage/sqlite-facade.d.ts +54 -6
  261. package/dist/core/storage/sqlite-facade.js +384 -18
  262. package/dist/core/storage/sqlite-facade.js.map +1 -1
  263. package/dist/core/storage/statement-sequence.d.ts +83 -0
  264. package/dist/core/storage/statement-sequence.js +21 -0
  265. package/dist/core/storage/statement-sequence.js.map +1 -1
  266. package/dist/core/storage/storage-status.code.js +1 -1
  267. package/dist/core/storage/storage-status.impl.js +3 -3
  268. package/dist/core/storage/storage-status.js +3 -3
  269. package/dist/core/storage/team.code.js +1 -1
  270. package/dist/core/storage/team.impl.js +3 -3
  271. package/dist/core/storage/team.js +3 -3
  272. package/dist/core/structured-output/index.code.js +1 -1
  273. package/dist/core/structured-output/index.impl.js +3 -3
  274. package/dist/core/structured-output/index.js +3 -3
  275. package/dist/core/tasks/task-completion-entry.code.js +1 -1
  276. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  277. package/dist/core/tasks/task-completion-entry.js +3 -3
  278. package/dist/core/tasks/task-file-history.code.js +4 -4
  279. package/dist/core/tasks/task-file-history.impl.js +3 -3
  280. package/dist/core/tasks/task-file-history.js +3 -3
  281. package/dist/core/tasks/task-reference-archive.code.js +5 -5
  282. package/dist/core/tasks/task-reference-archive.js +3 -3
  283. package/dist/core/tasks/task-reference-identity.js +3 -3
  284. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  285. package/dist/core/tasks/task-reference-stream.js +3 -3
  286. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  287. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  288. package/dist/core/tasks/task-view-source.code.js +1 -1
  289. package/dist/core/tasks/task-view-source.impl.js +3 -3
  290. package/dist/core/tasks/task-view-source.js +3 -3
  291. package/dist/core/tools/bash.d.ts +8 -4
  292. package/dist/core/tools/history-session.d.ts +7 -0
  293. package/dist/core/tools/history-tasks.d.ts +123 -0
  294. package/dist/core/tools/kill.d.ts +5 -2
  295. package/dist/core/tools/powershell.d.ts +2 -2
  296. package/dist/core/tools/read-url.code.js +3 -3
  297. package/dist/core/tools/read-url.impl.js +3 -3
  298. package/dist/core/tools/read-url.js +3 -3
  299. package/dist/core/tools/read.d.ts +12 -2
  300. package/dist/core/tools/resource-selectors.d.ts +2 -0
  301. package/dist/core/tools/search.d.ts +12 -2
  302. package/dist/core/worktree-snapshot/blob-store.d.ts +45 -2
  303. package/dist/core/worktree-snapshot/blob-store.js +228 -60
  304. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  305. package/dist/core/worktree-snapshot/errors.code.js +3 -3
  306. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  307. package/dist/core/worktree-snapshot/errors.js +3 -3
  308. package/dist/core/worktree-snapshot/fork-snapshot-index.js +121 -0
  309. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -0
  310. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  311. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  312. package/dist/extensions/codemode/execute.code.js +3 -3
  313. package/dist/extensions/codemode/execute.impl.js +3 -3
  314. package/dist/extensions/codemode/execute.js +3 -3
  315. package/dist/extensions/codemode/renderer.code.js +2 -2
  316. package/dist/extensions/codemode/renderer.impl.js +3 -3
  317. package/dist/extensions/codemode/renderer.js +3 -3
  318. package/dist/extensions/mcp/cli.code.js +3 -3
  319. package/dist/extensions/mcp/cli.impl.js +3 -3
  320. package/dist/extensions/mcp/cli.js +3 -3
  321. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  322. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  323. package/dist/extensions/mcp/cli.lazy.js +3 -3
  324. package/dist/extensions/mcp/runtime.code.js +1 -1
  325. package/dist/extensions/mcp/runtime.impl.js +3 -3
  326. package/dist/extensions/mcp/runtime.js +3 -3
  327. package/dist/index.js +8 -8
  328. package/dist/main-first-time-setup.code.js +2 -2
  329. package/dist/main-first-time-setup.impl.js +3 -3
  330. package/dist/main-first-time-setup.js +3 -3
  331. package/dist/main.js +1 -1
  332. package/dist/modes/interactive/components/agent-panel.d.ts +1 -0
  333. package/dist/modes/interactive/components/stored-tree-view.code.js +3 -3
  334. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  335. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  336. package/dist/modes/interactive/components/task-inspector.d.ts +2 -0
  337. package/dist/modes/interactive/components/user-message-selector-archive.code.js +1 -1
  338. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  339. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  340. package/dist/modes/interactive/interactive-mode-helpers.d.ts +2 -2
  341. package/dist/modes/print-mode.js +1 -1
  342. package/dist/modes/rpc/agent-panel-bridge.d.ts +5 -0
  343. package/dist/package-manager-cli.code.js +7 -7
  344. package/dist/package-manager-cli.impl.js +3 -3
  345. package/dist/package-manager-cli.js +3 -3
  346. package/dist/rpc-entry.js +1 -1
  347. package/dist/startup-files.json +1 -1
  348. package/dist/startup-stages/0.js +1 -1
  349. package/dist/startup-stages/1.js +1 -1
  350. package/dist/startup-stages/10.js +1 -1
  351. package/dist/startup-stages/12.js +1 -1
  352. package/dist/startup-stages/2.js +9 -1
  353. package/dist/startup-stages/3.js +1 -6
  354. package/dist/startup-stages/5.js +1 -1
  355. package/dist/startup-stages/7.js +1 -1
  356. package/dist/startup-stages/8.js +2 -2
  357. package/dist/utils/startup-database-spare.code.js +3 -3
  358. package/dist/utils/startup-database-spare.impl.js +3 -3
  359. package/dist/utils/startup-database-spare.js +3 -3
  360. package/dist/utils/tools-manager.code.js +1 -1
  361. package/dist/utils/tools-manager.impl.js +3 -3
  362. package/dist/utils/tools-manager.js +3 -3
  363. package/docs/background-tasks.md +123 -23
  364. package/docs/compaction.md +18 -0
  365. package/docs/docs.json +2 -0
  366. package/docs/environment-variables.md +1 -1
  367. package/docs/getting-started/installation.md +9 -2
  368. package/docs/guides/postgres-pgbouncer.md +346 -0
  369. package/docs/guides/postgres-tuning.md +311 -0
  370. package/docs/guides/resume-on-any-machine.md +2 -2
  371. package/docs/guides.md +2 -0
  372. package/docs/index.md +1 -1
  373. package/docs/libraries/agent-core.md +1 -1
  374. package/docs/libraries/ai.md +2 -2
  375. package/docs/libraries/codemode.md +1 -1
  376. package/docs/libraries/storage-libsql.md +6 -1
  377. package/docs/libraries/storage-postgres.md +11 -6
  378. package/docs/libraries/tui.md +1 -1
  379. package/docs/libraries.md +2 -2
  380. package/docs/programmatic.md +1 -1
  381. package/docs/quickstart.md +1 -1
  382. package/docs/sdk/storage.md +1 -1
  383. package/docs/sdk/web-server.md +1 -3
  384. package/docs/sdk.md +1 -7
  385. package/docs/sessions.md +67 -2
  386. package/docs/settings.md +20 -1
  387. package/docs/skills/authoring.md +1 -1
  388. package/docs/skills.md +79 -6
  389. package/docs/storage.md +305 -14
  390. package/docs/subagents/reference.md +2 -2
  391. package/docs/subagents.md +4 -3
  392. package/docs/tools.md +44 -10
  393. package/docs/windows.md +1 -1
  394. package/package.json +9 -9
  395. package/dist/_shared/sdk-RRLVN7ER.js.map +0 -1
  396. package/dist/_shared/settings-startup-4QCVCI53.js.map +0 -1
  397. package/dist/_shared/startup-0-0-4VG2G44V.js.map +0 -1
  398. package/dist/_shared/startup-0-1-XTIL65D4.js.map +0 -1
  399. package/dist/_shared/startup-0-2-27OWFHV6.js.map +0 -1
  400. package/dist/_shared/startup-0-3-T4DVFYWX.js.map +0 -1
  401. package/dist/_shared/startup-0-5-FD2P735I.js.map +0 -1
  402. package/dist/_shared/startup-8-1-4KANEHRA.js.map +0 -1
@@ -1,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,216 @@ 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 {
28
+ ensureBrokerSchema,
29
+ openCatalogOf,
30
+ stampBrokerSchemaAtOpenEnd,
31
+ withBrokerSchemaCatalog,
32
+ } from "./sql-schema.js";
21
33
 
22
34
  /** Store-clock milliseconds since the lease was renewed, never negative. */
23
35
  const age = ({ greatest, nowMs }: StorageDialect) => greatest("0", `${nowMs} - renewed_at`);
24
36
 
25
37
  /**
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.
38
+ * `ensureTableFillfactor` of the storage API, which an Atomic installation older than #6560 lacks: taken from the module
39
+ * namespace, so the lease table keeps its default fillfactor there.
40
+ */
41
+ const fillfactorApi: Partial<Pick<typeof storage, "ensureTableFillfactor">> = storage;
42
+
43
+ /**
44
+ * The fillfactor of the lease table on PostgreSQL: a fifth of each page stays free, so a renewal's new row version
45
+ * fits on its page and stays a HOT update (#6560).
46
+ */
47
+ const LEASE_FILLFACTOR = 80;
48
+
49
+ /**
50
+ * The kind of the row whose `last_token` counts acquisitions on PostgreSQL where the order sequence is missing: see
51
+ * `nextOrder`.
52
+ */
53
+ const ACQUISITION_ORDER_KIND = "acquisition-order";
54
+
55
+ /**
56
+ * Creates the sequence first acquisitions take their order from on PostgreSQL, `<table>_order`, once per database
57
+ * (recorded as the `intercom-lease-order` schema step), starting past every order taken so far, the counter row's
58
+ * included. False where it is missing and this role may not create it: a runtime role on a database `atomic storage
59
+ * migrate` has not upgraded yet keeps the counter row (#6560).
60
+ */
61
+ async function ensureOrderSequence(
62
+ database: SqliteDatabase,
63
+ prefix: string | undefined,
64
+ table: string,
65
+ ): Promise<boolean> {
66
+ try {
67
+ await ensureBrokerSchema(database, prefix, "lease-order", async (tx) => {
68
+ await tx.exec(`CREATE SEQUENCE IF NOT EXISTS ${table}_order AS BIGINT`);
69
+ await tx.get(
70
+ `SELECT setval('${table}_order', GREATEST(
71
+ (SELECT COALESCE(MAX(first_acquired_order), 0) FROM ${table}),
72
+ (SELECT COALESCE(MAX(last_token), 0) FROM ${table} WHERE kind = '${ACQUISITION_ORDER_KIND}'),
73
+ 1
74
+ ))`,
75
+ );
76
+ });
77
+ return true;
78
+ } catch (error) {
79
+ if (isMissingPrivilege(error)) return false;
80
+ throw error;
81
+ }
82
+ }
83
+
84
+ /**
85
+ * The columns `listLiveFor` finds a send's presences by, each generated by the database from the row's key and subject,
86
+ * so the rows every broker writes, an older one's included, carry them, and each indexed (#6560). `presence_name` is
87
+ * `=` and the name in lower case when the name is ASCII, and `*` for a row the lookup reads for every target: a name
88
+ * that is not ASCII (only the JavaScript lower case a send's resolution compares is exact for it), several aliases, or
89
+ * a subject the database cannot read exactly. Every column is null on a row that is not a presence.
90
+ */
91
+ const ADDRESS_COLUMNS = ["presence_id", "presence_id_head", "presence_name", "presence_host", "presence_alias"] as const;
92
+
93
+ type AddressColumn = (typeof ADDRESS_COLUMNS)[number];
94
+
95
+ /**
96
+ * The expressions of the address columns. A subject or key is read only where its JSON text has no escape of NUL or of
97
+ * half a surrogate pair (`\ud800` to `\udfff`): PostgreSQL's `json` refuses to turn those into text, so a row an earlier
98
+ * broker wrote with one would fail every write of it and the columns' addition; on SQLite they read as bytes no target
99
+ * binds as. Such a row is marked `*`, read for every target (#6560). On SQLite a subject is read only where it is valid
100
+ * JSON. On PostgreSQL the columns are stored: a renewal that leaves their values as they were changes no indexed value,
101
+ * so it stays a HOT update.
102
+ */
103
+ function addressExpressions(dialect: StorageDialect): Record<AddressColumn, string> {
104
+ const returnPrefix = `'["return",'`;
105
+ if (dialect.name === "postgres") {
106
+ const subject = "subject_json::json";
107
+ /** Whether the column's JSON text holds an escape no `json` value can turn into text: NUL or half a surrogate pair. */
108
+ const escaped = (column: string) => `${column} ~ (chr(92) || chr(92) || 'u(0000|[dD][89a-fA-F])')`;
109
+ const readable = `kind = 'presence' AND subject_json IS NOT NULL AND NOT ${escaped("subject_json")}`;
110
+ const id = `(${subject} #>> '{session,id}')`;
111
+ const name = `(${subject} #>> '{session,name}')`;
112
+ const aliases = `(${subject} -> 'aliases')`;
113
+ const aliasCount = `CASE WHEN json_typeof(${aliases}) = 'array' THEN json_array_length(${aliases}) END`;
114
+ return {
115
+ presence_id: `CASE WHEN ${readable} THEN ${id} END`,
116
+ presence_id_head: `CASE WHEN ${readable} THEN lower(left(${id}, 8)) END`,
117
+ presence_name: `CASE WHEN kind <> 'presence' OR subject_json IS NULL THEN NULL
118
+ WHEN ${escaped("subject_json")} OR ${escaped("key")} THEN '*'
119
+ WHEN ${aliasCount} > 1 THEN '*'
120
+ WHEN ${name} IS NULL THEN NULL
121
+ WHEN ${name} ~ ('[^' || chr(1) || '-' || chr(127) || ']') THEN '*'
122
+ ELSE '=' || translate(${name}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') END`,
123
+ presence_host: `CASE WHEN kind = 'presence' AND left(key, 10) = ${returnPrefix} AND NOT ${escaped("key")}
124
+ THEN key::json ->> 1 END`,
125
+ presence_alias: `CASE WHEN ${readable} AND ${aliasCount} = 1 THEN ${subject} #>> '{aliases,0,id}' END`,
126
+ };
127
+ }
128
+ /**
129
+ * Whether the column's JSON text holds an escape of NUL or of half a surrogate pair, which SQLite reads into bytes no
130
+ * send's target binds as: such a row is read for every target, as on PostgreSQL.
131
+ */
132
+ const escaped = (column: string) =>
133
+ `(${column} GLOB '*\\u0000*' OR ${column} GLOB '*\\u[dD][89a-fA-F]*')`;
134
+ const readable = `kind = 'presence' AND json_valid(subject_json) AND NOT ${escaped("subject_json")}`;
135
+ const id = "json_extract(subject_json, '$.session.id')";
136
+ const name = "json_extract(subject_json, '$.session.name')";
137
+ const aliasCount =
138
+ "CASE WHEN json_type(subject_json, '$.aliases') = 'array' THEN json_array_length(subject_json, '$.aliases') END";
139
+ return {
140
+ presence_id: `CASE WHEN ${readable} THEN ${id} END`,
141
+ presence_id_head: `CASE WHEN ${readable} THEN lower(substr(${id}, 1, 8)) END`,
142
+ // A name with a character past ASCII, or a NUL, has more bytes than characters.
143
+ presence_name: `CASE WHEN kind <> 'presence' OR subject_json IS NULL THEN NULL
144
+ WHEN NOT json_valid(subject_json) OR ${escaped("subject_json")} OR ${escaped("key")} THEN '*'
145
+ WHEN ${aliasCount} > 1 THEN '*'
146
+ WHEN ${name} IS NULL THEN NULL
147
+ WHEN length(CAST(${name} AS BLOB)) <> length(${name}) THEN '*'
148
+ ELSE '=' || lower(${name}) END`,
149
+ presence_host: `CASE WHEN kind = 'presence' AND substr(key, 1, 10) = ${returnPrefix} AND json_valid(key)
150
+ AND NOT ${escaped("key")} THEN json_extract(key, '$[1]') END`,
151
+ presence_alias: `CASE WHEN ${readable} AND ${aliasCount} = 1 THEN json_extract(subject_json, '$.aliases[0].id') END`,
152
+ };
153
+ }
154
+
155
+ /**
156
+ * Adds the address columns and their indexes, once per database (recorded as the `intercom-lease-addresses` schema
157
+ * step). False where they are missing and this role may not add them: `listLiveFor` is then absent until `atomic
158
+ * storage migrate` adds them (#6560).
159
+ */
160
+ async function ensureAddressColumns(database: SqliteDatabase, prefix: string | undefined, table: string): Promise<boolean> {
161
+ const dialect = dialectOf(database);
162
+ const expressions = addressExpressions(dialect);
163
+ const indexes = ADDRESS_COLUMNS.map(
164
+ (column) => `CREATE INDEX IF NOT EXISTS ${table}_${column} ON ${table}(${column})`,
165
+ ).join(";\n");
166
+ const setup = async (tx: SqliteExecutor) => {
167
+ if (dialect.name === "postgres") {
168
+ // One statement, so the table is rewritten once.
169
+ await tx.exec(
170
+ `ALTER TABLE ${table} ${ADDRESS_COLUMNS.map(
171
+ (column) => `ADD COLUMN IF NOT EXISTS ${column} TEXT GENERATED ALWAYS AS (${expressions[column]}) STORED`,
172
+ ).join(", ")};\n${indexes}`,
173
+ );
174
+ return;
175
+ }
176
+ // SQLite runs this on every open: `pragma_table_xinfo` lists generated columns, which `pragma_table_info` hides.
177
+ const present = new Set(
178
+ (await tx.all<SqliteRow & { name: string }>("SELECT name FROM pragma_table_xinfo(?)", table)).map(
179
+ (row) => row.name,
180
+ ),
181
+ );
182
+ for (const column of ADDRESS_COLUMNS)
183
+ if (!present.has(column))
184
+ await tx.exec(
185
+ `ALTER TABLE ${table} ADD COLUMN ${column} TEXT GENERATED ALWAYS AS (${expressions[column]}) VIRTUAL`,
186
+ );
187
+ await tx.exec(indexes);
188
+ };
189
+ // On SQLite, which records no step, the catalog an open read finds the columns and their indexes, so a current
190
+ // table costs no write transaction (#6560); the open's end stamps it, so the next open answers from the stamp.
191
+ const catalog = dialect.versionedMigrations ? undefined : await openCatalogOf(database);
192
+ if (
193
+ catalog?.sqliteObjectType !== undefined &&
194
+ ADDRESS_COLUMNS.every(
195
+ (column) => catalog.hasColumn(table, column) && catalog.sqliteObjectType?.(`${table}_${column}`) === "index",
196
+ )
197
+ ) {
198
+ await stampBrokerSchemaAtOpenEnd(database, prefix, "lease-addresses", setup, (found) =>
199
+ ADDRESS_COLUMNS.every(
200
+ (column) => found.hasColumn(table, column) && found.sqliteObjectType?.(`${table}_${column}`) === "index",
201
+ ),
202
+ );
203
+ return true;
204
+ }
205
+ try {
206
+ await ensureBrokerSchema(database, prefix, "lease-addresses", setup);
207
+ return true;
208
+ } catch (error) {
209
+ if (isMissingPrivilege(error)) return false;
210
+ throw error;
211
+ }
212
+ }
213
+
214
+ /**
215
+ * `presence_name`'s value for the names a send to `target` compares (`target` and its trimmed form, in lower case), or
216
+ * null for one that is not ASCII, which only rows marked `*` can match.
28
217
  */
29
- const liveLeases = (dialect: StorageDialect, table: string) =>
218
+ function nameKey(target: string): string | null {
219
+ const lower = target.toLowerCase();
220
+ return /^[\x01-\x7f]*$/.test(lower) ? `=${lower}` : null;
221
+ }
222
+
223
+ /**
224
+ * A read of the held leases of one kind whose age compares to the bound as `comparison` does, oldest first, that reads
225
+ * the clock once: PostgreSQL's moves on between two readings, and a lease it found within the stale bound would
226
+ * otherwise report an age past it.
227
+ */
228
+ const leasesByAge = (dialect: StorageDialect, table: string, comparison: "<=" | ">=") =>
30
229
  `WITH clock AS (SELECT ${dialect.nowMs} AS now)
31
230
  SELECT kind, key, holder_id, fencing_token, subject_json, ${dialect.greatest("0", "(SELECT now FROM clock) - renewed_at")} AS age_ms
32
231
  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`;
232
+ AND ${dialect.greatest("0", "(SELECT now FROM clock) - renewed_at")} ${comparison} ? ORDER BY first_acquired_order, key`;
233
+
234
+ const liveLeases = (dialect: StorageDialect, table: string) => leasesByAge(dialect, table, "<=");
34
235
 
35
236
  type HolderRow = SqliteRow & {
36
237
  holder_id: string | null;
@@ -48,6 +249,8 @@ type StateRow = SqliteRow & {
48
249
  age_ms: number | bigint;
49
250
  };
50
251
 
252
+ const compare = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
253
+
51
254
  const invalid = (reason: StateStoreInvalidReason): InvalidStateInput => ({ status: "invalid", reason });
52
255
 
53
256
  function keyOf(subject: LeaseSubject): LeaseKey {
@@ -69,8 +272,23 @@ function invalidKey(key: LeaseKey): InvalidStateInput | undefined {
69
272
  return invalid(key.kind === "broker" ? "empty-broker-id" : "empty-target-identity");
70
273
  }
71
274
 
275
+ /**
276
+ * Every string well formed (#6560): half a surrogate pair, which a UTF-16 slice of a longer string leaves, becomes U+FFFD,
277
+ * as a UTF-8 encoder writes it. `JSON.stringify` would write it as a lone `\ud83d` escape, which PostgreSQL's `json`
278
+ * refuses to turn into text.
279
+ */
280
+ function wellFormed(_key: string, value: unknown): unknown {
281
+ return typeof value === "string" ? value.toWellFormed() : value;
282
+ }
283
+
284
+ /** A subject as the lease table stores it, with every string well formed. */
285
+ function subjectJson(subject: LeaseSubject): string {
286
+ return JSON.stringify(subject, wellFormed);
287
+ }
288
+
72
289
  function stateFromRow(row: StateRow): LeaseState {
73
- const subject: LeaseSubject = JSON.parse(row.subject_json);
290
+ // A row an earlier broker wrote may hold half a surrogate pair: it reads as a stored one would.
291
+ const subject: LeaseSubject = JSON.parse(row.subject_json, wellFormed);
74
292
  return {
75
293
  key: keyFor(row.kind === "broker" ? "broker" : "presence", row.key),
76
294
  holderId: row.holder_id,
@@ -101,7 +319,13 @@ export async function readLiveBrokerNodes(
101
319
  }
102
320
 
103
321
  /** 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> {
322
+ export function openSqlBrokerLeaseStore(options: IntercomBrokerStateOptions): Promise<BrokerLeaseStore> {
323
+ // Its schema checks answer from one read of the catalog, shared with an open around it: a current schema costs
324
+ // no transaction and no lock, also when the store is opened on its own (#6560).
325
+ return withBrokerSchemaCatalog(options.database, options.prefix, () => openBrokerLeaseStoreInCatalog(options));
326
+ }
327
+
328
+ async function openBrokerLeaseStoreInCatalog(options: IntercomBrokerStateOptions): Promise<BrokerLeaseStore> {
105
329
  const { database } = options;
106
330
  const table = `${validateStoragePrefix(options.prefix, dialectOf(database).name)}intercom_leases`;
107
331
  const dialect = dialectOf(database);
@@ -116,6 +340,16 @@ export async function openSqlBrokerLeaseStore(options: IntercomBrokerStateOption
116
340
  )
117
341
  `;
118
342
  await ensureBrokerSchema(database, options.prefix, "leases", (tx) => tx.exec(schema));
343
+ const orderSequence = `${table}_order`;
344
+ const sequenced = dialect.name === "postgres" && (await ensureOrderSequence(database, options.prefix, table));
345
+ const addressed = await ensureAddressColumns(database, options.prefix, table);
346
+ await fillfactorApi.ensureTableFillfactor?.(database, {
347
+ ledger: storageMigrationTable(options.prefix),
348
+ domain: "intercom-lease-fillfactor",
349
+ revision: 1,
350
+ table,
351
+ fillfactor: LEASE_FILLFACTOR,
352
+ });
119
353
 
120
354
  const holderOf = (executor: SqliteExecutor, key: LeaseKey) =>
121
355
  executor.get<HolderRow>(
@@ -131,6 +365,54 @@ export async function openSqlBrokerLeaseStore(options: IntercomBrokerStateOption
131
365
  invalidKey(lease.key) ?? (lease.holderId.length === 0 ? invalid("empty-holder-id") : undefined);
132
366
  const owned = `kind = ? AND key = ? AND holder_id = ? AND fencing_token = ?`;
133
367
  const ownedParams = (lease: Lease) => [lease.key.kind, keyId(lease.key), lease.holderId, lease.fencingToken];
368
+ /** In `acquire`'s upsert: the row is the acquiring holder's already. */
369
+ const mine = `${table}.holder_id = excluded.holder_id`;
370
+ /** In `acquire`'s upsert: the age of the row it found. */
371
+ const rowAge = dialect.greatest("0", `${nowMs} - ${table}.renewed_at`);
372
+ /**
373
+ * Every write decides on its own row in one guarded statement, so leases never wait for the database's serial lock,
374
+ * which a broker's renewals must not wait behind (#6560): see `fencedPath("intercom-lease")`.
375
+ */
376
+ const fenced = { concurrency: { kind: "fenced", audit: fencedPath("intercom-lease") } } as const;
377
+ /**
378
+ * The order of a key acquired for the first time. A serial database runs one acquisition at a time, so the
379
+ * largest order so far, plus one, is unique. PostgreSQL runs acquisitions beside one another, so each takes the
380
+ * next value of the order sequence, which no acquisition waits for (#6560). Where `atomic storage migrate` has not
381
+ * created it yet and this role may not, each takes the next value of a counter row, upserted by the statement
382
+ * itself, whose row lock orders them; the counter's kind is no lease's, so no lease query reads it.
383
+ */
384
+ const largestOrder = `(SELECT COALESCE(MAX(first_acquired_order), 0) FROM ${table})`;
385
+ const nextOrder = sequenced
386
+ ? { with: "", value: `nextval('${orderSequence}')` }
387
+ : dialect.name === "postgres"
388
+ ? {
389
+ with: `WITH next_order AS (
390
+ INSERT INTO ${table}(kind, key, last_token, first_acquired_order)
391
+ VALUES ('${ACQUISITION_ORDER_KIND}', '', ${largestOrder} + 1, 0)
392
+ ON CONFLICT(kind, key) DO UPDATE SET last_token = ${table}.last_token + 1
393
+ RETURNING last_token
394
+ ) `,
395
+ value: "(SELECT last_token FROM next_order)",
396
+ }
397
+ : { with: "", value: `${largestOrder} + 1` };
398
+ /** Latency-bound reads, which must not queue behind this database's writes (#6560). */
399
+ const reader = options.reader ?? database;
400
+ const clockAge = dialect.greatest("0", "(SELECT now FROM clock) - renewed_at");
401
+ /**
402
+ * `listLiveFor`'s read: each term is one indexed column's lookup, so SQLite takes the union of five index searches
403
+ * and PostgreSQL a bitmap OR of them. No `kind` term: on SQLite it would make the primary key's `kind` prefix, every
404
+ * presence, the search instead; the address columns are null on every other kind's rows.
405
+ */
406
+ const liveAddressed = `WITH clock AS (SELECT ${nowMs} AS now)
407
+ SELECT kind, key, holder_id, fencing_token, subject_json, ${clockAge} AS age_ms FROM ${table}
408
+ WHERE (presence_id IN (?, ?) OR presence_id_head = ? OR presence_name IN (?, ?, '*') OR presence_host = ?
409
+ OR presence_alias = ?)
410
+ AND holder_id IS NOT NULL AND ${clockAge} <= ? ORDER BY first_acquired_order, key`;
411
+
412
+ const listLive = async (kind: LeaseKind, staleAfterMs: number): Promise<LeaseState[]> => {
413
+ const rows = await reader.all<StateRow>(liveLeases(dialect, table), kind, staleAfterMs);
414
+ return rows.map(stateFromRow);
415
+ };
134
416
 
135
417
  return {
136
418
  async acquire(subject, holderId, staleAfterMs) {
@@ -138,50 +420,49 @@ export async function openSqlBrokerLeaseStore(options: IntercomBrokerStateOption
138
420
  const bad = invalidKey(key);
139
421
  if (bad !== undefined) return bad;
140
422
  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
- );
423
+ const stored = subjectJson(subject);
424
+ // #5607: a send that read the recipient's presence before this acquisition committed found it absent,
425
+ // free or stale, wrote no wake-up hint, and may still be writing its row. On PostgreSQL a presence
426
+ // acquisition therefore waits, once it committed, for every send to that recipient under way, holding the
427
+ // recipient's lock domain for an instant: the registration's first outbox scan, which follows, then finds
428
+ // their rows; a later send reads the live presence and wakes its holder (#6560).
429
+ const acquired = await database.transaction(async (tx) => {
430
+ // One guarded statement takes the lease: a new key, or a row that is free, stale or already this
431
+ // holder's; a steal gets the key's next token, a re-acquisition keeps its own. Renewals run beside it,
432
+ // so the decision is never made on an earlier read (#6560).
433
+ const taken = await tx.get<SqliteRow & { fencing_token: number | bigint }>(
434
+ `${nextOrder.with}INSERT INTO ${table}(kind, key, holder_id, fencing_token, last_token, subject_json,
435
+ renewed_at, first_acquired_order)
436
+ VALUES (?, ?, ?, 1, 1, ?, ${nowMs}, ${nextOrder.value})
437
+ ON CONFLICT(kind, key) DO UPDATE SET
438
+ fencing_token = CASE WHEN ${mine} THEN ${table}.fencing_token ELSE ${table}.last_token + 1 END,
439
+ last_token = CASE WHEN ${mine} THEN ${table}.last_token ELSE ${table}.last_token + 1 END,
440
+ holder_id = excluded.holder_id, subject_json = excluded.subject_json, renewed_at = excluded.renewed_at
441
+ WHERE ${table}.holder_id IS NULL OR ${mine} OR ${rowAge} > ?
442
+ RETURNING fencing_token`,
443
+ key.kind,
444
+ keyId(key),
445
+ holderId,
446
+ stored,
447
+ staleAfterMs,
448
+ );
449
+ if (taken !== undefined) {
164
450
  return {
165
451
  status: "acquired",
166
- lease: { key, holderId, fencingToken: Number(row.fencing_token) },
452
+ lease: { key, holderId, fencingToken: Number(taken.fencing_token) },
167
453
  } as const;
168
454
  }
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),
455
+ // Held by another live holder. PostgreSQL locks the row whose guard failed until this transaction
456
+ // ends, so this reads the holder that refused it.
457
+ const row = (await holderOf(tx, key))!;
458
+ return { status: "held", holderId: row.holder_id!, fencingToken: Number(row.fencing_token) } as const;
459
+ }, fenced);
460
+ if (acquired.status === "acquired" && subject.kind === "presence" && dialect.name === "postgres")
461
+ await database.transaction(
462
+ async () => {},
463
+ recipientTransaction(database, options.prefix, subject.targetIdentity),
182
464
  );
183
- return { status: "acquired", lease: { key, holderId, fencingToken } } as const;
184
- });
465
+ return acquired;
185
466
  },
186
467
  async renew(lease, subject) {
187
468
  const bad = validLease(lease);
@@ -195,11 +476,11 @@ export async function openSqlBrokerLeaseStore(options: IntercomBrokerStateOption
195
476
  ? await tx.run(`UPDATE ${table} SET renewed_at = ${nowMs} WHERE ${owned}`, ...ownedParams(lease))
196
477
  : await tx.run(
197
478
  `UPDATE ${table} SET renewed_at = ${nowMs}, subject_json = ? WHERE ${owned}`,
198
- JSON.stringify(subject),
479
+ subjectJson(subject),
199
480
  ...ownedParams(lease),
200
481
  );
201
482
  return changes === 1 ? ({ status: "renewed" } as const) : stale(await holderOf(tx, lease.key));
202
- });
483
+ }, fenced);
203
484
  },
204
485
  async renewMany(requests) {
205
486
  if (requests.length === 0) return [];
@@ -220,21 +501,35 @@ export async function openSqlBrokerLeaseStore(options: IntercomBrokerStateOption
220
501
  }
221
502
  }
222
503
  if (validCount === 0) return results as LeaseRenewResult[];
504
+ // Rows locked in one order on every broker, so two renewals of overlapping leases never deadlock.
505
+ const order = requests
506
+ .map((request, index) => ({ index, kind: request.lease.key.kind, id: keyId(request.lease.key) }))
507
+ .filter(({ index }) => results[index] === undefined)
508
+ .sort((a, b) => compare(a.kind, b.kind) || compare(a.id, b.id))
509
+ .map(({ index }) => index);
223
510
  await database.transaction(async (tx) => {
224
- for (let i = 0; i < requests.length; i++) {
225
- if (results[i] !== undefined) continue;
511
+ // Every update is sent before any answer is awaited, in the lock order: a pipelined connection sends them
512
+ // in one round trip, and the server runs them in the order sent (#6560).
513
+ const renewals = order.map((i) => {
226
514
  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
- });
515
+ return subject === undefined
516
+ ? tx.run(`UPDATE ${table} SET renewed_at = ${nowMs} WHERE ${owned}`, ...ownedParams(lease))
517
+ : tx.run(
518
+ `UPDATE ${table} SET renewed_at = ${nowMs}, subject_json = ? WHERE ${owned}`,
519
+ subjectJson(subject),
520
+ ...ownedParams(lease),
521
+ );
522
+ });
523
+ const settled = await Promise.allSettled(renewals);
524
+ const failed = settled.find((outcome) => outcome.status === "rejected");
525
+ if (failed !== undefined) throw failed.reason;
526
+ const renewed = settled.map((outcome) => (outcome as PromiseFulfilledResult<SqliteRunResult>).value);
527
+ for (const [position, i] of order.entries())
528
+ results[i] =
529
+ renewed[position]!.changes === 1
530
+ ? ({ status: "renewed" } as const)
531
+ : stale(await holderOf(tx, requests[i]!.lease.key));
532
+ }, fenced);
238
533
  return results as LeaseRenewResult[];
239
534
  },
240
535
  async release(lease) {
@@ -247,12 +542,12 @@ export async function openSqlBrokerLeaseStore(options: IntercomBrokerStateOption
247
542
  ...ownedParams(lease),
248
543
  );
249
544
  return changes === 1 ? ({ status: "released" } as const) : stale(await holderOf(tx, lease.key));
250
- });
545
+ }, fenced);
251
546
  },
252
547
  async read(key) {
253
548
  const bad = invalidKey(key);
254
549
  if (bad !== undefined) return bad;
255
- const row = await database.get<StateRow>(
550
+ const row = await reader.get<StateRow>(
256
551
  `SELECT kind, key, holder_id, fencing_token, subject_json, ${leaseAge} AS age_ms FROM ${table}
257
552
  WHERE kind = ? AND key = ? AND holder_id IS NOT NULL`,
258
553
  key.kind,
@@ -260,8 +555,34 @@ export async function openSqlBrokerLeaseStore(options: IntercomBrokerStateOption
260
555
  );
261
556
  return row === undefined ? { status: "missing" } : { status: "found", lease: stateFromRow(row) };
262
557
  },
263
- async listLive(kind, staleAfterMs) {
264
- const rows = await database.all<StateRow>(liveLeases(dialect, table), kind, staleAfterMs);
558
+ listLive,
559
+ ...(addressed
560
+ ? {
561
+ async listLiveFor(named: string, staleAfterMs: number) {
562
+ // No statement may carry a NUL character: such a target, which no index can look up, reads every
563
+ // presence, as before.
564
+ if (named.includes("\u0000")) return listLive("presence", staleAfterMs);
565
+ // Its strings as the stored subjects' are, every one well formed, on every backend (#6560).
566
+ const target = named.toWellFormed();
567
+ const trimmed = target.trim();
568
+ const head = /^[0-9a-f]{8}$/i.test(trimmed) ? trimmed.toLowerCase() : null;
569
+ const rows = await reader.all<StateRow>(
570
+ liveAddressed,
571
+ target,
572
+ trimmed,
573
+ head,
574
+ nameKey(target),
575
+ nameKey(trimmed),
576
+ trimmed,
577
+ target,
578
+ staleAfterMs,
579
+ );
580
+ return rows.map(stateFromRow);
581
+ },
582
+ }
583
+ : {}),
584
+ async listAged(kind, minAgeMs) {
585
+ const rows = await reader.all<StateRow>(leasesByAge(dialect, table, ">="), kind, minAgeMs);
265
586
  return rows.map(stateFromRow);
266
587
  },
267
588
  async retireHolder(holderId) {