@bastani/atomic 0.10.10 → 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 (380) hide show
  1. package/CHANGELOG.md +83 -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 +18 -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 +12 -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/index.bundle.mjs +1 -1
  70. package/dist/builtin/web-access/package.json +1 -1
  71. package/dist/cli/args.js +2 -2
  72. package/dist/cli/auth-cli.code.js +4 -4
  73. package/dist/cli/auth-cli.impl.js +3 -3
  74. package/dist/cli/auth-cli.js +3 -3
  75. package/dist/cli/blueprint-command.code.js +3 -3
  76. package/dist/cli/blueprint-command.impl.js +3 -3
  77. package/dist/cli/blueprint-command.js +3 -3
  78. package/dist/cli/intercom-command.code.js +2 -2
  79. package/dist/cli/intercom-command.impl.js +3 -3
  80. package/dist/cli/intercom-command.js +3 -3
  81. package/dist/cli/list-models.code.js +2 -2
  82. package/dist/cli/list-models.impl.js +3 -3
  83. package/dist/cli/list-models.js +3 -3
  84. package/dist/cli/session-picker.code.js +1 -1
  85. package/dist/cli/session-picker.impl.js +3 -3
  86. package/dist/cli/session-picker.js +3 -3
  87. package/dist/cli/startup-ui.code.js +1 -1
  88. package/dist/cli/startup-ui.impl.js +3 -3
  89. package/dist/cli/startup-ui.js +3 -3
  90. package/dist/cli/storage-command.impl.js +3 -3
  91. package/dist/cli/storage-command.js +3 -3
  92. package/dist/cli/storage-search-session.code.js +3 -3
  93. package/dist/cli/storage-search-session.impl.js +3 -3
  94. package/dist/cli/storage-search-session.js +3 -3
  95. package/dist/cli/team-command.code.js +2 -2
  96. package/dist/cli/team-command.impl.js +3 -3
  97. package/dist/cli/team-command.js +3 -3
  98. package/dist/cli.js +2 -2
  99. package/dist/core/agent-session-methods.d.ts +3 -0
  100. package/dist/core/agent-session-methods.js.map +1 -1
  101. package/dist/core/agent-session.d.ts +1 -0
  102. package/dist/core/compaction/compactor.d.ts +2 -0
  103. package/dist/core/debug.impl.js +3 -3
  104. package/dist/core/debug.js +3 -3
  105. package/dist/core/export-html/card-projection.code.js +1 -1
  106. package/dist/core/export-html/card-projection.impl.js +3 -3
  107. package/dist/core/export-html/card-projection.js +3 -3
  108. package/dist/core/export-html/index.code.js +2 -2
  109. package/dist/core/export-html/index.impl.js +3 -3
  110. package/dist/core/export-html/index.js +3 -3
  111. package/dist/core/export-html/json-spans.impl.js +3 -3
  112. package/dist/core/export-html/json-spans.js +3 -3
  113. package/dist/core/export-html/oversized-render-inputs.code.js +1 -1
  114. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  115. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  116. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  117. package/dist/core/export-html/tool-renderer.js +3 -3
  118. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  119. package/dist/core/extensions/jiti-loader.js +3 -3
  120. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  121. package/dist/core/extensions/jiti-static-loader.js +3 -3
  122. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  123. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  124. package/dist/core/extensions/loader-host-modules.js +3 -3
  125. package/dist/core/extensions/loader-virtual-modules.js +2 -2
  126. package/dist/core/extensions/runner-context.js +3 -3
  127. package/dist/core/extensions/runner-context.js.map +1 -1
  128. package/dist/core/intercom-broker-control-host.code.js +1 -1
  129. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  130. package/dist/core/intercom-broker-control-host.js +3 -3
  131. package/dist/core/intercom-broker-control.code.js +3 -3
  132. package/dist/core/intercom-broker-control.impl.js +3 -3
  133. package/dist/core/intercom-broker-control.js +3 -3
  134. package/dist/core/model-registry.js +1 -1
  135. package/dist/core/model-resolver-defaults.d.ts +3 -2
  136. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  137. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  138. package/dist/core/package-manager-storage-adapters.js +3 -3
  139. package/dist/core/sdk.code.js +3 -4
  140. package/dist/core/sdk.impl.js +3 -3
  141. package/dist/core/sdk.js +3 -3
  142. package/dist/core/session-manager-core.d.ts +5 -2
  143. package/dist/core/session-manager-core.js +17 -13
  144. package/dist/core/session-manager-core.js.map +1 -1
  145. package/dist/core/session-manager-list.impl.js +3 -3
  146. package/dist/core/session-manager-list.js +3 -3
  147. package/dist/core/session-manager.code.js +1 -1
  148. package/dist/core/session-manager.impl.js +3 -3
  149. package/dist/core/session-manager.js +3 -3
  150. package/dist/core/session-storage.code.js +1 -1
  151. package/dist/core/session-storage.impl.js +3 -3
  152. package/dist/core/session-storage.js +3 -3
  153. package/dist/core/storage/added-exports.d.ts +6 -0
  154. package/dist/core/storage/added-exports.js +16 -0
  155. package/dist/core/storage/added-exports.js.map +1 -0
  156. package/dist/core/storage/database.d.ts +16 -0
  157. package/dist/core/storage/database.js.map +1 -1
  158. package/dist/core/storage/fenced-paths.d.ts +47 -0
  159. package/dist/core/storage/fenced-paths.js +53 -0
  160. package/dist/core/storage/fenced-paths.js.map +1 -1
  161. package/dist/core/storage/file-identity.js +31 -2
  162. package/dist/core/storage/file-identity.js.map +1 -1
  163. package/dist/core/storage/index.d.ts +3 -0
  164. package/dist/core/storage/index.js +5 -2
  165. package/dist/core/storage/index.js.map +1 -1
  166. package/dist/core/storage/migrations.d.ts +22 -0
  167. package/dist/core/storage/migrations.js +55 -0
  168. package/dist/core/storage/migrations.js.map +1 -1
  169. package/dist/core/storage/node-sqlite-thread.js +19 -6
  170. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  171. package/dist/core/storage/node-sqlite.js +53 -4
  172. package/dist/core/storage/node-sqlite.js.map +1 -1
  173. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  174. package/dist/core/storage/offline-snapshot-file.js +3 -3
  175. package/dist/core/storage/prefix.d.ts +3 -2
  176. package/dist/core/storage/prefix.js +18 -2
  177. package/dist/core/storage/prefix.js.map +1 -1
  178. package/dist/core/storage/provider.js +2 -2
  179. package/dist/core/storage/schema-catalog.d.ts +42 -0
  180. package/dist/core/storage/schema-catalog.js +141 -0
  181. package/dist/core/storage/schema-catalog.js.map +1 -0
  182. package/dist/core/storage/selection.js +2 -2
  183. package/dist/core/storage/session/branch-fork-source.code.js +41 -20
  184. package/dist/core/storage/session/branch-fork-source.code.js.map +1 -1
  185. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  186. package/dist/core/storage/session/branch-fork-source.js +3 -3
  187. package/dist/core/storage/session/card-view.impl.js +3 -3
  188. package/dist/core/storage/session/card-view.js +3 -3
  189. package/dist/core/storage/session/child-reader.code.js +3 -3
  190. package/dist/core/storage/session/child-reader.impl.js +3 -3
  191. package/dist/core/storage/session/child-reader.js +3 -3
  192. package/dist/core/storage/session/chunked-resume-projection.code.js +1 -1
  193. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  194. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  195. package/dist/core/storage/session/expanded-child-details.code.js +3 -3
  196. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  197. package/dist/core/storage/session/expanded-child-details.js +3 -3
  198. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  199. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  200. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  201. package/dist/core/storage/session/fork-row-index.js +3 -3
  202. package/dist/core/storage/session/fork-staging.code.js +176 -36
  203. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  204. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  205. package/dist/core/storage/session/fork-staging.js +3 -3
  206. package/dist/core/storage/session/fork-window.code.js +3 -3
  207. package/dist/core/storage/session/fork-window.impl.js +3 -3
  208. package/dist/core/storage/session/fork-window.js +3 -3
  209. package/dist/core/storage/session/history-pages.impl.js +3 -3
  210. package/dist/core/storage/session/history-pages.js +3 -3
  211. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  212. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  213. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  214. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  215. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  216. package/dist/core/storage/session/memory-session-store.js +3 -3
  217. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  218. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  219. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  220. package/dist/core/storage/session/released-history-files.code.js +2 -2
  221. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  222. package/dist/core/storage/session/released-history-files.js +3 -3
  223. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  224. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  225. package/dist/core/storage/session/session-resume.impl.js +3 -3
  226. package/dist/core/storage/session/session-resume.js +3 -3
  227. package/dist/core/storage/session/session-search-index.d.ts +5 -0
  228. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  229. package/dist/core/storage/session/snapshot-cut.js +3 -3
  230. package/dist/core/storage/session/snapshot-history.code.js +3 -3
  231. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  232. package/dist/core/storage/session/snapshot-history.js +3 -3
  233. package/dist/core/storage/session/sql-chat-records.d.ts +15 -0
  234. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  235. package/dist/core/storage/session/sql-session-store.d.ts +102 -5
  236. package/dist/core/storage/session/sql-session-store.impl.js +4 -4
  237. package/dist/core/storage/session/sql-session-store.js +4 -4
  238. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  239. package/dist/core/storage/session/tree-outline.js +3 -3
  240. package/dist/core/storage/session/tree-presentation.code.js +1 -1
  241. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  242. package/dist/core/storage/session/tree-presentation.js +3 -3
  243. package/dist/core/storage/session/types.d.ts +14 -0
  244. package/dist/core/storage/sqlite-facade.d.ts +37 -5
  245. package/dist/core/storage/sqlite-facade.js +351 -18
  246. package/dist/core/storage/sqlite-facade.js.map +1 -1
  247. package/dist/core/storage/statement-sequence.d.ts +83 -0
  248. package/dist/core/storage/statement-sequence.js +21 -0
  249. package/dist/core/storage/statement-sequence.js.map +1 -1
  250. package/dist/core/storage/storage-status.code.js +1 -1
  251. package/dist/core/storage/storage-status.impl.js +3 -3
  252. package/dist/core/storage/storage-status.js +3 -3
  253. package/dist/core/storage/team.code.js +1 -1
  254. package/dist/core/storage/team.impl.js +3 -3
  255. package/dist/core/storage/team.js +3 -3
  256. package/dist/core/structured-output/index.code.js +1 -1
  257. package/dist/core/structured-output/index.impl.js +3 -3
  258. package/dist/core/structured-output/index.js +3 -3
  259. package/dist/core/tasks/task-completion-entry.code.js +1 -1
  260. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  261. package/dist/core/tasks/task-completion-entry.js +3 -3
  262. package/dist/core/tasks/task-file-history.code.js +3 -3
  263. package/dist/core/tasks/task-file-history.impl.js +3 -3
  264. package/dist/core/tasks/task-file-history.js +3 -3
  265. package/dist/core/tasks/task-reference-archive.code.js +4 -4
  266. package/dist/core/tasks/task-reference-archive.js +3 -3
  267. package/dist/core/tasks/task-reference-identity.js +3 -3
  268. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  269. package/dist/core/tasks/task-reference-stream.js +3 -3
  270. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  271. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  272. package/dist/core/tasks/task-view-source.code.js +1 -1
  273. package/dist/core/tasks/task-view-source.impl.js +3 -3
  274. package/dist/core/tasks/task-view-source.js +3 -3
  275. package/dist/core/tools/bash.d.ts +8 -4
  276. package/dist/core/tools/history-session.d.ts +5 -0
  277. package/dist/core/tools/history-tasks.d.ts +123 -0
  278. package/dist/core/tools/kill.d.ts +5 -2
  279. package/dist/core/tools/powershell.d.ts +2 -2
  280. package/dist/core/tools/read-url.code.js +3 -3
  281. package/dist/core/tools/read-url.impl.js +3 -3
  282. package/dist/core/tools/read-url.js +3 -3
  283. package/dist/core/tools/read.d.ts +12 -2
  284. package/dist/core/tools/resource-selectors.d.ts +2 -0
  285. package/dist/core/tools/search.d.ts +12 -2
  286. package/dist/core/worktree-snapshot/blob-store.d.ts +14 -2
  287. package/dist/core/worktree-snapshot/blob-store.js +69 -16
  288. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  289. package/dist/core/worktree-snapshot/errors.code.js +2 -2
  290. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  291. package/dist/core/worktree-snapshot/errors.js +3 -3
  292. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  293. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  294. package/dist/extensions/codemode/execute.code.js +2 -2
  295. package/dist/extensions/codemode/execute.impl.js +3 -3
  296. package/dist/extensions/codemode/execute.js +3 -3
  297. package/dist/extensions/codemode/renderer.code.js +2 -2
  298. package/dist/extensions/codemode/renderer.impl.js +3 -3
  299. package/dist/extensions/codemode/renderer.js +3 -3
  300. package/dist/extensions/mcp/cli.code.js +3 -3
  301. package/dist/extensions/mcp/cli.impl.js +3 -3
  302. package/dist/extensions/mcp/cli.js +3 -3
  303. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  304. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  305. package/dist/extensions/mcp/cli.lazy.js +3 -3
  306. package/dist/extensions/mcp/runtime.code.js +1 -1
  307. package/dist/extensions/mcp/runtime.impl.js +3 -3
  308. package/dist/extensions/mcp/runtime.js +3 -3
  309. package/dist/index.js +5 -5
  310. package/dist/main-first-time-setup.code.js +1 -1
  311. package/dist/main-first-time-setup.impl.js +3 -3
  312. package/dist/main-first-time-setup.js +3 -3
  313. package/dist/main.js +1 -1
  314. package/dist/modes/interactive/components/agent-panel.d.ts +1 -0
  315. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  316. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  317. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  318. package/dist/modes/interactive/components/task-inspector.d.ts +2 -0
  319. package/dist/modes/interactive/components/user-message-selector-archive.code.js +1 -1
  320. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  321. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  322. package/dist/modes/interactive/interactive-mode-helpers.d.ts +2 -2
  323. package/dist/modes/print-mode.js +1 -1
  324. package/dist/modes/rpc/agent-panel-bridge.d.ts +5 -0
  325. package/dist/package-manager-cli.code.js +6 -6
  326. package/dist/package-manager-cli.impl.js +3 -3
  327. package/dist/package-manager-cli.js +3 -3
  328. package/dist/rpc-entry.js +1 -1
  329. package/dist/startup-files.json +1 -1
  330. package/dist/startup-stages/0.js +1 -1
  331. package/dist/startup-stages/1.js +1 -1
  332. package/dist/startup-stages/10.js +1 -1
  333. package/dist/startup-stages/12.js +1 -1
  334. package/dist/startup-stages/2.js +8 -1
  335. package/dist/startup-stages/3.js +1 -6
  336. package/dist/startup-stages/5.js +1 -1
  337. package/dist/startup-stages/7.js +1 -5
  338. package/dist/utils/startup-database-spare.code.js +2 -2
  339. package/dist/utils/startup-database-spare.impl.js +3 -3
  340. package/dist/utils/startup-database-spare.js +3 -3
  341. package/dist/utils/tools-manager.code.js +1 -1
  342. package/dist/utils/tools-manager.impl.js +3 -3
  343. package/dist/utils/tools-manager.js +3 -3
  344. package/docs/background-tasks.md +123 -23
  345. package/docs/compaction.md +18 -0
  346. package/docs/docs.json +2 -0
  347. package/docs/environment-variables.md +1 -1
  348. package/docs/getting-started/installation.md +9 -2
  349. package/docs/guides/postgres-pgbouncer.md +339 -0
  350. package/docs/guides/postgres-tuning.md +311 -0
  351. package/docs/guides/resume-on-any-machine.md +2 -2
  352. package/docs/guides.md +2 -0
  353. package/docs/index.md +1 -1
  354. package/docs/libraries/agent-core.md +1 -1
  355. package/docs/libraries/ai.md +2 -2
  356. package/docs/libraries/codemode.md +1 -1
  357. package/docs/libraries/storage-libsql.md +6 -1
  358. package/docs/libraries/storage-postgres.md +11 -6
  359. package/docs/libraries/tui.md +1 -1
  360. package/docs/libraries.md +2 -2
  361. package/docs/programmatic.md +1 -1
  362. package/docs/quickstart.md +1 -1
  363. package/docs/sdk/storage.md +1 -1
  364. package/docs/sdk/web-server.md +1 -3
  365. package/docs/sdk.md +1 -7
  366. package/docs/sessions.md +58 -2
  367. package/docs/settings.md +20 -1
  368. package/docs/skills/authoring.md +1 -1
  369. package/docs/skills.md +79 -6
  370. package/docs/storage.md +262 -12
  371. package/docs/subagents/reference.md +2 -2
  372. package/docs/subagents.md +4 -3
  373. package/docs/tools.md +44 -10
  374. package/docs/windows.md +1 -1
  375. package/package.json +9 -9
  376. package/dist/_shared/sdk-RRLVN7ER.js.map +0 -1
  377. package/dist/_shared/startup-0-0-4VG2G44V.js.map +0 -1
  378. package/dist/_shared/startup-0-1-XTIL65D4.js.map +0 -1
  379. package/dist/_shared/startup-0-5-FD2P735I.js.map +0 -1
  380. package/dist/_shared/startup-8-1-4KANEHRA.js.map +0 -1
@@ -1,16 +1,16 @@
1
1
  import { __name } from "./rolldown-runtime-BGM3D5V3.js";
2
2
  import { APP_NAME, CONFIG_DIR_NAME, createChildProcessEnvironment, findHelperExecutable, getAgentDir, helperLaunch, helperLaunchAsync, missingHelperOptions, startedWithHangupIgnored, stripBom } from "./p0-cli-BB45ZQY6.js";
3
- import { CONTINUE_AFTER_FAILURE, DynamicBorder, EventSourceError, FramedSelector, LATEST_PROTOCOL_VERSION, SubscriptionClosedError, SubscriptionConfigError, SubscriptionSetupError, SubscriptionTimeoutError, abortFailure, announceHistoryLoad, applySessionSummaryEntries, bindChatEpoch, blueprintBuildsSettled, boundedChatRecord, canonicalEventBusFor, collectDeclaredDisplaySecrets, decodeChatOrder, decodeChatRecord, encodeChatOrder, extractHeaderSecrets, firstChatOrders, flushRawStdout, hasHistoryLoadObserver, isObject, isSensitiveKeyNameForMasking, materializeSessionSummaryMetadata, nativeForkReader, noteSnapshotGeneration, onBlueprintBuildFinished, onBlueprintBuildWaiting, raceWithAbortSignal, redactAuthorizationUrlForDisplay, redactCredentials, redactOAuthErrorText, redactUrlForDisplay, redactUrlForTransportDisplay, registerArchiveLoad, registerForkScope, registerHistorySnapshot, resolveDecisionDeadlineMs, scrubFetchError, sha256Hex, sharedWakeDispatcher, sliceHead, stripUrlUserinfoAndHash, whenAborted, withinDecisionDeadline, writeRawStdout, yieldTurn } from "./startup-0-0-4VG2G44V.js";
4
- import { CommandDeliveries, SqlSessionSearchIndex, WorkspacePublicationError, collectCommandDeliveries, normalizeModelFailureSignal, reportDiagnostics, requireTimerMs } from "./startup-0-1-XTIL65D4.js";
3
+ import { CONTINUE_AFTER_FAILURE, DynamicBorder, EventSourceError, FramedSelector, LATEST_PROTOCOL_VERSION, SubscriptionClosedError, SubscriptionConfigError, SubscriptionSetupError, SubscriptionTimeoutError, abortFailure, announceHistoryLoad, applySessionSummaryEntries, bindChatEpoch, blueprintBuildsSettled, boundedChatRecord, canonicalEventBusFor, collectDeclaredDisplaySecrets, decodeChatOrder, decodeChatRecord, encodeChatOrder, extractHeaderSecrets, firstChatOrders, flushRawStdout, forkStoreRelation, hasHistoryLoadObserver, isObject, isSensitiveKeyNameForMasking, materializeSessionSummaryMetadata, nativeForkReader, noteSnapshotGeneration, onBlueprintBuildFinished, onBlueprintBuildWaiting, raceWithAbortSignal, redactAuthorizationUrlForDisplay, redactCredentials, redactOAuthErrorText, redactUrlForDisplay, redactUrlForTransportDisplay, registerArchiveLoad, registerForkScope, registerHistorySnapshot, resolveDecisionDeadlineMs, scrubFetchError, sessionWriteTransaction, sha256Hex, sharedWakeDispatcher, sliceHead, stripUrlUserinfoAndHash, whenAborted, withinDecisionDeadline, writeRawStdout, yieldTurn } from "./startup-0-0-57KF6LZH.js";
4
+ import { CommandDeliveries, SqlSessionSearchIndex, WorkspacePublicationError, collectCommandDeliveries, normalizeModelFailureSignal, reportDiagnostics, requireTimerMs } from "./startup-0-1-GIY75K46.js";
5
5
  import { getAvailableThemes, keyHint } from "./p2-shell-main-B2WIALFD.js";
6
6
  import { releaseLock, reportDebugAsync, waitForLock } from "./p1b-elig-ENCUPKKJ.js";
7
7
  import { FileAuthStorageBackend, ResumePreconditionError, STRUCTURED_OUTPUT_TOOL_NAME, asyncAuthStorageReads, classifyRepository, killTrackedDetachedChildren, markNativeMcpToolDefinition, matchesMcpDirectToolSelection, providerRetryHint } from "./startup-0-2-27OWFHV6.js";
8
8
  import { CODEMODE_TOOL_NAME, assistantRetryAttempt, runWorkspaceProcess } from "./startup-0-3-T4DVFYWX.js";
9
9
  import { DecisionConfigError, DecisionModelUnavailableError, DecisionOutputError, DecisionProviderError, DecisionRequestError, SESSION_HISTORY_CHUNK_BYTES, SESSION_HISTORY_PAGE_BYTES, entrySizeLimit, isDecisionError, isDecisionProviderError } from "./settings-startup-4QCVCI53.js";
10
10
  import { RESUME_UPGRADE_SOURCES, branchRanges, childCatalogCut, foldSessionResume, foreignResumeIds, isSessionResumeIndex, isUpgradableSessionResumeIndex, latestCompactionOf, readEarlierCompletionIntents, selectedPagePlan, sessionResumeFrom, sessionResumePlan, sessionResumeUpgrade, sessionTailFrom, snapshotCutOf, stateSeqsBefore, transcriptBranchSpan, validateSessionEntries, validateSessionHeader, validateSessionText } from "./startup-8-0-34CBHPZH.js";
11
- import { LIST_MCP_RESOURCES_TOOL, LIST_MCP_RESOURCE_TEMPLATES_TOOL, READ_MCP_RESOURCE_TOOL, TOOL_SEARCH_TOOL_NAME, createMcpResourceToolDefinitions, createMcpToolDefinition, createMcpToolName, createMcpToolRenderers, defaultResumePreflightIo, enablePrintModelSelection, gitUnavailableProblem, hasPrintModelSelection, openWorkspaceRepository, ranOnModelLine, removeRestoredWorktree } from "./startup-0-5-FD2P735I.js";
11
+ import { LIST_MCP_RESOURCES_TOOL, LIST_MCP_RESOURCE_TEMPLATES_TOOL, READ_MCP_RESOURCE_TOOL, TOOL_SEARCH_TOOL_NAME, createMcpResourceToolDefinitions, createMcpToolDefinition, createMcpToolName, createMcpToolRenderers, defaultResumePreflightIo, enablePrintModelSelection, gitUnavailableProblem, hasPrintModelSelection, openWorkspaceRepository, ranOnModelLine, removeRestoredWorktree } from "./startup-0-5-YDW47QX6.js";
12
12
  import { assertWorkspaceGitAvailable, formatModelLabel, gitOutput, runWorkspaceGit } from "./startup-0-4-ZMJV547D.js";
13
- import { SettingsManager, checkoutsNeedingRebuild, inheritedRemotes, isInside, pathExists, resumeStoreDir, savedProjectTrustAsync, setUpResumedBlueprints, settingsFileTarget, settingsFileTargetAsync, writeSettingsFile, writeSettingsFileAsync } from "./startup-8-1-4KANEHRA.js";
13
+ import { SettingsManager, checkoutsNeedingRebuild, inheritedRemotes, isInside, pathExists, resumeStoreDir, savedProjectTrustAsync, setUpResumedBlueprints, settingsFileTarget, settingsFileTargetAsync, writeSettingsFile, writeSettingsFileAsync } from "./startup-8-1-X32CYSXB.js";
14
14
  import "./startup-15-0-YUKGAC63.js";
15
15
  import "./startup-10-0-TDQNBDDL.js";
16
16
  import "./p1a-prewarm-XIU57JHF.js";
@@ -40,9 +40,12 @@ import { publishExtensionContextEffect, registerExtensionContextRetirementEffect
40
40
  import { Type as Type$1 } from "@bastani/atomic-ai/utils/typebox/index";
41
41
  import { ModelRegistry } from "../core/model-registry.js";
42
42
  import { dialectOf, postgresJsonb } from "../core/storage/dialect.js";
43
+ import { ensureStorageSchema } from "../core/storage/migrations.js";
44
+ import { schemaCatalogOf, withStorageSchemaCatalog } from "../core/storage/schema-catalog.js";
43
45
  import { sequenceRunner } from "../core/storage/statement-sequence.js";
44
46
  import { createServer } from "node:http";
45
47
  import { Check, Errors } from "@bastani/atomic-ai/utils/typebox/value";
48
+ import { ensureTableFillfactor, storageSchemaCurrent, transactionFinisher } from "../core/storage/added-exports.js";
46
49
  import { assertStorageSchemaVersion, assertStoredSchemaVersion } from "../core/storage/schema.js";
47
50
  import { applyStorageMigrationsTogether, statementBatch } from "../core/storage/statement-batches.js";
48
51
  import { CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL, createGatewayBindingFetch } from "@bastani/atomic-ai/api/cloudflare-gateway-binding";
@@ -914,6 +917,155 @@ async function restoreRunWorktree(remotes, restore, options = {}) {
914
917
  }], options);
915
918
  return root;
916
919
  }
920
+ // dist/core/storage/session/fork-row-copy.js
921
+ /** How many entry IDs a run builder holds for lookups before it sends its runs, bounding what a fork holds. */
922
+ const HELD_RUN_ROWS = 4096;
923
+ /** How many hashes one blob statement names, so a statement stays small whatever the session holds. */
924
+ const BLOB_HASHES_PER_STATEMENT = 256;
925
+ /**
926
+ * The source's stored rows a fork copies, gathered into runs of consecutive seqs and copied a run at a time, each run in
927
+ * one `INSERT … SELECT` for its entries and one for their chunks (#6560), not one statement per row and chunk. Rows are
928
+ * copied in seq order, so the snapshot index's triggers meet a parent before its children, as they do for an append.
929
+ */
930
+ var ForkRowRuns = class {
931
+ tables;
932
+ child;
933
+ source;
934
+ runs = [];
935
+ /** The latest child seq of each entry ID among the rows not sent yet, for the fork's lookups. */
936
+ held = /* @__PURE__ */ new Map();
937
+ heldRows = 0;
938
+ constructor(tables, child, source) {
939
+ this.tables = tables;
940
+ this.child = child;
941
+ this.source = source;
942
+ }
943
+ /** Adds the source row at `sourceSeq` as the child's row at `childSeq`, whose entry ID is `entryId`. */
944
+ add(sourceSeq, childSeq, entryId) {
945
+ const last = this.runs.at(-1);
946
+ if (last !== void 0 && last.sourceFrom + last.count === sourceSeq && last.childFrom + last.count === childSeq) last.count++;
947
+ else this.runs.push({
948
+ sourceFrom: sourceSeq,
949
+ childFrom: childSeq,
950
+ count: 1
951
+ });
952
+ this.held.set(entryId, childSeq);
953
+ this.heldRows++;
954
+ }
955
+ /** The latest child seq of `entryId` among the rows added and not taken yet. */
956
+ heldSeq(entryId) {
957
+ return this.held.get(entryId);
958
+ }
959
+ /** Whether the runs hold as many rows as a fork may hold before it sends them. */
960
+ get full() {
961
+ return this.heldRows >= HELD_RUN_ROWS;
962
+ }
963
+ /**
964
+ * The statements that copy the runs added since the last call, in seq order, each with the rows it must copy: a run's
965
+ * entries statement copies one row for each of its seqs, or the source changed under the fork.
966
+ */
967
+ drain() {
968
+ const { entries, entryChunks } = this.tables;
969
+ const statements = [];
970
+ for (const { sourceFrom, childFrom, count } of this.runs) {
971
+ const params = [
972
+ this.child,
973
+ childFrom - sourceFrom,
974
+ this.source,
975
+ sourceFrom,
976
+ sourceFrom + count - 1
977
+ ];
978
+ statements.push({
979
+ sql: `INSERT INTO ${entries} (session_id, seq, entry_id, entry_json, chunks) SELECT ?, seq + ?, entry_id, entry_json, chunks FROM ${entries} WHERE session_id = ? AND seq BETWEEN ? AND ? ORDER BY seq`,
980
+ params,
981
+ changes: count,
982
+ mismatch: () => new SessionConflictError$1(this.source, sourceFrom, sourceFrom + count - 1)
983
+ }, {
984
+ sql: `INSERT INTO ${entryChunks} (session_id, seq, idx, data) SELECT ?, seq + ?, idx, data FROM ${entryChunks} WHERE session_id = ? AND seq BETWEEN ? AND ? ORDER BY seq, idx`,
985
+ params
986
+ });
987
+ }
988
+ this.runs = [];
989
+ this.held = /* @__PURE__ */ new Map();
990
+ this.heldRows = 0;
991
+ return statements;
992
+ }
993
+ };
994
+ /**
995
+ * The read that finds a stored entry of `child` missing any of its chunks, which the fork checks before it commits: an
996
+ * entry copied from the source names its chunk count, and the chunks were copied in the same statements.
997
+ */
998
+ function incompleteEntryRead(tables, child) {
999
+ return {
1000
+ sql: `SELECT e.seq FROM ${tables.entries} e WHERE e.session_id = ? AND e.chunks > 0 AND e.chunks <> (SELECT count(*) FROM ${tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq) LIMIT 1`,
1001
+ params: [child]
1002
+ };
1003
+ }
1004
+ /**
1005
+ * Copies the blobs `hashes` of session `source` to `child`, with their chunks, a few statements for all of them (#6560):
1006
+ * as `copyForkBlob` copied each one, a blob the child already holds is kept, one in the legacy one-row layout is copied
1007
+ * only with all its bytes, and each chunk only at its full length.
1008
+ */
1009
+ function forkBlobCopy(tables, options, source, child, hashes) {
1010
+ const { blobs, blobChunks } = tables;
1011
+ const columns = options.legacyBlobData ? ", data" : "";
1012
+ const sourceColumns = options.legacyBlobData ? ", p.data" : "";
1013
+ const whole = options.legacyBlobData ? " AND (p.chunks <> -1 OR length(p.data) = p.bytes)" : "";
1014
+ const statements = [];
1015
+ const checks = [];
1016
+ const groups = [];
1017
+ for (let start = 0; start < hashes.length; start += BLOB_HASHES_PER_STATEMENT) groups.push(hashes.slice(start, start + BLOB_HASHES_PER_STATEMENT));
1018
+ for (const group of groups) {
1019
+ const named = group.map(() => "?").join(", ");
1020
+ statements.push({
1021
+ sql: `INSERT INTO ${blobs} (session_id, hash, bytes, chunks${columns}) SELECT ?, p.hash, p.bytes, p.chunks${sourceColumns} FROM ${blobs} p WHERE p.session_id = ? AND p.hash IN (${named})${whole} AND NOT EXISTS (SELECT 1 FROM ${blobs} c WHERE c.session_id = ? AND c.hash = p.hash) ORDER BY p.hash`,
1022
+ params: [
1023
+ child,
1024
+ source,
1025
+ ...group,
1026
+ child
1027
+ ]
1028
+ }, {
1029
+ sql: `INSERT INTO ${blobChunks} (session_id, hash, idx, data) SELECT ?, k.hash, k.idx, k.data FROM ${blobChunks} k JOIN ${blobs} p ON p.session_id = k.session_id AND p.hash = k.hash WHERE k.session_id = ? AND k.hash IN (${named}) AND k.idx < p.chunks AND length(k.data) = CASE WHEN k.idx = p.chunks - 1 THEN p.bytes - k.idx * ? ELSE ? END AND NOT EXISTS (SELECT 1 FROM ${blobChunks} x WHERE x.session_id = ? AND x.hash = k.hash AND x.idx = k.idx) ORDER BY k.hash, k.idx`,
1030
+ params: [
1031
+ child,
1032
+ source,
1033
+ ...group,
1034
+ options.chunkBytes,
1035
+ options.chunkBytes,
1036
+ child
1037
+ ]
1038
+ });
1039
+ checks.push({
1040
+ sql: `SELECT p.hash, p.bytes, p.chunks, (SELECT count(*) FROM ${blobs} c WHERE c.session_id = ? AND c.hash = p.hash) AS copied, (SELECT count(*) FROM ${blobChunks} k WHERE k.session_id = ? AND k.hash = p.hash) AS parts FROM ${blobs} p WHERE p.session_id = ? AND p.hash IN (${named})`,
1041
+ params: [
1042
+ child,
1043
+ child,
1044
+ source,
1045
+ ...group
1046
+ ]
1047
+ });
1048
+ }
1049
+ return {
1050
+ statements,
1051
+ checks,
1052
+ remaining(answers) {
1053
+ const held = /* @__PURE__ */ new Set();
1054
+ for (const row of answers.flat()) {
1055
+ const hash = String(row.hash);
1056
+ const bytes = Number(row.bytes);
1057
+ const chunks = Number(row.chunks);
1058
+ if (!(Number(row.copied) === 1 && (chunks < 0 || chunks === Math.ceil(bytes / options.chunkBytes) && Number(row.parts) === chunks))) throw new SessionBlobError("blob-incomplete", {
1059
+ sessionId: source,
1060
+ hash,
1061
+ bytes
1062
+ });
1063
+ held.add(hash);
1064
+ }
1065
+ return hashes.filter((hash) => !held.has(hash));
1066
+ }
1067
+ };
1068
+ }
917
1069
  /** Never load the clone writer in an ordinary open. Fence a lapsed transfer before deleting so a paused donor
918
1070
  * cannot publish a partially swept transfer. When more rows remain, the new token stays expired. */
919
1071
  async function tryCleanupForkStaging(database, dialect, table) {
@@ -946,23 +1098,42 @@ const ORDER_BATCH = 128;
946
1098
  const lineKey = (anchor) => `L${anchor}`;
947
1099
  const orderKey = (promptId) => `O${promptId}`;
948
1100
  /**
949
- * Each write runs in a transaction of its own, as every session write does, on the session writer's connection and
950
- * in its order. A statement outside a transaction would wait for another process's write lock in node:sqlite's busy
951
- * handler, which blocks the event loop for up to the busy timeout (#5682); a transaction waits for the lock without
952
- * blocking it. A transient failure runs the write again, as one statement outside a transaction would.
1101
+ * The schema's setup runs in a transaction of its own, on the session writer's connection and in its order. A statement
1102
+ * outside a transaction would wait for another process's write lock in node:sqlite's busy handler, which blocks the
1103
+ * event loop for up to the busy timeout (#5682); a transaction waits for the lock without blocking it. A transient
1104
+ * failure runs it again, as one statement outside a transaction would. Each record's write does the same, as a write
1105
+ * of its session's rows (`sessionWriteTransaction`).
953
1106
  */
954
1107
  const SIDE_WRITE = { retryTransientFailures: true };
955
- /** A new physical table per format version; the main sessions schema (and all its old readers) stay unchanged. */
956
- function sqlChatRecords(database, sessions, table, index) {
1108
+ /** The chat records' name in the storage ledger: `atomic storage migrate` sets them up as the owner role. */
1109
+ const SESSION_CHAT_DOMAIN = "session-chat";
1110
+ /** The revision of the chat records' table and index: raise it whenever their setup creates anything new. */
1111
+ const SESSION_CHAT_REVISION = 1;
1112
+ /**
1113
+ * A new physical table per format version; the main sessions schema (and all its old readers) stay unchanged. `ledger`
1114
+ * is the prefix's storage ledger, which records the table and index once set up, so a runtime role without DDL
1115
+ * privileges runs no DDL once the owner created them.
1116
+ */
1117
+ function sqlChatRecords(database, sessions, table, index, ledger) {
957
1118
  const dialect = dialectOf(database);
1119
+ const schema = {
1120
+ ledger,
1121
+ domain: SESSION_CHAT_DOMAIN,
1122
+ revision: SESSION_CHAT_REVISION
1123
+ };
958
1124
  let initialized;
959
1125
  function initialize() {
960
- const create = () => database.transaction(async (tx) => {
961
- await tx.exec(`CREATE TABLE IF NOT EXISTS ${table} (
1126
+ const create = async () => {
1127
+ if (await withStorageSchemaCatalog(database, ledger, () => storageSchemaCurrent(database, schema))) return;
1128
+ await database.transaction((tx) => ensureStorageSchema(tx, dialect, schema, async () => {
1129
+ const probe = dialect.schemaObjects([table, index]);
1130
+ if ((await tx.all(probe.sql, ...probe.params)).length === 2) return;
1131
+ await tx.exec(`CREATE TABLE IF NOT EXISTS ${table} (
962
1132
  position ${dialect.types.serialKey}, session_id TEXT NOT NULL REFERENCES ${sessions}(id) ON DELETE CASCADE,
963
1133
  epoch TEXT NOT NULL, anchor TEXT NOT NULL, data TEXT NOT NULL)`);
964
- await tx.exec(`CREATE INDEX IF NOT EXISTS ${index} ON ${table}(session_id, epoch, anchor, position)`);
965
- }, SIDE_WRITE);
1134
+ await tx.exec(`CREATE INDEX IF NOT EXISTS ${index} ON ${table}(session_id, epoch, anchor, position)`);
1135
+ }), SIDE_WRITE);
1136
+ };
966
1137
  initialized ??= create().catch(() => create()).catch((error) => {
967
1138
  initialized = void 0;
968
1139
  throw error;
@@ -972,6 +1143,7 @@ function sqlChatRecords(database, sessions, table, index) {
972
1143
  const current = dialect.jsonText("summary_state", "epoch");
973
1144
  const bytes = (column) => dialect.textByteLength(column);
974
1145
  return {
1146
+ initialize,
975
1147
  async append(owner, anchor, record) {
976
1148
  record = boundedChatRecord(record);
977
1149
  await initialize();
@@ -989,7 +1161,7 @@ function sqlChatRecords(database, sessions, table, index) {
989
1161
  data,
990
1162
  owner.id,
991
1163
  owner.epoch
992
- ])), SIDE_WRITE);
1164
+ ])), sessionWriteTransaction(sessions, owner.id));
993
1165
  },
994
1166
  async has(owner) {
995
1167
  return !!await database.get(`SELECT 1 AS present FROM ${table} WHERE session_id=? AND epoch=? LIMIT 1`, owner.id, owner.epoch).catch(() => void 0);
@@ -1045,6 +1217,10 @@ const SESSION_SCHEMA_VERSION = 2;
1045
1217
  const SESSION_SCHEMA_VERSION_UNCHUNKED = 1;
1046
1218
  /** The schema domain of the session tables in the prefix's migration ledger. */
1047
1219
  const SESSION_DOMAIN = "sessions";
1220
+ /** The ledger step, `schema:session-fillfactor`, that sets the sessions table's fillfactor on PostgreSQL (#6560). */
1221
+ const SESSION_FILLFACTOR_DOMAIN = "session-fillfactor";
1222
+ /** The fillfactor of the sessions table on PostgreSQL: a fifth of each page stays free for head row updates. */
1223
+ const SESSION_ROW_FILLFACTOR = 80;
1048
1224
  /**
1049
1225
  * The most bytes of a chunked session blob one row holds. New blobs use a header row and rows of at most this size,
1050
1226
  * so their bound and returned values stay within it: libSQL servers cap a row and a bound value (sqld's default is
@@ -1218,6 +1394,14 @@ const LISTING_SCOPES = 8;
1218
1394
  * ended before it committed runs again (#4383); `append` and `replace` check `expectSeq` again on each run.
1219
1395
  */
1220
1396
  const SESSION_TRANSACTION = { retryTransientFailures: true };
1397
+ /**
1398
+ * A session read: one snapshot that takes no write lock, so it neither waits for writers nor makes them wait. Its
1399
+ * statements all run in that snapshot: split into separate ones, a read could join rows of two generations.
1400
+ */
1401
+ const SESSION_READ = {
1402
+ retryTransientFailures: true,
1403
+ readOnly: true
1404
+ };
1221
1405
  /** The largest content index or suffix length a task-reference query binds, an SQL `INTEGER` on every backend. */
1222
1406
  const TASK_REFERENCE_INTEGER = 2 ** 31 - 1;
1223
1407
  /**
@@ -1297,6 +1481,51 @@ function statementBytes(statement) {
1297
1481
  else bytes += 8;
1298
1482
  return bytes;
1299
1483
  }
1484
+ /**
1485
+ * Writes of one transaction sent without waiting for each answer: the connection runs them in the order they were
1486
+ * sent, behind the transaction's earlier calls and ahead of its later ones, so a read made after `send` sees them. On a
1487
+ * pipelined connection they share round trips instead of taking one each. At most `STATEMENT_BATCH_BYTES` of them are
1488
+ * unanswered at a time. `settle` waits for every one sent and throws the first that failed.
1489
+ */
1490
+ var SentWrites = class {
1491
+ tx;
1492
+ sent = [];
1493
+ unansweredBytes = 0;
1494
+ failure;
1495
+ constructor(tx) {
1496
+ this.tx = tx;
1497
+ }
1498
+ /** Sends `statements`; a counted one fails when its answer reports another number of changed rows. */
1499
+ async send(statements) {
1500
+ for (const statement of statements) {
1501
+ const { changes, mismatch } = statement;
1502
+ this.sent.push(this.tx.run(statement.sql, ...statement.params).then((result) => {
1503
+ if (changes !== void 0 && result.changes !== changes) this.failure ??= { error: mismatch?.() ?? new StorageError(`A write changed ${result.changes} rows where ${changes} were expected`) };
1504
+ }, (error) => {
1505
+ this.failure ??= { error };
1506
+ }));
1507
+ this.unansweredBytes += statementBytes(statement);
1508
+ if (this.unansweredBytes > STATEMENT_BATCH_BYTES) await this.settle();
1509
+ }
1510
+ }
1511
+ async settle() {
1512
+ await Promise.all(this.sent.splice(0));
1513
+ this.unansweredBytes = 0;
1514
+ if (this.failure !== void 0) throw this.failure.error;
1515
+ }
1516
+ /** Settles after `body`, and reports the first write that failed before what `body` met, as its cause. */
1517
+ async around(body) {
1518
+ let value;
1519
+ try {
1520
+ value = await body();
1521
+ } catch (error) {
1522
+ await this.settle();
1523
+ throw error;
1524
+ }
1525
+ await this.settle();
1526
+ return value;
1527
+ }
1528
+ };
1300
1529
  var SqlSessionStore = class SqlSessionStore {
1301
1530
  database;
1302
1531
  dialect;
@@ -1312,6 +1541,8 @@ var SqlSessionStore = class SqlSessionStore {
1312
1541
  openMarkers;
1313
1542
  searchIndex;
1314
1543
  chatStore;
1544
+ /** The database's reader handle, once a read opened it: see `readerDatabase`. */
1545
+ reader;
1315
1546
  /**
1316
1547
  * Absent on a local libSQL file, which then behaves as before: @libsql/client waits for another process's write
1317
1548
  * lock on the calling thread, even to begin a transaction, so a side write would stop the event loop where an
@@ -1325,7 +1556,7 @@ var SqlSessionStore = class SqlSessionStore {
1325
1556
  rows: "chat_v1",
1326
1557
  byAnchor: "chat_v1_anchor"
1327
1558
  }, this.prefix);
1328
- this.chatStore = sqlChatRecords(this.database, this.tables.sessions, names.rows, names.byAnchor);
1559
+ this.chatStore = sqlChatRecords(this.database, this.tables.sessions, names.rows, names.byAnchor, storageMigrationTable(this.prefix));
1329
1560
  }
1330
1561
  return this.chatStore;
1331
1562
  }
@@ -1350,11 +1581,15 @@ var SqlSessionStore = class SqlSessionStore {
1350
1581
  this.entryByteLength = entryByteLength;
1351
1582
  this.tables = tables;
1352
1583
  this.prefix = prefix ?? "";
1353
- registerForkScope(this, () => ({
1354
- kind: "sql",
1355
- backing: this.database,
1356
- prefix: this.prefix
1357
- }));
1584
+ registerForkScope(this, () => {
1585
+ const identity = this.database.databaseIdentity?.();
1586
+ return {
1587
+ kind: "sql",
1588
+ backing: this.database,
1589
+ prefix: this.prefix,
1590
+ ...identity === void 0 ? {} : { identity }
1591
+ };
1592
+ });
1358
1593
  this.cwdMatcher = cwdMatcher;
1359
1594
  this.snapshotBlobs = snapshotBlobs;
1360
1595
  this.blobTable = snapshotBlobs;
@@ -1363,10 +1598,10 @@ var SqlSessionStore = class SqlSessionStore {
1363
1598
  registerHistorySnapshot(this, (sessionId, project) => {
1364
1599
  this.assertOpen();
1365
1600
  validateSessionText("sessionId", sessionId);
1366
- return this.transaction(async (tx) => {
1367
- const head = await this.historyHead(tx, sessionId);
1601
+ return this.readTransaction(async (tx) => {
1602
+ const head = await this.historyHead(tx, sessionId, true);
1368
1603
  return project(head.epoch, head.lastSeq, (from, through, backward) => this.historyPacket(tx, sessionId, head.epoch, from, through, backward));
1369
- }, SESSION_TRANSACTION);
1604
+ });
1370
1605
  });
1371
1606
  this.forkStagingTable = renderStorageIdentifiers("sessions", SESSION_FORK_STAGING_TABLES, prefix).forkStaging;
1372
1607
  }
@@ -1379,6 +1614,9 @@ var SqlSessionStore = class SqlSessionStore {
1379
1614
  }
1380
1615
  static async open(database, options = {}) {
1381
1616
  validateStoragePrefix(options.prefix, dialectOf(database).name);
1617
+ return withStorageSchemaCatalog(database, storageMigrationTable(options.prefix), () => SqlSessionStore.openWithCatalog(database, options));
1618
+ }
1619
+ static async openWithCatalog(database, options) {
1382
1620
  const tables = renderStorageIdentifiers("sessions", SESSION_TABLES, options.prefix);
1383
1621
  let legacyBlobData = false;
1384
1622
  const createTables = async (tx, dialect) => {
@@ -1487,9 +1725,17 @@ var SqlSessionStore = class SqlSessionStore {
1487
1725
  acceptNewer: true
1488
1726
  }
1489
1727
  }]);
1728
+ await ensureTableFillfactor(database, {
1729
+ ledger: storageMigrationTable(options.prefix),
1730
+ domain: SESSION_FILLFACTOR_DOMAIN,
1731
+ revision: 1,
1732
+ table: tables.sessions,
1733
+ fillfactor: SESSION_ROW_FILLFACTOR
1734
+ });
1490
1735
  const staging = renderStorageIdentifiers("sessions", SESSION_FORK_STAGING_TABLES, options.prefix).forkStaging;
1491
1736
  const stagingProbe = dialectOf(database).tableExists(staging);
1492
- const staged = database.readOnly === true || !database.tryMaintenance ? Promise.resolve(false) : database.get(stagingProbe.sql, ...stagingProbe.params).then((row) => row !== void 0, () => false);
1737
+ const catalog = await schemaCatalogOf(database);
1738
+ const staged = database.readOnly === true || !database.tryMaintenance ? Promise.resolve(false) : catalog !== void 0 ? Promise.resolve(catalog.hasTable(staging)) : database.get(stagingProbe.sql, ...stagingProbe.params).then((row) => row !== void 0, () => false);
1493
1739
  const opening = current === void 0 ? await SqlSnapshotBlobStore$1.open(database, options.prefix) : void 0;
1494
1740
  const [blobs, searchIndex, entryByteLength] = await Promise.all([
1495
1741
  opening ?? SqlSnapshotBlobStore$1.open(database, options.prefix),
@@ -1521,22 +1767,34 @@ var SqlSessionStore = class SqlSessionStore {
1521
1767
  static async currentSchema(database, tables, open, orphans) {
1522
1768
  const dialect = dialectOf(database);
1523
1769
  if (dialect.versionedMigrations) return void 0;
1524
- const probes = [
1525
- ...[...Object.values(tables), open].map((table) => dialect.tableExists(table)),
1526
- dialect.columnExists(tables.sessions, "revision"),
1527
- dialect.columnExists(tables.entries, "chunks"),
1528
- dialect.columnExists(tables.blobs, "chunks"),
1529
- dialect.columnExists(open, "schema_version")
1770
+ const required = [...Object.values(tables), open];
1771
+ const columns = [
1772
+ [tables.sessions, "revision"],
1773
+ [tables.entries, "chunks"],
1774
+ [tables.blobs, "chunks"],
1775
+ [open, "schema_version"]
1530
1776
  ];
1531
- const legacy = dialect.columnExists(tables.blobs, "data");
1532
- const [legacyFound, ...found] = await Promise.all([legacy, ...probes].map((probe) => database.get(probe.sql, ...probe.params)));
1533
- if (!found.every((row) => row !== void 0)) return void 0;
1777
+ const reading = schemaCatalogOf(database);
1534
1778
  const orphaned = orphans === void 0 ? void 0 : database.get(`SELECT 1 FROM (${orphans}) AS orphaned LIMIT 1`);
1535
1779
  orphaned?.catch(() => {});
1536
- const versions = await database.all(`SELECT schema_version FROM ${tables.meta}`);
1780
+ const versionsRead = database.all(`SELECT schema_version FROM ${tables.meta}`);
1781
+ versionsRead.catch(() => {});
1782
+ let legacyBlobs;
1783
+ const catalog = await reading;
1784
+ if (catalog !== void 0) {
1785
+ if (!(required.every((table) => catalog.hasTable(table)) && columns.every(([table, column]) => catalog.hasColumn(table, column)))) return void 0;
1786
+ legacyBlobs = catalog.hasColumn(tables.blobs, "data");
1787
+ } else {
1788
+ const probes = [...required.map((table) => dialect.tableExists(table)), ...columns.map(([table, column]) => dialect.columnExists(table, column))];
1789
+ const legacy = dialect.columnExists(tables.blobs, "data");
1790
+ const [legacyFound, ...found] = await Promise.all([legacy, ...probes].map((probe) => database.get(probe.sql, ...probe.params)));
1791
+ if (!found.every((row) => row !== void 0)) return void 0;
1792
+ legacyBlobs = legacyFound !== void 0;
1793
+ }
1794
+ const versions = await versionsRead;
1537
1795
  if (versions.length === 0 || versions.some((row) => row.schema_version !== SESSION_SCHEMA_VERSION_UNCHUNKED && row.schema_version !== 2)) return void 0;
1538
1796
  return {
1539
- legacyBlobData: legacyFound !== void 0,
1797
+ legacyBlobData: legacyBlobs,
1540
1798
  orphaned: await orphaned !== void 0
1541
1799
  };
1542
1800
  }
@@ -1548,7 +1806,54 @@ var SqlSessionStore = class SqlSessionStore {
1548
1806
  return this.database.transaction(async (tx) => {
1549
1807
  await this.assertReadableSchema(tx);
1550
1808
  return body(tx);
1551
- }, options);
1809
+ }, this.checkedFirst(options));
1810
+ }
1811
+ /**
1812
+ * `options` with the schema check its transaction makes first, before the reads `options.leading` names, sent with
1813
+ * the transaction's start where the connection is pipelined.
1814
+ */
1815
+ checkedFirst(options) {
1816
+ return {
1817
+ ...options,
1818
+ leading: [this.schemaCheck(), ...options.leading ?? []]
1819
+ };
1820
+ }
1821
+ /**
1822
+ * `transaction` for a write to the rows of the session `sessionId` only, beside writers of other sessions. `leading`
1823
+ * names the reads the body makes first, after the schema check.
1824
+ */
1825
+ sessionWrite(sessionId, ...leading) {
1826
+ const options = sessionWriteTransaction(this.tables.sessions, sessionId);
1827
+ return leading.length === 0 ? options : {
1828
+ ...options,
1829
+ leading
1830
+ };
1831
+ }
1832
+ /**
1833
+ * `transaction` for a body that only reads, in one read-only snapshot, on the database's reader handle when it
1834
+ * offers one: its reads then wait for neither the writes queued on this store's connection nor their locks.
1835
+ */
1836
+ async readTransaction(body, leading = []) {
1837
+ return (await this.readerDatabase()).transaction(async (tx) => {
1838
+ await this.assertReadableSchema(tx);
1839
+ return body(tx);
1840
+ }, this.checkedFirst(leading.length === 0 ? SESSION_READ : {
1841
+ ...SESSION_READ,
1842
+ leading
1843
+ }));
1844
+ }
1845
+ /**
1846
+ * The database's reader handle, opened at the first read and closed with the store; the database without one. A
1847
+ * reader that cannot open, such as when its file can no longer be opened anew, leaves the read on the store's own
1848
+ * connection, as every read ran before readers, and the next read tries to open one again.
1849
+ */
1850
+ readerDatabase() {
1851
+ if (this.database.openReader === void 0) return this.database;
1852
+ this.reader ??= this.database.openReader().catch((error) => {
1853
+ this.reader = void 0;
1854
+ throw error;
1855
+ });
1856
+ return this.reader.catch(() => this.database);
1552
1857
  }
1553
1858
  /**
1554
1859
  * `transaction` for a body that only reads and writes the database. The version check is sent first, as there, but on
@@ -1569,10 +1874,17 @@ var SqlSessionStore = class SqlSessionStore {
1569
1874
  await checked;
1570
1875
  if ("failure" in outcome) throw outcome.failure;
1571
1876
  return outcome.value;
1572
- }, options);
1877
+ }, this.checkedFirst(options));
1878
+ }
1879
+ /** The read that checks the sessions schema version, which every transaction of this store makes first. */
1880
+ schemaCheck() {
1881
+ return {
1882
+ sql: `SELECT schema_version FROM ${this.tables.meta}`,
1883
+ params: []
1884
+ };
1573
1885
  }
1574
1886
  assertReadableSchema(executor) {
1575
- return assertStoredSchemaVersion(executor, { sql: `SELECT schema_version FROM ${this.tables.meta}` }, "sessions", 2, "schema_version", SESSION_SCHEMA_VERSION_UNCHUNKED);
1887
+ return assertStoredSchemaVersion(executor, this.schemaCheck(), "sessions", 2, "schema_version", SESSION_SCHEMA_VERSION_UNCHUNKED);
1576
1888
  }
1577
1889
  get descriptor() {
1578
1890
  return {
@@ -1584,8 +1896,12 @@ var SqlSessionStore = class SqlSessionStore {
1584
1896
  this.assertOpen();
1585
1897
  validateSessionHeader(header);
1586
1898
  validateSessionEntries(entries);
1899
+ const existing = {
1900
+ sql: `SELECT id FROM ${this.tables.sessions} WHERE id = ?`,
1901
+ params: [header.id]
1902
+ };
1587
1903
  return this.transactionCheckedAlongside(async (tx, checked) => {
1588
- if (await tx.get(`SELECT id FROM ${this.tables.sessions} WHERE id = ?`, header.id)) throw new SessionExistsError$1(header.id);
1904
+ if (await tx.get(existing.sql, ...existing.params)) throw new SessionExistsError$1(header.id);
1589
1905
  const summary = this.summaryWrite(header.id, {
1590
1906
  header,
1591
1907
  entries,
@@ -1597,11 +1913,11 @@ var SqlSessionStore = class SqlSessionStore {
1597
1913
  lastSeq: entries.length,
1598
1914
  epoch: summary.epoch
1599
1915
  };
1600
- }, SESSION_TRANSACTION);
1916
+ }, this.sessionWrite(header.id, existing));
1601
1917
  }
1602
1918
  async createFork(header, entries, source) {
1603
1919
  if (this.create !== SqlSessionStore.prototype.create) return void 0;
1604
- if (source.store !== this) {
1920
+ if (!this.sharesTablesWith(source.store)) {
1605
1921
  if ("read" in entries) return entries.kind === "complete-session" ? this.createStagedFork(header, entries, source) : void 0;
1606
1922
  if (source.receipts.size < 2) return void 0;
1607
1923
  return this.createStagedFork(header, { async *read() {
@@ -1616,36 +1932,111 @@ var SqlSessionStore = class SqlSessionStore {
1616
1932
  validateSessionHeader(header);
1617
1933
  validateSessionEntries(entries);
1618
1934
  return this.transaction(async (tx) => {
1619
- if (await tx.get(`SELECT id FROM ${this.tables.sessions} WHERE id = ?`, header.id)) throw new SessionExistsError$1(header.id);
1620
- const donor = await this.historyHead(tx, source.sessionId);
1621
- if (source.epoch !== void 0 && donor.epoch !== source.epoch) throw new SessionConflictError$1(source.sessionId, 0, donor.lastSeq);
1622
- const { texts, epoch } = await this.saveSummary(tx, header.id, {
1935
+ const donor = await this.forkDonor(tx, header.id, source);
1936
+ for (const entry of entries) {
1937
+ const ref = source.receipts.get(entry.id);
1938
+ if (ref && (source.sessionId !== ref.sessionId || donor.epoch !== ref.epoch || donor.lastSeq < ref.seq)) throw new SessionConflictError$1(ref.sessionId, ref.seq, donor.lastSeq);
1939
+ }
1940
+ const summary = this.summaryWrite(header.id, {
1623
1941
  header,
1624
1942
  entries,
1625
1943
  lastSeq: entries.length
1626
1944
  });
1627
- await this.insertEntries(tx, header.id, entries, 0, texts);
1628
- for (const [i, entry] of entries.entries()) {
1629
- const ref = source.receipts.get(entry.id);
1630
- if (!ref) continue;
1631
- if (source.sessionId !== ref.sessionId || donor.epoch !== ref.epoch || donor.lastSeq < ref.seq) throw new SessionConflictError$1(ref.sessionId, ref.seq, donor.lastSeq);
1632
- const original = await tx.get(`SELECT chunks FROM ${this.tables.entries} WHERE session_id=? AND seq=? AND entry_id=?`, ref.sessionId, ref.seq, entry.id);
1633
- if (!original) throw new SessionConflictError$1(ref.sessionId, ref.seq, donor.lastSeq);
1634
- await tx.run(`DELETE FROM ${this.tables.entries} WHERE session_id=? AND seq=?`, header.id, i + 1);
1635
- await tx.run(`INSERT INTO ${this.tables.entries} (session_id, seq, entry_id, entry_json, chunks) SELECT ?, ?, entry_id,entry_json,chunks FROM ${this.tables.entries} WHERE session_id=? AND seq=?`, header.id, i + 1, ref.sessionId, ref.seq);
1636
- for (let part = 0; part < original.chunks; part++) {
1637
- const { changes } = await tx.run(`INSERT INTO ${this.tables.entryChunks} (session_id, seq, idx, data) SELECT ?, ?, idx, data FROM ${this.tables.entryChunks} WHERE session_id=? AND seq=? AND idx=?`, header.id, i + 1, ref.sessionId, ref.seq, part);
1638
- if (changes !== 1) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing chunk of session entry ${ref.seq}`));
1639
- }
1640
- }
1641
- const remainingBlobs = [];
1642
- for (const hash of source.hashes) if (!await this.copyForkBlob(tx, source.sessionId, header.id, hash)) remainingBlobs.push(hash);
1945
+ const blobs = this.forkBlobCopy(source.sessionId, header.id, source.hashes);
1946
+ const writes = new SentWrites(tx);
1947
+ const remainingBlobs = await writes.around(async () => {
1948
+ await writes.send([summary.statement]);
1949
+ await writes.send(this.receiptForkWrites(header.id, entries, source, donor.lastSeq));
1950
+ await writes.send(this.entryWrites(header.id, [], 0, summary.texts, false));
1951
+ return this.finishForkCopy(tx, writes, header.id, blobs, source.hashes);
1952
+ });
1953
+ await this.finishFork(tx, header.id);
1643
1954
  return {
1644
1955
  lastSeq: entries.length,
1645
- epoch,
1956
+ epoch: summary.epoch,
1646
1957
  remainingBlobs
1647
1958
  };
1648
- }, SESSION_TRANSACTION);
1959
+ }, this.sessionWrite(header.id));
1960
+ }
1961
+ /**
1962
+ * The source session's head, its row locked for share, once the child is known to be new: both reads go out together,
1963
+ * one round trip (#6560). Fails as the source changed when it is no longer the generation the fork read.
1964
+ */
1965
+ async forkDonor(tx, child, source) {
1966
+ const existing = tx.get(`SELECT id FROM ${this.tables.sessions} WHERE id = ?`, child);
1967
+ const head = this.historyHead(tx, source.sessionId).then((value) => ({ value }), (error) => ({ error }));
1968
+ if (await existing) throw new SessionExistsError$1(child);
1969
+ const read = await head;
1970
+ if ("error" in read) throw read.error;
1971
+ const donor = read.value;
1972
+ if (source.epoch !== void 0 && donor.epoch !== source.epoch) throw new SessionConflictError$1(source.sessionId, 0, donor.lastSeq);
1973
+ return donor;
1974
+ }
1975
+ /**
1976
+ * The statements that store a fork's `entries`, in seq order: an entry with a receipt as the source stores it, its row
1977
+ * and chunks copied in two statements whatever their size, and any other as `create` stores it. A receipt's row that
1978
+ * names another entry fails the fork: the source changed under it.
1979
+ */
1980
+ *receiptForkWrites(child, entries, source, donorLastSeq) {
1981
+ for (const [index, entry] of entries.entries()) {
1982
+ const ref = source.receipts.get(entry.id);
1983
+ if (ref === void 0) {
1984
+ yield* this.entryWrites(child, [entry], index, [], false);
1985
+ continue;
1986
+ }
1987
+ yield {
1988
+ sql: `INSERT INTO ${this.tables.entries} (session_id, seq, entry_id, entry_json, chunks) SELECT ?, ?, entry_id, entry_json, chunks FROM ${this.tables.entries} WHERE session_id = ? AND seq = ? AND entry_id = ?`,
1989
+ params: [
1990
+ child,
1991
+ index + 1,
1992
+ ref.sessionId,
1993
+ ref.seq,
1994
+ entry.id
1995
+ ],
1996
+ changes: 1,
1997
+ mismatch: () => new SessionConflictError$1(ref.sessionId, ref.seq, donorLastSeq)
1998
+ };
1999
+ yield {
2000
+ sql: `INSERT INTO ${this.tables.entryChunks} (session_id, seq, idx, data) SELECT ?, ?, idx, data FROM ${this.tables.entryChunks} WHERE session_id = ? AND seq = ? ORDER BY idx`,
2001
+ params: [
2002
+ child,
2003
+ index + 1,
2004
+ ref.sessionId,
2005
+ ref.seq
2006
+ ]
2007
+ };
2008
+ }
2009
+ }
2010
+ /**
2011
+ * The blob copy of a fork from session `source` of this store's tables (#6560), or undefined when a subclass stores
2012
+ * blobs its own way: `createForkArchive` then copies every one through it.
2013
+ */
2014
+ forkBlobCopy(source, child, hashes) {
2015
+ if (this.getBlob !== SqlSessionStore.prototype.getBlob || this.putBlob !== SqlSessionStore.prototype.putBlob) return void 0;
2016
+ return forkBlobCopy(this.tables, {
2017
+ legacyBlobData: this.legacyBlobData,
2018
+ chunkBytes: SESSION_BLOB_CHUNK_BYTES
2019
+ }, source, child, [...new Set(hashes)]);
2020
+ }
2021
+ /**
2022
+ * Sends a fork's blob copy behind its entries, then checks, in one round trip with them, that every stored entry of
2023
+ * the child has all its chunks and which blobs were copied whole. Resolves with the hashes left for
2024
+ * `copySessionBlobs`: those the source does not hold, or all of them where this store does not copy blobs itself.
2025
+ */
2026
+ async finishForkCopy(tx, writes, child, blobs, hashes) {
2027
+ if (blobs) await writes.send(blobs.statements);
2028
+ const incomplete = incompleteEntryRead(this.tables, child);
2029
+ const [missing, ...answers] = await Promise.all([tx.get(incomplete.sql, ...incomplete.params), ...(blobs?.checks ?? []).map((check) => tx.all(check.sql, ...check.params))]);
2030
+ if (missing !== void 0) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing chunk of session entry ${missing.seq}`));
2031
+ return blobs ? blobs.remaining(answers) : [...new Set(hashes)];
2032
+ }
2033
+ /**
2034
+ * Whether `store` keeps its sessions in this store's very tables, so that this store's transaction reads its rows: this
2035
+ * store, or another session store opened on the same database with the same prefix, such as through another handle
2036
+ * (#6560). A wrapper that serves sessions of its own does not.
2037
+ */
2038
+ sharesTablesWith(store) {
2039
+ return store === this || store instanceof SqlSessionStore && forkStoreRelation(store, this) === "same";
1649
2040
  }
1650
2041
  /**
1651
2042
  * Clone a complete session, as `create` with every source entry and blob would, from a store on a handle this one
@@ -1669,6 +2060,15 @@ var SqlSessionStore = class SqlSessionStore {
1669
2060
  await ensureForkStagingTable(this.database, this.dialect, this.forkStagingTable);
1670
2061
  await cleanupForkStaging(this.database, this.dialect, this.forkStagingTable, Number.POSITIVE_INFINITY);
1671
2062
  }
2063
+ /**
2064
+ * Creates the chat records' table and index unless the ledger records them, as `atomic storage migrate` does as the
2065
+ * owner role: a runtime role without DDL privileges then saves chat records too. Opens never create them; the first
2066
+ * chat record does where `migrate` has not run.
2067
+ */
2068
+ async prepareChatRecords() {
2069
+ this.assertOpen();
2070
+ await this.chatRecords?.initialize();
2071
+ }
1672
2072
  forkStagingTarget() {
1673
2073
  return {
1674
2074
  database: this.database,
@@ -1681,8 +2081,8 @@ var SqlSessionStore = class SqlSessionStore {
1681
2081
  unchunkedSchemaVersion: SESSION_SCHEMA_VERSION_UNCHUNKED,
1682
2082
  chunkedSchemaVersion: 2,
1683
2083
  ownsBlobs: this.getBlob === SqlSessionStore.prototype.getBlob && this.putBlob === SqlSessionStore.prototype.putBlob,
1684
- transaction: (body) => this.transaction(body, SESSION_TRANSACTION),
1685
- saveSummary: (tx, header, lastSeq, summary, index) => this.saveSummary(tx, header.id, {
2084
+ transaction: (sessionId, body, leading) => this.transaction(body, this.sessionWrite(sessionId, ...leading)),
2085
+ summaryWrite: (header, lastSeq, summary, index) => this.summaryWrite(header.id, {
1686
2086
  header,
1687
2087
  entries: [],
1688
2088
  lastSeq
@@ -1704,6 +2104,10 @@ var SqlSessionStore = class SqlSessionStore {
1704
2104
  sourceBlobParts: (source) => {
1705
2105
  const store = nativeForkReader(source, "blob");
1706
2106
  return store instanceof SqlSessionStore && store.getBlob === SqlSessionStore.prototype.getBlob ? (sessionId, hash, offset, legacyBytes) => store.readBlobPart(sessionId, hash, offset, legacyBytes) : void 0;
2107
+ },
2108
+ sourceBlobFirstParts: (source) => {
2109
+ const store = nativeForkReader(source, "blob");
2110
+ return store instanceof SqlSessionStore && store.getBlob === SqlSessionStore.prototype.getBlob ? (sessionId, hashes, maxBytes) => store.readBlobFirstParts(sessionId, hashes, maxBytes) : void 0;
1707
2111
  }
1708
2112
  };
1709
2113
  }
@@ -1713,9 +2117,9 @@ var SqlSessionStore = class SqlSessionStore {
1713
2117
  */
1714
2118
  async readStoredEntryChunk(reference, index) {
1715
2119
  this.assertOpen();
1716
- return this.transaction(async (tx) => {
2120
+ return this.readTransaction(async (tx) => {
1717
2121
  const { sessionId, epoch, seq } = reference;
1718
- const head = await this.historyHead(tx, sessionId);
2122
+ const head = await this.historyHead(tx, sessionId, true);
1719
2123
  if (head.epoch !== epoch) throw new SessionConflictError$1(sessionId, seq, head.lastSeq);
1720
2124
  const row = await tx.get(`SELECT e.chunks, c.data FROM ${this.tables.entries} e LEFT JOIN ${this.tables.entryChunks} c
1721
2125
  ON c.session_id = e.session_id AND c.seq = e.seq AND c.idx = ? WHERE e.session_id = ? AND e.seq = ?`, index, sessionId, seq);
@@ -1723,19 +2127,39 @@ var SqlSessionStore = class SqlSessionStore {
1723
2127
  if (Number(row.chunks) === 0) return void 0;
1724
2128
  if (row.data == null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing chunk of session entry ${seq}`));
1725
2129
  return row.data;
1726
- }, SESSION_TRANSACTION);
2130
+ });
1727
2131
  }
1728
2132
  /** How many chunks the entry `reference` names is stored in, 0 when it is stored whole, in its generation. */
1729
2133
  async readStoredChunks(reference) {
1730
2134
  this.assertOpen();
1731
- return this.transaction(async (tx) => {
2135
+ return this.readTransaction(async (tx) => {
1732
2136
  const { sessionId, epoch, seq } = reference;
1733
- const head = await this.historyHead(tx, sessionId);
2137
+ const head = await this.historyHead(tx, sessionId, true);
1734
2138
  if (head.epoch !== epoch) throw new SessionConflictError$1(sessionId, seq, head.lastSeq);
1735
2139
  const row = await tx.get(`SELECT chunks FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, seq);
1736
2140
  if (!row) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing session entry ${seq}`));
1737
2141
  return Number(row.chunks);
1738
- }, SESSION_TRANSACTION);
2142
+ });
2143
+ }
2144
+ /**
2145
+ * The headers of the blobs `hashes` of session `sessionId` in one read (#6560), each with its first chunk row when it
2146
+ * is stored in chunks of at most `maxBytes` in all, as `readBlobPart` reads them at offset 0. A blob the session does
2147
+ * not hold is left out; one in the legacy one-row layout comes without its value.
2148
+ */
2149
+ async readBlobFirstParts(sessionId, hashes, maxBytes) {
2150
+ this.assertOpen();
2151
+ const parts = /* @__PURE__ */ new Map();
2152
+ if (hashes.length === 0) return parts;
2153
+ const rows = await this.database.all(`SELECT b.hash, b.bytes, b.chunks, CASE WHEN b.chunks >= 0 AND b.bytes <= ? THEN c.data END AS data
2154
+ FROM ${this.tables.blobs} b LEFT JOIN ${this.tables.blobChunks} c
2155
+ ON c.session_id = b.session_id AND c.hash = b.hash AND c.idx = 0
2156
+ WHERE b.session_id = ? AND b.hash IN (${hashes.map(() => "?").join(", ")})`, maxBytes, sessionId, ...hashes);
2157
+ for (const row of rows) parts.set(String(row.hash), {
2158
+ bytes: Number(row.bytes),
2159
+ chunks: Number(row.chunks),
2160
+ ...row.data == null ? {} : { data: row.data }
2161
+ });
2162
+ return parts;
1739
2163
  }
1740
2164
  /**
1741
2165
  * The bytes of a blob from `offset`, a multiple of {@link SESSION_BLOB_CHUNK_BYTES}, so a staged clone never holds
@@ -1756,34 +2180,13 @@ var SqlSessionStore = class SqlSessionStore {
1756
2180
  ...row.data == null ? {} : { data: row.data }
1757
2181
  };
1758
2182
  }
1759
- async copyForkBlob(tx, sessionId, childId, hash) {
1760
- if (this.getBlob !== SqlSessionStore.prototype.getBlob || this.putBlob !== SqlSessionStore.prototype.putBlob) return false;
1761
- const blob = await tx.get(`SELECT bytes,chunks FROM ${this.tables.blobs} WHERE session_id=? AND hash=?`, sessionId, hash);
1762
- if (!blob) return false;
1763
- if (await tx.get(`SELECT hash FROM ${this.tables.blobs} WHERE session_id=? AND hash=?`, childId, hash)) return true;
1764
- const columns = this.legacyBlobData ? ", data" : "";
1765
- const { changes } = await tx.run(`INSERT INTO ${this.tables.blobs} (session_id,hash,bytes,chunks${columns}) SELECT ?,hash,bytes,chunks${columns} FROM ${this.tables.blobs} WHERE session_id=? AND hash=?${this.legacyBlobData ? " AND (chunks<>-1 OR length(data)=bytes)" : ""}`, childId, sessionId, hash);
1766
- if (changes !== 1 || blob.chunks >= 0 && blob.chunks !== Math.ceil(blob.bytes / 1048576)) throw new SessionBlobError("blob-incomplete", {
1767
- sessionId,
1768
- hash,
1769
- bytes: blob.bytes
1770
- });
1771
- for (let part = 0; part < blob.chunks; part++) if ((await tx.run(`INSERT INTO ${this.tables.blobChunks} (session_id,hash,idx,data) SELECT ?,hash,idx,data FROM ${this.tables.blobChunks} WHERE session_id=? AND hash=? AND idx=? AND length(data)=?`, childId, sessionId, hash, part, Math.min(1048576, blob.bytes - part * 1048576))).changes !== 1) throw new SessionBlobError("blob-incomplete", {
1772
- sessionId,
1773
- hash,
1774
- bytes: blob.bytes
1775
- });
1776
- return true;
1777
- }
1778
2183
  async createStreamedFork(header, stream, source) {
1779
2184
  this.assertOpen();
1780
2185
  validateSessionHeader(header);
1781
2186
  const { encodedForkRow } = await import("../core/storage/session/fork-row-bytes.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
1782
2187
  const { foldForkRow } = await import("../core/storage/session/fork-row-index.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
1783
2188
  return this.transaction(async (tx) => {
1784
- if (await tx.get(`SELECT id FROM ${this.tables.sessions} WHERE id=?`, header.id)) throw new SessionExistsError$1(header.id);
1785
- const head = await this.historyHead(tx, source.sessionId);
1786
- if (source.epoch !== void 0 && head.epoch !== source.epoch) throw new SessionConflictError$1(source.sessionId, 0, head.lastSeq);
2189
+ const head = await this.forkDonor(tx, header.id, source);
1787
2190
  const reader = new SqlSessionStore({
1788
2191
  descriptor: this.database.descriptor,
1789
2192
  dialect: this.dialect,
@@ -1797,11 +2200,13 @@ var SqlSessionStore = class SqlSessionStore {
1797
2200
  }, this.tables, this.prefix, this.cwdMatcher, this.blobTable, this.legacyBlobData, void 0, this.entryByteLength);
1798
2201
  const { index: donorIndex } = await reader.prepareResume(source.sessionId);
1799
2202
  reader.readBranchSpan = async (id, cut) => transcriptBranchSpan(id, donorIndex, cut);
1800
- const lookup = (id) => this.seqOfEntry(tx, header.id, id);
2203
+ reader.readEntryChunk = this.forkChunkReader(tx, reader, source.sessionId, head.epoch);
2204
+ const copies = new ForkRowRuns(this.tables, header.id, source.sessionId);
2205
+ const lookup = async (id) => copies.heldSeq(id) ?? this.seqOfEntry(tx, header.id, id);
1801
2206
  let summary = applySessionSummaryEntries(void 0, []).state;
1802
2207
  let index = foldSessionResume(void 0, []);
1803
2208
  let seq = 0;
1804
- const remainingBlobs = /* @__PURE__ */ new Set();
2209
+ const hashes = /* @__PURE__ */ new Set();
1805
2210
  const inlineSnapshot = async (ref) => {
1806
2211
  const text = (key) => this.dialect.jsonText("entry_json", key);
1807
2212
  const ty = (key) => this.dialect.jsonType("entry_json", key);
@@ -1821,57 +2226,105 @@ var SqlSessionStore = class SqlSessionStore {
1821
2226
  ...s.degraded ? { degradedFrom: s.degraded } : {}
1822
2227
  };
1823
2228
  };
1824
- for await (const row of stream.read(reader, async (id) => await lookup(id) !== void 0, inlineSnapshot)) {
1825
- index = await foldForkRow(index, row, lookup);
1826
- const entry = row.entry;
1827
- const listed = applySessionSummaryEntries(summary, [entry]);
1828
- summary = listed.state;
1829
- if (entry.type === "custom" && entry.customType === "atomic.tool-output") {
1830
- const hash = entry.data?.hash;
1831
- if (typeof hash === "string" && !remainingBlobs.has(hash) && !await this.copyForkBlob(tx, source.sessionId, header.id, hash)) remainingBlobs.add(hash);
1832
- }
1833
- if (!row.reference) await this.insertEntries(tx, header.id, [entry], seq, listed.texts);
1834
- else if (row.inlineSnapshot) await this.writeInlineForkSnapshot(tx, reader, row.reference, header.id, seq, listed.texts, row.edits);
1835
- else {
1836
- const encoded = await encodedForkRow(reader, row);
1837
- const chunks = Math.ceil(encoded.size / SESSION_ENTRY_CHUNK_BYTES);
1838
- await tx.run(`INSERT INTO ${this.tables.entries} (session_id,seq,entry_id,entry_json,chunks) VALUES (?,?,?,?,?)`, header.id, seq + 1, entry.id, JSON.stringify({
1839
- type: entry.type,
1840
- id: entry.id,
1841
- parentId: entry.parentId ?? null
1842
- }), chunks);
1843
- let n = 0;
1844
- let used = 0;
1845
- let buffer = new Uint8Array(SESSION_ENTRY_CHUNK_BYTES);
1846
- const write = async () => {
1847
- await tx.run(`INSERT INTO ${this.tables.entryChunks} (session_id,seq,idx,data) VALUES (?,?,?,?)`, header.id, seq + 1, n++, buffer.subarray(0, used));
1848
- used = 0;
1849
- };
1850
- for await (const part of encoded.chunks()) for (let start = 0; start < part.length;) {
1851
- const count = Math.min(part.length - start, buffer.length - used);
1852
- buffer.set(part.subarray(start, start + count), used);
1853
- start += count;
1854
- used += count;
1855
- if (used === buffer.length) await write();
2229
+ const writes = new SentWrites(tx);
2230
+ const blobs = {};
2231
+ const remainingBlobs = await writes.around(async () => {
2232
+ for await (const row of stream.read(reader, async (id) => await lookup(id) !== void 0, inlineSnapshot)) {
2233
+ index = await foldForkRow(index, row, lookup);
2234
+ const entry = row.entry;
2235
+ const listed = applySessionSummaryEntries(summary, [entry]);
2236
+ summary = listed.state;
2237
+ if (entry.type === "custom" && entry.customType === "atomic.tool-output") {
2238
+ const hash = entry.data?.hash;
2239
+ if (typeof hash === "string") hashes.add(hash);
2240
+ }
2241
+ if (row.stored?.sessionId === source.sessionId && row.edits === void 0) {
2242
+ copies.add(row.stored.seq, seq + 1, entry.id);
2243
+ await writes.send(this.entryWrites(header.id, [], seq, listed.texts, false));
2244
+ if (copies.full) await writes.send(copies.drain());
2245
+ seq++;
2246
+ continue;
1856
2247
  }
1857
- if (used) await write();
1858
- if (n !== chunks) throw new StorageError("Incomplete historical entry in fork");
1859
- for (const { text } of listed.texts) await tx.run(`INSERT INTO ${this.tables.searchTexts} (session_id,seq,text_json) VALUES (?,?,?)`, header.id, seq + 1, this.encode(text));
1860
- await tx.run(`UPDATE ${this.tables.meta} SET schema_version=? WHERE schema_version=?`, 2, SESSION_SCHEMA_VERSION_UNCHUNKED);
2248
+ await writes.send(copies.drain());
2249
+ if (!row.reference) await writes.send(this.entryWrites(header.id, [entry], seq, listed.texts, false));
2250
+ else if (row.inlineSnapshot) await this.writeInlineForkSnapshot(tx, reader, row.reference, header.id, seq, listed.texts, row.edits);
2251
+ else {
2252
+ const encoded = await encodedForkRow(reader, row);
2253
+ const chunks = Math.ceil(encoded.size / SESSION_ENTRY_CHUNK_BYTES);
2254
+ await tx.run(`INSERT INTO ${this.tables.entries} (session_id,seq,entry_id,entry_json,chunks) VALUES (?,?,?,?,?)`, header.id, seq + 1, entry.id, JSON.stringify({
2255
+ type: entry.type,
2256
+ id: entry.id,
2257
+ parentId: entry.parentId ?? null
2258
+ }), chunks);
2259
+ let n = 0;
2260
+ let used = 0;
2261
+ let buffer = new Uint8Array(SESSION_ENTRY_CHUNK_BYTES);
2262
+ const write = async () => {
2263
+ await tx.run(`INSERT INTO ${this.tables.entryChunks} (session_id,seq,idx,data) VALUES (?,?,?,?)`, header.id, seq + 1, n++, buffer.subarray(0, used));
2264
+ used = 0;
2265
+ };
2266
+ for await (const part of encoded.chunks()) for (let start = 0; start < part.length;) {
2267
+ const count = Math.min(part.length - start, buffer.length - used);
2268
+ buffer.set(part.subarray(start, start + count), used);
2269
+ start += count;
2270
+ used += count;
2271
+ if (used === buffer.length) await write();
2272
+ }
2273
+ if (used) await write();
2274
+ if (n !== chunks) throw new StorageError("Incomplete historical entry in fork");
2275
+ await writes.send(this.entryWrites(header.id, [], seq, listed.texts, false));
2276
+ }
2277
+ seq++;
1861
2278
  }
1862
- seq++;
1863
- }
1864
- const { epoch } = await this.saveSummary(tx, header.id, {
1865
- header,
1866
- entries: [],
1867
- lastSeq: seq
1868
- }, summary, index);
2279
+ await writes.send(copies.drain());
2280
+ blobs.copy = this.forkBlobCopy(source.sessionId, header.id, hashes);
2281
+ const statement = this.summaryWrite(header.id, {
2282
+ header,
2283
+ entries: [],
2284
+ lastSeq: seq
2285
+ }, summary, index);
2286
+ await writes.send([statement.statement]);
2287
+ return {
2288
+ remaining: await this.finishForkCopy(tx, writes, header.id, blobs.copy, hashes),
2289
+ epoch: statement.epoch
2290
+ };
2291
+ });
2292
+ await this.finishFork(tx, header.id);
1869
2293
  return {
1870
2294
  lastSeq: seq,
1871
- epoch,
1872
- remainingBlobs: [...remainingBlobs]
2295
+ epoch: remainingBlobs.epoch,
2296
+ remainingBlobs: remainingBlobs.remaining
1873
2297
  };
1874
- }, SESSION_TRANSACTION);
2298
+ }, this.sessionWrite(header.id));
2299
+ }
2300
+ /**
2301
+ * `readEntryChunk` for a fork's reader bound to transaction `tx`, reading session `source` in generation `epoch`: a
2302
+ * read of an entry fetches a whole stored chunk row, or a part as large of an entry stored whole, and answers the next
2303
+ * reads of it from that, so an entry costs a round trip a chunk, not one every 64 KiB (#6560). The fork holds the
2304
+ * source's row, so its generation cannot change meanwhile. Other reads go to `reader` as before.
2305
+ */
2306
+ forkChunkReader(tx, reader, source, epoch) {
2307
+ const json = this.dialect.name === "sqlite" ? "CAST(e.entry_json AS BLOB)" : "convert_to(e.entry_json, 'UTF8')";
2308
+ let held;
2309
+ return async (reference, offset, bytes = SESSION_HISTORY_CHUNK_BYTES) => {
2310
+ if (reference.sessionId !== source || reference.epoch !== epoch) return SqlSessionStore.prototype.readEntryChunk.call(reader, reference, offset, bytes);
2311
+ const part = Math.floor(offset / SESSION_ENTRY_CHUNK_BYTES);
2312
+ const start = part * SESSION_ENTRY_CHUNK_BYTES;
2313
+ if (held?.seq !== reference.seq || held.start !== start) {
2314
+ const row = await tx.get(`SELECT CASE WHEN e.chunks > 0
2315
+ THEN (SELECT c.data FROM ${this.tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx = ?)
2316
+ ELSE substr(${json}, CAST(? AS INTEGER), CAST(? AS INTEGER)) END AS data
2317
+ FROM ${this.tables.entries} e WHERE e.session_id = ? AND e.seq = ?`, part, start + 1, SESSION_ENTRY_CHUNK_BYTES, source, reference.seq);
2318
+ if (row?.data == null || row.data.byteLength <= offset - start) return SqlSessionStore.prototype.readEntryChunk.call(reader, reference, offset, bytes);
2319
+ held = {
2320
+ seq: reference.seq,
2321
+ start,
2322
+ data: row.data
2323
+ };
2324
+ }
2325
+ const from = offset - start;
2326
+ return held.data.subarray(from, from + Math.min(Math.max(1, Math.trunc(bytes) || 1), SESSION_HISTORY_PAGE_BYTES));
2327
+ };
1875
2328
  }
1876
2329
  /** Keep the legacy inline payload outside the iterator's yielded value and the caller's async frame:
1877
2330
  * neither may retain this row while the next SQLite result is being delivered. */
@@ -1881,7 +2334,7 @@ var SqlSessionStore = class SqlSessionStore {
1881
2334
  await this.insertEntries(tx, child, [edits ? {
1882
2335
  ...original,
1883
2336
  ...edits
1884
- } : original], seq, texts);
2337
+ } : original], seq, texts, false);
1885
2338
  }
1886
2339
  async append(sessionId, entries, options) {
1887
2340
  this.assertOpen();
@@ -1900,7 +2353,7 @@ var SqlSessionStore = class SqlSessionStore {
1900
2353
  await checked;
1901
2354
  await this.writeEntries(tx, summary.statement, written);
1902
2355
  return { lastSeq };
1903
- }, SESSION_TRANSACTION);
2356
+ }, this.sessionWrite(sessionId, this.headRead(sessionId, options, true)));
1904
2357
  }
1905
2358
  async replace(sessionId, header, entries, options) {
1906
2359
  this.assertOpen();
@@ -1924,7 +2377,7 @@ var SqlSessionStore = class SqlSessionStore {
1924
2377
  lastSeq: entries.length,
1925
2378
  epoch
1926
2379
  };
1927
- }, SESSION_TRANSACTION);
2380
+ }, this.sessionWrite(sessionId));
1928
2381
  }
1929
2382
  async updateHeader(header, options) {
1930
2383
  this.assertOpen();
@@ -1933,7 +2386,7 @@ var SqlSessionStore = class SqlSessionStore {
1933
2386
  const { row, state } = await this.forWrite(tx, header.id, options, true);
1934
2387
  const epoch = newRevision();
1935
2388
  const resume = windowIndex(state, row.last_seq);
1936
- await this.saveSummary(tx, header.id, {
2389
+ const { statement } = this.summaryWrite(header.id, {
1937
2390
  header,
1938
2391
  entries: [],
1939
2392
  lastSeq: row.last_seq
@@ -1944,11 +2397,12 @@ var SqlSessionStore = class SqlSessionStore {
1944
2397
  ...resume,
1945
2398
  epoch
1946
2399
  });
2400
+ if (transactionFinisher(tx)?.([statement]) !== true) await tx.run(statement.sql, ...statement.params);
1947
2401
  return {
1948
2402
  lastSeq: row.last_seq,
1949
2403
  epoch
1950
2404
  };
1951
- }, SESSION_TRANSACTION);
2405
+ }, this.sessionWrite(header.id, this.headRead(header.id, options, true)));
1952
2406
  }
1953
2407
  async load(sessionId) {
1954
2408
  this.assertOpen();
@@ -1957,49 +2411,56 @@ var SqlSessionStore = class SqlSessionStore {
1957
2411
  const row = await this.database.get(`SELECT last_seq FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
1958
2412
  if (row) announceHistoryLoad(row.last_seq);
1959
2413
  }
1960
- return this.transaction((tx) => this.read(tx, sessionId), SESSION_TRANSACTION);
2414
+ return this.readTransaction((tx) => this.read(tx, sessionId));
1961
2415
  }
1962
2416
  async readEntryRange(sessionId, query) {
1963
2417
  this.assertOpen();
1964
2418
  validateSessionText("sessionId", sessionId);
1965
2419
  query.signal?.throwIfAborted();
1966
- const session = await this.database.get(`SELECT last_seq FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
1967
- if (!session) throw new SessionNotFoundError$1(sessionId);
1968
- const lastSeq = Number(session.last_seq);
1969
2420
  const fromSeq = Math.max(1, query.fromSeq);
1970
- const toSeq = Math.min(query.toSeq, lastSeq);
1971
- if (fromSeq > toSeq) return {
1972
- lastSeq,
1973
- entries: [],
1974
- throughSeq: Math.max(toSeq, fromSeq - 1)
1975
- };
1976
- if (query.maxChars !== void 0 && query.maxChars <= 0) return {
1977
- lastSeq,
1978
- entries: [],
1979
- throughSeq: fromSeq - 1
1980
- };
1981
2421
  const skippedSet = query.skipTypes === void 0 ? void 0 : new Set(query.skipTypes);
1982
2422
  const skippedPrefixes = (query.skipTypes ?? []).map((type) => `{"type":${JSON.stringify(type)},`);
1983
2423
  const largeBytes = query.largeEntryBytes ?? 0x7fffffff;
1984
- const rows = await this.database.all(`WITH sized AS (
2424
+ const read = await this.database.all(`WITH sized AS (
1985
2425
  SELECT seq, chunks, ${this.entryByteLength("entry_json")} AS raw_bytes,
1986
2426
  ${this.entryByteLength("entry_json")} + chunks * ? AS bytes
1987
2427
  FROM ${this.tables.entries}
1988
2428
  WHERE session_id = ? AND seq >= ? AND seq <= ?
2429
+ AND seq <= (SELECT last_seq FROM ${this.tables.sessions} WHERE id = ?)
1989
2430
  ),
1990
2431
  paged AS (
1991
2432
  SELECT seq, chunks, raw_bytes, count(*) OVER () AS remaining,
1992
2433
  sum(bytes) OVER (ORDER BY seq) - bytes AS before_chars
1993
2434
  FROM sized
2435
+ ),
2436
+ page AS (
2437
+ SELECT p.seq, CASE WHEN p.chunks = 0 AND p.raw_bytes <= ? THEN e.entry_json END AS entry_json,
2438
+ substr(e.entry_json, 1, 64) AS entry_head, p.chunks, p.remaining,
2439
+ CASE WHEN p.chunks = 0 AND p.raw_bytes > ? AND substr(e.entry_json, 1, 8) <> '{"type":'
2440
+ THEN ${this.dialect.jsonText("e.entry_json", "type")} END AS entry_type
2441
+ FROM paged p
2442
+ JOIN ${this.tables.entries} e ON e.session_id = ? AND e.seq = p.seq
2443
+ WHERE p.before_chars < ?
1994
2444
  )
1995
- SELECT p.seq, CASE WHEN p.chunks = 0 AND p.raw_bytes <= ? THEN e.entry_json END AS entry_json,
1996
- substr(e.entry_json, 1, 64) AS entry_head, p.chunks, p.remaining,
1997
- CASE WHEN p.chunks = 0 AND p.raw_bytes > ? AND substr(e.entry_json, 1, 8) <> '{"type":'
1998
- THEN ${this.dialect.jsonText("e.entry_json", "type")} END AS entry_type
1999
- FROM paged p
2000
- JOIN ${this.tables.entries} e ON e.session_id = ? AND e.seq = p.seq
2001
- WHERE p.before_chars < ?
2002
- ORDER BY p.seq`, SESSION_ENTRY_CHUNK_BYTES, sessionId, fromSeq, toSeq, largeBytes, largeBytes, sessionId, query.maxChars ?? Number.MAX_SAFE_INTEGER);
2445
+ SELECT s.last_seq, page.seq, page.entry_json, page.entry_head, page.chunks, page.remaining, page.entry_type
2446
+ FROM ${this.tables.sessions} s LEFT JOIN page ON 1 = 1
2447
+ WHERE s.id = ?
2448
+ ORDER BY page.seq`, SESSION_ENTRY_CHUNK_BYTES, sessionId, fromSeq, Math.min(query.toSeq, Number.MAX_SAFE_INTEGER), sessionId, largeBytes, largeBytes, sessionId, query.maxChars !== void 0 && query.maxChars <= 0 ? 0 : query.maxChars ?? Number.MAX_SAFE_INTEGER, sessionId);
2449
+ const session = read[0];
2450
+ if (!session) throw new SessionNotFoundError$1(sessionId);
2451
+ const lastSeq = Number(session.last_seq);
2452
+ const toSeq = Math.min(query.toSeq, lastSeq);
2453
+ if (fromSeq > toSeq) return {
2454
+ lastSeq,
2455
+ entries: [],
2456
+ throughSeq: Math.max(toSeq, fromSeq - 1)
2457
+ };
2458
+ if (query.maxChars !== void 0 && query.maxChars <= 0) return {
2459
+ lastSeq,
2460
+ entries: [],
2461
+ throughSeq: fromSeq - 1
2462
+ };
2463
+ const rows = read.filter((row) => row.seq !== null && row.seq !== void 0);
2003
2464
  const entries = [];
2004
2465
  for (const row of rows) {
2005
2466
  query.signal?.throwIfAborted();
@@ -2079,7 +2540,7 @@ var SqlSessionStore = class SqlSessionStore {
2079
2540
  };
2080
2541
  const previous = await this.blobHeader(sessionId, blob.hash);
2081
2542
  if (previous) {
2082
- if (previous.chunks === -1) while (await this.database.transaction((tx) => migrateLegacyBlobBatch(tx, this.tables, sessionId, blob.hash, stored))) await new Promise((resolve) => setTimeout(resolve, 0));
2543
+ if (previous.chunks === -1) while (await this.database.transaction((tx) => migrateLegacyBlobBatch(tx, this.tables, sessionId, blob.hash, stored), this.sessionWrite(sessionId))) await new Promise((resolve) => setTimeout(resolve, 0));
2083
2544
  return blob;
2084
2545
  }
2085
2546
  const chunks = Math.ceil(blob.bytes / SESSION_BLOB_CHUNK_BYTES);
@@ -2201,6 +2662,9 @@ var SqlSessionStore = class SqlSessionStore {
2201
2662
  this.closed = true;
2202
2663
  this.scopes.clear();
2203
2664
  this.summaries.clear();
2665
+ const reader = this.reader;
2666
+ this.reader = void 0;
2667
+ if (reader !== void 0) await (await reader.catch(() => void 0))?.close();
2204
2668
  }
2205
2669
  /**
2206
2670
  * `data_version` moves when another connection commits and `total_changes()` when this one writes, so
@@ -2443,11 +2907,11 @@ var SqlSessionStore = class SqlSessionStore {
2443
2907
  query.signal?.throwIfAborted();
2444
2908
  }
2445
2909
  async read(tx, sessionId) {
2446
- const row = await tx.get(`SELECT header_json, last_seq,CASE WHEN ${this.dialect.jsonValid("summary_state")} THEN ${this.dialect.jsonText("summary_state", "epoch")} END AS chat_epoch,revision FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
2910
+ const [row, rows] = await Promise.all([tx.get(`SELECT header_json, last_seq,CASE WHEN ${this.dialect.jsonValid("summary_state")} THEN ${this.dialect.jsonText("summary_state", "epoch")} END AS chat_epoch,revision FROM ${this.tables.sessions} WHERE id = ?`, sessionId), this.readRows(tx, sessionId)]);
2447
2911
  if (!row) throw new SessionNotFoundError$1(sessionId);
2448
2912
  const snapshot = {
2449
2913
  header: JSON.parse(row.header_json),
2450
- entries: (await this.readRows(tx, sessionId)).map(({ entry }) => entry),
2914
+ entries: rows.map(({ entry }) => entry),
2451
2915
  lastSeq: row.last_seq
2452
2916
  };
2453
2917
  if (typeof row.chat_epoch === "string") bindChatEpoch(snapshot.header, row.chat_epoch);
@@ -2498,8 +2962,19 @@ var SqlSessionStore = class SqlSessionStore {
2498
2962
  }
2499
2963
  return entries;
2500
2964
  }
2965
+ /**
2966
+ * The read of the session's row that `resumeSource` makes first: a read transaction that starts with it names it as
2967
+ * a leading read, so a pipelined connection sends it with the transaction's start (#6560).
2968
+ */
2969
+ resumeRow(sessionId) {
2970
+ return {
2971
+ sql: `SELECT header_json,last_seq,summary_state,revision FROM ${this.tables.sessions} WHERE id = ?`,
2972
+ params: [sessionId]
2973
+ };
2974
+ }
2501
2975
  async resumeSource(tx, sessionId) {
2502
- const row = await tx.get(`SELECT header_json,last_seq,summary_state,revision FROM ${this.tables.sessions} WHERE id = ?${this.dialect.lockClause("share")}`, sessionId);
2976
+ const read = this.resumeRow(sessionId);
2977
+ const row = await tx.get(read.sql, ...read.params);
2503
2978
  if (!row) throw new SessionNotFoundError$1(sessionId);
2504
2979
  const stored = windowIndex(JSON.parse(row.summary_state), Number(row.last_seq));
2505
2980
  const remembered = this.resumeIndexes.get(sessionId);
@@ -2511,6 +2986,21 @@ var SqlSessionStore = class SqlSessionStore {
2511
2986
  row
2512
2987
  };
2513
2988
  }
2989
+ /**
2990
+ * Runs `read`, a read transaction that finds the session's index with `resumeSource`, at once; only when that index is
2991
+ * missing or stale (`resumeSource` rejects with `SessionConflictError`) does it compute the index with
2992
+ * `prepareResume` and run `read` again. A current index, the usual case, then costs no read before the transaction:
2993
+ * on a server, one round trip fewer (#6560).
2994
+ */
2995
+ async withResumeIndex(sessionId, read) {
2996
+ try {
2997
+ return await read();
2998
+ } catch (error) {
2999
+ if (!(error instanceof SessionConflictError$1)) throw error;
3000
+ }
3001
+ await this.prepareResume(sessionId);
3002
+ return read();
3003
+ }
2514
3004
  async prepareResume(sessionId, leafId, throughSeq) {
2515
3005
  attempts: for (let attempt = 0; attempt < 3; attempt++) {
2516
3006
  const row = await this.database.get(`SELECT header_json,last_seq,summary_state,revision FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
@@ -2846,27 +3336,26 @@ var SqlSessionStore = class SqlSessionStore {
2846
3336
  async readTail(sessionId, fromSeq) {
2847
3337
  this.assertOpen();
2848
3338
  validateSessionText("sessionId", sessionId);
2849
- await this.prepareResume(sessionId);
2850
3339
  const start = Math.max(1, fromSeq);
2851
- const { tail } = await this.transaction(async (tx) => {
3340
+ const { tail } = await this.withResumeIndex(sessionId, () => this.readTransaction(async (tx) => {
2852
3341
  const source = await this.resumeSource(tx, sessionId);
2853
3342
  const stateSeqs = stateSeqsBefore(source.index, start);
2854
3343
  if (hasHistoryLoadObserver()) announceHistoryLoad(stateSeqs.length + Math.max(0, source.index.seq - start + 1));
2855
- const state = await this.readSeqs(tx, sessionId, stateSeqs);
2856
- const entries = (await this.readRows(tx, sessionId, "seq >= ?", [start])).map(({ entry }) => entry);
3344
+ const [state, rows] = await Promise.all([this.readSeqs(tx, sessionId, stateSeqs), this.readRows(tx, sessionId, "seq >= ?", [start])]);
3345
+ const entries = rows.map(({ entry }) => entry);
2857
3346
  return {
2858
3347
  tail: sessionTailFrom(source.index, source.header, start, state, entries),
2859
3348
  source
2860
3349
  };
2861
- }, SESSION_TRANSACTION);
3350
+ }, [this.resumeRow(sessionId)]));
2862
3351
  return tail;
2863
3352
  }
2864
3353
  async readRange(sessionId, startSeq, endSeq, expectedEpoch) {
2865
3354
  this.assertOpen();
2866
3355
  validateSessionText("sessionId", sessionId);
2867
3356
  const start = Math.max(1, startSeq);
2868
- return this.transaction(async (tx) => {
2869
- const head = await this.historyHead(tx, sessionId);
3357
+ return this.readTransaction(async (tx) => {
3358
+ const head = await this.historyHead(tx, sessionId, true);
2870
3359
  if (expectedEpoch !== void 0 && expectedEpoch !== head.epoch) throw new SessionConflictError$1(sessionId, endSeq, head.lastSeq);
2871
3360
  const entries = endSeq < start ? [] : await this.readRows(tx, sessionId, "seq >= ? AND seq <= ?", [start, endSeq]);
2872
3361
  return {
@@ -2875,7 +3364,7 @@ var SqlSessionStore = class SqlSessionStore {
2875
3364
  seqs: entries.map(({ seq }) => seq),
2876
3365
  ...head
2877
3366
  };
2878
- }, SESSION_TRANSACTION);
3367
+ });
2879
3368
  }
2880
3369
  async historyHead(tx, sessionId, readOnly = false) {
2881
3370
  const generation = this.generation(sessionId);
@@ -2923,14 +3412,11 @@ var SqlSessionStore = class SqlSessionStore {
2923
3412
  const { childDisplayCut } = await import("../core/storage/session/card-view.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
2924
3413
  const { index } = await this.prepareResume(sessionId);
2925
3414
  if (typeof launch.launchLeafId !== "string") return childDisplayCut(index, launch);
2926
- return this.transaction(async (tx) => {
3415
+ return this.readTransaction(async (tx) => {
2927
3416
  const head = await this.historyHead(tx, sessionId, true);
2928
3417
  if (head.epoch !== index.epoch || head.lastSeq < index.seq) throw new SessionConflictError$1(sessionId, index.seq, head.lastSeq);
2929
3418
  const row = await tx.get(`SELECT seq FROM ${this.tables.entries} WHERE session_id=? AND entry_id=? AND seq<=? ORDER BY seq DESC LIMIT 1`, sessionId, launch.launchLeafId, index.seq);
2930
3419
  return childDisplayCut(index, launch, row === void 0 ? void 0 : Number(row.seq));
2931
- }, {
2932
- ...SESSION_TRANSACTION,
2933
- readOnly: true
2934
3420
  });
2935
3421
  }
2936
3422
  /**
@@ -2969,8 +3455,8 @@ var SqlSessionStore = class SqlSessionStore {
2969
3455
  * timestamp; its caller streams those fields instead of joining or decoding the stored body. */
2970
3456
  async readTreeOutline(sessionId, fromSeq, toSeq, epoch) {
2971
3457
  this.assertOpen();
2972
- return this.transaction(async (tx) => {
2973
- const head = await this.historyHead(tx, sessionId);
3458
+ return this.readTransaction(async (tx) => {
3459
+ const head = await this.historyHead(tx, sessionId, true);
2974
3460
  if (epoch !== void 0 && head.epoch !== epoch || head.lastSeq < toSeq) throw new SessionConflictError$1(sessionId, toSeq, head.lastSeq);
2975
3461
  const sqlite = this.dialect.name === "sqlite";
2976
3462
  const j = (...path) => this.dialect.jsonText("entry_json", ...path);
@@ -3005,7 +3491,7 @@ var SqlSessionStore = class SqlSessionStore {
3005
3491
  label: typeof row.label === "string" ? row.label : void 0
3006
3492
  } : {}
3007
3493
  });
3008
- }, SESSION_TRANSACTION);
3494
+ });
3009
3495
  }
3010
3496
  /** Sparse page of child state in one fenced read, bounded by the same byte and row caps as a transcript page. */
3011
3497
  async readSelectedPage(sessionId, seqs, epoch, options = {}) {
@@ -3013,8 +3499,8 @@ var SqlSessionStore = class SqlSessionStore {
3013
3499
  const limit = entrySizeLimit(options.limit);
3014
3500
  const wanted = options.backward ? seqs.slice(-limit) : seqs.slice(0, limit);
3015
3501
  if (!wanted.length) return { items: [] };
3016
- return this.transaction(async (tx) => {
3017
- const head = await this.historyHead(tx, sessionId);
3502
+ return this.readTransaction(async (tx) => {
3503
+ const head = await this.historyHead(tx, sessionId, true);
3018
3504
  if (head.epoch !== epoch || head.lastSeq < wanted.at(-1)) throw new SessionConflictError$1(sessionId, wanted.at(-1), head.lastSeq);
3019
3505
  const tail = `(SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id=e.session_id AND c.seq=e.seq AND c.idx=e.chunks-1)`;
3020
3506
  const rows = await tx.all(`SELECT seq,CASE WHEN chunks=0 THEN ${this.entryByteLength("entry_json")} ELSE (chunks-1)*?+${tail} END bytes FROM ${this.tables.entries} e WHERE session_id=? AND seq IN (${wanted.map(() => "?").join(",")}) ORDER BY seq`, SESSION_ENTRY_CHUNK_BYTES, sessionId, ...wanted);
@@ -3031,7 +3517,7 @@ var SqlSessionStore = class SqlSessionStore {
3031
3517
  ...plan.oversized
3032
3518
  }] };
3033
3519
  return { items: await this.readSeqs(tx, sessionId, plan.seqs) };
3034
- }, SESSION_TRANSACTION);
3520
+ });
3035
3521
  }
3036
3522
  /**
3037
3523
  * The snapshot entries of the session's resume index, read with the index and nothing else: no entry is read, and an
@@ -3051,8 +3537,8 @@ var SqlSessionStore = class SqlSessionStore {
3051
3537
  async readEntrySizes(sessionId, startSeq, endSeq, limit) {
3052
3538
  this.assertOpen();
3053
3539
  validateSessionText("sessionId", sessionId);
3054
- return this.transaction(async (tx) => {
3055
- const head = await this.historyHead(tx, sessionId);
3540
+ return this.readTransaction(async (tx) => {
3541
+ const head = await this.historyHead(tx, sessionId, true);
3056
3542
  const lastChunk = `(SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx = e.chunks - 1)`;
3057
3543
  const rows = await tx.all(`SELECT seq, CASE WHEN chunks = 0 THEN ${this.entryByteLength("entry_json")} ELSE (chunks - 1) * ? + ${lastChunk} END AS bytes FROM ${this.tables.entries} e WHERE session_id = ? AND seq BETWEEN ? AND ? ORDER BY seq LIMIT ?`, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, endSeq, entrySizeLimit(limit));
3058
3544
  return {
@@ -3065,7 +3551,7 @@ var SqlSessionStore = class SqlSessionStore {
3065
3551
  };
3066
3552
  })
3067
3553
  };
3068
- }, SESSION_TRANSACTION);
3554
+ });
3069
3555
  }
3070
3556
  /**
3071
3557
  * One statement, so one snapshot without a transaction: the session row (its generation, watermark and schema version)
@@ -3260,8 +3746,8 @@ var SqlSessionStore = class SqlSessionStore {
3260
3746
  this.assertOpen();
3261
3747
  validateSessionText("sessionId", sessionId);
3262
3748
  const { candidates, afterSeq, limit } = taskReferenceDuplicateQuery(query);
3263
- return this.transaction(async (tx) => {
3264
- const head = await this.historyHead(tx, sessionId);
3749
+ return this.readTransaction(async (tx) => {
3750
+ const head = await this.historyHead(tx, sessionId, true);
3265
3751
  if (head.epoch !== query.epoch || head.lastSeq < query.throughSeq) throw new SessionConflictError$1(sessionId, query.throughSeq, head.lastSeq);
3266
3752
  if (candidates.length === 0) return { seqs: [] };
3267
3753
  const t = snapshotIndexTables$1(this.prefix);
@@ -3317,15 +3803,15 @@ var SqlSessionStore = class SqlSessionStore {
3317
3803
  seqs: seqs.slice(0, limit),
3318
3804
  nextAfterSeq: seqs[limit - 1]
3319
3805
  } : { seqs };
3320
- }, SESSION_TRANSACTION);
3806
+ });
3321
3807
  }
3322
3808
  async readForkWindow(sessionId, entryId, options) {
3323
3809
  this.assertOpen();
3324
3810
  validateSessionText("sessionId", sessionId);
3325
3811
  const { indexedForkWindow, forkMetadata, byteMetadata, locateFork } = await import("../core/storage/session/fork-window.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
3326
- return this.transaction(async (tx) => {
3812
+ return this.readTransaction(async (tx) => {
3327
3813
  const snapshots = snapshotIndexTables$1(this.prefix);
3328
- const row = await tx.get(`SELECT header_json,last_seq,summary_state,revision,CASE WHEN EXISTS (SELECT 1 FROM ${snapshots.sources} WHERE source='session-entries' AND backfilled_through>=watermark) THEN (SELECT max(seq) FROM ${snapshots.sessionLinks} WHERE session_id=s.id AND entry_id=?) ELSE (SELECT max(seq) FROM ${this.tables.entries} WHERE session_id=s.id AND entry_id=?) END AS leaf_seq FROM ${this.tables.sessions} s WHERE s.id=?${this.dialect.lockClause("share")}`, entryId, entryId, sessionId);
3814
+ const row = await tx.get(`SELECT header_json,last_seq,summary_state,revision,CASE WHEN EXISTS (SELECT 1 FROM ${snapshots.sources} WHERE source='session-entries' AND backfilled_through>=watermark) THEN (SELECT max(seq) FROM ${snapshots.sessionLinks} WHERE session_id=s.id AND entry_id=?) ELSE (SELECT max(seq) FROM ${this.tables.entries} WHERE session_id=s.id AND entry_id=?) END AS leaf_seq FROM ${this.tables.sessions} s WHERE s.id=?`, entryId, entryId, sessionId);
3329
3815
  if (!row) throw new SessionNotFoundError$1(sessionId);
3330
3816
  const header = JSON.parse(row.header_json);
3331
3817
  const state = JSON.parse(row.summary_state);
@@ -3446,7 +3932,7 @@ var SqlSessionStore = class SqlSessionStore {
3446
3932
  ...selected.extras,
3447
3933
  ...options
3448
3934
  });
3449
- }, SESSION_TRANSACTION);
3935
+ });
3450
3936
  }
3451
3937
  async *forkEntryChunks(tx, id, seq, count) {
3452
3938
  for (let i = 0; i < count; i++) {
@@ -3469,34 +3955,46 @@ var SqlSessionStore = class SqlSessionStore {
3469
3955
  this.assertOpen();
3470
3956
  validateSessionText("sessionId", sessionId);
3471
3957
  if (leafId !== void 0) validateSessionText("entry.id", leafId);
3958
+ if (leafId === void 0 && throughSeq === void 0) try {
3959
+ return await this.readTransaction(async (tx) => {
3960
+ const { header, index } = await this.resumeSource(tx, sessionId);
3961
+ return this.resumeIn(tx, sessionId, header, index, options);
3962
+ }, [this.resumeRow(sessionId)]);
3963
+ } catch (error) {
3964
+ if (!(error instanceof SessionConflictError$1)) throw error;
3965
+ }
3472
3966
  for (let attempt = 0; attempt < 3; attempt++) {
3473
3967
  const { index, revision } = await this.prepareResume(sessionId, leafId, throughSeq);
3474
- const resume = await this.transaction(async (tx) => {
3475
- const head = await tx.get(`SELECT header_json,revision FROM ${this.tables.sessions} WHERE id = ?${this.dialect.lockClause("share")}`, sessionId);
3968
+ const resume = await this.readTransaction(async (tx) => {
3969
+ const head = await tx.get(`SELECT header_json,revision FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
3476
3970
  if (!head) throw new SessionNotFoundError$1(sessionId);
3477
3971
  if (revision !== head.revision) return void 0;
3478
- const header = JSON.parse(head.header_json);
3479
- const { leafSeq } = index;
3480
- const plan = sessionResumePlan(index, index.leafSeq, options?.deferChildRecords);
3481
- announceHistoryLoad(plan.state.length + plan.branch.reduce((sum, [a, b]) => sum + b - a + 1, 0));
3482
- const branch = [];
3483
- for (const [start, end] of plan.branch) branch.push(...await this.readRows(tx, sessionId, "seq >= ? AND seq <= ?", [start, end]));
3484
- const state = await this.readSeqs(tx, sessionId, plan.state);
3485
- const leaf = leafSeq <= 0 ? void 0 : await tx.get(`SELECT entry_id FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, leafSeq);
3486
- const resume = sessionResumeFrom(index, header, branch, state, leaf?.entry_id ?? null, plan.children);
3487
- if (resume.compaction) await readEarlierCompletionIntents(index, resume, (seqs) => this.readSeqs(tx, sessionId, seqs));
3488
- return resume;
3489
- }, SESSION_TRANSACTION);
3972
+ return this.resumeIn(tx, sessionId, JSON.parse(head.header_json), index, options);
3973
+ });
3490
3974
  if (resume !== void 0) return resume;
3491
3975
  }
3492
3976
  throw new SessionConflictError$1(sessionId, 0, 0);
3493
3977
  }
3978
+ /** The resume of `index`, the session's index as of the snapshot of `tx`, with `header`. */
3979
+ async resumeIn(tx, sessionId, header, index, options) {
3980
+ const { leafSeq } = index;
3981
+ const plan = sessionResumePlan(index, index.leafSeq, options?.deferChildRecords);
3982
+ announceHistoryLoad(plan.state.length + plan.branch.reduce((sum, [a, b]) => sum + b - a + 1, 0));
3983
+ const [ranges, state, leaf] = await Promise.all([
3984
+ Promise.all(plan.branch.map(([start, end]) => this.readRows(tx, sessionId, "seq >= ? AND seq <= ?", [start, end]))),
3985
+ this.readSeqs(tx, sessionId, plan.state),
3986
+ leafSeq <= 0 ? void 0 : tx.get(`SELECT entry_id FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, leafSeq)
3987
+ ]);
3988
+ const branch = ranges.flat();
3989
+ const resume = sessionResumeFrom(index, header, branch, state, leaf?.entry_id ?? null, plan.children);
3990
+ if (resume.compaction) await readEarlierCompletionIntents(index, resume, (seqs) => this.readSeqs(tx, sessionId, seqs));
3991
+ return resume;
3992
+ }
3494
3993
  async findLatestCompaction(sessionId, leafId) {
3495
3994
  this.assertOpen();
3496
3995
  validateSessionText("sessionId", sessionId);
3497
3996
  if (leafId !== void 0) validateSessionText("entry.id", leafId);
3498
- await this.prepareResume(sessionId);
3499
- const { point } = await this.transaction(async (tx) => {
3997
+ const { point } = await this.withResumeIndex(sessionId, () => this.readTransaction(async (tx) => {
3500
3998
  const source = await this.resumeSource(tx, sessionId);
3501
3999
  const { index } = source;
3502
4000
  const leafSeq = leafId === void 0 ? index.leafSeq : await this.seqOfEntry(tx, sessionId, leafId) ?? -1;
@@ -3505,8 +4003,7 @@ var SqlSessionStore = class SqlSessionStore {
3505
4003
  point: void 0,
3506
4004
  source
3507
4005
  };
3508
- const [boundary] = await this.readSeqs(tx, sessionId, [found.seq]);
3509
- const leaf = await tx.get(`SELECT entry_id FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, leafSeq);
4006
+ const [[boundary], leaf] = await Promise.all([this.readSeqs(tx, sessionId, [found.seq]), tx.get(`SELECT entry_id FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, leafSeq)]);
3510
4007
  if (boundary === void 0 || leaf === void 0) return {
3511
4008
  point: void 0,
3512
4009
  source
@@ -3520,7 +4017,7 @@ var SqlSessionStore = class SqlSessionStore {
3520
4017
  },
3521
4018
  source
3522
4019
  };
3523
- }, SESSION_TRANSACTION);
4020
+ }, [this.resumeRow(sessionId)]));
3524
4021
  return point;
3525
4022
  }
3526
4023
  /** The JSON of a long entry, from its chunks, one statement each. */
@@ -3556,8 +4053,8 @@ var SqlSessionStore = class SqlSessionStore {
3556
4053
  return row ? [new TextEncoder().encode(row.entry_json)] : [];
3557
4054
  }
3558
4055
  async forWrite(tx, sessionId, options, includeSummaryState = false) {
3559
- const row = await tx.get(`SELECT header_json, last_seq${includeSummaryState || options.epoch !== void 0 ? ", summary_state" : ""}
3560
- FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
4056
+ const read = this.headRead(sessionId, options, includeSummaryState);
4057
+ const row = await tx.get(read.sql, ...read.params);
3561
4058
  if (!row) throw new SessionNotFoundError$1(sessionId);
3562
4059
  const state = row.summary_state === void 0 ? void 0 : JSON.parse(String(row.summary_state));
3563
4060
  if (row.last_seq !== options.expectSeq || options.epoch !== void 0 && state?.epoch !== options.epoch) throw new SessionConflictError$1(sessionId, options.expectSeq, row.last_seq);
@@ -3566,6 +4063,14 @@ var SqlSessionStore = class SqlSessionStore {
3566
4063
  state
3567
4064
  };
3568
4065
  }
4066
+ /** The read of the session's row that `forWrite` checks a write against. */
4067
+ headRead(sessionId, options, includeSummaryState) {
4068
+ return {
4069
+ sql: `SELECT header_json, last_seq${includeSummaryState || options.epoch !== void 0 ? ", summary_state" : ""}
4070
+ FROM ${this.tables.sessions} WHERE id = ?`,
4071
+ params: [sessionId]
4072
+ };
4073
+ }
3569
4074
  async appendedResume(tx, sessionId, previous, lastSeq, entries) {
3570
4075
  if (!isSessionResumeIndex(previous, lastSeq)) return void 0;
3571
4076
  const seqs = /* @__PURE__ */ new Map();
@@ -3640,15 +4145,32 @@ var SqlSessionStore = class SqlSessionStore {
3640
4145
  epoch
3641
4146
  };
3642
4147
  }
3643
- async insertEntries(tx, sessionId, entries, lastSeq, texts) {
3644
- for (const { sql, params } of this.entryWrites(sessionId, entries, lastSeq, texts)) await tx.run(sql, ...params);
4148
+ async insertEntries(tx, sessionId, entries, lastSeq, texts, versionStep = true) {
4149
+ const writes = new SentWrites(tx);
4150
+ await writes.around(() => writes.send(this.entryWrites(sessionId, entries, lastSeq, texts, versionStep)));
4151
+ }
4152
+ /**
4153
+ * A fork's version step, once every entry of the child is in, as the transaction's last write: the same row order as
4154
+ * an append, which takes the snapshot index's progress rows with its entries inserts and the schema row after them,
4155
+ * so the two never deadlock (#6560). The body makes no call after it.
4156
+ */
4157
+ async finishFork(tx, child) {
4158
+ const step = {
4159
+ sql: `UPDATE ${this.tables.meta} SET schema_version = ? WHERE schema_version = ? AND EXISTS (SELECT 1 FROM ${this.tables.entries} WHERE session_id = ? AND chunks > 0)`,
4160
+ params: [
4161
+ 2,
4162
+ SESSION_SCHEMA_VERSION_UNCHUNKED,
4163
+ child
4164
+ ]
4165
+ };
4166
+ if (transactionFinisher(tx)?.([step]) !== true) await tx.run(step.sql, ...step.params);
3645
4167
  }
3646
4168
  /**
3647
4169
  * The statements that store `entries` after `lastSeq`, in order, each entry encoded only when its statements are
3648
- * taken: each entry's row and its chunks, the version step a first chunked entry takes, then the entries' search
3649
- * texts.
4170
+ * taken: each entry's row and its chunks, the version step a first chunked entry takes unless `versionStep` is
4171
+ * false (a fork takes it once its last entry is in), then the entries' search texts.
3650
4172
  */
3651
- *entryWrites(sessionId, entries, lastSeq, texts) {
4173
+ *entryWrites(sessionId, entries, lastSeq, texts, versionStep = true) {
3652
4174
  let chunked = false;
3653
4175
  for (const [index, entry] of entries.entries()) {
3654
4176
  const seq = lastSeq + index + 1;
@@ -3678,7 +4200,7 @@ var SqlSessionStore = class SqlSessionStore {
3678
4200
  ]
3679
4201
  };
3680
4202
  }
3681
- if (chunked) yield {
4203
+ if (chunked && versionStep) yield {
3682
4204
  sql: `UPDATE ${this.tables.meta} SET schema_version = ? WHERE schema_version = ?`,
3683
4205
  params: [2, SESSION_SCHEMA_VERSION_UNCHUNKED]
3684
4206
  };
@@ -3697,6 +4219,7 @@ var SqlSessionStore = class SqlSessionStore {
3697
4219
  * it once. A larger one runs its statements one at a time as they are made, as before, so it never holds more than
3698
4220
  * about that much of them, or sends it, at once.
3699
4221
  */
4222
+ /** Writes the session's row and its entries as the transaction's last calls: the body makes none after them. */
3700
4223
  async writeEntries(tx, summary, entries) {
3701
4224
  const batch = [summary];
3702
4225
  let bytes = statementBytes(summary);
@@ -3709,6 +4232,7 @@ var SqlSessionStore = class SqlSessionStore {
3709
4232
  for (let rest = pending.next(); rest.done !== true; rest = pending.next()) await tx.run(rest.value.sql, ...rest.value.params);
3710
4233
  return;
3711
4234
  }
4235
+ if (transactionFinisher(tx)?.(batch) === true) return;
3712
4236
  await statementBatch(tx, batch, []);
3713
4237
  }
3714
4238
  encode(value) {
@@ -10277,16 +10801,16 @@ var ThemeSelectorComponent = class extends FramedSelector {
10277
10801
  * update without an ESM missing-export error.
10278
10802
  */
10279
10803
  const COMPACTOR_COMPRESSION_RATIO = .5;
10280
- export { CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL, COMPACTOR_COMPRESSION_RATIO, ClassifierDecisionError, GITHUB_COPILOT_ERROR_DIAGNOSTIC, GitHubCopilotAuthenticationError, GitHubCopilotContentFilterError, GitHubCopilotEmptyResponseError, GitHubCopilotError, GitHubCopilotInvalidRequestError, GitHubCopilotModelUnavailableError, GitHubCopilotPromptTooLargeError, GitHubCopilotQuotaExhaustedError, GitHubCopilotRateLimitError, GitHubCopilotServiceUnavailableError, GitHubCopilotStreamEndedEarlyError, GitHubCopilotUnrecognizedResponseError, IntercomBrokerError, IntercomBrokerProtocolError, IntercomBrokerStopTimeoutError, IntercomBrokerSuccessorTimeoutError, IntercomBrokerUpgradeError, IntercomRoutingChangedError, IntercomRoutingError, IntercomRoutingMismatchError, IntercomRoutingTimeoutError, IntercomRoutingUnavailableError, LISTING_FETCH_BATCH, MAX_SESSION_START_TIMEOUT_MS, McpOAuthAuthorizationRequiredError, McpOAuthCredentialStore, McpSignInCancelledError, MemorySnapshotBlobStore, ModelRegistry, OAuthRefreshRejectedError, OAuthTemporarilyUnavailableError, OutputRepairExhaustedError, ProjectGroupError, ProviderRequestFailure, RUNTIME_INTERCOM_GROUP_ENV, SESSION_BLOB_CHUNK_BYTES, SESSION_DOMAIN, SESSION_ENTRY_CHUNK_BYTES, SESSION_PRESENCE_DOMAIN, SESSION_PRESENCE_TABLES, SESSION_READ_FETCH, SESSION_READ_PAGE_CHARS, SESSION_RESUME_REBUILD, SESSION_SCHEMA_VERSION, SESSION_TABLES, SNAPSHOT_COLLECTION_BATCH, SessionConflictError, SessionExistsError, SessionFormatVersionError, SessionIdMismatchError, SessionInvalidTextError, SessionInvalidTimestampError, SessionNotFoundError, SessionStartConfigError, SessionStartError, SessionStartTimeoutError, ShowImagesSelectorComponent, SqlSessionStore, SqlSnapshotBlobStore, TerminalDecisionError, ThemeSelectorComponent, addMcpServerConfigAsync, announceBlueprintBuildWaits, clampThinkingLevel, classifyGitHubCopilotFailure, configuredSecretRedactor, createGatewayBindingFetch, createMcpAuthProvider, createMcpExtension, createTranscript, decide, decisionFailure, describeGitHubCopilotModel, deserializeGitHubCopilotError, findGitHubCopilotError, findSessionStartError, generateStructuredOutput, getGitHubCopilotError, getMcpToolExposure, getSupportedThinkingLevels, githubChecks, githubReviews, interval, isGitHubCopilotAuthenticationError, isGitHubCopilotContentFilterError, isGitHubCopilotEmptyResponseError, isGitHubCopilotError, isGitHubCopilotInvalidRequestError, isGitHubCopilotModelUnavailableError, isGitHubCopilotPromptTooLargeError, isGitHubCopilotQuotaExhaustedError, isGitHubCopilotRateLimitError, isGitHubCopilotServiceUnavailableError, isGitHubCopilotStreamEndedEarlyError, isGitHubCopilotUnrecognizedResponseError, isIntercomBrokerError, isIntercomBrokerProtocolError, isIntercomBrokerStopTimeoutError, isIntercomBrokerSuccessorTimeoutError, isIntercomBrokerUpgradeError, isIntercomRoutingChangedError, isIntercomRoutingError, isIntercomRoutingMismatchError, isIntercomRoutingTimeoutError, isIntercomRoutingUnavailableError, isOAuthRefreshRejectedError, isProjectGroupError, isRetryableGitHubCopilotError, isRetryableIntercomBrokerError, isRetryableIntercomRoutingError, isRetryableSessionStartError, isSessionStartConfigError, isSessionStartError, isSessionStartTimeoutError, loadMcpConfigAsync, logTail, mcpNamespace, mcpRequestTimeoutMs, parseFlattenedKeyPath, parseSessionStartTimeoutMs, publishExtensionContextEffect, publishPullRequest, readRuntimeIntercomGroup, reconstructFlattenedKeys, registerExtensionContextRetirementEffect, rehydrateIntercomBrokerError, rehydrateSessionStartError, removeMcpServerConfigAsync, resolveAutoModel, resolveDecisionModel, resolveMcpServerUrl, restoreRunWorktree, runDecision, runPrintMode, runRestorePreconditionError, runtimeIntercomGroupEnvKey, serializeGitHubCopilotError, serializeIntercomBrokerError, serializeSessionStartError, sessionScopedExtensionState, sessionStartStepText, setUpRestoredRunWorktrees, setUpResumedRunWorktrees, signInMcpServer, snapshotBlobHashes, snapshotIndexTables, unflattenArgumentsWithSchema, updateMcpServerConfig, updateMcpServerConfigAsync, validateMcpServerConfig, webhook, workspaceChangeSet, writeBlueprintBuildEvent };
10804
+ export { CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL, COMPACTOR_COMPRESSION_RATIO, ClassifierDecisionError, GITHUB_COPILOT_ERROR_DIAGNOSTIC, GitHubCopilotAuthenticationError, GitHubCopilotContentFilterError, GitHubCopilotEmptyResponseError, GitHubCopilotError, GitHubCopilotInvalidRequestError, GitHubCopilotModelUnavailableError, GitHubCopilotPromptTooLargeError, GitHubCopilotQuotaExhaustedError, GitHubCopilotRateLimitError, GitHubCopilotServiceUnavailableError, GitHubCopilotStreamEndedEarlyError, GitHubCopilotUnrecognizedResponseError, IntercomBrokerError, IntercomBrokerProtocolError, IntercomBrokerStopTimeoutError, IntercomBrokerSuccessorTimeoutError, IntercomBrokerUpgradeError, IntercomRoutingChangedError, IntercomRoutingError, IntercomRoutingMismatchError, IntercomRoutingTimeoutError, IntercomRoutingUnavailableError, LISTING_FETCH_BATCH, MAX_SESSION_START_TIMEOUT_MS, McpOAuthAuthorizationRequiredError, McpOAuthCredentialStore, McpSignInCancelledError, MemorySnapshotBlobStore, ModelRegistry, OAuthRefreshRejectedError, OAuthTemporarilyUnavailableError, OutputRepairExhaustedError, ProjectGroupError, ProviderRequestFailure, RUNTIME_INTERCOM_GROUP_ENV, SESSION_BLOB_CHUNK_BYTES, SESSION_DOMAIN, SESSION_ENTRY_CHUNK_BYTES, SESSION_FILLFACTOR_DOMAIN, SESSION_PRESENCE_DOMAIN, SESSION_PRESENCE_TABLES, SESSION_READ_FETCH, SESSION_READ_PAGE_CHARS, SESSION_RESUME_REBUILD, SESSION_SCHEMA_VERSION, SESSION_TABLES, SNAPSHOT_COLLECTION_BATCH, SessionConflictError, SessionExistsError, SessionFormatVersionError, SessionIdMismatchError, SessionInvalidTextError, SessionInvalidTimestampError, SessionNotFoundError, SessionStartConfigError, SessionStartError, SessionStartTimeoutError, ShowImagesSelectorComponent, SqlSessionStore, SqlSnapshotBlobStore, TerminalDecisionError, ThemeSelectorComponent, addMcpServerConfigAsync, announceBlueprintBuildWaits, clampThinkingLevel, classifyGitHubCopilotFailure, configuredSecretRedactor, createGatewayBindingFetch, createMcpAuthProvider, createMcpExtension, createTranscript, decide, decisionFailure, describeGitHubCopilotModel, deserializeGitHubCopilotError, findGitHubCopilotError, findSessionStartError, generateStructuredOutput, getGitHubCopilotError, getMcpToolExposure, getSupportedThinkingLevels, githubChecks, githubReviews, interval, isGitHubCopilotAuthenticationError, isGitHubCopilotContentFilterError, isGitHubCopilotEmptyResponseError, isGitHubCopilotError, isGitHubCopilotInvalidRequestError, isGitHubCopilotModelUnavailableError, isGitHubCopilotPromptTooLargeError, isGitHubCopilotQuotaExhaustedError, isGitHubCopilotRateLimitError, isGitHubCopilotServiceUnavailableError, isGitHubCopilotStreamEndedEarlyError, isGitHubCopilotUnrecognizedResponseError, isIntercomBrokerError, isIntercomBrokerProtocolError, isIntercomBrokerStopTimeoutError, isIntercomBrokerSuccessorTimeoutError, isIntercomBrokerUpgradeError, isIntercomRoutingChangedError, isIntercomRoutingError, isIntercomRoutingMismatchError, isIntercomRoutingTimeoutError, isIntercomRoutingUnavailableError, isOAuthRefreshRejectedError, isProjectGroupError, isRetryableGitHubCopilotError, isRetryableIntercomBrokerError, isRetryableIntercomRoutingError, isRetryableSessionStartError, isSessionStartConfigError, isSessionStartError, isSessionStartTimeoutError, loadMcpConfigAsync, logTail, mcpNamespace, mcpRequestTimeoutMs, parseFlattenedKeyPath, parseSessionStartTimeoutMs, publishExtensionContextEffect, publishPullRequest, readRuntimeIntercomGroup, reconstructFlattenedKeys, registerExtensionContextRetirementEffect, rehydrateIntercomBrokerError, rehydrateSessionStartError, removeMcpServerConfigAsync, resolveAutoModel, resolveDecisionModel, resolveMcpServerUrl, restoreRunWorktree, runDecision, runPrintMode, runRestorePreconditionError, runtimeIntercomGroupEnvKey, serializeGitHubCopilotError, serializeIntercomBrokerError, serializeSessionStartError, sessionScopedExtensionState, sessionStartStepText, setUpRestoredRunWorktrees, setUpResumedRunWorktrees, signInMcpServer, snapshotBlobHashes, snapshotIndexTables, unflattenArgumentsWithSchema, updateMcpServerConfig, updateMcpServerConfigAsync, validateMcpServerConfig, webhook, workspaceChangeSet, writeBlueprintBuildEvent };
10281
10805
 
10282
- //# sourceMappingURL=sdk-RRLVN7ER.js.map
10806
+ //# sourceMappingURL=sdk-AVFII7NK.js.map
10283
10807
  // __atomicOnDemandFailed: written by the build (scripts/in-place-update-gate.mjs). An import of this release's code on
10284
10808
  // demand that fails in a process an in-place update left running says to restart.
10285
10809
  function __atomicOnDemandFailed(error, feature) {
10286
10810
  return (async () => {
10287
10811
  const root = new URL("../", import.meta.url);
10288
10812
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
10289
- const key = `${root.href}#0.10.10`;
10813
+ const key = `${root.href}#0.10.11-alpha.1`;
10290
10814
  let release = releases.get(key);
10291
10815
  if (release === undefined) {
10292
10816
  const current = (async () => {
@@ -10314,7 +10838,7 @@ function __atomicOnDemandFailed(error, feature) {
10314
10838
  } catch {
10315
10839
  // No installation to read, as in a bundle of the package: the release the process runs decides.
10316
10840
  }
10317
- const updatedTo = typeof installed === "string" && installed !== "0.10.10" ? installed : running !== undefined && running.version !== "0.10.10" ? "0.10.10" : undefined;
10841
+ const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.1" ? installed : running !== undefined && running.version !== "0.10.11-alpha.1" ? "0.10.11-alpha.1" : undefined;
10318
10842
  if (updatedTo === undefined) throw error;
10319
10843
  const application = typeof running?.name === "string" ? running.name : "atomic";
10320
10844
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {