@bastani/atomic 0.10.11-alpha.1 → 0.10.11-alpha.3

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 (457) hide show
  1. package/CHANGELOG.md +155 -0
  2. package/README.md +5 -8
  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 +9 -9
  7. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +8 -8
  8. package/dist/_shared/mode-shared-2QJSCUM6.js +9 -9
  9. package/dist/_shared/p0-cli-BB45ZQY6.js +46 -67
  10. package/dist/_shared/p0-cli-BB45ZQY6.js.map +1 -1
  11. package/dist/_shared/p1a-prewarm-XIU57JHF.js +7 -8
  12. package/dist/_shared/p1a-prewarm-XIU57JHF.js.map +1 -1
  13. package/dist/_shared/{p1b-elig-ENCUPKKJ.js → p1b-elig-TVB5CBLL.js} +14 -2
  14. package/dist/_shared/{p1b-elig-ENCUPKKJ.js.map → p1b-elig-TVB5CBLL.js.map} +1 -1
  15. package/dist/_shared/runtime-O4KCSG4C.js +5 -5
  16. package/dist/_shared/{sdk-AVFII7NK.js → sdk-B5LEWGGI.js} +2633 -488
  17. package/dist/_shared/sdk-B5LEWGGI.js.map +1 -0
  18. package/dist/_shared/session-data-AHTU7IS6.js +3 -3
  19. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  20. package/dist/_shared/settings-startup-8-DNZ2RIHM.js +1 -1
  21. package/dist/_shared/{settings-startup-4QCVCI53.js → settings-startup-HXQLSUWM.js} +8 -2
  22. package/dist/_shared/settings-startup-HXQLSUWM.js.map +1 -0
  23. package/dist/_shared/{startup-0-0-57KF6LZH.js → startup-0-0-EZUKEP4Q.js} +436 -51
  24. package/dist/_shared/startup-0-0-EZUKEP4Q.js.map +1 -0
  25. package/dist/_shared/{startup-0-1-GIY75K46.js → startup-0-1-RTOHJFDJ.js} +240 -279
  26. package/dist/_shared/startup-0-1-RTOHJFDJ.js.map +1 -0
  27. package/dist/_shared/{startup-0-2-27OWFHV6.js → startup-0-2-5QHPCEON.js} +254 -46
  28. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -0
  29. package/dist/_shared/{startup-0-3-T4DVFYWX.js → startup-0-3-4ZYBYQNM.js} +273 -14
  30. package/dist/_shared/startup-0-3-4ZYBYQNM.js.map +1 -0
  31. package/dist/_shared/startup-0-4-ZMJV547D.js +14 -9
  32. package/dist/_shared/startup-0-4-ZMJV547D.js.map +1 -1
  33. package/dist/_shared/startup-0-5-YDW47QX6.js +10 -10
  34. package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -1
  35. package/dist/_shared/startup-10-0-TDQNBDDL.js +9 -9
  36. package/dist/_shared/startup-12-0-55AAXBJZ.js +3 -3
  37. package/dist/_shared/startup-14-0-MLX36RBG.js +6 -7
  38. package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
  39. package/dist/_shared/startup-15-0-YUKGAC63.js +7 -7
  40. package/dist/_shared/startup-15-1-4S7FLMNG.js +22 -30
  41. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  42. package/dist/_shared/startup-8-0-34CBHPZH.js +455 -102
  43. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  44. package/dist/_shared/{startup-8-1-X32CYSXB.js → startup-8-1-LZFXSD3Z.js} +162 -1184
  45. package/dist/_shared/startup-8-1-LZFXSD3Z.js.map +1 -0
  46. package/dist/_shared/storage-command-7MGXLJGZ.js +189 -36
  47. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  48. package/dist/_shared/storage-status-K7PX2RXA.js +557 -0
  49. package/dist/_shared/storage-status-K7PX2RXA.js.map +1 -0
  50. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  51. package/dist/_shared/team-DOQKICG2.js +376 -0
  52. package/dist/_shared/team-DOQKICG2.js.map +1 -0
  53. package/dist/_shared/tree-outline-MUEPK5B7.js +3 -3
  54. package/dist/builtin/intercom/CHANGELOG.md +34 -0
  55. package/dist/builtin/intercom/README.md +2 -2
  56. package/dist/builtin/intercom/broker/broker.bundle.mjs +1091 -344
  57. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +243 -64
  58. package/dist/builtin/intercom/broker/multinode-router.ts +154 -22
  59. package/dist/builtin/intercom/broker/multinode-state-store.ts +30 -3
  60. package/dist/builtin/intercom/broker/open-broker-state.ts +14 -0
  61. package/dist/builtin/intercom/broker/sql-add-column.ts +29 -5
  62. package/dist/builtin/intercom/broker/sql-ended-child-queue-store.ts +3 -2
  63. package/dist/builtin/intercom/broker/sql-held-send-store.ts +2 -2
  64. package/dist/builtin/intercom/broker/sql-known-session-store.ts +43 -19
  65. package/dist/builtin/intercom/broker/sql-lease-store.ts +208 -101
  66. package/dist/builtin/intercom/broker/sql-outbox-store.ts +516 -102
  67. package/dist/builtin/intercom/broker/sql-pending-ask-store.ts +8 -5
  68. package/dist/builtin/intercom/broker/sql-released-ask-store.ts +12 -5
  69. package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +24 -7
  70. package/dist/builtin/intercom/broker/sql-retention.ts +141 -0
  71. package/dist/builtin/intercom/broker/sql-schema.ts +199 -27
  72. package/dist/builtin/intercom/broker/sql-sent-message-authority.ts +74 -19
  73. package/dist/builtin/intercom/broker/wake-up-bus.ts +6 -0
  74. package/dist/builtin/intercom/index.bundle.mjs +2 -3
  75. package/dist/builtin/intercom/package.json +1 -1
  76. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  77. package/dist/builtin/mcp/package.json +1 -1
  78. package/dist/builtin/subagents/CHANGELOG.md +6 -0
  79. package/dist/builtin/subagents/package.json +1 -1
  80. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  81. package/dist/builtin/web-access/index.bundle.mjs +2 -10
  82. package/dist/builtin/web-access/package.json +1 -1
  83. package/dist/bun/bundled-sqlite.js +41 -0
  84. package/dist/bun/bundled-sqlite.js.map +1 -0
  85. package/dist/cli/args.js +2 -2
  86. package/dist/cli/auth-cli.code.js +6 -6
  87. package/dist/cli/auth-cli.impl.js +3 -3
  88. package/dist/cli/auth-cli.js +3 -3
  89. package/dist/cli/blueprint-command.code.js +4 -4
  90. package/dist/cli/blueprint-command.impl.js +3 -3
  91. package/dist/cli/blueprint-command.js +3 -3
  92. package/dist/cli/intercom-command.code.js +4 -4
  93. package/dist/cli/intercom-command.code.js.map +1 -1
  94. package/dist/cli/intercom-command.impl.js +3 -3
  95. package/dist/cli/intercom-command.js +3 -3
  96. package/dist/cli/list-models.code.js +2 -2
  97. package/dist/cli/list-models.impl.js +3 -3
  98. package/dist/cli/list-models.js +3 -3
  99. package/dist/cli/session-picker.code.js +2 -2
  100. package/dist/cli/session-picker.impl.js +3 -3
  101. package/dist/cli/session-picker.js +3 -3
  102. package/dist/cli/startup-ui.code.js +2 -2
  103. package/dist/cli/startup-ui.impl.js +3 -3
  104. package/dist/cli/startup-ui.js +3 -3
  105. package/dist/cli/storage-command.impl.js +3 -3
  106. package/dist/cli/storage-command.js +3 -3
  107. package/dist/cli/storage-search-session.code.js +3 -3
  108. package/dist/cli/storage-search-session.impl.js +3 -3
  109. package/dist/cli/storage-search-session.js +3 -3
  110. package/dist/cli/team-command.code.js +20 -114
  111. package/dist/cli/team-command.code.js.map +1 -1
  112. package/dist/cli/team-command.impl.js +3 -3
  113. package/dist/cli/team-command.js +3 -3
  114. package/dist/cli.js +5 -18
  115. package/dist/cli.js.map +1 -1
  116. package/dist/core/agent-rehydrate-errors.d.ts +4 -9
  117. package/dist/core/compaction/compactor.d.ts +3 -3
  118. package/dist/core/debug.code.js +1 -1
  119. package/dist/core/debug.impl.js +3 -3
  120. package/dist/core/debug.js +3 -3
  121. package/dist/core/export-html/card-projection.impl.js +3 -3
  122. package/dist/core/export-html/card-projection.js +3 -3
  123. package/dist/core/export-html/index.code.js +2 -2
  124. package/dist/core/export-html/index.impl.js +3 -3
  125. package/dist/core/export-html/index.js +3 -3
  126. package/dist/core/export-html/json-spans.impl.js +3 -3
  127. package/dist/core/export-html/json-spans.js +3 -3
  128. package/dist/core/export-html/oversized-render-inputs.code.js +1 -1
  129. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  130. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  131. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  132. package/dist/core/export-html/tool-renderer.js +3 -3
  133. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  134. package/dist/core/extensions/jiti-loader.js +3 -3
  135. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  136. package/dist/core/extensions/jiti-static-loader.js +3 -3
  137. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  138. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  139. package/dist/core/extensions/loader-host-modules.js +3 -3
  140. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  141. package/dist/core/extensions/runner-context.js +3 -3
  142. package/dist/core/intercom-broker-control-host.code.js +2 -2
  143. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  144. package/dist/core/intercom-broker-control-host.js +3 -3
  145. package/dist/core/intercom-broker-control.code.js +3 -3
  146. package/dist/core/intercom-broker-control.impl.js +3 -3
  147. package/dist/core/intercom-broker-control.js +3 -3
  148. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  149. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  150. package/dist/core/package-manager-storage-adapters.js +3 -3
  151. package/dist/core/process-start-token.d.ts +8 -0
  152. package/dist/core/process-tree-containment.d.ts +16 -0
  153. package/dist/core/sdk-types.d.ts +1 -2
  154. package/dist/core/sdk-types.js.map +1 -1
  155. package/dist/core/sdk.code.js +4 -4
  156. package/dist/core/sdk.impl.js +3 -3
  157. package/dist/core/sdk.js +3 -3
  158. package/dist/core/session-manager-core.js +27 -15
  159. package/dist/core/session-manager-core.js.map +1 -1
  160. package/dist/core/session-manager-list.impl.js +3 -3
  161. package/dist/core/session-manager-list.js +3 -3
  162. package/dist/core/session-manager.code.js +3 -3
  163. package/dist/core/session-manager.impl.js +3 -3
  164. package/dist/core/session-manager.js +3 -3
  165. package/dist/core/session-open-markers.js +3 -0
  166. package/dist/core/session-open-markers.js.map +1 -0
  167. package/dist/core/session-storage.code.js +1 -1
  168. package/dist/core/session-storage.impl.js +3 -3
  169. package/dist/core/session-storage.js +3 -3
  170. package/dist/core/settings-schema.d.ts +0 -3
  171. package/dist/core/storage/added-exports-0-10-11.js +19 -0
  172. package/dist/core/storage/added-exports-0-10-11.js.map +1 -0
  173. package/dist/core/storage/added-exports.js +3 -0
  174. package/dist/core/storage/added-exports.js.map +1 -1
  175. package/dist/core/storage/creation-time.js +105 -0
  176. package/dist/core/storage/creation-time.js.map +1 -0
  177. package/dist/core/storage/database.d.ts +56 -5
  178. package/dist/core/storage/database.js.map +1 -1
  179. package/dist/core/storage/dialect.d.ts +1 -1
  180. package/dist/core/storage/dialect.js +1 -1
  181. package/dist/core/storage/dialect.js.map +1 -1
  182. package/dist/core/storage/errors.d.ts +13 -13
  183. package/dist/core/storage/errors.js +10 -16
  184. package/dist/core/storage/errors.js.map +1 -1
  185. package/dist/core/storage/fenced-paths.d.ts +11 -0
  186. package/dist/core/storage/fenced-paths.js +11 -0
  187. package/dist/core/storage/fenced-paths.js.map +1 -1
  188. package/dist/core/storage/file-identity.d.ts +2 -0
  189. package/dist/core/storage/file-identity.js +24 -8
  190. package/dist/core/storage/file-identity.js.map +1 -1
  191. package/dist/core/storage/index.d.ts +4 -3
  192. package/dist/core/storage/index.js +5 -3
  193. package/dist/core/storage/index.js.map +1 -1
  194. package/dist/core/storage/libsql-removed.d.ts +71 -0
  195. package/dist/core/storage/libsql-removed.js +123 -0
  196. package/dist/core/storage/libsql-removed.js.map +1 -0
  197. package/dist/core/storage/migrations.d.ts +81 -8
  198. package/dist/core/storage/migrations.js +386 -47
  199. package/dist/core/storage/migrations.js.map +1 -1
  200. package/dist/core/storage/node-sqlite-file-gate.js +0 -15
  201. package/dist/core/storage/node-sqlite-file-gate.js.map +1 -1
  202. package/dist/core/storage/node-sqlite-thread.js +36 -12
  203. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  204. package/dist/core/storage/node-sqlite.js +135 -3
  205. package/dist/core/storage/node-sqlite.js.map +1 -1
  206. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  207. package/dist/core/storage/offline-snapshot-file.js +3 -3
  208. package/dist/core/storage/prefix.d.ts +1 -1
  209. package/dist/core/storage/prefix.js +14 -2
  210. package/dist/core/storage/prefix.js.map +1 -1
  211. package/dist/core/storage/process-selection.d.ts +5 -5
  212. package/dist/core/storage/provider.js +2 -2
  213. package/dist/core/storage/schema-catalog.d.ts +82 -5
  214. package/dist/core/storage/schema-catalog.js +244 -34
  215. package/dist/core/storage/schema-catalog.js.map +1 -1
  216. package/dist/core/storage/selection.d.ts +7 -82
  217. package/dist/core/storage/selection.js +20 -235
  218. package/dist/core/storage/selection.js.map +1 -1
  219. package/dist/core/storage/session/branch-fork-source.code.js +9 -8
  220. package/dist/core/storage/session/branch-fork-source.code.js.map +1 -1
  221. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  222. package/dist/core/storage/session/branch-fork-source.js +3 -3
  223. package/dist/core/storage/session/card-view.impl.js +3 -3
  224. package/dist/core/storage/session/card-view.js +3 -3
  225. package/dist/core/storage/session/child-reader.code.js +4 -4
  226. package/dist/core/storage/session/child-reader.impl.js +3 -3
  227. package/dist/core/storage/session/child-reader.js +3 -3
  228. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  229. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  230. package/dist/core/storage/session/errors.js +1 -1
  231. package/dist/core/storage/session/expanded-child-details.code.js +3 -3
  232. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  233. package/dist/core/storage/session/expanded-child-details.js +3 -3
  234. package/dist/core/storage/session/fork-detach.d.ts +118 -0
  235. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  236. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  237. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  238. package/dist/core/storage/session/fork-row-index.js +3 -3
  239. package/dist/core/storage/session/fork-schema.js +53 -0
  240. package/dist/core/storage/session/fork-schema.js.map +1 -0
  241. package/dist/core/storage/session/fork-segments.d.ts +58 -0
  242. package/dist/core/storage/session/fork-staging.code.js +5 -8
  243. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  244. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  245. package/dist/core/storage/session/fork-staging.js +3 -3
  246. package/dist/core/storage/session/fork-sweep.js +61 -0
  247. package/dist/core/storage/session/fork-sweep.js.map +1 -0
  248. package/dist/core/storage/session/fork-window.code.js +4 -4
  249. package/dist/core/storage/session/fork-window.impl.js +3 -3
  250. package/dist/core/storage/session/fork-window.js +3 -3
  251. package/dist/core/storage/session/history-pages.impl.js +3 -3
  252. package/dist/core/storage/session/history-pages.js +3 -3
  253. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  254. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  255. package/dist/core/storage/session/jsonl-session-store.d.ts +42 -2
  256. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  257. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  258. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  259. package/dist/core/storage/session/memory-session-store.js +3 -3
  260. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  261. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  262. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  263. package/dist/core/storage/session/released-history-files.code.js +4 -4
  264. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  265. package/dist/core/storage/session/released-history-files.js +3 -3
  266. package/dist/core/storage/session/resident-fork-rows.code.js +1 -1
  267. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  268. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  269. package/dist/core/storage/session/session-resume.impl.js +3 -3
  270. package/dist/core/storage/session/session-resume.js +3 -3
  271. package/dist/core/storage/session/session-search-index.d.ts +43 -4
  272. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  273. package/dist/core/storage/session/snapshot-cut.js +3 -3
  274. package/dist/core/storage/session/snapshot-history.code.js +4 -4
  275. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  276. package/dist/core/storage/session/snapshot-history.js +3 -3
  277. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  278. package/dist/core/storage/session/sql-session-store.d.ts +394 -20
  279. package/dist/core/storage/session/sql-session-store.impl.js +4 -4
  280. package/dist/core/storage/session/sql-session-store.js +4 -4
  281. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  282. package/dist/core/storage/session/tree-outline.js +3 -3
  283. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  284. package/dist/core/storage/session/tree-presentation.js +3 -3
  285. package/dist/core/storage/session/types.d.ts +22 -0
  286. package/dist/core/storage/sqlite-facade.d.ts +23 -2
  287. package/dist/core/storage/sqlite-facade.js +34 -0
  288. package/dist/core/storage/sqlite-facade.js.map +1 -1
  289. package/dist/core/storage/storage-status.code.js +1 -1
  290. package/dist/core/storage/storage-status.impl.js +3 -3
  291. package/dist/core/storage/storage-status.js +3 -3
  292. package/dist/core/storage/team.code.js +1 -1
  293. package/dist/core/storage/team.d.ts +26 -115
  294. package/dist/core/storage/team.impl.js +3 -3
  295. package/dist/core/storage/team.js +3 -3
  296. package/dist/core/structured-output/index.code.js +1 -1
  297. package/dist/core/structured-output/index.impl.js +3 -3
  298. package/dist/core/structured-output/index.js +3 -3
  299. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  300. package/dist/core/tasks/task-completion-entry.js +3 -3
  301. package/dist/core/tasks/task-file-history.code.js +4 -4
  302. package/dist/core/tasks/task-file-history.impl.js +3 -3
  303. package/dist/core/tasks/task-file-history.js +3 -3
  304. package/dist/core/tasks/task-reference-archive.code.js +5 -5
  305. package/dist/core/tasks/task-reference-archive.js +3 -3
  306. package/dist/core/tasks/task-reference-identity.js +3 -3
  307. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  308. package/dist/core/tasks/task-reference-stream.js +3 -3
  309. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  310. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  311. package/dist/core/tasks/task-view-source.code.js +1 -1
  312. package/dist/core/tasks/task-view-source.impl.js +3 -3
  313. package/dist/core/tasks/task-view-source.js +3 -3
  314. package/dist/core/tools/history-session.d.ts +2 -0
  315. package/dist/core/tools/history-tasks.d.ts +3 -2
  316. package/dist/core/tools/read-url.code.js +4 -4
  317. package/dist/core/tools/read-url.impl.js +3 -3
  318. package/dist/core/tools/read-url.js +3 -3
  319. package/dist/core/worktree-snapshot/blob-store.d.ts +71 -3
  320. package/dist/core/worktree-snapshot/blob-store.js +575 -67
  321. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  322. package/dist/core/worktree-snapshot/errors.code.js +3 -3
  323. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  324. package/dist/core/worktree-snapshot/errors.js +3 -3
  325. package/dist/core/worktree-snapshot/fork-blob-guard.js +81 -0
  326. package/dist/core/worktree-snapshot/fork-blob-guard.js.map +1 -0
  327. package/dist/core/worktree-snapshot/fork-snapshot-index.js +162 -0
  328. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -0
  329. package/dist/core/worktree-snapshot/session-index-reset.code.js +4 -0
  330. package/dist/core/worktree-snapshot/session-index-reset.code.js.map +1 -1
  331. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  332. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  333. package/dist/extensions/codemode/execute.code.js +2 -2
  334. package/dist/extensions/codemode/execute.impl.js +3 -3
  335. package/dist/extensions/codemode/execute.js +3 -3
  336. package/dist/extensions/codemode/renderer.code.js +2 -2
  337. package/dist/extensions/codemode/renderer.impl.js +3 -3
  338. package/dist/extensions/codemode/renderer.js +3 -3
  339. package/dist/extensions/mcp/cli.code.js +3 -3
  340. package/dist/extensions/mcp/cli.impl.js +3 -3
  341. package/dist/extensions/mcp/cli.js +3 -3
  342. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  343. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  344. package/dist/extensions/mcp/cli.lazy.js +3 -3
  345. package/dist/extensions/mcp/runtime.code.js +1 -1
  346. package/dist/extensions/mcp/runtime.impl.js +3 -3
  347. package/dist/extensions/mcp/runtime.js +3 -3
  348. package/dist/index.d.ts +3 -1
  349. package/dist/index.js +8 -8
  350. package/dist/main-first-time-setup.code.js +2 -2
  351. package/dist/main-first-time-setup.impl.js +3 -3
  352. package/dist/main-first-time-setup.js +3 -3
  353. package/dist/main.js +1 -1
  354. package/dist/modes/interactive/components/stored-tree-view.code.js +3 -3
  355. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  356. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  357. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  358. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  359. package/dist/modes/interactive/startup-shell-eligibility.js +1 -1
  360. package/dist/modes/interactive-engine/engine-prewarm.d.ts +1 -1
  361. package/dist/modes/print-mode.js +1 -1
  362. package/dist/package-manager-cli.code.js +7 -7
  363. package/dist/package-manager-cli.impl.js +3 -3
  364. package/dist/package-manager-cli.js +3 -3
  365. package/dist/rpc-entry.js +1 -1
  366. package/dist/startup-files.json +1 -1
  367. package/dist/startup-stages/10.js +1 -1
  368. package/dist/startup-stages/11.js +1 -1
  369. package/dist/startup-stages/12.js +1 -1
  370. package/dist/startup-stages/2.js +2 -3
  371. package/dist/startup-stages/3.js +1 -3
  372. package/dist/startup-stages/4.js +1 -2
  373. package/dist/startup-stages/5.js +1 -1
  374. package/dist/startup-stages/6.js +5 -7
  375. package/dist/startup-stages/7.js +3 -6
  376. package/dist/startup-stages/8.js +7 -2
  377. package/dist/startup-stages/9.js +1 -7
  378. package/dist/startup-stages/stages.json +1 -1
  379. package/dist/utils/compile-cache-deferral.js +8 -13
  380. package/dist/utils/compile-cache-deferral.js.map +1 -1
  381. package/dist/utils/compile-cache-warmup-host.js +3 -4
  382. package/dist/utils/compile-cache-warmup-host.js.map +1 -1
  383. package/dist/utils/compile-cache.js +12 -100
  384. package/dist/utils/compile-cache.js.map +1 -1
  385. package/dist/utils/startup-database-spare.code.js +3 -3
  386. package/dist/utils/startup-database-spare.impl.js +3 -3
  387. package/dist/utils/startup-database-spare.js +3 -3
  388. package/dist/utils/tools-manager.code.js +1 -1
  389. package/dist/utils/tools-manager.impl.js +3 -3
  390. package/dist/utils/tools-manager.js +3 -3
  391. package/dist/utils/worker-threads.js +2 -15
  392. package/dist/utils/worker-threads.js.map +1 -1
  393. package/docs/build.md +3 -3
  394. package/docs/changelog.mdx +1421 -69
  395. package/docs/compaction/reference.md +5 -5
  396. package/docs/compaction.md +7 -9
  397. package/docs/containerization.md +2 -2
  398. package/docs/custom-provider/api-reference.md +1 -1
  399. package/docs/docs.json +37 -10
  400. package/docs/environment-variables.md +0 -2
  401. package/docs/extensions/api-reference.md +4 -4
  402. package/docs/getting-started/installation.md +3 -0
  403. package/docs/guides/configuration.md +1 -1
  404. package/docs/guides/non-interactive.md +1 -1
  405. package/docs/guides/resume-on-any-machine.md +14 -22
  406. package/docs/guides/team-setup.md +56 -83
  407. package/docs/guides.md +2 -4
  408. package/docs/herdr.md +1 -1
  409. package/docs/index.md +1 -1
  410. package/docs/intercom/operations.md +26 -21
  411. package/docs/intercom/reference.md +2 -2
  412. package/docs/intercom.md +1 -1
  413. package/docs/libraries/storage-postgres.md +9 -9
  414. package/docs/libraries.md +2 -3
  415. package/docs/models-configuration.md +2 -2
  416. package/docs/models.md +2 -3
  417. package/docs/packages/authoring.md +7 -7
  418. package/docs/packages.md +1 -1
  419. package/docs/programmatic.md +2 -2
  420. package/docs/quickstart.md +1 -1
  421. package/docs/reference/cli.md +6 -11
  422. package/docs/reference.md +2 -2
  423. package/docs/rpc/extension-ui.md +2 -2
  424. package/docs/sdk/reference.md +5 -4
  425. package/docs/sdk/storage.md +8 -92
  426. package/docs/sdk/structured-decisions.md +1 -1
  427. package/docs/sdk/web-server.md +3 -3
  428. package/docs/sdk.md +14 -4
  429. package/docs/security.md +1 -1
  430. package/docs/session-format.md +5 -5
  431. package/docs/sessions.md +31 -42
  432. package/docs/settings.md +7 -8
  433. package/docs/storage/custom-adapters.md +255 -0
  434. package/docs/storage/jsonl.md +117 -0
  435. package/docs/{guides/postgres-pgbouncer.md → storage/postgres/pgbouncer.md} +73 -68
  436. package/docs/storage/postgres/tuning.md +337 -0
  437. package/docs/storage/postgres.md +556 -0
  438. package/docs/storage/sqlite.md +99 -0
  439. package/docs/storage.md +333 -956
  440. package/docs/subagents/authoring.md +1 -1
  441. package/docs/subagents.md +2 -2
  442. package/docs/tools.md +1 -1
  443. package/docs/worktree-snapshots.md +2 -2
  444. package/package.json +9 -9
  445. package/schemas/models.schema.json +2 -2
  446. package/schemas/settings.schema.json +0 -14
  447. package/dist/_shared/sdk-AVFII7NK.js.map +0 -1
  448. package/dist/_shared/settings-startup-4QCVCI53.js.map +0 -1
  449. package/dist/_shared/startup-0-0-57KF6LZH.js.map +0 -1
  450. package/dist/_shared/startup-0-1-GIY75K46.js.map +0 -1
  451. package/dist/_shared/startup-0-2-27OWFHV6.js.map +0 -1
  452. package/dist/_shared/startup-0-3-T4DVFYWX.js.map +0 -1
  453. package/dist/_shared/startup-8-1-X32CYSXB.js.map +0 -1
  454. package/dist/core/intercom-broker-control.d.ts +0 -129
  455. package/dist/startup-stages/13.js +0 -1
  456. package/docs/guides/postgres-tuning.md +0 -311
  457. package/docs/libraries/storage-libsql.md +0 -97
@@ -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, 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";
3
+ import { CONTINUE_AFTER_FAILURE, DynamicBorder, EventSourceError, ForkSourceIncompleteError, FramedSelector, LATEST_PROTOCOL_VERSION, SubscriptionClosedError, SubscriptionConfigError, SubscriptionSetupError, SubscriptionTimeoutError, abortFailure, announceHistoryLoad, applySessionSummaryEntries, assertForkSegments, bindChatEpoch, blueprintBuildsSettled, boundedChatRecord, canonicalEventBusFor, collectDeclaredDisplaySecrets, decodeChatOrder, decodeChatRecord, dropStoredNotes, encodeChatOrder, extractHeaderSecrets, firstChatOrders, flushRawStdout, forkRunSegments, forkStoreRelation, hasHistoryLoadObserver, isObject, isSensitiveKeyNameForMasking, materializeSessionSummaryMetadata, nativeForkReader, noteSnapshotGeneration, onBlueprintBuildFinished, onBlueprintBuildWaiting, prefixForkSegments, raceWithAbortSignal, redactAuthorizationUrlForDisplay, redactCredentials, redactOAuthErrorText, redactUrlForDisplay, redactUrlForTransportDisplay, registerArchiveLoad, registerForkScope, registerHistorySnapshot, resolveDecisionDeadlineMs, scrubFetchError, segmentLength, sha256Hex, sharedHistorySwitchHost, sharedWakeDispatcher, sliceHead, storedEntryNotes, storedRows, stripUrlUserinfoAndHash, whenAborted, withinDecisionDeadline, writeRawStdout, yieldTurn } from "./startup-0-0-EZUKEP4Q.js";
4
+ import { CommandDeliveries, SqlSessionSearchIndex, WorkspacePublicationError, collectCommandDeliveries, normalizeModelFailureSignal, reportDiagnostics, requireTimerMs } from "./startup-0-1-RTOHJFDJ.js";
5
5
  import { getAvailableThemes, keyHint } from "./p2-shell-main-B2WIALFD.js";
6
- import { releaseLock, reportDebugAsync, waitForLock } from "./p1b-elig-ENCUPKKJ.js";
7
- import { FileAuthStorageBackend, ResumePreconditionError, STRUCTURED_OUTPUT_TOOL_NAME, asyncAuthStorageReads, classifyRepository, killTrackedDetachedChildren, markNativeMcpToolDefinition, matchesMcpDirectToolSelection, providerRetryHint } from "./startup-0-2-27OWFHV6.js";
8
- import { CODEMODE_TOOL_NAME, assistantRetryAttempt, runWorkspaceProcess } from "./startup-0-3-T4DVFYWX.js";
9
- import { DecisionConfigError, DecisionModelUnavailableError, DecisionOutputError, DecisionProviderError, DecisionRequestError, SESSION_HISTORY_CHUNK_BYTES, SESSION_HISTORY_PAGE_BYTES, entrySizeLimit, isDecisionError, isDecisionProviderError } from "./settings-startup-4QCVCI53.js";
6
+ import { releaseLock, reportDebugAsync, waitForLock } from "./p1b-elig-TVB5CBLL.js";
7
+ import { FileAuthStorageBackend, ResumePreconditionError, STRUCTURED_OUTPUT_TOOL_NAME, asyncAuthStorageReads, classifyRepository, detachForkChildren, detachForkWithin, isTombstoned, killTrackedDetachedChildren, lockedReferrers, markNativeMcpToolDefinition, matchesMcpDirectToolSelection, noteForkCopyRefusal, providerRetryHint, removeStoredRows, resumeForkDetaches } from "./startup-0-2-5QHPCEON.js";
8
+ import { CODEMODE_TOOL_NAME, assistantRetryAttempt, runWorkspaceProcess } from "./startup-0-3-4ZYBYQNM.js";
9
+ import { DecisionConfigError, DecisionModelUnavailableError, DecisionOutputError, DecisionProviderError, DecisionRequestError, SESSION_HISTORY_CHUNK_BYTES, SESSION_HISTORY_PAGE_BYTES, entrySizeLimit, isDecisionError, isDecisionProviderError } from "./settings-startup-HXQLSUWM.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
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-X32CYSXB.js";
13
+ import { SettingsManager, checkoutsNeedingRebuild, inheritedRemotes, isInside, pathExists, resumeStoreDir, savedProjectTrustAsync, setUpResumedBlueprints, settingsFileTarget, settingsFileTargetAsync, writeSettingsFile, writeSettingsFileAsync } from "./startup-8-1-LZFXSD3Z.js";
14
14
  import "./startup-15-0-YUKGAC63.js";
15
15
  import "./startup-10-0-TDQNBDDL.js";
16
16
  import "./p1a-prewarm-XIU57JHF.js";
@@ -35,19 +35,25 @@ import lockfile from "proper-lockfile";
35
35
  import { clampThinkingLevel, clampThinkingLevel as clampThinkingLevel$1, getSupportedThinkingLevels } from "@bastani/atomic-ai/compat";
36
36
  import { once } from "node:events";
37
37
  import { SessionConflictError, SessionConflictError as SessionConflictError$1, SessionExistsError, SessionExistsError as SessionExistsError$1, SessionFormatVersionError, SessionIdMismatchError, SessionIdMismatchError as SessionIdMismatchError$1, SessionInvalidTextError, SessionInvalidTimestampError, SessionNotFoundError, SessionNotFoundError as SessionNotFoundError$1, StorageUnavailableError as StorageUnavailableError$1, StoreClosedError as StoreClosedError$1 } from "../core/storage/session/errors.js";
38
+ import * as blobStore from "../core/worktree-snapshot/blob-store.js";
38
39
  import { MemorySnapshotBlobStore, SNAPSHOT_COLLECTION_BATCH, SqlSnapshotBlobStore, SqlSnapshotBlobStore as SqlSnapshotBlobStore$1, snapshotBlobHashes, snapshotIndexTables, snapshotIndexTables as snapshotIndexTables$1 } from "../core/worktree-snapshot/blob-store.js";
39
40
  import { publishExtensionContextEffect, registerExtensionContextRetirementEffect } from "../core/extensions/runner-context.js";
40
41
  import { Type as Type$1 } from "@bastani/atomic-ai/utils/typebox/index";
41
42
  import { ModelRegistry } from "../core/model-registry.js";
43
+ import { ensureTableFillfactor, storageSchemaCurrent, transactionFinisher } from "../core/storage/added-exports.js";
42
44
  import { dialectOf, postgresJsonb } from "../core/storage/dialect.js";
43
45
  import { ensureStorageSchema } from "../core/storage/migrations.js";
44
46
  import { schemaCatalogOf, withStorageSchemaCatalog } from "../core/storage/schema-catalog.js";
45
47
  import { sequenceRunner } from "../core/storage/statement-sequence.js";
46
48
  import { createServer } from "node:http";
47
49
  import { Check, Errors } from "@bastani/atomic-ai/utils/typebox/value";
48
- import { ensureTableFillfactor, storageSchemaCurrent, transactionFinisher } from "../core/storage/added-exports.js";
50
+ import { TEAM_JOIN_COMMAND } from "../core/storage/libsql-removed.js";
51
+ import { ensureForkInheritedBlobGuard, installForkInheritedBlobGuard } from "../core/worktree-snapshot/fork-blob-guard.js";
52
+ import { forkLinkWrites, legacyForkLinksTriggerName } from "../core/worktree-snapshot/fork-snapshot-index.js";
53
+ import { MAX_SEQUENCE_REQUEST_STATEMENTS, noteStorageSchemaTables, refreshStorageSchemaCatalog } from "../core/storage/added-exports-0-10-11.js";
49
54
  import { assertStorageSchemaVersion, assertStoredSchemaVersion } from "../core/storage/schema.js";
50
55
  import { applyStorageMigrationsTogether, statementBatch } from "../core/storage/statement-batches.js";
56
+ import { createSharedHistoryTables, sessionForkTables, sharedHistoryTablesScript } from "../core/storage/session/fork-schema.js";
51
57
  import { CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL, createGatewayBindingFetch } from "@bastani/atomic-ai/api/cloudflare-gateway-binding";
52
58
  import { configuredSecretRedactor } from "../core/storage/sqlite-facade.js";
53
59
  import { oauthErrorHtml, oauthSuccessHtml } from "@bastani/atomic-ai/utils/oauth-page";
@@ -917,12 +923,32 @@ async function restoreRunWorktree(remotes, restore, options = {}) {
917
923
  }], options);
918
924
  return root;
919
925
  }
926
+ // dist/core/storage/session/json-list.js
927
+ /**
928
+ * `expression IN (…)` over a list bound as one parameter, the list as a JSON array (`JSON.stringify(values)`): the
929
+ * statement's text is the same however many values the list holds, so a server that keeps prepared statements, and
930
+ * pg_stat_statements, see one statement instead of one per length (#6560). On PostgreSQL the list becomes an array the
931
+ * comparison takes whole (`= ANY`), so an index on `expression` is searched for each value, as for a list of
932
+ * parameters. With `int`, PostgreSQL's text elements are compared as integers.
933
+ */
934
+ function inJsonList(dialect, expression, int = false) {
935
+ const values = `SELECT ${int ? `CAST(value AS ${dialect.types.int})` : "value"} FROM ${dialect.jsonValues("?")}`;
936
+ return dialect.name === "postgres" ? `${expression} = ANY(ARRAY(${values}))` : `${expression} IN (${values})`;
937
+ }
920
938
  // dist/core/storage/session/fork-row-copy.js
921
939
  /** How many entry IDs a run builder holds for lookups before it sends its runs, bounding what a fork holds. */
922
940
  const HELD_RUN_ROWS = 4096;
923
941
  /** How many hashes one blob statement names, so a statement stays small whatever the session holds. */
924
942
  const BLOB_HASHES_PER_STATEMENT = 256;
925
943
  /**
944
+ * The chunk rows `INSERT … SELECT` copies of the entries of session `?` at seqs `?` to `?`: only each entry's chunks 0 to
945
+ * `chunks - 1`, as the copy one chunk at a time did, never a row an older version left past them or at an entry stored
946
+ * whole. `incompleteEntryRead` then finds an entry missing any of those.
947
+ */
948
+ function entryChunkRows(tables, seqs) {
949
+ return `FROM ${tables.entryChunks} c JOIN ${tables.entries} e ON e.session_id = c.session_id AND e.seq = c.seq WHERE c.session_id = ? AND c.seq ${seqs} AND c.idx >= 0 AND c.idx < e.chunks ORDER BY c.seq, c.idx`;
950
+ }
951
+ /**
926
952
  * 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
953
  * one `INSERT … SELECT` for its entries and one for their chunks (#6560), not one statement per row and chunk. Rows are
928
954
  * copied in seq order, so the snapshot index's triggers meet a parent before its children, as they do for an append.
@@ -981,7 +1007,7 @@ var ForkRowRuns = class {
981
1007
  changes: count,
982
1008
  mismatch: () => new SessionConflictError$1(this.source, sourceFrom, sourceFrom + count - 1)
983
1009
  }, {
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`,
1010
+ sql: `INSERT INTO ${entryChunks} (session_id, seq, idx, data) SELECT ?, c.seq + ?, c.idx, c.data ${entryChunkRows(this.tables, "BETWEEN ? AND ?")}`,
985
1011
  params
986
1012
  });
987
1013
  }
@@ -993,11 +1019,12 @@ var ForkRowRuns = class {
993
1019
  };
994
1020
  /**
995
1021
  * 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.
1022
+ * entry copied from the source names its chunk count, and the chunks were copied in the same statements. It counts the
1023
+ * entry's chunk rows from 0 to `chunks - 1`, keyed by their index, so a count of `chunks` is each of them.
997
1024
  */
998
1025
  function incompleteEntryRead(tables, child) {
999
1026
  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`,
1027
+ 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 AND c.idx >= 0 AND c.idx < e.chunks) LIMIT 1`,
1001
1028
  params: [child]
1002
1029
  };
1003
1030
  }
@@ -1006,7 +1033,7 @@ function incompleteEntryRead(tables, child) {
1006
1033
  * as `copyForkBlob` copied each one, a blob the child already holds is kept, one in the legacy one-row layout is copied
1007
1034
  * only with all its bytes, and each chunk only at its full length.
1008
1035
  */
1009
- function forkBlobCopy(tables, options, source, child, hashes) {
1036
+ function forkBlobCopy(dialect, tables, options, source, child, hashes) {
1010
1037
  const { blobs, blobChunks } = tables;
1011
1038
  const columns = options.legacyBlobData ? ", data" : "";
1012
1039
  const sourceColumns = options.legacyBlobData ? ", p.data" : "";
@@ -1016,33 +1043,33 @@ function forkBlobCopy(tables, options, source, child, hashes) {
1016
1043
  const groups = [];
1017
1044
  for (let start = 0; start < hashes.length; start += BLOB_HASHES_PER_STATEMENT) groups.push(hashes.slice(start, start + BLOB_HASHES_PER_STATEMENT));
1018
1045
  for (const group of groups) {
1019
- const named = group.map(() => "?").join(", ");
1046
+ const named = JSON.stringify(group);
1020
1047
  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`,
1048
+ 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 ${inJsonList(dialect, "p.hash")}${whole} AND NOT EXISTS (SELECT 1 FROM ${blobs} c WHERE c.session_id = ? AND c.hash = p.hash) ORDER BY p.hash`,
1022
1049
  params: [
1023
1050
  child,
1024
1051
  source,
1025
- ...group,
1052
+ named,
1026
1053
  child
1027
1054
  ]
1028
1055
  }, {
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`,
1056
+ 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 ${inJsonList(dialect, "k.hash")} 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
1057
  params: [
1031
1058
  child,
1032
1059
  source,
1033
- ...group,
1060
+ named,
1034
1061
  options.chunkBytes,
1035
1062
  options.chunkBytes,
1036
1063
  child
1037
1064
  ]
1038
1065
  });
1039
1066
  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})`,
1067
+ 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 ${inJsonList(dialect, "p.hash")}`,
1041
1068
  params: [
1042
1069
  child,
1043
1070
  child,
1044
1071
  source,
1045
- ...group
1072
+ named
1046
1073
  ]
1047
1074
  });
1048
1075
  }
@@ -1066,6 +1093,394 @@ function forkBlobCopy(tables, options, source, child, hashes) {
1066
1093
  }
1067
1094
  };
1068
1095
  }
1096
+ // dist/core/storage/session/fork-lineage.js
1097
+ /** Segment rows one statement inserts at most: six parameters each, well under every backend's parameter limit. */
1098
+ const SEGMENT_ROWS_PER_INSERT = 500;
1099
+ /** Session `sessionId`'s segments, in view order, read through `tx`. None for a session that inherits nothing. */
1100
+ async function readForkSegments(tx, tables, sessionId) {
1101
+ return (await tx.all(`SELECT source_id, from_seq, to_seq, base_seq FROM ${tables.forkSegments} WHERE session_id = ? ORDER BY idx`, sessionId)).map((row) => ({
1102
+ sourceId: String(row.source_id),
1103
+ fromSeq: Number(row.from_seq),
1104
+ toSeq: Number(row.to_seq),
1105
+ baseSeq: Number(row.base_seq)
1106
+ }));
1107
+ }
1108
+ /**
1109
+ * The statements that make `segments` session `sessionId`'s segments, in place of any it had, and give its lineage row a
1110
+ * new generation: with `lineage`, the parent and cut-off a new fork records; without, the row keeps them. Throws unless
1111
+ * `segments` are well formed for a view of `length` seqs. The session's own rows must not sit at a seq they cover:
1112
+ * a view is the rows its segments name and the session's own rows, both read.
1113
+ */
1114
+ function forkSegmentWrites(tables, sessionId, segments, length, lineage) {
1115
+ assertForkSegments(sessionId, segments, length);
1116
+ return [
1117
+ {
1118
+ sql: `DELETE FROM ${tables.forkSegments} WHERE session_id = ?`,
1119
+ params: [sessionId]
1120
+ },
1121
+ ...forkSegmentInserts(tables, sessionId, 0, segments),
1122
+ forkLineageWrite(tables, sessionId, lineage)
1123
+ ];
1124
+ }
1125
+ /** The statements that insert `segments` as session `sessionId`'s segments from index `firstIndex` on. */
1126
+ function forkSegmentInserts(tables, sessionId, firstIndex, segments) {
1127
+ const statements = [];
1128
+ for (let start = 0; start < segments.length; start += SEGMENT_ROWS_PER_INSERT) {
1129
+ const batch = segments.slice(start, start + SEGMENT_ROWS_PER_INSERT);
1130
+ statements.push({
1131
+ sql: `INSERT INTO ${tables.forkSegments} (session_id, idx, source_id, from_seq, to_seq, base_seq) VALUES ${batch.map(() => "(?, ?, ?, ?, ?, ?)").join(", ")}`,
1132
+ params: batch.flatMap((segment, index) => [
1133
+ sessionId,
1134
+ firstIndex + start + index,
1135
+ segment.sourceId,
1136
+ segment.fromSeq,
1137
+ segment.toSeq,
1138
+ segment.baseSeq
1139
+ ])
1140
+ });
1141
+ }
1142
+ return statements;
1143
+ }
1144
+ /**
1145
+ * The statement that gives session `sessionId`'s lineage row a new generation, as every change to its segments must:
1146
+ * with `lineage`, the parent and cut-off a new fork records; without, the row keeps them.
1147
+ */
1148
+ function forkLineageWrite(tables, sessionId, lineage) {
1149
+ return {
1150
+ sql: `INSERT INTO ${tables.forkLineage} (session_id, parent_id, cut_seq, generation) VALUES (?, ?, ?, ?)
1151
+ ON CONFLICT(session_id) DO UPDATE SET generation = excluded.generation${lineage === void 0 ? "" : ", parent_id = excluded.parent_id, cut_seq = excluded.cut_seq"}`,
1152
+ params: [
1153
+ sessionId,
1154
+ lineage?.parentId ?? null,
1155
+ lineage?.cutSeq ?? null,
1156
+ crypto.randomUUID()
1157
+ ]
1158
+ };
1159
+ }
1160
+ /** Runs {@link forkSegmentWrites} through `tx`. */
1161
+ async function writeForkSegments(tx, tables, sessionId, segments, length, lineage) {
1162
+ for (const { sql, params } of forkSegmentWrites(tables, sessionId, segments, length, lineage)) await tx.run(sql, ...params);
1163
+ }
1164
+ /** The sessions with a segment that names `sourceId`, by id: the forks that read rows `sourceId` stores. */
1165
+ async function forkChildren(tx, tables, sourceId) {
1166
+ return (await tx.all(`SELECT DISTINCT session_id FROM ${tables.forkSegments} WHERE source_id = ? ORDER BY session_id`, sourceId)).map((row) => String(row.session_id));
1167
+ }
1168
+ /**
1169
+ * Locks the sessions rows of `ids`, in id order so that two transactions never wait for each other: `key-share` keeps
1170
+ * them from being deleted or locked `update` while the transaction lasts, as a fork that names them in its segments
1171
+ * needs; `update` excludes those. Nothing on SQLite, whose write transactions already run one at a time.
1172
+ */
1173
+ async function lockForkSources(tx, dialect, tables, ids, mode) {
1174
+ const sorted = [...new Set(ids)].sort();
1175
+ if (dialect.name === "sqlite" || sorted.length === 0) return;
1176
+ await tx.all(`SELECT id FROM ${tables.sessions} WHERE ${inJsonList(dialect, "id")} ORDER BY id${dialect.lockClause(mode)}`, JSON.stringify(sorted));
1177
+ }
1178
+ /**
1179
+ * The segments of a fork that shares its parent's history, gathered as the fork's rows stream past (#6560): each row the
1180
+ * parent stores unchanged extends a run of the parent's view, and `drain` composes the runs gathered since the last
1181
+ * one with the parent's own segments, so that each segment names the session that stores its rows, and returns the
1182
+ * statements that insert them. Drain before the fork writes a row of its own, so that its segments come first in seq
1183
+ * order. `heldSeq` answers for the rows of runs not yet drained.
1184
+ */
1185
+ var ForkSegmentRuns = class {
1186
+ segments = [];
1187
+ runs = [];
1188
+ held = /* @__PURE__ */ new Map();
1189
+ tables;
1190
+ child;
1191
+ parent;
1192
+ constructor(tables, child, parent) {
1193
+ this.tables = tables;
1194
+ this.child = child;
1195
+ this.parent = parent;
1196
+ }
1197
+ /** The parent's row at view seq `parentSeq` is the child's row at `childSeq`, entry `id`. */
1198
+ add(parentSeq, childSeq, id) {
1199
+ const run = this.runs.at(-1);
1200
+ if (run && parentSeq === run.toSeq + 1 && childSeq === run.baseSeq + (run.toSeq - run.fromSeq) + 2) run.toSeq++;
1201
+ else this.runs.push({
1202
+ fromSeq: parentSeq,
1203
+ toSeq: parentSeq,
1204
+ baseSeq: childSeq - 1
1205
+ });
1206
+ this.held.set(id, childSeq);
1207
+ }
1208
+ /** The child seq of entry `id` among the rows not yet drained, the latest when several hold it. */
1209
+ heldSeq(id) {
1210
+ return this.held.get(id);
1211
+ }
1212
+ /** Whether enough rows wait that they should be drained before more are added. */
1213
+ get full() {
1214
+ return this.held.size >= 8192;
1215
+ }
1216
+ /** The statements that insert the segments of the runs gathered since the last drain. */
1217
+ drain() {
1218
+ if (this.runs.length === 0) return [];
1219
+ const composed = this.runs.flatMap((run) => forkRunSegments(this.parent.id, this.parent.segments, this.parent.length, run));
1220
+ const first = this.segments.length;
1221
+ this.segments.push(...composed);
1222
+ this.runs.length = 0;
1223
+ this.held.clear();
1224
+ return forkSegmentInserts(this.tables, this.child, first, composed);
1225
+ }
1226
+ };
1227
+ /**
1228
+ * `segments` without the view seqs `pieces` cover: each piece must lie within one segment, naming the same rows of the
1229
+ * same source. Throws otherwise.
1230
+ */
1231
+ function withoutForkPieces(segments, pieces) {
1232
+ const end = (segment) => segment.baseSeq + segmentLength(segment);
1233
+ const remaining = [];
1234
+ for (const segment of segments) {
1235
+ const inside = pieces.filter((piece) => piece.baseSeq >= segment.baseSeq && end(piece) <= end(segment) && piece.sourceId === segment.sourceId).sort((a, b) => a.baseSeq - b.baseSeq);
1236
+ let view = segment.baseSeq;
1237
+ for (const piece of inside) {
1238
+ if (piece.fromSeq - piece.baseSeq !== segment.fromSeq - segment.baseSeq || piece.baseSeq < view) throw new RangeError(`Fork piece ${JSON.stringify(piece)} does not lie within ${JSON.stringify(segment)}`);
1239
+ if (piece.baseSeq > view) remaining.push({
1240
+ ...segment,
1241
+ fromSeq: segment.fromSeq + (view - segment.baseSeq),
1242
+ toSeq: piece.fromSeq - 1,
1243
+ baseSeq: view
1244
+ });
1245
+ view = end(piece);
1246
+ }
1247
+ if (view < end(segment)) remaining.push({
1248
+ ...segment,
1249
+ fromSeq: segment.fromSeq + (view - segment.baseSeq),
1250
+ baseSeq: view
1251
+ });
1252
+ }
1253
+ const covered = pieces.reduce((sum, piece) => sum + segmentLength(piece), 0);
1254
+ if (segments.reduce((sum, segment) => sum + segmentLength(segment), 0) - remaining.reduce((sum, segment) => sum + segmentLength(segment), 0) !== covered) throw new RangeError("Fork pieces overlap or lie outside the fork's segments");
1255
+ return remaining;
1256
+ }
1257
+ /** The first seq of `piece` whose entry its source lacks, or holds without one of its chunks: why its copy was refused. */
1258
+ async function firstIncomplete(tx, tables, piece) {
1259
+ const rows = await tx.all(`SELECT e.seq, e.chunks, (SELECT count(*) FROM ${tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx >= 0 AND c.idx < e.chunks) AS held FROM ${tables.entries} e WHERE e.session_id = ? AND e.seq BETWEEN ? AND ? ORDER BY e.seq`, piece.sourceId, piece.fromSeq, piece.toSeq);
1260
+ let expected = piece.fromSeq;
1261
+ for (const row of rows) {
1262
+ if (Number(row.seq) !== expected || Number(row.chunks) > 0 && Number(row.held) !== Number(row.chunks)) return expected;
1263
+ expected++;
1264
+ }
1265
+ return expected;
1266
+ }
1267
+ /**
1268
+ * Copies into session `childId`, a fork that shares history, the rows `pieces` of its segments name, with their chunks,
1269
+ * search texts and the blobs their tool outputs name, and links them in the snapshot index with `links.materialized`
1270
+ * (see `materializedForkLinks`), a statement a piece, then writes its segments without them, with a new generation, so
1271
+ * its view stays as it was at every commit (#6560). `links.settle` writes the segments, and in the same request checks
1272
+ * the child's links from the first row copied on against the ones a save in seq order writes, linking them again where
1273
+ * they differ (`sessionEntryLinks`). Each piece lies within one of the child's segments: a sub-range of
1274
+ * it, or all of it. The caller holds the child's row locked `update`, and the sources' rows locked, so neither its
1275
+ * segments nor the rows they name change meanwhile; `length` is the child's last seq.
1276
+ */
1277
+ async function materializeForkSegments(tx, dialect, tables, blobs, links, childId, length, pieces) {
1278
+ const remaining = withoutForkPieces(await readForkSegments(tx, tables, childId), pieces);
1279
+ const text = (...path) => dialect.jsonText("entry_json", ...path);
1280
+ for (const piece of [...pieces].sort((a, b) => a.baseSeq - b.baseSeq)) {
1281
+ const shift = piece.baseSeq - piece.fromSeq + 1;
1282
+ const range = [
1283
+ piece.sourceId,
1284
+ piece.fromSeq,
1285
+ piece.toSeq
1286
+ ];
1287
+ const copied = await tx.run(`INSERT INTO ${tables.entries} (session_id, seq, entry_id, entry_json, chunks) SELECT ?, e.seq + ?, e.entry_id, e.entry_json, e.chunks FROM ${tables.entries} e WHERE e.session_id = ? AND e.seq BETWEEN ? AND ? AND (e.chunks = 0 OR e.chunks = (SELECT count(*) FROM ${tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx >= 0 AND c.idx < e.chunks)) ORDER BY e.seq`, childId, shift, ...range);
1288
+ if (Number(copied.changes) !== segmentLength(piece)) throw new ForkSourceIncompleteError(childId, piece.sourceId, await firstIncomplete(tx, tables, piece));
1289
+ await Promise.all([links.materialized === void 0 ? void 0 : tx.run(links.materialized, childId, shift, ...range, childId), tx.run(`INSERT INTO ${tables.entryChunks} (session_id, seq, idx, data) SELECT ?, c.seq + ?, c.idx, c.data FROM ${tables.entryChunks} c JOIN ${tables.entries} e ON e.session_id = c.session_id AND e.seq = c.seq WHERE c.session_id = ? AND c.seq BETWEEN ? AND ? AND c.idx >= 0 AND c.idx < e.chunks ORDER BY c.seq, c.idx`, childId, shift, ...range)]);
1290
+ await tx.run(`INSERT INTO ${tables.searchTexts} (session_id, seq, text_json) SELECT ?, seq + ?, text_json FROM ${tables.searchTexts} WHERE session_id = ? AND seq BETWEEN ? AND ? ORDER BY seq`, childId, shift, ...range);
1291
+ const named = await tx.all(`SELECT DISTINCT ${text("data", "hash")} AS hash FROM ${tables.entries} WHERE session_id = ? AND seq BETWEEN ? AND ?
1292
+ AND chunks = 0 AND ${text("type")} = 'custom' AND ${text("customType")} = 'atomic.tool-output' AND ${text("data", "hash")} IS NOT NULL`, ...range);
1293
+ const copy = forkBlobCopy(dialect, tables, blobs, piece.sourceId, childId, named.map((row) => String(row.hash)));
1294
+ for (const { sql, params } of copy.statements) await tx.run(sql, ...params);
1295
+ const answers = [];
1296
+ for (const { sql, params } of copy.checks) answers.push(await tx.all(sql, ...params));
1297
+ copy.remaining(answers);
1298
+ }
1299
+ const writes = forkSegmentWrites(tables, childId, remaining, length);
1300
+ if (pieces.length === 0) for (const { sql, params } of writes) await tx.run(sql, ...params);
1301
+ else await links.settle(tx, childId, Math.min(...pieces.map((piece) => piece.baseSeq + 1)), writes);
1302
+ }
1303
+ // dist/core/storage/session/fork-detach-host.js
1304
+ /**
1305
+ * The SQL session store's side of detaching and pinning shared fork history (#6560): its fork segments, read and
1306
+ * written through fork-lineage.ts, in transactions of the store.
1307
+ */
1308
+ /** The fork host of a store whose sessions schema has shared-history forks. */
1309
+ function forkDetachHost(store) {
1310
+ const { dialect, tables, forkTables } = store;
1311
+ const lineage = {
1312
+ sessions: tables.sessions,
1313
+ forkSegments: forkTables.forkSegments,
1314
+ forkLineage: forkTables.forkLineage
1315
+ };
1316
+ const materialize = {
1317
+ ...tables,
1318
+ ...lineage
1319
+ };
1320
+ /** A session's last seq: the length of its view. A deleted session's tombstone has no row, and no view to keep. */
1321
+ const length = async (tx, sessionId) => {
1322
+ const row = await tx.get(`SELECT last_seq FROM ${tables.sessions} WHERE id = ?`, sessionId);
1323
+ return row === void 0 ? 0 : Number(row.last_seq);
1324
+ };
1325
+ return {
1326
+ forkDetachTable: forkTables.forkDetach,
1327
+ pinTables: {
1328
+ entries: tables.entries,
1329
+ entryChunks: tables.entryChunks,
1330
+ searchTexts: tables.searchTexts,
1331
+ blobs: tables.blobs,
1332
+ blobChunks: tables.blobChunks,
1333
+ tombstones: forkTables.forkTombstones,
1334
+ forkSegments: forkTables.forkSegments,
1335
+ forkLineage: forkTables.forkLineage
1336
+ },
1337
+ forkTransaction: (body) => store.transaction(body),
1338
+ lockClause: (mode) => dialect.lockClause(mode),
1339
+ forkSegments: (tx, sessionId) => readForkSegments(tx, lineage, sessionId),
1340
+ forkChildren: (tx, sourceId) => forkChildren(tx, lineage, sourceId),
1341
+ async materializeForkSegments(tx, childId, pieces) {
1342
+ await materializeForkSegments(tx, dialect, materialize, store.blobs, store.entryLinks, childId, await length(tx, childId), pieces);
1343
+ },
1344
+ async writeForkSegments(tx, sessionId, segments) {
1345
+ if (segments.length > 0) await store.entryLinks.settle(tx, sessionId, Math.min(...segments.map((segment) => segment.baseSeq + 1)), forkSegmentWrites(lineage, sessionId, segments, await length(tx, sessionId)));
1346
+ else if ((await readForkSegments(tx, lineage, sessionId)).length > 0) await writeForkSegments(tx, lineage, sessionId, segments, await length(tx, sessionId));
1347
+ },
1348
+ async lockForkSources(tx, ids, mode) {
1349
+ await lockForkSources(tx, dialect, lineage, ids, mode);
1350
+ const sorted = [...new Set(ids)].sort();
1351
+ if (dialect.name !== "sqlite" && sorted.length > 0) await tx.all(`SELECT session_id FROM ${forkTables.forkTombstones} WHERE ${inJsonList(dialect, "session_id")} ORDER BY session_id${dialect.lockClause(mode)}`, JSON.stringify(sorted));
1352
+ },
1353
+ async forkRewriteEpoch(tx, sessionId) {
1354
+ return (await tx.get(`SELECT COALESCE(${dialect.jsonText("summary_state", "epoch")}, ${dialect.jsonText("summary_state", "resume", "epoch")}) AS epoch FROM ${tables.sessions} WHERE id = ?`, sessionId))?.epoch ?? void 0;
1355
+ }
1356
+ };
1357
+ }
1358
+ // dist/core/storage/session/fork-pins.js
1359
+ /**
1360
+ * What deleting, replacing and re-creating a session does when forks read rows it stores. A fork's segments name the
1361
+ * session that stores each row it inherited, so those rows stay for as long as any segment names them:
1362
+ *
1363
+ * - Deleting a session that forks still read removes it from every read (its sessions row and its search texts go)
1364
+ * but keeps the rows they read, its entries, entry chunks and blobs, under a tombstone. The rows go with the
1365
+ * tombstone once nothing names them any more: when the last fork reading them is deleted, replaced or detached.
1366
+ * - Replacing a session that forks still read first gives each of them its own copy of the rows it read (detach),
1367
+ * since the replace deletes those rows.
1368
+ * - Creating a session under the ID of a tombstone, by `create` or by any fork, first detaches the forks that still
1369
+ * read the old rows, then removes them, so the new session starts empty.
1370
+ *
1371
+ * A session's own segments go when it is deleted or replaced, which may leave a deleted source no fork reads; the caller
1372
+ * sweeps it once its transaction commits (fork-sweep.ts). A delete and a replace lock the session's row for update
1373
+ * before they read anything of its fork history, as the first read of their transaction ({@link forkPinReads}), so
1374
+ * they drop its own segments and list the forks that name it only under that lock. A fork locks every session its
1375
+ * segments name for key share, tombstones included, so a fork being made either commits first and is listed, or waits
1376
+ * and finds the session gone.
1377
+ *
1378
+ * Every transaction locks tombstones before sessions rows, and the sessions rows it locks together in one statement,
1379
+ * in id order, so no two of them wait for each other in a cycle: a replace locks the forks reading the session with
1380
+ * the session itself, as a fork locks its donor with the sessions its segments name.
1381
+ */
1382
+ /**
1383
+ * A replace listed a fork of the session that its first read did not lock: a fork made while that read waited for its
1384
+ * locks. The replace runs again, locking it in order with the rest.
1385
+ */
1386
+ var ForkReadersMoved = class extends Error {
1387
+ constructor() {
1388
+ super("A fork of the session was made while its replace waited for its locks");
1389
+ }
1390
+ };
1391
+ /**
1392
+ * The statements a delete or a replace of `sessionId` reads its fork history with, as the first reads of its
1393
+ * transaction: where writers can run together, the session's row, locked for update so that no fork of it starts
1394
+ * meanwhile, with `readers` also the rows of the forks reading it, which a replace detaches, all in id order; then
1395
+ * the listing. Sent with the transaction's start, they cost no round trip of their own.
1396
+ */
1397
+ function forkPinReads(host, sessions, sessionId, readers = false) {
1398
+ const { forkSegments, forkLineage } = host.pinTables;
1399
+ const lock = host.lockClause("update");
1400
+ const locked = readers ? {
1401
+ sql: `SELECT id FROM ${sessions} WHERE id = ? OR id IN (SELECT session_id FROM ${forkSegments} WHERE source_id = ?) ORDER BY id${lock}`,
1402
+ params: [sessionId, sessionId]
1403
+ } : {
1404
+ sql: `SELECT id FROM ${sessions} WHERE id = ?${lock}`,
1405
+ params: [sessionId]
1406
+ };
1407
+ return [...lock === "" ? [] : [locked], {
1408
+ sql: `SELECT 's' AS kind, source_id AS id FROM ${forkSegments} WHERE session_id = ?
1409
+ UNION SELECT 'r', session_id FROM ${forkSegments} WHERE source_id = ? AND session_id <> ?
1410
+ UNION SELECT 'l', session_id FROM ${forkLineage} WHERE session_id = ?`,
1411
+ params: [
1412
+ sessionId,
1413
+ sessionId,
1414
+ sessionId,
1415
+ sessionId
1416
+ ]
1417
+ }];
1418
+ }
1419
+ /** Reads `sessionId`'s fork history through the statements of {@link forkPinReads}, in order. */
1420
+ async function readForkPins(tx, reads) {
1421
+ const listing = reads.at(-1);
1422
+ const locks = reads.slice(0, -1);
1423
+ const locked = /* @__PURE__ */ new Set();
1424
+ for (const lock of locks) for (const row of await tx.all(lock.sql, ...lock.params)) locked.add(String(row.id));
1425
+ const rows = await tx.all(listing.sql, ...listing.params);
1426
+ const of = (kind) => [...new Set(rows.filter((row) => row.kind === kind).map((row) => String(row.id)))].sort();
1427
+ return {
1428
+ sources: of("s"),
1429
+ readers: of("r"),
1430
+ lineage: rows.some((row) => row.kind === "l"),
1431
+ ...locks.length === 0 ? {} : { locked }
1432
+ };
1433
+ }
1434
+ /**
1435
+ * In `delete`'s transaction, before the session's rows go, given what {@link readForkPins} read. `keepRows` when forks
1436
+ * still read rows the session stores: the caller then removes only its sessions row, and the rows stay under a
1437
+ * tombstone. `released` are the sources the session's own segments named, to sweep once the transaction commits. A
1438
+ * session no fork history names costs no statement.
1439
+ */
1440
+ async function deleteForkedSessionWithin(host, tx, sessionId, deletedAt, pins) {
1441
+ if (pins.sources.length > 0) await tx.run(`DELETE FROM ${host.pinTables.forkSegments} WHERE session_id = ?`, sessionId);
1442
+ if (pins.lineage) await tx.run(`DELETE FROM ${host.pinTables.forkLineage} WHERE session_id = ?`, sessionId);
1443
+ if (pins.readers.length === 0) return {
1444
+ keepRows: false,
1445
+ released: pins.sources
1446
+ };
1447
+ await tx.run(`INSERT INTO ${host.pinTables.tombstones} (session_id, deleted_at) VALUES (?, ?) ON CONFLICT DO NOTHING`, sessionId, deletedAt);
1448
+ return {
1449
+ keepRows: true,
1450
+ released: pins.sources
1451
+ };
1452
+ }
1453
+ /**
1454
+ * In `replace`'s transaction, before the session's rows go, given what {@link readForkPins} read: each fork reading
1455
+ * them gets its own copy, and the session drops its own segments, as a replaced session holds every row of its view
1456
+ * itself. Resolves with the sources those segments named, to sweep once the transaction commits. A session no fork
1457
+ * history names costs no statement. Throws {@link ForkReadersMoved}, unless `lockLate`, when it lists a fork its first
1458
+ * read did not lock: locked now, after the session's row, a fork of that fork could wait for the replace while it
1459
+ * waits for the fork. `lockLate` locks it all the same, as a replace that ran again too often does.
1460
+ */
1461
+ async function replaceForkedSessionWithin(host, tx, sessionId, pins, lockLate = false) {
1462
+ const { locked } = pins;
1463
+ if (!lockLate && locked !== void 0 && pins.readers.some((reader) => !locked.has(reader))) throw new ForkReadersMoved();
1464
+ if (pins.sources.length > 0) await host.writeForkSegments(tx, sessionId, []);
1465
+ for (const child of pins.readers) await detachForkWithin(host, tx, sessionId, child, false);
1466
+ return pins.sources;
1467
+ }
1468
+ /**
1469
+ * In the transaction that writes a new session, by `create` or by a fork, before the session is written: when a
1470
+ * deleted session with this ID left a tombstone, the forks still reading its rows get their own copy, and the rows go.
1471
+ * Resolves with whether there was a tombstone.
1472
+ *
1473
+ * The tombstone is locked before the forks that read the rows, as every writer orders them: a fork locks the
1474
+ * tombstones among its sources before any session's row, so a fork that waits for this tombstone holds no row this
1475
+ * transaction locks next. Under the tombstone's lock no fork starts reading the rows, so the forks listed then are all
1476
+ * of them.
1477
+ */
1478
+ async function createOverTombstoneWithin(host, tx, sessionId) {
1479
+ if (!await isTombstoned(host, tx, sessionId)) return false;
1480
+ for (const child of await lockedReferrers(host, tx, sessionId)) await detachForkWithin(host, tx, sessionId, child, false);
1481
+ await removeStoredRows(host, tx, sessionId);
1482
+ return true;
1483
+ }
1069
1484
  /** Never load the clone writer in an ordinary open. Fence a lapsed transfer before deleting so a paused donor
1070
1485
  * cannot publish a partially swept transfer. When more rows remain, the new token stays expired. */
1071
1486
  async function tryCleanupForkStaging(database, dialect, table) {
@@ -1081,6 +1496,107 @@ async function tryCleanupForkStaging(database, dialect, table) {
1081
1496
  if ((await tx.run(`DELETE FROM ${table} WHERE transfer_id=? AND kind>${lease} AND (kind,seq,idx) IN (SELECT kind,seq,idx FROM ${table} WHERE transfer_id=? AND kind>${lease} LIMIT ?)`, id, id, 32)).changes < 32) await tx.run(`DELETE FROM ${table} WHERE transfer_id=? AND kind=${lease}`, id);
1082
1497
  });
1083
1498
  }
1499
+ // dist/core/storage/session/fork-view.js
1500
+ /** The largest view seq a range reads when it has no upper bound. */
1501
+ const FORK_VIEW_END = Number.MAX_SAFE_INTEGER;
1502
+ /**
1503
+ * The common table expression `name`: session `sessionId`'s rows of `table`, a table keyed by `(session_id, seq)` and
1504
+ * maybe more, whose view seqs are after `after` and at most `through`, with `columns` and `session_id`, `seq`, `src_id`
1505
+ * and `src_seq`. Bounding the range lets each source's index read only the rows asked for.
1506
+ */
1507
+ function forkView(tables, view) {
1508
+ const { name, table, sessionId, after, through, match } = view;
1509
+ const int = tables.dialect.types.int;
1510
+ const guard = tables.guard === void 0 ? "" : ` AND ${tables.guard}`;
1511
+ const matching = (alias) => match === void 0 ? "" : ` AND ${alias}${match.column} = ?`;
1512
+ const matched = match === void 0 ? [] : [match.value];
1513
+ const own = `SELECT session_id, seq${view.columns.map((column) => `, ${column}`).join("")}, session_id AS src_id, seq AS src_seq
1514
+ FROM ${table} WHERE session_id = ? AND seq > CAST(? AS ${int}) AND seq <= CAST(? AS ${int})${matching("")}${guard}`;
1515
+ if (tables.segments === void 0) return {
1516
+ cte: `${name} AS NOT MATERIALIZED (${own})`,
1517
+ params: [
1518
+ sessionId,
1519
+ after,
1520
+ through,
1521
+ ...matched
1522
+ ]
1523
+ };
1524
+ const { greatest, least } = tables.dialect;
1525
+ const rows = sourceRows(tables, table, view.columns, (x) => `${x}.seq >= ${greatest("f.from_seq", `CAST(? AS ${int}) + f.from_seq - f.base_seq`)}
1526
+ AND ${x}.seq <= ${least("f.to_seq", `CAST(? AS ${int}) + f.from_seq - f.base_seq - 1`)}${matching(`${x}.`)}`);
1527
+ return {
1528
+ cte: `${name} AS NOT MATERIALIZED (${`SELECT f.session_id AS session_id, f.base_seq + (x.seq - f.from_seq) + 1 AS seq${view.columns.map((column) => `, x.${column} AS ${column}`).join("")}, x.session_id AS src_id, x.seq AS src_seq
1529
+ FROM ${rows}
1530
+ WHERE f.session_id = ? AND f.base_seq < CAST(? AS ${int})
1531
+ AND f.base_seq + (f.to_seq - f.from_seq) + 1 > CAST(? AS ${int})${guard}`} UNION ALL ${own})`,
1532
+ params: [
1533
+ after,
1534
+ through,
1535
+ ...matched,
1536
+ sessionId,
1537
+ through,
1538
+ after,
1539
+ sessionId,
1540
+ after,
1541
+ through,
1542
+ ...matched
1543
+ ]
1544
+ };
1545
+ }
1546
+ /**
1547
+ * The segments `f` joined with the rows `x` of `table` each names that hold to `condition`, of the rows' alias and
1548
+ * `f`. On PostgreSQL the rows are read per segment through the table's index, as a lateral subquery
1549
+ * behind `OFFSET 0`, rather than by a hash join that would read the whole table; SQLite joins them that way itself.
1550
+ */
1551
+ function sourceRows(tables, table, columns, condition) {
1552
+ if (tables.dialect.name !== "postgres") return `${tables.segments} f JOIN ${table} x ON x.session_id = f.source_id AND ${condition("x")}`;
1553
+ return `${tables.segments} f CROSS JOIN LATERAL (SELECT r.session_id, r.seq${columns.map((column) => `, r.${column}`).join("")}
1554
+ FROM ${table} r WHERE r.session_id = f.source_id AND ${condition("r")} OFFSET 0) x`;
1555
+ }
1556
+ /**
1557
+ * The rows of `table` through the view of the session that `session`, an SQL expression such as a column of an outer
1558
+ * query, names: a derived table with `columns`, `session_id` and `seq`, and no parameters, for a statement that reads
1559
+ * the rows of many sessions, each in a subquery of its own. Each half of the union looks the session up by its key
1560
+ * itself, so neither reads the rows of every session to find one's.
1561
+ */
1562
+ function forkViewOf(tables, view, session) {
1563
+ const { table } = view;
1564
+ const guard = tables.guard === void 0 ? "" : ` AND ${tables.guard}`;
1565
+ const own = `SELECT session_id, seq${view.columns.map((column) => `, ${column}`).join("")} FROM ${table} WHERE session_id = ${session}${guard}`;
1566
+ if (tables.segments === void 0) return `(${own})`;
1567
+ return `(SELECT f.session_id AS session_id, f.base_seq + (x.seq - f.from_seq) + 1 AS seq${view.columns.map((column) => `, x.${column} AS ${column}`).join("")}
1568
+ FROM ${sourceRows(tables, table, view.columns, (x) => `${x}.seq >= f.from_seq AND ${x}.seq <= f.to_seq`)}
1569
+ WHERE f.session_id = ${session}${guard}
1570
+ UNION ALL ${own})`;
1571
+ }
1572
+ /** `sql`, a statement that may begin with `WITH`, with `views` first in its `WITH`. */
1573
+ function withForkViews(views, sql) {
1574
+ if (views.length === 0) return sql;
1575
+ const ctes = views.map((view) => view.cte).join(", ");
1576
+ const body = sql.trimStart();
1577
+ return /^WITH\s/i.test(body) ? `WITH ${ctes}, ${body.slice(4).trimStart()}` : `WITH ${ctes} ${body}`;
1578
+ }
1579
+ /** The parameters of `views`, in order, for the start of the statement's parameters. */
1580
+ function forkViewParams(views) {
1581
+ return views.flatMap((view) => view.params);
1582
+ }
1583
+ // dist/core/storage/session/session-transactions.js
1584
+ /**
1585
+ * A write to the rows of the session `sessionId` of the sessions table `sessions`: on Postgres it is the only writer of
1586
+ * that session, while writers of other sessions run beside it; SQLite runs every write alone anyway. Every writer of a
1587
+ * session's rows names this one domain, whatever table it writes (the session store, its chat records, its search
1588
+ * index), so the checks each makes against the session's row hold until it commits. A transient failure runs it again
1589
+ * (#4383).
1590
+ */
1591
+ function sessionWriteTransaction(sessions, sessionId) {
1592
+ return {
1593
+ retryTransientFailures: true,
1594
+ concurrency: {
1595
+ kind: "serial",
1596
+ domain: `${sessions}:${sessionId}`
1597
+ }
1598
+ };
1599
+ }
1084
1600
  // dist/core/storage/session/sql-chat-records.js
1085
1601
  /** Rows one read fetches at most. */
1086
1602
  const READ_PAGE_ROWS = 64;
@@ -1176,9 +1692,9 @@ function sqlChatRecords(database, sessions, table, index, ledger) {
1176
1692
  row_number() OVER (ORDER BY position) AS page_row,
1177
1693
  sum(${bytes("anchor")}+${bytes("data")}) OVER (ORDER BY position) AS page_bytes
1178
1694
  FROM (SELECT position,anchor,data FROM ${table}
1179
- WHERE session_id=? AND epoch=? AND position>? AND anchor IN (${anchors.map(() => "?").join(",")})
1695
+ WHERE session_id=? AND epoch=? AND position>? AND ${inJsonList(dialect, "anchor")}
1180
1696
  ORDER BY position LIMIT ${READ_PAGE_ROWS}) AS candidates
1181
- ) AS page WHERE page_row=1 OR page_bytes<=? ORDER BY position`, owner.id, owner.epoch, after, ...anchors.map(lineKey), CHAT_READ_PAGE_BYTES);
1697
+ ) AS page WHERE page_row=1 OR page_bytes<=? ORDER BY position`, owner.id, owner.epoch, after, JSON.stringify(anchors.map(lineKey)), CHAT_READ_PAGE_BYTES);
1182
1698
  for (const { anchor, data } of rows) {
1183
1699
  const record = decodeChatRecord(data);
1184
1700
  if (record) result.push({
@@ -1195,7 +1711,7 @@ function sqlChatRecords(database, sessions, table, index, ledger) {
1195
1711
  const orders = [];
1196
1712
  for (let i = 0; i < promptIds.length; i += ORDER_BATCH) {
1197
1713
  const keys = promptIds.slice(i, i + ORDER_BATCH).map(orderKey);
1198
- const rows = await database.all(`SELECT data FROM ${table} WHERE session_id=? AND epoch=? AND anchor IN (${keys.map(() => "?").join(",")}) ORDER BY position`, owner.id, owner.epoch, ...keys);
1714
+ const rows = await database.all(`SELECT data FROM ${table} WHERE session_id=? AND epoch=? AND ${inJsonList(dialect, "anchor")} ORDER BY position`, owner.id, owner.epoch, JSON.stringify(keys));
1199
1715
  for (const { data } of rows) {
1200
1716
  const order = decodeChatOrder(data);
1201
1717
  if (order) orders.push(order);
@@ -1207,14 +1723,32 @@ function sqlChatRecords(database, sessions, table, index, ledger) {
1207
1723
  }
1208
1724
  // dist/core/storage/session/sql-session-store.js
1209
1725
  /**
1726
+ * `sessionEntryLinks` of `blob-store.ts`, which the copy a process of an earlier release loaded lacks. Such a process
1727
+ * keeps that copy after an in-place update, and can load this module from the update: a named import would fail to link
1728
+ * there. Without it, a materialization leaves the links the index's triggers wrote until the index is rebuilt (#6560).
1729
+ */
1730
+ const entryLinkers = blobStore;
1731
+ /**
1210
1732
  * The newest sessions schema this build reads and writes. Version 2 stores long entries in chunks (#4954), which a build
1211
1733
  * that knows only version 1 would read as stubs. A database stays at version 1, which older builds still open, until
1212
1734
  * this build writes its first chunked entry: that transaction moves the sessions meta to 2, and older builds refuse it
1213
1735
  * when next opened with `StorageSchemaVersionError`. Builds before 2 check only the meta row, on SQLite and Postgres alike.
1736
+ * Version 3 turns on forks that share their parent's history ({@link SESSION_SCHEMA_VERSION_SHARED_HISTORY}).
1214
1737
  */
1215
- const SESSION_SCHEMA_VERSION = 2;
1738
+ const SESSION_SCHEMA_VERSION = 3;
1216
1739
  /** The sessions schema of a database without chunked entries, which older builds read too. */
1217
1740
  const SESSION_SCHEMA_VERSION_UNCHUNKED = 1;
1741
+ /** The sessions schema the first chunked entry raises a version 1 database to, which builds since #4954 read. */
1742
+ const SESSION_SCHEMA_VERSION_CHUNKED = 2;
1743
+ /**
1744
+ * The sessions schema in which a fork shares its parent's history instead of copying it (#6560). A new database's
1745
+ * sessions schema starts at it; a store's open, or `atomic storage migrate`, raises an older one to it by itself once
1746
+ * no session of an older build runs there (`SqlSessionStore.enableSharedHistoryForks`); a fork or any other write never
1747
+ * does. Builds that know only versions 1
1748
+ * and 2 refuse it, at their open and in every transaction, rather than read a fork's own rows as its whole history.
1749
+ * `SqlSessionStore.sharedHistoryForks(tx)` tells a transaction whether its database is there.
1750
+ */
1751
+ const SESSION_SCHEMA_VERSION_SHARED_HISTORY = 3;
1218
1752
  /** The schema domain of the session tables in the prefix's migration ledger. */
1219
1753
  const SESSION_DOMAIN = "sessions";
1220
1754
  /** The ledger step, `schema:session-fillfactor`, that sets the sessions table's fillfactor on PostgreSQL (#6560). */
@@ -1222,6 +1756,19 @@ const SESSION_FILLFACTOR_DOMAIN = "session-fillfactor";
1222
1756
  /** The fillfactor of the sessions table on PostgreSQL: a fifth of each page stays free for head row updates. */
1223
1757
  const SESSION_ROW_FILLFACTOR = 80;
1224
1758
  /**
1759
+ * The ledger step, `schema:session-append-function`, that creates the session append function on PostgreSQL (#6599).
1760
+ * Raise its revision whenever the function's body changes: `atomic storage migrate` of an older build then leaves the
1761
+ * newer body in place.
1762
+ */
1763
+ const SESSION_APPEND_FUNCTION_DOMAIN = "session-append-function";
1764
+ const SESSION_APPEND_FUNCTION_REVISION = 1;
1765
+ /**
1766
+ * The session append function's name under the store's prefix. The version in the name is the function's contract:
1767
+ * its arguments and what it answers. A build that needs another contract creates a function of a new name beside
1768
+ * this one, which builds that call this one keep using.
1769
+ */
1770
+ const SESSION_APPEND_FUNCTION = "append_v1";
1771
+ /**
1225
1772
  * The most bytes of a chunked session blob one row holds. New blobs use a header row and rows of at most this size,
1226
1773
  * so their bound and returned values stay within it: libSQL servers cap a row and a bound value (sqld's default is
1227
1774
  * 5 MB) and a statement's response (10 MB), and the HTTP protocol carries a blob as base64 in JSON, about 1.4 MB for
@@ -1268,6 +1815,31 @@ const SESSION_FORK_STAGING_TABLES = Object.freeze({ forkStaging: "fork_staging"
1268
1815
  /** The schema domain, in the prefix's migration ledger, of the table of open sessions (#4971). */
1269
1816
  const SESSION_PRESENCE_DOMAIN = "session-presence";
1270
1817
  const SESSION_PRESENCE_TABLES = Object.freeze({ open: "open" });
1818
+ /** The donor's segments name a session the fork did not lock: the fork runs again, locking it too (#6560). */
1819
+ var ForkSourcesMoved = class extends Error {
1820
+ constructor() {
1821
+ super("The fork's source moved its history while the fork read it");
1822
+ }
1823
+ };
1824
+ /**
1825
+ * A fork into the ID of a deleted session forks still read, whose reads did not lock that session's tombstone and the
1826
+ * forks reading it before the donor's row: the fork runs again with reads that do (#6560).
1827
+ */
1828
+ var ForkChildTombstoned = class extends Error {
1829
+ constructor() {
1830
+ super("The fork's child has the ID of a deleted session forks still read");
1831
+ }
1832
+ };
1833
+ /** The leading statements of a fork's transaction: its reads of {@link SharedForkReads}, in the order it makes them. */
1834
+ function sharedForkLeading(reads) {
1835
+ return [
1836
+ reads.exists,
1837
+ ...reads.childTombstone === void 0 ? [] : [reads.childTombstone],
1838
+ reads.tombstones,
1839
+ reads.lock,
1840
+ reads.segments
1841
+ ];
1842
+ }
1271
1843
  function windowIndex(state, seq) {
1272
1844
  return isSessionResumeIndex(state.windowResume, seq) ? state.windowResume : isSessionResumeIndex(state.resume, seq) ? state.resume : void 0;
1273
1845
  }
@@ -1295,6 +1867,11 @@ const SESSION_READ_FETCH = {
1295
1867
  min: 1,
1296
1868
  max: 8192
1297
1869
  };
1870
+ /**
1871
+ * The seqs of a shared history one page of a selective scan reads at most (#6560): the page then accounts for the range
1872
+ * through them, and the next page reads the next ones.
1873
+ */
1874
+ const SCAN_SELECT_WINDOW = 4096;
1298
1875
  const SESSION_READ_INLINE_BYTES = 4096;
1299
1876
  function nextFetch(limit, rows) {
1300
1877
  const kept = rows.length;
@@ -1470,9 +2047,11 @@ async function entryByteLengthOf(database) {
1470
2047
  }
1471
2048
  /**
1472
2049
  * The most bytes of statements a session write sends as one batch: an ordinary message's are far fewer. A larger
1473
- * write, an import or a fork's whole window, runs its statements one at a time as they are made.
2050
+ * write, an import or a fork's whole window, sends its statements a request's worth at a time as they are made.
1474
2051
  */
1475
2052
  const STATEMENT_BATCH_BYTES = 1048576;
2053
+ /** The most sessions whose last written row a store remembers for appends through the append function. */
2054
+ const WRITTEN_ROWS = 64;
1476
2055
  /** About how many bytes `statement` carries: its text and its parameters. */
1477
2056
  function statementBytes(statement) {
1478
2057
  let bytes = statement.sql.length;
@@ -1481,6 +2060,80 @@ function statementBytes(statement) {
1481
2060
  else bytes += 8;
1482
2061
  return bytes;
1483
2062
  }
2063
+ const ENTRY_COLUMNS = [
2064
+ "session_id",
2065
+ "seq",
2066
+ "entry_id",
2067
+ "entry_json",
2068
+ "chunks"
2069
+ ];
2070
+ const TEXT_COLUMNS = [
2071
+ "session_id",
2072
+ "seq",
2073
+ "text_json"
2074
+ ];
2075
+ /** The most rows one insert of {@link RowInserts} names: 320 parameters for an entry's five, below SQLite's old 999. */
2076
+ const ROWS_PER_INSERT = 64;
2077
+ /** The most bytes of values one insert of {@link RowInserts} takes, unless one row's alone are more. */
2078
+ const ROW_INSERT_BYTES = 262144;
2079
+ /**
2080
+ * Rows of `table` inserted several to a statement (#6560): one statement's SQL prepared, and its triggers compiled, for
2081
+ * up to {@link ROWS_PER_INSERT} rows, not for each, so an append of a burst prepares once on a server that keeps no
2082
+ * prepared statements. The rows go in in the order they are added, each as its own insert would, the triggers firing
2083
+ * for each in turn: the triggers read only what the triggers of the rows before wrote, not the rows themselves.
2084
+ */
2085
+ var RowInserts = class {
2086
+ table;
2087
+ columns;
2088
+ sqls = [];
2089
+ rows = [];
2090
+ bytes = 0;
2091
+ constructor(table, columns) {
2092
+ this.table = table;
2093
+ this.columns = columns;
2094
+ }
2095
+ /** The insert of `count` rows. */
2096
+ sql(count) {
2097
+ let sql = this.sqls[count];
2098
+ if (sql === void 0) {
2099
+ const row = `(${this.columns.map(() => "?").join(", ")})`;
2100
+ sql = `INSERT INTO ${this.table} (${this.columns.join(", ")}) VALUES ${Array(count).fill(row).join(", ")}`;
2101
+ this.sqls[count] = sql;
2102
+ }
2103
+ return sql;
2104
+ }
2105
+ /** Adds `row`, and yields the inserts of the rows before it once they are as many, or as large, as one takes. */
2106
+ *add(row) {
2107
+ const bytes = statementBytes({
2108
+ sql: "",
2109
+ params: row
2110
+ });
2111
+ if (this.rows.length === ROWS_PER_INSERT || this.rows.length > 0 && this.bytes + bytes > ROW_INSERT_BYTES) yield* this.drain();
2112
+ this.rows.push(row);
2113
+ this.bytes += bytes;
2114
+ }
2115
+ /** The inserts of the rows added and not yet yielded. */
2116
+ *drain() {
2117
+ const rows = this.rows;
2118
+ if (rows.length === 0) return;
2119
+ this.rows = [];
2120
+ this.bytes = 0;
2121
+ yield {
2122
+ sql: this.sql(rows.length),
2123
+ params: rows.flat()
2124
+ };
2125
+ }
2126
+ };
2127
+ /** What `first` yields, then `last`. */
2128
+ function* thenAll(first, last) {
2129
+ yield* first;
2130
+ yield* last;
2131
+ }
2132
+ /** `first`, then what is left of `rest`. */
2133
+ function* withRest(first, rest) {
2134
+ yield* first;
2135
+ for (let next = rest.next(); next.done !== true; next = rest.next()) yield next.value;
2136
+ }
1484
2137
  /**
1485
2138
  * Writes of one transaction sent without waiting for each answer: the connection runs them in the order they were
1486
2139
  * sent, behind the transaction's earlier calls and ahead of its later ones, so a read made after `send` sees them. On a
@@ -1543,14 +2196,29 @@ var SqlSessionStore = class SqlSessionStore {
1543
2196
  chatStore;
1544
2197
  /** The database's reader handle, once a read opened it: see `readerDatabase`. */
1545
2198
  reader;
2199
+ /** Each session's writes this store started and has not finished, each settled as its write is: see `writing`. */
2200
+ unfinishedWrites = /* @__PURE__ */ new Map();
2201
+ /** The sessions schema version each transaction read first, by its handle: see `sharedHistoryForks`. */
2202
+ schemaVersions = /* @__PURE__ */ new WeakMap();
2203
+ /** The fork tables under this store's prefix, which exist once its sessions schema is version 3 (#6560). */
2204
+ forkTables;
2205
+ /** See {@link forkLinks}. */
2206
+ forkLinkStatements;
2207
+ /** See {@link entryLinks}. */
2208
+ entryLinkStatements;
1546
2209
  /**
1547
- * Absent on a local libSQL file, which then behaves as before: @libsql/client waits for another process's write
1548
- * lock on the calling thread, even to begin a transaction, so a side write would stop the event loop where an
1549
- * ordinary turn-ending notice writes nothing (#5682).
2210
+ * Whether a read of this store found its sessions schema at {@link SESSION_SCHEMA_VERSION_SHARED_HISTORY}: one way,
2211
+ * as the switch is. A read outside a transaction reads sessions through their views once it is set, and before that
2212
+ * reads the tables themselves on the condition, checked in the read's own snapshot, that the schema is older.
1550
2213
  */
2214
+ sharedHistorySeen = false;
2215
+ /** For each transaction, whether each session whose row it read has fork segments, as that read found (#6560). */
2216
+ forkedIn = /* @__PURE__ */ new WeakMap();
2217
+ /** Whether each recently read session had fork segments: only a first guess, which a read checks (#6560). */
2218
+ forkedSessions = /* @__PURE__ */ new Map();
2219
+ /** The sessions each recently forked session's segments named when this store last read them (#6560). */
2220
+ forkSources = /* @__PURE__ */ new Map();
1551
2221
  get chatRecords() {
1552
- const { adapter, location } = this.database.descriptor;
1553
- if (adapter === "libsql" && /^file:/i.test(location)) return void 0;
1554
2222
  if (!this.chatStore) {
1555
2223
  const names = renderStorageIdentifiers("sessions", {
1556
2224
  rows: "chat_v1",
@@ -1575,8 +2243,16 @@ var SqlSessionStore = class SqlSessionStore {
1575
2243
  forkStagingTable;
1576
2244
  /** The generation each recently read session's row held at a revision: see `generation`. */
1577
2245
  generations = /* @__PURE__ */ new Map();
1578
- constructor(database, tables, prefix, cwdMatcher, snapshotBlobs, legacyBlobData, searchIndex, entryByteLength) {
2246
+ /**
2247
+ * The session append function of this store's tables, when the open found it and this role may run it (#6599):
2248
+ * `atomic storage migrate` creates it. Absent elsewhere, where appends take their two round trips as before.
2249
+ */
2250
+ appendFunction;
2251
+ /** The row each recent write of this store left for its session, which an append through the function plans from. */
2252
+ writtenRows = /* @__PURE__ */ new Map();
2253
+ constructor(database, tables, prefix, cwdMatcher, snapshotBlobs, legacyBlobData, searchIndex, entryByteLength, appendFunction) {
1579
2254
  this.database = database;
2255
+ if (appendFunction !== void 0) this.appendFunction = appendFunction;
1580
2256
  this.dialect = dialectOf(database);
1581
2257
  this.entryByteLength = entryByteLength;
1582
2258
  this.tables = tables;
@@ -1598,12 +2274,13 @@ var SqlSessionStore = class SqlSessionStore {
1598
2274
  registerHistorySnapshot(this, (sessionId, project) => {
1599
2275
  this.assertOpen();
1600
2276
  validateSessionText("sessionId", sessionId);
1601
- return this.readTransaction(async (tx) => {
2277
+ return this.readTransaction(sessionId, async (tx) => {
1602
2278
  const head = await this.historyHead(tx, sessionId, true);
1603
2279
  return project(head.epoch, head.lastSeq, (from, through, backward) => this.historyPacket(tx, sessionId, head.epoch, from, through, backward));
1604
2280
  });
1605
2281
  });
1606
2282
  this.forkStagingTable = renderStorageIdentifiers("sessions", SESSION_FORK_STAGING_TABLES, prefix).forkStaging;
2283
+ this.forkTables = sessionForkTables(prefix);
1607
2284
  }
1608
2285
  /** Bind an existing transcript for the storage search command. No schema setup, markers or search index. */
1609
2286
  static async openTranscriptReader(database) {
@@ -1619,6 +2296,8 @@ var SqlSessionStore = class SqlSessionStore {
1619
2296
  static async openWithCatalog(database, options) {
1620
2297
  const tables = renderStorageIdentifiers("sessions", SESSION_TABLES, options.prefix);
1621
2298
  let legacyBlobData = false;
2299
+ const forkTables = sessionForkTables(options.prefix);
2300
+ let createdShared = false;
1622
2301
  const createTables = async (tx, dialect) => {
1623
2302
  const { int, text, blob } = dialect.types;
1624
2303
  const strict = dialect.tableOptions;
@@ -1628,7 +2307,7 @@ var SqlSessionStore = class SqlSessionStore {
1628
2307
  return async () => await tx.get(probe.sql, ...probe.params) !== void 0;
1629
2308
  };
1630
2309
  const [versions] = await statementBatch(tx, [`CREATE TABLE IF NOT EXISTS ${tables.meta} (schema_version ${int} NOT NULL)${strict}`], [() => tx.all(`SELECT schema_version FROM ${tables.meta}`)]);
1631
- for (const version of versions) assertStorageSchemaVersion("sessions", version.schema_version, 2, SESSION_SCHEMA_VERSION_UNCHUNKED);
2310
+ for (const version of versions) assertStorageSchemaVersion("sessions", version.schema_version, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
1632
2311
  const tablesScript = `
1633
2312
  CREATE TABLE IF NOT EXISTS ${tables.sessions} (
1634
2313
  id ${text} PRIMARY KEY, cwd ${text} NOT NULL, created_at ${text} NOT NULL,
@@ -1656,10 +2335,19 @@ var SqlSessionStore = class SqlSessionStore {
1656
2335
  PRIMARY KEY(session_id, hash, idx)
1657
2336
  )${strict};
1658
2337
  `;
1659
- const [revision, data] = await statementBatch(tx, [versions.length === 0 && {
1660
- sql: `INSERT INTO ${tables.meta} VALUES (?)`,
1661
- params: [SESSION_SCHEMA_VERSION_UNCHUNKED]
1662
- }, tablesScript], [columnExists(tables.sessions, "revision"), columnExists(tables.blobs, "data")]);
2338
+ const created = versions.length === 0;
2339
+ const [revision, data] = await statementBatch(tx, [
2340
+ created && {
2341
+ sql: `INSERT INTO ${tables.meta} VALUES (?)`,
2342
+ params: [3]
2343
+ },
2344
+ created ? `${tablesScript}\n${sharedHistoryTablesScript(dialect, forkTables)}` : tablesScript,
2345
+ created && dialect.versionedMigrations && {
2346
+ sql: `INSERT INTO ${storageMigrationTable(options.prefix)} (domain, version, applied_at) VALUES (?, ?, ${dialect.nowMs}) ON CONFLICT DO NOTHING`,
2347
+ params: ["sessions", 3]
2348
+ }
2349
+ ], [columnExists(tables.sessions, "revision"), columnExists(tables.blobs, "data")]);
2350
+ createdShared = created;
1663
2351
  legacyBlobData = data;
1664
2352
  const [chunks] = legacyBlobData ? await statementBatch(tx, [], [columnExists(tables.blobs, "chunks")]) : [true];
1665
2353
  await statementBatch(tx, [!revision && `ALTER TABLE ${tables.sessions} ADD COLUMN revision ${text} NOT NULL DEFAULT ''`, !chunks && `ALTER TABLE ${tables.blobs} ADD COLUMN chunks ${int} NOT NULL DEFAULT -1`], []);
@@ -1693,38 +2381,57 @@ var SqlSessionStore = class SqlSessionStore {
1693
2381
  };
1694
2382
  const presence = renderStorageIdentifiers("sessions", SESSION_PRESENCE_TABLES, options.prefix);
1695
2383
  const current = await SqlSessionStore.currentSchema(database, tables, presence.open, database.readOnly === true ? void 0 : orphanedEntryKeys);
2384
+ let sharedHistory;
1696
2385
  if (current !== void 0) {
1697
2386
  legacyBlobData = current.legacyBlobData;
2387
+ sharedHistory = current.sharedHistory;
1698
2388
  if (current.orphaned) await database.transaction(async (tx) => {
1699
- await assertStoredSchemaVersion(tx, { sql: `SELECT schema_version FROM ${tables.meta}` }, "sessions", 2, "schema_version", SESSION_SCHEMA_VERSION_UNCHUNKED);
2389
+ await assertStoredSchemaVersion(tx, { sql: `SELECT schema_version FROM ${tables.meta}` }, "sessions", 3, "schema_version", SESSION_SCHEMA_VERSION_UNCHUNKED);
1700
2390
  await tx.run(removeOrphanedEntryChunks.sql);
1701
2391
  }).catch((error) => {
1702
2392
  if (error instanceof StorageSchemaVersionError) throw error;
1703
2393
  });
1704
- } else await applyStorageMigrationsTogether(database, [{
1705
- domain: SESSION_DOMAIN,
1706
- steps: [{
1707
- version: 1,
1708
- up: createTables
1709
- }, {
1710
- version: 2,
1711
- up: addEntryChunks
1712
- }],
1713
- options: { table: storageMigrationTable(options.prefix) }
1714
- }, {
1715
- domain: SESSION_PRESENCE_DOMAIN,
1716
- steps: [{
1717
- version: 1,
1718
- up: (tx, dialect) => SqlSessionOpenMarkers.createTable(tx, dialect, presence.open)
2394
+ } else {
2395
+ const [sessionsSchema] = await applyStorageMigrationsTogether(database, [{
2396
+ domain: SESSION_DOMAIN,
2397
+ steps: [{
2398
+ version: 1,
2399
+ up: createTables
2400
+ }, {
2401
+ version: 2,
2402
+ up: addEntryChunks
2403
+ }],
2404
+ options: {
2405
+ table: storageMigrationTable(options.prefix),
2406
+ acceptNewer: true
2407
+ }
1719
2408
  }, {
1720
- version: 2,
1721
- up: (tx, dialect) => SqlSessionOpenMarkers.addSchemaVersion(tx, dialect, presence.open)
1722
- }],
1723
- options: {
1724
- table: storageMigrationTable(options.prefix),
1725
- acceptNewer: true
1726
- }
1727
- }]);
2409
+ domain: SESSION_PRESENCE_DOMAIN,
2410
+ steps: [
2411
+ {
2412
+ version: 1,
2413
+ up: (tx, dialect) => SqlSessionOpenMarkers.createTable(tx, dialect, presence.open)
2414
+ },
2415
+ {
2416
+ version: 2,
2417
+ up: (tx, dialect) => SqlSessionOpenMarkers.addSchemaVersion(tx, dialect, presence.open)
2418
+ },
2419
+ {
2420
+ version: 3,
2421
+ up: (tx, dialect) => SqlSessionOpenMarkers.addBuild(tx, dialect, presence.open)
2422
+ }
2423
+ ],
2424
+ options: {
2425
+ table: storageMigrationTable(options.prefix),
2426
+ acceptNewer: true
2427
+ }
2428
+ }]);
2429
+ if ((sessionsSchema?.version ?? 0) > 3) throw new StorageSchemaVersionError(SESSION_DOMAIN, sessionsSchema.version, 3);
2430
+ if (createdShared) {
2431
+ sharedHistory = true;
2432
+ noteStorageSchemaTables(database, Object.values(forkTables));
2433
+ } else if (dialectOf(database).versionedMigrations) sharedHistory = (sessionsSchema?.version ?? 0) >= 3;
2434
+ }
1728
2435
  await ensureTableFillfactor(database, {
1729
2436
  ledger: storageMigrationTable(options.prefix),
1730
2437
  domain: SESSION_FILLFACTOR_DOMAIN,
@@ -1732,6 +2439,13 @@ var SqlSessionStore = class SqlSessionStore {
1732
2439
  table: tables.sessions,
1733
2440
  fillfactor: SESSION_ROW_FILLFACTOR
1734
2441
  });
2442
+ const markers = new SqlSessionOpenMarkers(database, presence.open, () => store.assertOpen());
2443
+ let shared = sharedHistory === true;
2444
+ if (sharedHistory !== true && database.readOnly !== true) {
2445
+ const switched = await SqlSessionStore.switchAtOpen(database, options.prefix ?? "", tables, markers, sharedHistory === false);
2446
+ if (switched) refreshStorageSchemaCatalog(database);
2447
+ shared = switched;
2448
+ }
1735
2449
  const staging = renderStorageIdentifiers("sessions", SESSION_FORK_STAGING_TABLES, options.prefix).forkStaging;
1736
2450
  const stagingProbe = dialectOf(database).tableExists(staging);
1737
2451
  const catalog = await schemaCatalogOf(database);
@@ -1742,8 +2456,12 @@ var SqlSessionStore = class SqlSessionStore {
1742
2456
  SqlSessionSearchIndex.open(database, tables, options.prefix),
1743
2457
  entryByteLengthOf(database)
1744
2458
  ]);
1745
- const store = new SqlSessionStore(database, tables, options.prefix, options.cwdMatcher, blobs, legacyBlobData, searchIndex, entryByteLength);
1746
- store.openMarkers = new SqlSessionOpenMarkers(database, presence.open, () => store.assertOpen());
2459
+ if (shared) await ensureForkInheritedBlobGuard(database, snapshotIndexTables$1(options.prefix), forkTables.forkSegments, storageMigrationTable(options.prefix));
2460
+ const appendFunction = renderStorageIdentifiers("sessions", { append: SESSION_APPEND_FUNCTION }, options.prefix).append;
2461
+ const appendsThroughFunction = catalog?.hasFunction?.(appendFunction) === true && database.autocommit !== void 0 && typeof blobs.storedBlobsQuery === "function";
2462
+ const store = new SqlSessionStore(database, tables, options.prefix, options.cwdMatcher, blobs, legacyBlobData, searchIndex, entryByteLength, appendsThroughFunction ? appendFunction : void 0);
2463
+ store.openMarkers = markers;
2464
+ if (shared) store.noteSchemaVersion(3);
1747
2465
  if (await staged) await store.cleanupForkStaging();
1748
2466
  return store;
1749
2467
  }
@@ -1772,7 +2490,8 @@ var SqlSessionStore = class SqlSessionStore {
1772
2490
  [tables.sessions, "revision"],
1773
2491
  [tables.entries, "chunks"],
1774
2492
  [tables.blobs, "chunks"],
1775
- [open, "schema_version"]
2493
+ [open, "schema_version"],
2494
+ [open, "build"]
1776
2495
  ];
1777
2496
  const reading = schemaCatalogOf(database);
1778
2497
  const orphaned = orphans === void 0 ? void 0 : database.get(`SELECT 1 FROM (${orphans}) AS orphaned LIMIT 1`);
@@ -1792,10 +2511,11 @@ var SqlSessionStore = class SqlSessionStore {
1792
2511
  legacyBlobs = legacyFound !== void 0;
1793
2512
  }
1794
2513
  const versions = await versionsRead;
1795
- if (versions.length === 0 || versions.some((row) => row.schema_version !== SESSION_SCHEMA_VERSION_UNCHUNKED && row.schema_version !== 2)) return void 0;
2514
+ if (versions.length === 0 || versions.some((row) => typeof row.schema_version !== "number" || !Number.isInteger(row.schema_version) || row.schema_version < SESSION_SCHEMA_VERSION_UNCHUNKED || row.schema_version > 3)) return void 0;
1796
2515
  return {
1797
2516
  legacyBlobData: legacyBlobs,
1798
- orphaned: await orphaned !== void 0
2517
+ orphaned: await orphaned !== void 0,
2518
+ sharedHistory: versions.every((row) => Number(row.schema_version) >= 3)
1799
2519
  };
1800
2520
  }
1801
2521
  /**
@@ -1830,10 +2550,15 @@ var SqlSessionStore = class SqlSessionStore {
1830
2550
  };
1831
2551
  }
1832
2552
  /**
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.
2553
+ * `transaction` for a body that only reads session `sessionId`, in one read-only snapshot, on the database's reader
2554
+ * handle when it offers one: its reads then wait for neither the writes queued on this store's connection nor their
2555
+ * locks. It first waits for the writes of that session this store started and has not finished (`writing`), so a
2556
+ * caller that starts a write and then reads, without awaiting the write, reads it as the store's own connection would
2557
+ * have; with none unfinished it waits for nothing.
1835
2558
  */
1836
- async readTransaction(body, leading = []) {
2559
+ async readTransaction(sessionId, body, leading = []) {
2560
+ const unfinished = this.unfinishedWrites.get(sessionId);
2561
+ if (unfinished !== void 0) await Promise.all(unfinished);
1837
2562
  return (await this.readerDatabase()).transaction(async (tx) => {
1838
2563
  await this.assertReadableSchema(tx);
1839
2564
  return body(tx);
@@ -1843,6 +2568,22 @@ var SqlSessionStore = class SqlSessionStore {
1843
2568
  }));
1844
2569
  }
1845
2570
  /**
2571
+ * `write`, a write of session `sessionId` this store has just started, kept in `unfinishedWrites` until it settles,
2572
+ * for the reads of the session that start meanwhile to wait for (`readTransaction`). No write waits for a read, and
2573
+ * no write of this store reads through `readTransaction`, so the wait never comes back to the write.
2574
+ */
2575
+ writing(sessionId, write) {
2576
+ const writes = this.unfinishedWrites.get(sessionId) ?? /* @__PURE__ */ new Set();
2577
+ this.unfinishedWrites.set(sessionId, writes);
2578
+ const settled = write.then(() => {}, () => {});
2579
+ writes.add(settled);
2580
+ settled.then(() => {
2581
+ writes.delete(settled);
2582
+ if (writes.size === 0 && this.unfinishedWrites.get(sessionId) === writes) this.unfinishedWrites.delete(sessionId);
2583
+ });
2584
+ return write;
2585
+ }
2586
+ /**
1846
2587
  * The database's reader handle, opened at the first read and closed with the store; the database without one. A
1847
2588
  * reader that cannot open, such as when its file can no longer be opened anew, leaves the read on the store's own
1848
2589
  * connection, as every read ran before readers, and the next read tries to open one again.
@@ -1883,8 +2624,216 @@ var SqlSessionStore = class SqlSessionStore {
1883
2624
  params: []
1884
2625
  };
1885
2626
  }
2627
+ /**
2628
+ * Reads the sessions schema version through `executor` and refuses one this build does not read. The answer is kept
2629
+ * for `executor`, a transaction's own handle, so {@link sharedHistoryForks} costs that transaction no read.
2630
+ */
1886
2631
  assertReadableSchema(executor) {
1887
- return assertStoredSchemaVersion(executor, this.schemaCheck(), "sessions", 2, "schema_version", SESSION_SCHEMA_VERSION_UNCHUNKED);
2632
+ const check = this.schemaCheck();
2633
+ const version = executor.get(check.sql, ...check.params).then((row) => {
2634
+ const found = row?.schema_version ?? null;
2635
+ assertStorageSchemaVersion("sessions", found, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
2636
+ this.noteSchemaVersion(found);
2637
+ return found;
2638
+ });
2639
+ this.schemaVersions.set(executor, version);
2640
+ return version.then(() => {});
2641
+ }
2642
+ /**
2643
+ * Whether the database `tx` runs in has forks that share their parent's history turned on: its sessions schema, as
2644
+ * `tx` read it, is {@link SESSION_SCHEMA_VERSION_SHARED_HISTORY} (#6560). Every transaction of this store reads the
2645
+ * version first, so this costs no further read there; `tx` of any other transaction reads it once. Asked again in each
2646
+ * transaction, never kept on the store: another process may turn the forks on at any time, and the switch is one way,
2647
+ * so an answer read before it only means a fork is copied.
2648
+ */
2649
+ async sharedHistoryForks(tx) {
2650
+ if (!this.schemaVersions.has(tx)) await this.assertReadableSchema(tx);
2651
+ return await this.schemaVersions.get(tx) >= 3;
2652
+ }
2653
+ /** Notes a sessions schema version a read of this store found: see {@link sharedHistorySeen}. */
2654
+ noteSchemaVersion(version) {
2655
+ if (typeof version === "number" && version >= 3) this.sharedHistorySeen = true;
2656
+ }
2657
+ /** How transaction `tx` reads a session's rows: through its view where its database has shared history (#6560). */
2658
+ async viewTables(tx, sessionId) {
2659
+ return {
2660
+ segments: !(sessionId !== void 0 && this.forkedIn.get(tx)?.get(sessionId) === false) && await this.sharedHistoryForks(tx) ? this.forkTables.forkSegments : void 0,
2661
+ dialect: this.dialect
2662
+ };
2663
+ }
2664
+ /**
2665
+ * A column, `forked`, of a read of a sessions row whose id is `id`: 1 when the session has fork segments (#6560),
2666
+ * found by the segments' key. Only where `segments`, the fork segments table, exists.
2667
+ */
2668
+ forkedColumn(segments, id = "id") {
2669
+ return segments === void 0 ? "" : `, CASE WHEN EXISTS (SELECT 1 FROM ${segments} WHERE session_id = ${id}) THEN 1 ELSE 0 END AS forked`;
2670
+ }
2671
+ /**
2672
+ * Notes what a read of session `sessionId`'s row in transaction `tx` found, `forked` from {@link forkedColumn}: the
2673
+ * transaction's later reads of a session without segments read its tables directly. The store remembers it too, as a
2674
+ * first guess for a read that sends its statements before that row's answer, and checks it against that answer.
2675
+ */
2676
+ noteForked(tx, sessionId, forked) {
2677
+ if (forked === void 0 || forked === null) return;
2678
+ const value = Number(forked) === 1;
2679
+ if (tx !== void 0) {
2680
+ const known = this.forkedIn.get(tx) ?? /* @__PURE__ */ new Map();
2681
+ this.forkedIn.set(tx, known);
2682
+ known.set(sessionId, value);
2683
+ }
2684
+ this.forkedSessions.delete(sessionId);
2685
+ this.forkedSessions.set(sessionId, value);
2686
+ while (this.forkedSessions.size > 256) this.forkedSessions.delete(this.forkedSessions.keys().next().value);
2687
+ }
2688
+ /**
2689
+ * How a read outside a transaction reads a session's rows: through its view once this store has seen shared history,
2690
+ * and otherwise from the tables themselves, but only while the schema, read in the same statement, is older. Such a
2691
+ * read that finds nothing asks `outsideTransaction` to try again.
2692
+ */
2693
+ outsideViewTables() {
2694
+ const version = `(SELECT max(schema_version) FROM ${this.tables.meta})`;
2695
+ return this.sharedHistorySeen ? {
2696
+ segments: this.forkTables.forkSegments,
2697
+ dialect: this.dialect,
2698
+ guard: `${version} <= 3`
2699
+ } : {
2700
+ segments: void 0,
2701
+ dialect: this.dialect,
2702
+ guard: `${version} < 3`
2703
+ };
2704
+ }
2705
+ /**
2706
+ * `read`, a read outside a transaction of a session's rows through `outsideViewTables`, once more through the views
2707
+ * when it found nothing (`found` says) before this store had seen shared history, and the schema, read after it, is
2708
+ * now at version 3: the read's own check then held its rows back. The switch is one way, so a schema older than 3
2709
+ * read after the read was older at the read too, and its answer stands.
2710
+ */
2711
+ async outsideTransaction(read, found) {
2712
+ const seen = this.sharedHistorySeen;
2713
+ const value = await read(this.outsideViewTables());
2714
+ if (found(value)) return value;
2715
+ return await this.schemaNowShared(seen) ? read(this.outsideViewTables()) : value;
2716
+ }
2717
+ /**
2718
+ * `read`, a read outside a transaction of session `sessionId`'s rows that also reads, as `forked`, whether the
2719
+ * session has fork segments, through `outsideTransaction` (#6560): from the tables themselves when this store last
2720
+ * found the session without segments, and through its view again when the read's own answer says it now has them.
2721
+ */
2722
+ outsideSessionRead(sessionId, read, found, forkedOf) {
2723
+ return this.outsideTransaction(async (tables) => {
2724
+ const plain = tables.segments !== void 0 && this.forkedSessions.get(sessionId) === false;
2725
+ const value = await read(plain ? {
2726
+ ...tables,
2727
+ segments: void 0
2728
+ } : tables);
2729
+ const forked = forkedOf(value);
2730
+ this.noteForked(void 0, sessionId, forked);
2731
+ return plain && Number(forked) === 1 ? read(tables) : value;
2732
+ }, found);
2733
+ }
2734
+ /** The `forked` column of a read outside a transaction of the sessions row `id` names: see `outsideSessionRead`. */
2735
+ outsideForkedColumn(id) {
2736
+ return this.forkedColumn(this.sharedHistorySeen ? this.forkTables.forkSegments : void 0, id);
2737
+ }
2738
+ /**
2739
+ * After a read outside a transaction found nothing: reads the sessions schema, refuses one this build does not read,
2740
+ * and tells whether shared history is on now where the read, made with `seen` as it was, read the tables themselves.
2741
+ */
2742
+ async schemaNowShared(seen) {
2743
+ const row = await this.database.get(`SELECT max(schema_version) AS version FROM ${this.tables.meta}`);
2744
+ const version = row?.version == null ? null : Number(row.version);
2745
+ assertStorageSchemaVersion("sessions", version, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
2746
+ this.noteSchemaVersion(version);
2747
+ return this.sharedHistorySeen && !seen;
2748
+ }
2749
+ /**
2750
+ * Turns on forks that share their parent's history (#6560), as a store's open does by itself: see
2751
+ * {@link SqlSessionStore.switchSharedHistory}. `live` judges whether the process of an older build's open-session
2752
+ * marker still runs; the application's judge by default.
2753
+ */
2754
+ enableSharedHistoryForks(options = {}) {
2755
+ this.assertOpen();
2756
+ return SqlSessionStore.switchSharedHistory(this.database, this.prefix, this.tables, this.openMarkers, options.live ?? sharedHistorySwitchHost().live);
2757
+ }
2758
+ /**
2759
+ * The switch to shared-history forks (#6560), in one transaction: creates the fork tables, records version 3 in the
2760
+ * migration ledger where there is one, and raises the sessions schema to it, so that builds which do not read it
2761
+ * refuse the database at their next open or transaction. One way: nothing lowers it again.
2762
+ *
2763
+ * It never leaves an older process reading what it cannot read: while `live` judges any open-session marker of an
2764
+ * older build to be a running process, it changes nothing and is `deferred`, and the next open tries again. The
2765
+ * transaction is the only writer of the whole database while it runs, so every session write either finished before
2766
+ * it, or starts after it and reads the new version first. Two hosts switching at once run one after the other, and
2767
+ * the second finds it `already` done.
2768
+ */
2769
+ static switchSharedHistory(database, prefix, tables, markers, live) {
2770
+ const dialect = dialectOf(database);
2771
+ return database.transaction(async (tx) => {
2772
+ const [row, older] = await statementBatch(tx, [], [() => tx.get(`SELECT max(schema_version) AS schema_version FROM ${tables.meta}`), () => markers.olderThan(tx, 3)]);
2773
+ const version = row?.schema_version ?? null;
2774
+ assertStorageSchemaVersion("sessions", version, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
2775
+ if (Number(version) >= 3) return { status: "already" };
2776
+ const holders = await liveMarkers(older, live);
2777
+ if (holders.length > 0) return {
2778
+ status: "deferred",
2779
+ holders
2780
+ };
2781
+ await createSharedHistoryTables(tx, dialect, sessionForkTables(prefix));
2782
+ await installForkInheritedBlobGuard(tx, dialect, snapshotIndexTables$1(prefix), sessionForkTables(prefix).forkSegments);
2783
+ await statementBatch(tx, [
2784
+ dialect.dropTrigger(legacyForkLinksTriggerName(tables.entries), tables.entries, true),
2785
+ dialect.versionedMigrations && {
2786
+ sql: `INSERT INTO ${storageMigrationTable(prefix)} (domain, version, applied_at) VALUES (?, ?, ${dialect.nowMs}) ON CONFLICT DO NOTHING`,
2787
+ params: ["sessions", 3]
2788
+ },
2789
+ {
2790
+ sql: `UPDATE ${tables.meta} SET schema_version = ? WHERE schema_version < ?`,
2791
+ params: [3, 3]
2792
+ }
2793
+ ], []);
2794
+ return { status: "enabled" };
2795
+ }, {
2796
+ retryTransientFailures: true,
2797
+ concurrency: { kind: "serial" }
2798
+ });
2799
+ }
2800
+ /**
2801
+ * An open's switch to shared-history forks, true when it switched the database. With `precheck`, for an open that
2802
+ * read the schema without a lock, it first reads, still without one, the version and the markers of older builds
2803
+ * together, so an open that must leave the switch for later, while an older build runs a session, takes no lock and
2804
+ * writes nothing; an open that set the schema up under the write lock goes straight to the switch. A switch that cannot run, such as for a role without the
2805
+ * privilege to create tables, is left for a later open or `atomic storage migrate`; forks copy meanwhile. Either way
2806
+ * the open goes on, and only the debug log notes it.
2807
+ */
2808
+ static async switchAtOpen(database, prefix, tables, markers, precheck) {
2809
+ const host = sharedHistorySwitchHost();
2810
+ const deferred = (holders) => host.skipped({
2811
+ reason: "older-sessions-running",
2812
+ prefix,
2813
+ sessions: holders.length,
2814
+ holders: holders.map((holder) => `${holder.host}:${holder.pid}`).join(", ")
2815
+ });
2816
+ try {
2817
+ if (precheck) {
2818
+ const [found, older] = await statementBatch(database, [], [() => database.get(`SELECT max(schema_version) AS schema_version FROM ${tables.meta}`), () => markers.olderThan(database, 3)]);
2819
+ if (Number(found?.schema_version) >= 3) return false;
2820
+ const holders = await liveMarkers(older, host.live);
2821
+ if (holders.length > 0) {
2822
+ deferred(holders);
2823
+ return false;
2824
+ }
2825
+ }
2826
+ const outcome = await SqlSessionStore.switchSharedHistory(database, prefix, tables, markers, host.live);
2827
+ if (outcome.status === "deferred") deferred(outcome.holders);
2828
+ return outcome.status === "enabled";
2829
+ } catch (error) {
2830
+ host.skipped({
2831
+ reason: "switch-failed",
2832
+ prefix,
2833
+ error: error.message
2834
+ });
2835
+ return false;
2836
+ }
1888
2837
  }
1889
2838
  get descriptor() {
1890
2839
  return {
@@ -1893,36 +2842,93 @@ var SqlSessionStore = class SqlSessionStore {
1893
2842
  };
1894
2843
  }
1895
2844
  async create(header, entries) {
2845
+ return this.writing(header.id, this.writeCreate(header, entries));
2846
+ }
2847
+ async writeCreate(header, entries) {
1896
2848
  this.assertOpen();
1897
2849
  validateSessionHeader(header);
1898
2850
  validateSessionEntries(entries);
1899
- const existing = {
1900
- sql: `SELECT id FROM ${this.tables.sessions} WHERE id = ?`,
1901
- params: [header.id]
1902
- };
1903
- return this.transactionCheckedAlongside(async (tx, checked) => {
1904
- if (await tx.get(existing.sql, ...existing.params)) throw new SessionExistsError$1(header.id);
2851
+ const existing = this.newSessionRead(header.id);
2852
+ let written = [];
2853
+ let writtenRow;
2854
+ const created = await this.transactionCheckedAlongside(async (tx, checked) => {
2855
+ writtenRow = void 0;
2856
+ const found = await tx.get(existing.sql, ...existing.params);
2857
+ await this.startNewSession(tx, header.id, found, "create");
1905
2858
  const summary = this.summaryWrite(header.id, {
1906
2859
  header,
1907
2860
  entries,
1908
2861
  lastSeq: entries.length
1909
2862
  });
1910
2863
  await checked;
1911
- await this.writeEntries(tx, summary.statement, this.entryWrites(header.id, entries, 0, summary.texts));
2864
+ written = [];
2865
+ writtenRow = summary.row;
2866
+ await this.writeEntries(tx, summary.statement, this.entryWrites(header.id, entries, 0, summary.texts, true, written));
1912
2867
  return {
1913
2868
  lastSeq: entries.length,
1914
2869
  epoch: summary.epoch
1915
2870
  };
1916
2871
  }, this.sessionWrite(header.id, existing));
2872
+ this.noteWritten(header.id, created.epoch, written);
2873
+ this.rememberWritten(header.id, writtenRow);
2874
+ return created;
1917
2875
  }
1918
- async createFork(header, entries, source) {
1919
- if (this.create !== SqlSessionStore.prototype.create) return void 0;
1920
- if (!this.sharesTablesWith(source.store)) {
1921
- if ("read" in entries) return entries.kind === "complete-session" ? this.createStagedFork(header, entries, source) : void 0;
1922
- if (source.receipts.size < 2) return void 0;
1923
- return this.createStagedFork(header, { async *read() {
1924
- for (const entry of entries) yield {
1925
- entry,
2876
+ /**
2877
+ * The read that begins a transaction writing a new session `id`, by `create` or by a fork: whether it exists and, where
2878
+ * this store has seen shared history, whether a deleted session with this ID left rows forks still read, in the same
2879
+ * statement.
2880
+ */
2881
+ newSessionRead(id) {
2882
+ return this.sharedHistorySeen ? {
2883
+ sql: `SELECT (SELECT id FROM ${this.tables.sessions} WHERE id = ?) AS id, (SELECT session_id FROM ${this.forkTables.forkTombstones} WHERE session_id = ?) AS tombstone`,
2884
+ params: [id, id]
2885
+ } : {
2886
+ sql: `SELECT id FROM ${this.tables.sessions} WHERE id = ?`,
2887
+ params: [id]
2888
+ };
2889
+ }
2890
+ /**
2891
+ * In the transaction that writes a new session `id`, before its writes, given what {@link newSessionRead} found:
2892
+ * refuses a session that exists. Where a deleted session with this ID left rows forks still read, those forks get
2893
+ * their own copies first and the rows go, so the new session starts empty and their sweep never takes its rows. A
2894
+ * fork whose copy a missing source chunk refuses keeps the old rows, and the new session is refused with it.
2895
+ */
2896
+ async startNewSession(tx, id, found, operation) {
2897
+ if (found?.id != null) throw new SessionExistsError$1(id);
2898
+ if (!await this.sharedHistoryForks(tx)) return false;
2899
+ if (!(found?.tombstone === void 0 ? await this.hasForkTombstone(tx, id) : found.tombstone !== null)) return false;
2900
+ return createOverTombstoneWithin(this.forkHost(), tx, id).catch((error) => {
2901
+ noteForkCopyRefusal(error, operation);
2902
+ throw error;
2903
+ });
2904
+ }
2905
+ /**
2906
+ * {@link startNewSession} for a fork with shared history, once it has read its donor: resolves with the donor. A donor
2907
+ * that read the rows a deleted session with the child's ID left holds its own copy of them now, in segments of its
2908
+ * own, and is read again (#6560).
2909
+ */
2910
+ async startSharedFork(tx, child, donor, source, withState) {
2911
+ const found = donor.child;
2912
+ const tombstoned = found?.tombstone === void 0 ? await this.hasForkTombstone(tx, child) : found.tombstone !== null;
2913
+ if (tombstoned && !donor.ordered && this.dialect.lockClause("update") !== "") throw new ForkChildTombstoned();
2914
+ if (!await this.startNewSession(tx, child, {
2915
+ id: null,
2916
+ tombstone: tombstoned ? child : null
2917
+ }, "fork")) return donor;
2918
+ if (!donor.segments.some((segment) => segment.sourceId === child)) return donor;
2919
+ return this.sharedForkDonor(tx, child, source, this.sharedForkReads(child, source.sessionId, withState));
2920
+ }
2921
+ async createFork(header, entries, source) {
2922
+ return this.writing(header.id, this.writeCreateFork(header, entries, source));
2923
+ }
2924
+ async writeCreateFork(header, entries, source) {
2925
+ if (this.create !== SqlSessionStore.prototype.create) return void 0;
2926
+ if (!this.sharesTablesWith(source.store)) {
2927
+ if ("read" in entries) return entries.kind === "complete-session" ? this.createStagedFork(header, entries, source) : void 0;
2928
+ if (source.receipts.size < 2) return void 0;
2929
+ return this.createStagedFork(header, { async *read() {
2930
+ for (const entry of entries) yield {
2931
+ entry,
1926
2932
  reference: source.receipts.get(entry.id)
1927
2933
  };
1928
2934
  } }, source);
@@ -1931,22 +2937,61 @@ var SqlSessionStore = class SqlSessionStore {
1931
2937
  this.assertOpen();
1932
2938
  validateSessionHeader(header);
1933
2939
  validateSessionEntries(entries);
1934
- return this.transaction(async (tx) => {
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);
2940
+ if (source.receipts.size === 0 && source.hashes.length === 0 && (!this.sharedHistorySeen || source.epoch === void 0)) return void 0;
2941
+ for (let attempt = 0, ordered = false;; attempt++) {
2942
+ const reads = this.sharedHistorySeen ? this.sharedForkReads(header.id, source.sessionId, false, ordered) : void 0;
2943
+ try {
2944
+ return await this.transactionCheckedAlongside((tx, checked) => this.writeEntriesFork(tx, checked, header, entries, source, reads), this.sessionWrite(header.id, ...reads === void 0 ? [] : sharedForkLeading(reads)));
2945
+ } catch (error) {
2946
+ if (error instanceof ForkChildTombstoned && !ordered) ordered = true;
2947
+ else if (!(error instanceof ForkSourcesMoved) || attempt >= 3) throw error;
1939
2948
  }
1940
- const summary = this.summaryWrite(header.id, {
1941
- header,
1942
- entries,
1943
- lastSeq: entries.length
1944
- });
2949
+ }
2950
+ }
2951
+ /**
2952
+ * A fork from the entries a caller holds. Where the database has shared history (#6560) and the source is still in
2953
+ * the generation the fork read it in, every entry the store read from the source and the caller kept unchanged, and
2954
+ * every receipt, is named by the child's segments, not stored again: the child stores only the entries it changed or
2955
+ * added, and their blobs. Otherwise the entries are stored as `create` stores them, receipts as the source stores
2956
+ * them. Undefined, with nothing written, for entries with neither receipts nor blobs that share nothing: `create`
2957
+ * then stores them, needing nothing of the source, so a source that changed or went away meanwhile does not fail it.
2958
+ */
2959
+ async writeEntriesFork(tx, checked, header, entries, source, reads) {
2960
+ const needsSource = source.receipts.size > 0 || source.hashes.length > 0;
2961
+ let shared;
2962
+ const unchecked = {
2963
+ ...source,
2964
+ epoch: void 0
2965
+ };
2966
+ const sharedRead = this.leadingForkDonor(tx, header.id, unchecked, reads);
2967
+ if (await this.sharedHistoryForks(tx)) try {
2968
+ shared = await (sharedRead ?? this.sharedForkDonor(tx, header.id, unchecked, this.sharedForkReads(header.id, source.sessionId, false)));
2969
+ } catch (error) {
2970
+ if (needsSource || !(error instanceof SessionNotFoundError$1)) throw error;
2971
+ return;
2972
+ }
2973
+ const sharing = shared !== void 0 && source.epoch !== void 0 && shared.epoch === source.epoch;
2974
+ if (!sharing && !needsSource) return void 0;
2975
+ if (shared !== void 0 && source.epoch !== void 0 && shared.epoch !== source.epoch) throw new SessionConflictError$1(source.sessionId, 0, shared.lastSeq);
2976
+ const donor = shared ?? await this.forkDonor(tx, header.id, source);
2977
+ for (const entry of entries) {
2978
+ const ref = source.receipts.get(entry.id);
2979
+ if (ref && (source.sessionId !== ref.sessionId || donor.epoch !== ref.epoch || donor.lastSeq < ref.seq)) throw new SessionConflictError$1(ref.sessionId, ref.seq, donor.lastSeq);
2980
+ }
2981
+ const summary = this.summaryWrite(header.id, {
2982
+ header,
2983
+ entries,
2984
+ lastSeq: entries.length
2985
+ });
2986
+ await checked;
2987
+ if (shared !== void 0) shared = await this.startSharedFork(tx, header.id, shared, unchecked, false);
2988
+ const tables = await this.viewTables(tx);
2989
+ const writes = new SentWrites(tx);
2990
+ if (!sharing) {
1945
2991
  const blobs = this.forkBlobCopy(source.sessionId, header.id, source.hashes);
1946
- const writes = new SentWrites(tx);
1947
2992
  const remainingBlobs = await writes.around(async () => {
1948
2993
  await writes.send([summary.statement]);
1949
- await writes.send(this.receiptForkWrites(header.id, entries, source, donor.lastSeq));
2994
+ await writes.send(this.receiptForkWrites(tables, header.id, entries, source, donor.lastSeq));
1950
2995
  await writes.send(this.entryWrites(header.id, [], 0, summary.texts, false));
1951
2996
  return this.finishForkCopy(tx, writes, header.id, blobs, source.hashes);
1952
2997
  });
@@ -1956,7 +3001,69 @@ var SqlSessionStore = class SqlSessionStore {
1956
3001
  epoch: summary.epoch,
1957
3002
  remainingBlobs
1958
3003
  };
1959
- }, this.sessionWrite(header.id));
3004
+ }
3005
+ const places = [];
3006
+ const stored = storedRows(source.sessionId, source.epoch);
3007
+ let sharedThrough = 0;
3008
+ for (const entry of entries) {
3009
+ const seq = source.receipts.get(entry.id)?.seq ?? stored?.seqOf(entry, sharedThrough);
3010
+ const shares = seq !== void 0 && seq > sharedThrough && seq <= donor.lastSeq;
3011
+ if (shares) sharedThrough = seq;
3012
+ places.push(shares ? seq : void 0);
3013
+ }
3014
+ const hashes = /* @__PURE__ */ new Set();
3015
+ let copiesReceipts = false;
3016
+ for (const [index, entry] of entries.entries()) {
3017
+ if (places[index] !== void 0) continue;
3018
+ copiesReceipts ||= source.receipts.has(entry.id);
3019
+ if (entry.type !== "custom" || entry.customType !== "atomic.tool-output") continue;
3020
+ const hash = entry.data?.hash;
3021
+ if (typeof hash === "string" && source.hashes.includes(hash)) hashes.add(hash);
3022
+ }
3023
+ const statements = this.sharedEntriesForkWrites(tables, header, entries, places, source, shared, summary.texts);
3024
+ if (!copiesReceipts && hashes.size === 0) {
3025
+ await this.writeEntries(tx, summary.statement, [...statements, this.forkVersionStep(header.id)]);
3026
+ return {
3027
+ lastSeq: entries.length,
3028
+ epoch: summary.epoch,
3029
+ remainingBlobs: []
3030
+ };
3031
+ }
3032
+ const remainingBlobs = await writes.around(async () => {
3033
+ await writes.send([summary.statement]);
3034
+ await writes.send(statements);
3035
+ return this.finishForkCopy(tx, writes, header.id, this.forkBlobCopy(source.sessionId, header.id, hashes), hashes);
3036
+ });
3037
+ await this.finishFork(tx, header.id);
3038
+ return {
3039
+ lastSeq: entries.length,
3040
+ epoch: summary.epoch,
3041
+ remainingBlobs
3042
+ };
3043
+ }
3044
+ /**
3045
+ * The statements of a fork from `entries` with shared history (#6560), in seq order, after its session row: the
3046
+ * segments that name the rows `places` puts in the source, each entry it does not as {@link entryForkWrites} stores it,
3047
+ * the search texts of those, and the lineage row. Throws, before the last of them, unless the segments are well formed.
3048
+ */
3049
+ *sharedEntriesForkWrites(tables, header, entries, places, source, donor, texts) {
3050
+ const lineage = this.lineageTables();
3051
+ const runs = new ForkSegmentRuns(lineage, header.id, {
3052
+ id: source.sessionId,
3053
+ segments: donor.segments,
3054
+ length: donor.lastSeq
3055
+ });
3056
+ yield* this.receiptForkWrites(tables, header.id, entries, source, donor.lastSeq, places, runs);
3057
+ yield* runs.drain();
3058
+ yield* this.entryWrites(header.id, [], 0, texts.filter((text) => places[text.index] === void 0), false);
3059
+ assertForkSegments(header.id, runs.segments, entries.length);
3060
+ yield forkLineageWrite(lineage, header.id, {
3061
+ parentId: source.sessionId,
3062
+ cutSeq: donor.lastSeq
3063
+ });
3064
+ if (runs.segments.length > 0) {
3065
+ for (const [index, place] of places.entries()) if (place === void 0) yield this.forkLinks().entry(header.id, index + 1);
3066
+ }
1960
3067
  }
1961
3068
  /**
1962
3069
  * The source session's head, its row locked for share, once the child is known to be new: both reads go out together,
@@ -1974,38 +3081,63 @@ var SqlSessionStore = class SqlSessionStore {
1974
3081
  }
1975
3082
  /**
1976
3083
  * 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.
3084
+ * and chunks copied in two statements whatever their size, and a run of others as `create` stores them, several rows
3085
+ * a statement. A receipt's row that names another entry fails the fork: the source changed under it. With `places`
3086
+ * and `runs`, an entry `places` puts in the source is named by `runs`' segments instead, and the segments before an
3087
+ * entry the child stores go first, for the snapshot index's triggers.
1979
3088
  */
1980
- *receiptForkWrites(child, entries, source, donorLastSeq) {
3089
+ *receiptForkWrites(tables, child, entries, source, donorLastSeq, places = [], runs) {
3090
+ let from = 0;
3091
+ let own = 0;
1981
3092
  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);
3093
+ const seq = places[index];
3094
+ if (seq === void 0 && !source.receipts.has(entry.id)) {
3095
+ if (own === 0) {
3096
+ if (runs !== void 0) yield* runs.drain();
3097
+ from = index;
3098
+ }
3099
+ own++;
1985
3100
  continue;
1986
3101
  }
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
- };
3102
+ if (own > 0) yield* this.entryWrites(child, entries.slice(from, from + own), from, [], false);
3103
+ own = 0;
3104
+ if (seq !== void 0) {
3105
+ runs.add(seq, index + 1, entry.id);
3106
+ if (runs.full) yield* runs.drain();
3107
+ continue;
3108
+ }
3109
+ if (runs !== void 0) yield* runs.drain();
3110
+ yield* this.entryForkWrites(tables, child, index, entry, source, donorLastSeq);
3111
+ }
3112
+ if (own > 0) yield* this.entryWrites(child, entries.slice(from, from + own), from, [], false);
3113
+ }
3114
+ /** The statements of {@link receiptForkWrites} that store `entry`, at index `index` of the fork's entries. */
3115
+ *entryForkWrites(tables, child, index, entry, source, donorLastSeq) {
3116
+ const ref = source.receipts.get(entry.id);
3117
+ if (ref === void 0) {
3118
+ yield* this.entryWrites(child, [entry], index, [], false);
3119
+ return;
2008
3120
  }
3121
+ const view = this.entriesView(tables, ref.sessionId, ref.seq - 1, ref.seq);
3122
+ yield {
3123
+ sql: withForkViews([view], `INSERT INTO ${this.tables.entries} (session_id, seq, entry_id, entry_json, chunks) SELECT ?, ?, entry_id, entry_json, chunks FROM ${view.name} WHERE entry_id = ?`),
3124
+ params: [
3125
+ ...view.params,
3126
+ child,
3127
+ index + 1,
3128
+ entry.id
3129
+ ],
3130
+ changes: 1,
3131
+ mismatch: () => new SessionConflictError$1(ref.sessionId, ref.seq, donorLastSeq)
3132
+ };
3133
+ yield {
3134
+ sql: withForkViews([view], `INSERT INTO ${this.tables.entryChunks} (session_id, seq, idx, data) SELECT ?, ?, c.idx, c.data FROM ${view.name} v JOIN ${this.tables.entryChunks} c ON c.session_id = v.src_id AND c.seq = v.src_seq WHERE c.idx >= 0 AND c.idx < v.chunks ORDER BY c.idx`),
3135
+ params: [
3136
+ ...view.params,
3137
+ child,
3138
+ index + 1
3139
+ ]
3140
+ };
2009
3141
  }
2010
3142
  /**
2011
3143
  * The blob copy of a fork from session `source` of this store's tables (#6560), or undefined when a subclass stores
@@ -2013,7 +3145,7 @@ var SqlSessionStore = class SqlSessionStore {
2013
3145
  */
2014
3146
  forkBlobCopy(source, child, hashes) {
2015
3147
  if (this.getBlob !== SqlSessionStore.prototype.getBlob || this.putBlob !== SqlSessionStore.prototype.putBlob) return void 0;
2016
- return forkBlobCopy(this.tables, {
3148
+ return forkBlobCopy(this.dialect, this.tables, {
2017
3149
  legacyBlobData: this.legacyBlobData,
2018
3150
  chunkBytes: SESSION_BLOB_CHUNK_BYTES
2019
3151
  }, source, child, [...new Set(hashes)]);
@@ -2045,6 +3177,9 @@ var SqlSessionStore = class SqlSessionStore {
2045
3177
  * `remainingBlobs` names the blobs left to copy with `copySessionBlobs`: those the source no longer holds.
2046
3178
  */
2047
3179
  async createStagedFork(header, stream, source) {
3180
+ return this.writing(header.id, this.writeCreateStagedFork(header, stream, source));
3181
+ }
3182
+ async writeCreateStagedFork(header, stream, source) {
2048
3183
  this.assertOpen();
2049
3184
  validateSessionHeader(header);
2050
3185
  const { createStagedFork } = await import("../core/storage/session/fork-staging.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
@@ -2069,6 +3204,80 @@ var SqlSessionStore = class SqlSessionStore {
2069
3204
  this.assertOpen();
2070
3205
  await this.chatRecords?.initialize();
2071
3206
  }
3207
+ /** Whether a deleted session with ID `sessionId` left rows forks still read. */
3208
+ async hasForkTombstone(tx, sessionId) {
3209
+ return await tx.get(`SELECT session_id FROM ${this.forkTables.forkTombstones} WHERE session_id = ?`, sessionId) !== void 0;
3210
+ }
3211
+ /** This store's side of detaching and pinning shared fork history: see fork-detach-host.ts. */
3212
+ forkHost() {
3213
+ return forkDetachHost({
3214
+ dialect: this.dialect,
3215
+ tables: this.tables,
3216
+ forkTables: this.forkTables,
3217
+ blobs: {
3218
+ legacyBlobData: this.legacyBlobData,
3219
+ chunkBytes: SESSION_BLOB_CHUNK_BYTES
3220
+ },
3221
+ entryLinks: this.entryLinks(),
3222
+ transaction: (body) => this.transaction(body, SESSION_TRANSACTION)
3223
+ });
3224
+ }
3225
+ /** The statements that link the entries a session with fork segments stores, as a copy links them (#6560). */
3226
+ forkLinks() {
3227
+ const index = snapshotIndexTables$1(this.prefix);
3228
+ this.forkLinkStatements ??= forkLinkWrites({
3229
+ entries: this.tables.entries,
3230
+ sessionLinks: index.sessionLinks,
3231
+ sources: index.sources,
3232
+ forkSegments: this.forkTables.forkSegments
3233
+ }, this.dialect);
3234
+ return this.forkLinkStatements;
3235
+ }
3236
+ /** How the snapshot index links a materialization's copies and a fork moved onto another copy (#6560). */
3237
+ entryLinks() {
3238
+ this.entryLinkStatements ??= entryLinkers.sessionEntryLinks?.(this.prefix, this.dialect, this.forkTables.forkSegments) ?? { async settle(tx, _sessionId, _fromSeq, before) {
3239
+ for (const { sql, params } of before) await tx.run(sql, ...params);
3240
+ } };
3241
+ return this.entryLinkStatements;
3242
+ }
3243
+ /**
3244
+ * @internal Gives every fork that shares history with `sessionId` its own copy of what it reads, so the session's
3245
+ * rows no longer stay for them; see fork-detach.ts. Detaches a crash stopped are finished first. Nothing to do where
3246
+ * shared-history forks are off.
3247
+ */
3248
+ async detachForks(sessionId, options = {}) {
3249
+ this.assertOpen();
3250
+ validateSessionText("sessionId", sessionId);
3251
+ if (!await this.transaction((tx) => this.sharedHistoryForks(tx), SESSION_TRANSACTION)) return {
3252
+ detached: [],
3253
+ reparented: []
3254
+ };
3255
+ const report = await detachForkChildren(this.forkHost(), sessionId, options).catch((error) => {
3256
+ noteForkCopyRefusal(error, "detach");
3257
+ throw error;
3258
+ });
3259
+ await this.sweepReleasedForkRows([sessionId]);
3260
+ return report;
3261
+ }
3262
+ /** @internal Finishes every detach a crash stopped. Nothing to do where shared-history forks are off. */
3263
+ async resumeForkDetaches() {
3264
+ this.assertOpen();
3265
+ if (!await this.transaction((tx) => this.sharedHistoryForks(tx), SESSION_TRANSACTION)) return {
3266
+ detached: [],
3267
+ reparented: []
3268
+ };
3269
+ return resumeForkDetaches(this.forkHost());
3270
+ }
3271
+ /**
3272
+ * @internal Removes the rows of deleted sessions that no fork reads any more, a batch per transaction: `sessionIds`,
3273
+ * and a few any earlier sweep left. Resolves with the sessions whose rows went.
3274
+ */
3275
+ async sweepForkTombstones(sessionIds = [], batchEntries) {
3276
+ this.assertOpen();
3277
+ if (!await this.transaction((tx) => this.sharedHistoryForks(tx), SESSION_TRANSACTION)) return [];
3278
+ const { sweepForkTombstones } = await import("../core/storage/session/fork-sweep.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
3279
+ return sweepForkTombstones(this.forkHost(), sessionIds, batchEntries === void 0 ? {} : { batchEntries });
3280
+ }
2072
3281
  forkStagingTarget() {
2073
3282
  return {
2074
3283
  database: this.database,
@@ -2088,6 +3297,10 @@ var SqlSessionStore = class SqlSessionStore {
2088
3297
  lastSeq
2089
3298
  }, summary, index),
2090
3299
  create: (header, entries) => this.create(header, entries),
3300
+ newSessionRead: (id) => this.newSessionRead(id),
3301
+ startNewSession: async (tx, id, found) => {
3302
+ await this.startNewSession(tx, id, found, "fork");
3303
+ },
2091
3304
  sourceStoredEntryChunks: (source) => {
2092
3305
  const store = nativeForkReader(source, "entry");
2093
3306
  return store instanceof SqlSessionStore && store.readEntryChunk === SqlSessionStore.prototype.readEntryChunk ? (reference, index) => store.readStoredEntryChunk(reference, index) : void 0;
@@ -2117,12 +3330,13 @@ var SqlSessionStore = class SqlSessionStore {
2117
3330
  */
2118
3331
  async readStoredEntryChunk(reference, index) {
2119
3332
  this.assertOpen();
2120
- return this.readTransaction(async (tx) => {
3333
+ return this.readTransaction(reference.sessionId, async (tx) => {
2121
3334
  const { sessionId, epoch, seq } = reference;
2122
3335
  const head = await this.historyHead(tx, sessionId, true);
2123
3336
  if (head.epoch !== epoch) throw new SessionConflictError$1(sessionId, seq, head.lastSeq);
2124
- const row = await tx.get(`SELECT e.chunks, c.data FROM ${this.tables.entries} e LEFT JOIN ${this.tables.entryChunks} c
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);
3337
+ const view = this.entriesView(await this.viewTables(tx, sessionId), sessionId, seq - 1, seq);
3338
+ const row = await tx.get(withForkViews([view], `SELECT e.chunks, c.data FROM ${view.name} e LEFT JOIN ${this.tables.entryChunks} c
3339
+ ON c.session_id = e.src_id AND c.seq = e.src_seq AND c.idx = ?`), ...view.params, index);
2126
3340
  if (!row) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing session entry ${seq}`));
2127
3341
  if (Number(row.chunks) === 0) return void 0;
2128
3342
  if (row.data == null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing chunk of session entry ${seq}`));
@@ -2132,11 +3346,12 @@ var SqlSessionStore = class SqlSessionStore {
2132
3346
  /** How many chunks the entry `reference` names is stored in, 0 when it is stored whole, in its generation. */
2133
3347
  async readStoredChunks(reference) {
2134
3348
  this.assertOpen();
2135
- return this.readTransaction(async (tx) => {
3349
+ return this.readTransaction(reference.sessionId, async (tx) => {
2136
3350
  const { sessionId, epoch, seq } = reference;
2137
3351
  const head = await this.historyHead(tx, sessionId, true);
2138
3352
  if (head.epoch !== epoch) throw new SessionConflictError$1(sessionId, seq, head.lastSeq);
2139
- const row = await tx.get(`SELECT chunks FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, seq);
3353
+ const view = this.entriesView(await this.viewTables(tx, sessionId), sessionId, seq - 1, seq);
3354
+ const row = await tx.get(withForkViews([view], `SELECT chunks FROM ${view.name}`), ...view.params);
2140
3355
  if (!row) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing session entry ${seq}`));
2141
3356
  return Number(row.chunks);
2142
3357
  });
@@ -2150,11 +3365,14 @@ var SqlSessionStore = class SqlSessionStore {
2150
3365
  this.assertOpen();
2151
3366
  const parts = /* @__PURE__ */ new Map();
2152
3367
  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), {
3368
+ const rows = await this.outsideTransaction((tables) => this.database.all(`SELECT b.hash, b.bytes, b.chunks, CASE WHEN b.chunks >= 0 AND b.bytes <= ? THEN c.data END AS data,
3369
+ CASE WHEN w.place = 0 THEN 1 ELSE 0 END AS own
3370
+ FROM ${this.blobPlaces(tables)} w JOIN ${this.tables.blobs} b
3371
+ ON b.session_id = w.owner AND ${inJsonList(this.dialect, "b.hash")}
3372
+ LEFT JOIN ${this.tables.blobChunks} c ON c.session_id = b.session_id AND c.hash = b.hash AND c.idx = 0
3373
+ ${tables.guard === void 0 ? "" : `WHERE ${tables.guard}`}
3374
+ ORDER BY own DESC, b.session_id`, maxBytes, ...this.blobPlaceParams(tables, sessionId), JSON.stringify(hashes)), (found) => found.length > 0);
3375
+ for (const row of rows) if (!parts.has(String(row.hash))) parts.set(String(row.hash), {
2158
3376
  bytes: Number(row.bytes),
2159
3377
  chunks: Number(row.chunks),
2160
3378
  ...row.data == null ? {} : { data: row.data }
@@ -2171,8 +3389,11 @@ var SqlSessionStore = class SqlSessionStore {
2171
3389
  this.assertOpen();
2172
3390
  const cut = this.legacyBlobData && legacyBytes > 0;
2173
3391
  const legacy = cut ? "CASE WHEN b.chunks = -1 THEN substr(b.data, ?, ?) ELSE c.data END" : "c.data";
2174
- const row = await this.database.get(`SELECT b.bytes, b.chunks, ${legacy} AS data FROM ${this.tables.blobs} b LEFT JOIN ${this.tables.blobChunks} c
2175
- ON c.session_id = b.session_id AND c.hash = b.hash AND c.idx = ? WHERE b.session_id = ? AND b.hash = ?`, ...cut ? [offset + 1, legacyBytes] : [], Math.floor(offset / SESSION_BLOB_CHUNK_BYTES), sessionId, hash);
3392
+ const row = await this.outsideTransaction((tables) => this.database.get(`SELECT b.bytes, b.chunks, ${legacy} AS data
3393
+ FROM ${this.blobPlaces(tables)} w JOIN ${this.tables.blobs} b ON b.session_id = w.owner AND b.hash = ?
3394
+ LEFT JOIN ${this.tables.blobChunks} c ON c.session_id = b.session_id AND c.hash = b.hash AND c.idx = ?
3395
+ ${tables.guard === void 0 ? "" : `WHERE ${tables.guard}`}
3396
+ ORDER BY w.place, b.session_id LIMIT 1`, ...cut ? [offset + 1, legacyBytes] : [], ...this.blobPlaceParams(tables, sessionId), hash, Math.floor(offset / SESSION_BLOB_CHUNK_BYTES)), (found) => found !== void 0);
2176
3397
  if (row === void 0) return void 0;
2177
3398
  return {
2178
3399
  bytes: Number(row.bytes),
@@ -2180,122 +3401,347 @@ var SqlSessionStore = class SqlSessionStore {
2180
3401
  ...row.data == null ? {} : { data: row.data }
2181
3402
  };
2182
3403
  }
3404
+ /**
3405
+ * A fork from a stream of the source's rows. Where the database has shared history (#6560), the child stores no copy
3406
+ * of the rows the source stores unchanged: its segments name them, and it stores only the rows the stream changed or
3407
+ * added. A stream of the source's whole history, as it stands, reads no row at all.
3408
+ */
2183
3409
  async createStreamedFork(header, stream, source) {
2184
3410
  this.assertOpen();
2185
3411
  validateSessionHeader(header);
3412
+ for (let attempt = 0, ordered = false;; attempt++) {
3413
+ const reads = this.sharedHistorySeen ? this.sharedForkReads(header.id, source.sessionId, stream.prefix !== void 0, ordered) : void 0;
3414
+ try {
3415
+ return await this.transactionCheckedAlongside((tx, checked) => this.writeStreamedFork(tx, checked, header, stream, source, reads), this.sessionWrite(header.id, ...reads === void 0 ? [] : sharedForkLeading(reads)));
3416
+ } catch (error) {
3417
+ if (error instanceof ForkChildTombstoned && !ordered) ordered = true;
3418
+ else if (!(error instanceof ForkSourcesMoved) || attempt >= 3) throw error;
3419
+ }
3420
+ }
3421
+ }
3422
+ async writeStreamedFork(tx, checked, header, stream, source, reads) {
3423
+ const sharedRead = this.leadingForkDonor(tx, header.id, source, reads);
3424
+ const withState = stream.prefix !== void 0;
3425
+ let shared = await this.sharedHistoryForks(tx) ? await (sharedRead ?? this.sharedForkDonor(tx, header.id, source, this.sharedForkReads(header.id, source.sessionId, withState))) : void 0;
3426
+ const read = shared ?? await this.forkDonor(tx, header.id, source);
3427
+ await checked;
3428
+ if (shared !== void 0) shared = await this.startSharedFork(tx, header.id, shared, source, withState);
3429
+ const head = shared ?? read;
2186
3430
  const { encodedForkRow } = await import("../core/storage/session/fork-row-bytes.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
2187
3431
  const { foldForkRow } = await import("../core/storage/session/fork-row-index.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
2188
- return this.transaction(async (tx) => {
2189
- const head = await this.forkDonor(tx, header.id, source);
2190
- const reader = new SqlSessionStore({
2191
- descriptor: this.database.descriptor,
2192
- dialect: this.dialect,
2193
- readOnly: true,
2194
- exec: tx.exec.bind(tx),
2195
- get: tx.get.bind(tx),
2196
- run: tx.run.bind(tx),
2197
- all: tx.all.bind(tx),
2198
- transaction: async (cb) => cb(tx),
2199
- close: async () => {}
2200
- }, this.tables, this.prefix, this.cwdMatcher, this.blobTable, this.legacyBlobData, void 0, this.entryByteLength);
2201
- const { index: donorIndex } = await reader.prepareResume(source.sessionId);
2202
- reader.readBranchSpan = async (id, cut) => transcriptBranchSpan(id, donorIndex, cut);
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);
2206
- let summary = applySessionSummaryEntries(void 0, []).state;
2207
- let index = foldSessionResume(void 0, []);
2208
- let seq = 0;
2209
- const hashes = /* @__PURE__ */ new Set();
2210
- const inlineSnapshot = async (ref) => {
2211
- const text = (key) => this.dialect.jsonText("entry_json", key);
2212
- const ty = (key) => this.dialect.jsonType("entry_json", key);
2213
- const s = await tx.get(`SELECT entry_id AS id,${text("parentId")} AS parent,${text("timestamp")} AS stamp,${text("root")} AS root,${text("snapshotId")} AS snapshot,${text("captureMs")} AS capture,${ty("snapshot")} AS record,${ty("restore")} AS restore,${ty("unrestored")} AS unrestored,${text("degradedFrom")} AS degraded FROM ${this.tables.entries} WHERE session_id=? AND seq=? AND chunks=0 AND ${text("type")}='worktree_snapshot'`, ref.sessionId, ref.seq);
2214
- if (!s) return void 0;
2215
- return {
2216
- type: "worktree_snapshot",
2217
- id: s.id,
2218
- parentId: s.parent,
2219
- timestamp: s.stamp,
2220
- root: s.root,
2221
- snapshotId: s.snapshot,
2222
- ...s.capture !== null ? { captureMs: Number(s.capture) } : {},
2223
- ...s.record === "object" ? { snapshot: {} } : {},
2224
- ...s.restore === "object" ? { restore: {} } : {},
2225
- ...s.unrestored === "object" ? { unrestored: {} } : {},
2226
- ...s.degraded ? { degradedFrom: s.degraded } : {}
2227
- };
3432
+ const prefix = stream.prefix;
3433
+ if (shared !== void 0 && prefix !== void 0 && prefix.sessionId === source.sessionId && prefix.through === shared.lastSeq && (prefix.epoch === void 0 || prefix.epoch === shared.epoch)) {
3434
+ const whole = await this.writeSharedPrefixFork(tx, header, source.sessionId, shared);
3435
+ if (whole !== void 0) return whole;
3436
+ }
3437
+ const reader = new SqlSessionStore({
3438
+ descriptor: this.database.descriptor,
3439
+ dialect: this.dialect,
3440
+ readOnly: true,
3441
+ exec: tx.exec.bind(tx),
3442
+ get: tx.get.bind(tx),
3443
+ run: tx.run.bind(tx),
3444
+ all: tx.all.bind(tx),
3445
+ transaction: async (cb) => cb(tx),
3446
+ close: async () => {}
3447
+ }, this.tables, this.prefix, this.cwdMatcher, this.blobTable, this.legacyBlobData, void 0, this.entryByteLength);
3448
+ reader.sharedHistorySeen = await this.sharedHistoryForks(tx);
3449
+ let donorIndex;
3450
+ reader.readBranchSpan = async (id, cut) => {
3451
+ donorIndex ??= reader.prepareResume(source.sessionId).then((prepared) => prepared.index);
3452
+ return transcriptBranchSpan(id, await donorIndex, cut);
3453
+ };
3454
+ reader.readEntryChunk = this.forkChunkReader(tx, await this.viewTables(tx), reader, source.sessionId, head.epoch);
3455
+ const copies = new ForkRowRuns(this.tables, header.id, source.sessionId);
3456
+ const lineage = this.lineageTables();
3457
+ const runs = shared === void 0 ? void 0 : new ForkSegmentRuns(lineage, header.id, {
3458
+ id: source.sessionId,
3459
+ segments: shared.segments,
3460
+ length: shared.lastSeq
3461
+ });
3462
+ const viewTables = await this.viewTables(tx);
3463
+ const lookup = async (id) => (runs ?? copies).heldSeq(id) ?? this.seqOfEntry(tx, viewTables, header.id, id);
3464
+ let summary = applySessionSummaryEntries(void 0, []).state;
3465
+ let index = foldSessionResume(void 0, []);
3466
+ let seq = 0;
3467
+ const hashes = /* @__PURE__ */ new Set();
3468
+ const inlineSnapshot = async (ref) => {
3469
+ const text = (key) => this.dialect.jsonText("entry_json", key);
3470
+ const ty = (key) => this.dialect.jsonType("entry_json", key);
3471
+ const view = this.entriesView(await this.viewTables(tx), ref.sessionId, ref.seq - 1, ref.seq);
3472
+ const s = await tx.get(withForkViews([view], `SELECT entry_id AS id,${text("parentId")} AS parent,${text("timestamp")} AS stamp,${text("root")} AS root,${text("snapshotId")} AS snapshot,${text("captureMs")} AS capture,${ty("snapshot")} AS record,${ty("restore")} AS restore,${ty("unrestored")} AS unrestored,${text("degradedFrom")} AS degraded FROM ${view.name} WHERE chunks=0 AND ${text("type")}='worktree_snapshot'`), ...view.params);
3473
+ if (!s) return void 0;
3474
+ return {
3475
+ type: "worktree_snapshot",
3476
+ id: s.id,
3477
+ parentId: s.parent,
3478
+ timestamp: s.stamp,
3479
+ root: s.root,
3480
+ snapshotId: s.snapshot,
3481
+ ...s.capture !== null ? { captureMs: Number(s.capture) } : {},
3482
+ ...s.record === "object" ? { snapshot: {} } : {},
3483
+ ...s.restore === "object" ? { restore: {} } : {},
3484
+ ...s.unrestored === "object" ? { unrestored: {} } : {},
3485
+ ...s.degraded ? { degradedFrom: s.degraded } : {}
2228
3486
  };
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;
2247
- }
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
- }
3487
+ };
3488
+ const writes = new SentWrites(tx);
3489
+ const blobs = {};
3490
+ let copiedRows = false;
3491
+ const ownSeqs = [];
3492
+ const remainingBlobs = await writes.around(async () => {
3493
+ for await (const row of stream.read(reader, async (id) => await lookup(id) !== void 0, inlineSnapshot)) {
3494
+ index = await foldForkRow(index, row, lookup);
3495
+ const entry = row.entry;
3496
+ const listed = applySessionSummaryEntries(summary, [entry]);
3497
+ summary = listed.state;
3498
+ const unchanged = row.stored?.sessionId === source.sessionId && row.edits === void 0;
3499
+ if (entry.type === "custom" && entry.customType === "atomic.tool-output" && !(unchanged && runs)) {
3500
+ const hash = entry.data?.hash;
3501
+ if (typeof hash === "string") hashes.add(hash);
3502
+ }
3503
+ if (unchanged && runs !== void 0) {
3504
+ runs.add(row.stored.seq, seq + 1, entry.id);
3505
+ if (runs.full) await writes.send(runs.drain());
3506
+ seq++;
3507
+ continue;
3508
+ }
3509
+ if (row.stored?.sessionId === source.sessionId && row.edits === void 0) {
3510
+ copiedRows = true;
3511
+ copies.add(row.stored.seq, seq + 1, entry.id);
3512
+ await writes.send(this.entryWrites(header.id, [], seq, listed.texts, false));
3513
+ if (copies.full) await writes.send(copies.drain());
2277
3514
  seq++;
3515
+ continue;
3516
+ }
3517
+ await writes.send(runs?.drain() ?? copies.drain());
3518
+ if (runs !== void 0) ownSeqs.push(seq + 1);
3519
+ if (!row.reference) await writes.send(this.entryWrites(header.id, [entry], seq, listed.texts, false));
3520
+ else if (row.inlineSnapshot) await this.writeInlineForkSnapshot(tx, reader, row.reference, header.id, seq, listed.texts, row.edits);
3521
+ else {
3522
+ copiedRows = true;
3523
+ const encoded = await encodedForkRow(reader, row);
3524
+ const chunks = Math.ceil(encoded.size / SESSION_ENTRY_CHUNK_BYTES);
3525
+ 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({
3526
+ type: entry.type,
3527
+ id: entry.id,
3528
+ parentId: entry.parentId ?? null
3529
+ }), chunks);
3530
+ let n = 0;
3531
+ let used = 0;
3532
+ let buffer = new Uint8Array(SESSION_ENTRY_CHUNK_BYTES);
3533
+ const write = async () => {
3534
+ await tx.run(`INSERT INTO ${this.tables.entryChunks} (session_id,seq,idx,data) VALUES (?,?,?,?)`, header.id, seq + 1, n++, buffer.subarray(0, used));
3535
+ used = 0;
3536
+ };
3537
+ for await (const part of encoded.chunks()) for (let start = 0; start < part.length;) {
3538
+ const count = Math.min(part.length - start, buffer.length - used);
3539
+ buffer.set(part.subarray(start, start + count), used);
3540
+ start += count;
3541
+ used += count;
3542
+ if (used === buffer.length) await write();
3543
+ }
3544
+ if (used) await write();
3545
+ if (n !== chunks) throw new StorageError("Incomplete historical entry in fork");
3546
+ await writes.send(this.entryWrites(header.id, [], seq, listed.texts, false));
2278
3547
  }
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]);
3548
+ seq++;
3549
+ }
3550
+ const last = [...runs?.drain() ?? copies.drain()];
3551
+ if (runs !== void 0) {
3552
+ assertForkSegments(header.id, runs.segments, seq);
3553
+ last.push(forkLineageWrite(lineage, header.id, {
3554
+ parentId: source.sessionId,
3555
+ cutSeq: head.lastSeq
3556
+ }));
3557
+ if (runs.segments.length > 0) for (const own of ownSeqs) last.push(this.forkLinks().entry(header.id, own));
3558
+ }
3559
+ const statement = this.summaryWrite(header.id, {
3560
+ header,
3561
+ entries: [],
3562
+ lastSeq: seq
3563
+ }, summary, index);
3564
+ last.push(statement.statement);
3565
+ if (!copiedRows && hashes.size === 0) {
3566
+ last.push(this.forkVersionStep(header.id));
3567
+ if (transactionFinisher(tx)?.(last) !== true) await writes.send(last);
2287
3568
  return {
2288
- remaining: await this.finishForkCopy(tx, writes, header.id, blobs.copy, hashes),
2289
- epoch: statement.epoch
3569
+ remaining: [],
3570
+ epoch: statement.epoch,
3571
+ finished: true
2290
3572
  };
2291
- });
2292
- await this.finishFork(tx, header.id);
3573
+ }
3574
+ await writes.send(last);
3575
+ blobs.copy = this.forkBlobCopy(source.sessionId, header.id, hashes);
2293
3576
  return {
2294
- lastSeq: seq,
2295
- epoch: remainingBlobs.epoch,
2296
- remainingBlobs: remainingBlobs.remaining
3577
+ remaining: await this.finishForkCopy(tx, writes, header.id, blobs.copy, hashes),
3578
+ epoch: statement.epoch,
3579
+ finished: false
2297
3580
  };
2298
- }, this.sessionWrite(header.id));
3581
+ });
3582
+ if (!remainingBlobs.finished) await this.finishFork(tx, header.id);
3583
+ return {
3584
+ lastSeq: seq,
3585
+ epoch: remainingBlobs.epoch,
3586
+ remainingBlobs: remainingBlobs.remaining
3587
+ };
3588
+ }
3589
+ /**
3590
+ * The donor `reads` read, when the fork made them, asked for at once: its reads then go out beside the schema check,
3591
+ * in one wait for the connection, as a `create`'s first read does. The fork uses it only once the schema it checks in
3592
+ * this transaction has shared history: a store that saw shared history may meet a database whose schema says
3593
+ * otherwise, and a fork there never names its source's rows. Unused, its failure is nobody's.
3594
+ */
3595
+ leadingForkDonor(tx, child, source, reads) {
3596
+ if (reads === void 0) return void 0;
3597
+ const read = this.sharedForkDonor(tx, child, source, reads);
3598
+ read.catch(() => {});
3599
+ return read;
3600
+ }
3601
+ /** Notes the sessions session `id`'s segments name, which a fork of it locks. */
3602
+ noteForkSources(id, sources) {
3603
+ this.forkSources.delete(id);
3604
+ this.forkSources.set(id, sources);
3605
+ while (this.forkSources.size > 16) this.forkSources.delete(this.forkSources.keys().next().value);
3606
+ }
3607
+ /** The fork tables of this store's database, which exist once it has shared history (#6560). */
3608
+ lineageTables() {
3609
+ return {
3610
+ sessions: this.tables.sessions,
3611
+ forkSegments: this.forkTables.forkSegments,
3612
+ forkLineage: this.forkTables.forkLineage
3613
+ };
3614
+ }
3615
+ /**
3616
+ * The reads that begin a fork of session `donor` into `child` with shared history (#6560), in order: whether the child
3617
+ * exists; the tombstones of the deleted sessions among the donor's sources, locked `key-share`; the rows of the donor
3618
+ * and of the sessions its segments name, as the statement starts or as this store last saw them, each locked
3619
+ * `key-share` in id order, unless the child exists, with the donor's watermark and generation, and with `withState`
3620
+ * its summary state; then the donor's segments, read once those locks are held.
3621
+ */
3622
+ sharedForkReads(child, donor, withState, ordered = false) {
3623
+ const ids = [.../* @__PURE__ */ new Set([donor, ...this.forkSources.get(donor) ?? []])].sort();
3624
+ const epoch = `COALESCE(${this.dialect.jsonText("summary_state", "epoch")}, ${this.dialect.jsonText("summary_state", "resume", "epoch")}, revision)`;
3625
+ const readers = ordered ? ` OR id IN (SELECT session_id FROM ${this.forkTables.forkSegments} WHERE source_id = ?)` : "";
3626
+ return {
3627
+ exists: this.newSessionRead(child),
3628
+ ...ordered ? { childTombstone: {
3629
+ sql: `SELECT session_id FROM ${this.forkTables.forkTombstones} WHERE session_id = ?${this.dialect.lockClause("update")}`,
3630
+ params: [child]
3631
+ } } : {},
3632
+ lock: {
3633
+ sql: `SELECT id, last_seq, CASE WHEN id = ? THEN ${epoch} END AS epoch${withState ? ", CASE WHEN id = ? THEN summary_state END AS summary_state" : ""}
3634
+ FROM ${this.tables.sessions} WHERE (${inJsonList(this.dialect, "id")}
3635
+ OR id IN (SELECT source_id FROM ${this.forkTables.forkSegments} WHERE session_id = ?)${readers})
3636
+ AND NOT EXISTS (SELECT 1 FROM ${this.tables.sessions} c WHERE c.id = ?) ORDER BY id${this.dialect.lockClause(ordered ? "update" : "key-share")}`,
3637
+ params: [
3638
+ donor,
3639
+ ...withState ? [donor] : [],
3640
+ JSON.stringify(ids),
3641
+ donor,
3642
+ ...ordered ? [child] : [],
3643
+ child
3644
+ ]
3645
+ },
3646
+ tombstones: {
3647
+ sql: `SELECT session_id FROM ${this.forkTables.forkTombstones} WHERE ${inJsonList(this.dialect, "session_id")}
3648
+ OR session_id IN (SELECT source_id FROM ${this.forkTables.forkSegments} WHERE session_id = ?)
3649
+ ORDER BY session_id${this.dialect.lockClause("key-share")}`,
3650
+ params: [JSON.stringify(ids), donor]
3651
+ },
3652
+ segments: {
3653
+ sql: `SELECT source_id, from_seq, to_seq, base_seq FROM ${this.forkTables.forkSegments} WHERE session_id = ? ORDER BY idx`,
3654
+ params: [donor]
3655
+ }
3656
+ };
3657
+ }
3658
+ /**
3659
+ * The donor of a fork with shared history (#6560), from `reads`: its watermark, as the locking read found it, is the
3660
+ * fork's cut-off. Throws `ForkSourcesMoved`, for the fork to run again, when the donor's segments name a session the
3661
+ * reads did not lock: the donor's segments changed since this store last forked it.
3662
+ */
3663
+ async sharedForkDonor(tx, child, source, reads) {
3664
+ const settle = (read) => read.then((value) => ({ value }), (error) => ({ error }));
3665
+ const existing = settle(tx.get(reads.exists.sql, ...reads.exists.params));
3666
+ const childTombstone = reads.childTombstone === void 0 ? void 0 : settle(tx.all(reads.childTombstone.sql, ...reads.childTombstone.params));
3667
+ const tombstones = settle(tx.all(reads.tombstones.sql, ...reads.tombstones.params));
3668
+ const locked = settle(tx.all(reads.lock.sql, ...reads.lock.params));
3669
+ const segmentRows = settle(tx.all(reads.segments.sql, ...reads.segments.params));
3670
+ for (const read of [
3671
+ existing,
3672
+ ...childTombstone === void 0 ? [] : [childTombstone],
3673
+ tombstones,
3674
+ locked,
3675
+ segmentRows
3676
+ ]) {
3677
+ const answer = await read;
3678
+ if ("error" in answer) throw answer.error;
3679
+ }
3680
+ const answer = (read) => read.value;
3681
+ const found = answer(await existing);
3682
+ if (found?.id != null) throw new SessionExistsError$1(child);
3683
+ const row = answer(await locked).find((candidate) => String(candidate.id) === source.sessionId);
3684
+ if (row === void 0) throw new SessionNotFoundError$1(source.sessionId);
3685
+ const segments = answer(await segmentRows).map((segment) => ({
3686
+ sourceId: String(segment.source_id),
3687
+ fromSeq: Number(segment.from_seq),
3688
+ toSeq: Number(segment.to_seq),
3689
+ baseSeq: Number(segment.base_seq)
3690
+ }));
3691
+ const sources = [...new Set(segments.map((segment) => segment.sourceId))].sort();
3692
+ this.noteForkSources(source.sessionId, sources);
3693
+ const lockedIds = /* @__PURE__ */ new Set([...answer(await locked).map((candidate) => String(candidate.id)), ...answer(await tombstones).map((candidate) => String(candidate.session_id))]);
3694
+ if (sources.some((id) => !lockedIds.has(id))) throw new ForkSourcesMoved();
3695
+ const lastSeq = Number(row.last_seq);
3696
+ const epoch = String(row.epoch);
3697
+ if (source.epoch !== void 0 && epoch !== source.epoch) throw new SessionConflictError$1(source.sessionId, 0, lastSeq);
3698
+ return {
3699
+ lastSeq,
3700
+ epoch,
3701
+ segments,
3702
+ child: found,
3703
+ ordered: reads.childTombstone !== void 0,
3704
+ ...typeof row.summary_state === "string" ? { state: JSON.parse(row.summary_state) } : {}
3705
+ };
3706
+ }
3707
+ /**
3708
+ * A fork with shared history of the donor's whole view as it stands (#6560): its segments, its lineage and its
3709
+ * session row, whose summary is the donor's in a generation of its own, and no row of any entry. Undefined, for
3710
+ * the fork to read the donor's rows, when the donor's resume index does not cover its watermark.
3711
+ */
3712
+ async writeSharedPrefixFork(tx, header, donorId, donor) {
3713
+ const index = donor.state === void 0 ? void 0 : windowIndex(donor.state, donor.lastSeq);
3714
+ if (donor.state === void 0 || index === void 0) return void 0;
3715
+ const epoch = newRevision();
3716
+ const segments = prefixForkSegments(donorId, donor.segments, donor.lastSeq, donor.lastSeq);
3717
+ const { resume: _resume, windowResume: _window, epoch: _epoch, ...listed } = donor.state;
3718
+ const summary = this.summaryWrite(header.id, {
3719
+ header,
3720
+ entries: [],
3721
+ lastSeq: donor.lastSeq
3722
+ }, {
3723
+ ...listed,
3724
+ epoch
3725
+ }, {
3726
+ ...index,
3727
+ epoch
3728
+ });
3729
+ const lineage = this.lineageTables();
3730
+ assertForkSegments(header.id, segments, donor.lastSeq);
3731
+ const statements = [
3732
+ ...forkSegmentInserts(lineage, header.id, 0, segments),
3733
+ forkLineageWrite(lineage, header.id, {
3734
+ parentId: donorId,
3735
+ cutSeq: donor.lastSeq
3736
+ }),
3737
+ summary.statement
3738
+ ];
3739
+ if (transactionFinisher(tx)?.(statements) !== true) for (const { sql, params } of statements) await tx.run(sql, ...params);
3740
+ return {
3741
+ lastSeq: donor.lastSeq,
3742
+ epoch: summary.epoch,
3743
+ remainingBlobs: []
3744
+ };
2299
3745
  }
2300
3746
  /**
2301
3747
  * `readEntryChunk` for a fork's reader bound to transaction `tx`, reading session `source` in generation `epoch`: a
@@ -2303,7 +3749,7 @@ var SqlSessionStore = class SqlSessionStore {
2303
3749
  * 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
3750
  * source's row, so its generation cannot change meanwhile. Other reads go to `reader` as before.
2305
3751
  */
2306
- forkChunkReader(tx, reader, source, epoch) {
3752
+ forkChunkReader(tx, tables, reader, source, epoch) {
2307
3753
  const json = this.dialect.name === "sqlite" ? "CAST(e.entry_json AS BLOB)" : "convert_to(e.entry_json, 'UTF8')";
2308
3754
  let held;
2309
3755
  return async (reference, offset, bytes = SESSION_HISTORY_CHUNK_BYTES) => {
@@ -2311,10 +3757,11 @@ var SqlSessionStore = class SqlSessionStore {
2311
3757
  const part = Math.floor(offset / SESSION_ENTRY_CHUNK_BYTES);
2312
3758
  const start = part * SESSION_ENTRY_CHUNK_BYTES;
2313
3759
  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 = ?)
3760
+ const view = this.entriesView(tables, source, reference.seq - 1, reference.seq);
3761
+ const row = await tx.get(withForkViews([view], `SELECT CASE WHEN e.chunks > 0
3762
+ THEN (SELECT c.data FROM ${this.tables.entryChunks} c WHERE c.session_id = e.src_id AND c.seq = e.src_seq AND c.idx = ?)
2316
3763
  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);
3764
+ FROM ${view.name} e`), ...view.params, part, start + 1, SESSION_ENTRY_CHUNK_BYTES);
2318
3765
  if (row?.data == null || row.data.byteLength <= offset - start) return SqlSessionStore.prototype.readEntryChunk.call(reader, reference, offset, bytes);
2319
3766
  held = {
2320
3767
  seq: reference.seq,
@@ -2337,10 +3784,18 @@ var SqlSessionStore = class SqlSessionStore {
2337
3784
  } : original], seq, texts, false);
2338
3785
  }
2339
3786
  async append(sessionId, entries, options) {
3787
+ return this.writing(sessionId, this.writeAppend(sessionId, entries, options));
3788
+ }
3789
+ async writeAppend(sessionId, entries, options) {
2340
3790
  this.assertOpen();
2341
3791
  validateSessionText("sessionId", sessionId);
2342
- return this.transactionCheckedAlongside(async (tx, checked) => {
2343
- const { row: previous, state: summaryState } = await this.forWrite(tx, sessionId, options, true);
3792
+ const fast = await this.appendThroughFunction(sessionId, entries, options);
3793
+ if (fast !== void 0) return fast;
3794
+ let written = [];
3795
+ let writtenRow;
3796
+ const appended = await this.transactionCheckedAlongside(async (tx, checked) => {
3797
+ writtenRow = void 0;
3798
+ const { row: previous, state: summaryState } = await this.forWrite(tx, sessionId, options, true, true);
2344
3799
  validateSessionEntries(entries);
2345
3800
  await this.blobTable.assertStored(tx, entries.flatMap((entry) => entry.type === "worktree_snapshot" && entry.snapshot !== void 0 ? [entry.snapshot] : []));
2346
3801
  const lastSeq = previous.last_seq + entries.length;
@@ -2349,20 +3804,256 @@ var SqlSessionStore = class SqlSessionStore {
2349
3804
  entries,
2350
3805
  lastSeq
2351
3806
  }, summaryState, await this.appendedResume(tx, sessionId, windowIndex(summaryState, previous.last_seq), previous.last_seq, entries));
2352
- const written = this.entryWrites(sessionId, entries, previous.last_seq, summary.texts);
3807
+ written = [];
3808
+ const statements = this.entryWrites(sessionId, entries, previous.last_seq, summary.texts, true, written);
2353
3809
  await checked;
2354
- await this.writeEntries(tx, summary.statement, written);
2355
- return { lastSeq };
2356
- }, this.sessionWrite(sessionId, this.headRead(sessionId, options, true)));
3810
+ const forked = previous.forked !== void 0 ? Number(previous.forked) === 1 : await this.sharedHistoryForks(tx) && await this.hasForkSegments(tx, sessionId);
3811
+ writtenRow = forked ? void 0 : summary.row;
3812
+ const links = forked ? entries.map((_, index) => this.forkLinks().entry(sessionId, previous.last_seq + index + 1)) : [];
3813
+ await this.writeEntries(tx, summary.statement, links.length === 0 ? statements : thenAll(statements, links));
3814
+ return {
3815
+ lastSeq,
3816
+ epoch: summary.epoch
3817
+ };
3818
+ }, this.sessionWrite(sessionId, this.headRead(sessionId, options, true, true)));
3819
+ this.noteWritten(sessionId, appended.epoch, written);
3820
+ this.rememberWritten(sessionId, writtenRow);
3821
+ return { lastSeq: appended.lastSeq };
3822
+ }
3823
+ /**
3824
+ * Remembers `row`, the session's row a committed write of this store left, for the next append to plan from, where
3825
+ * appends go through the append function; forgets the session's row when `row` is undefined. At most
3826
+ * {@link WRITTEN_ROWS} sessions are remembered, the latest written.
3827
+ */
3828
+ rememberWritten(sessionId, row) {
3829
+ this.writtenRows.delete(sessionId);
3830
+ if (row === void 0 || this.appendFunction === void 0) return;
3831
+ this.writtenRows.set(sessionId, row);
3832
+ while (this.writtenRows.size > WRITTEN_ROWS) this.writtenRows.delete(this.writtenRows.keys().next().value);
3833
+ }
3834
+ /**
3835
+ * Appends `entries` in one round trip through the session append function, planned from the row this store's last
3836
+ * write of the session left (#6599). The function takes the session's locks as a session write transaction does,
3837
+ * checks the schema version, the session and its expected seq as `forWrite` does, writes nothing unless the stored
3838
+ * row is still the one planned from, checks the snapshot blobs as `assertStored` does, and writes the row, the
3839
+ * entries and their search texts in the order an append's transaction does. Undefined, having written nothing, when
3840
+ * the append is not one it plans (no function, no remembered row, a row other than the stored one, invalid entries,
3841
+ * a chunked entry or more than one batch of writes, an entry that refers back past the resume window): the caller
3842
+ * then appends in a transaction as before, which reads the row itself and reports what fails.
3843
+ */
3844
+ async appendThroughFunction(sessionId, entries, options) {
3845
+ const fn = this.appendFunction;
3846
+ const autocommit = this.database.autocommit?.bind(this.database);
3847
+ const previous = this.writtenRows.get(sessionId);
3848
+ if (fn === void 0 || autocommit === void 0 || previous === void 0) return void 0;
3849
+ if (previous.last_seq !== options.expectSeq) return void 0;
3850
+ const state = JSON.parse(previous.summary_state);
3851
+ if (options.epoch !== void 0 && state.epoch !== options.epoch) return void 0;
3852
+ try {
3853
+ validateSessionEntries(entries);
3854
+ } catch {
3855
+ return;
3856
+ }
3857
+ const window = windowIndex(state, previous.last_seq);
3858
+ if (isSessionResumeIndex(window, previous.last_seq) && foreignResumeIds(window, entries).length > 0) return void 0;
3859
+ const lastSeq = previous.last_seq + entries.length;
3860
+ const summary = this.summaryWrite(sessionId, {
3861
+ header: JSON.parse(previous.header_json),
3862
+ entries,
3863
+ lastSeq
3864
+ }, state, await this.appendedResume(this.database, sessionId, window, previous.last_seq, entries));
3865
+ const rows = [];
3866
+ const written = [];
3867
+ let bytes = statementBytes(summary.statement);
3868
+ for (const [index, entry] of entries.entries()) {
3869
+ const json = this.encode(entry);
3870
+ const stored = storedEntry(entry, json);
3871
+ bytes += entry.id.length + stored.json.length;
3872
+ if (stored.chunks.length > 0 || bytes > STATEMENT_BATCH_BYTES) return void 0;
3873
+ rows.push([entry.id, stored.json]);
3874
+ written.push({
3875
+ entry,
3876
+ seq: previous.last_seq + index + 1,
3877
+ json
3878
+ });
3879
+ }
3880
+ const texts = summary.texts.map(({ index, text }) => [previous.last_seq + index + 1, this.encode(text)]);
3881
+ const blobs = this.blobTable.storedHashes(entries.flatMap((entry) => entry.type === "worktree_snapshot" && entry.snapshot !== void 0 ? [entry.snapshot] : []));
3882
+ const { concurrency = { kind: "serial" } } = sessionWriteTransaction(this.tables.sessions, sessionId);
3883
+ const [answer] = await autocommit({
3884
+ sql: `SELECT outcome, detail FROM ${fn}(${Array.from({ length: 24 }, () => "?").join(", ")})`,
3885
+ params: [
3886
+ concurrency.kind === "serial" ? concurrency.domain ?? "" : "",
3887
+ SESSION_SCHEMA_VERSION_UNCHUNKED,
3888
+ 3,
3889
+ sessionId,
3890
+ previous.last_seq,
3891
+ previous.revision,
3892
+ await sha256Hex(new TextEncoder().encode(`${previous.header_json}\n${previous.summary_state}`)),
3893
+ blobs.length === 0 ? null : JSON.stringify(blobs),
3894
+ ...summary.statement.params.slice(1),
3895
+ JSON.stringify(rows),
3896
+ JSON.stringify(texts)
3897
+ ]
3898
+ }, concurrency);
3899
+ switch (answer?.outcome) {
3900
+ case "appended":
3901
+ this.noteWritten(sessionId, summary.epoch, written);
3902
+ this.rememberWritten(sessionId, summary.row);
3903
+ return { lastSeq };
3904
+ case "version":
3905
+ assertStorageSchemaVersion("sessions", answer.detail === null ? null : Number(answer.detail), 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
3906
+ break;
3907
+ case "missing": throw new SessionNotFoundError$1(sessionId);
3908
+ case "conflict": throw new SessionConflictError$1(sessionId, options.expectSeq, Number(answer.detail));
3909
+ case "blob": return this.blobTable.refuseCollected(String(answer.detail));
3910
+ }
3911
+ this.writtenRows.delete(sessionId);
3912
+ }
3913
+ /**
3914
+ * The session append function of the store's tables, `<prefix>session_append_v1`: one statement, and so one round
3915
+ * trip, for what an append's transaction does with its two (#6599). Created by `atomic storage migrate` through
3916
+ * {@link prepareAppendFunction}. It runs with the caller's rights, so it lets a role do nothing its table
3917
+ * privileges do not, and in the caller's `search_path`, the schema a transaction of the store sets. It writes no
3918
+ * chunked entry: an append that has one goes through a transaction. Its answer is one row: `appended`, or why it
3919
+ * wrote nothing, with the stored version (`version`), the stored last seq (`conflict`), the first blob that is not
3920
+ * stored (`blob`), no session (`missing`), or a stored row other than the one the caller planned from (`stale`).
3921
+ */
3922
+ appendFunctionSql(fn) {
3923
+ const t = this.tables;
3924
+ return `CREATE OR REPLACE FUNCTION ${fn}(
3925
+ p_domain text, p_oldest bigint, p_newest bigint, p_session_id text, p_expect_seq bigint, p_revision text,
3926
+ p_digest text, p_blobs text, p_cwd text, p_created_at text, p_header_json text, p_internal bigint, p_last_seq bigint,
3927
+ p_modified_at text, p_message_count bigint, p_first_message text, p_name text, p_has_name bigint, p_summary text,
3928
+ p_summarized_through_id text, p_summary_state text, p_new_revision text, p_entries text, p_texts text
3929
+ ) RETURNS TABLE (outcome text, detail text) LANGUAGE plpgsql AS $append$
3930
+ #variable_conflict use_column
3931
+ DECLARE
3932
+ scope text := CASE WHEN current_schema() = 'public' THEN '' ELSE current_schema() || ':' END;
3933
+ stored_version bigint;
3934
+ head record;
3935
+ stored_blobs text[];
3936
+ missing_blob text;
3937
+ BEGIN
3938
+ -- The locks of a session write transaction, waited for as long as one waits: its lock wait is the statement timeout.
3939
+ PERFORM set_config('lock_timeout', current_setting('statement_timeout'), true);
3940
+ PERFORM pg_advisory_xact_lock_shared(hashtextextended(scope || 'atomic', 0)),
3941
+ pg_advisory_xact_lock(hashtextextended(scope || p_domain, 0));
3942
+ SELECT schema_version INTO stored_version FROM ${t.meta};
3943
+ IF stored_version IS NULL OR stored_version < p_oldest OR stored_version > p_newest THEN
3944
+ RETURN QUERY SELECT 'version'::text, stored_version::text;
3945
+ RETURN;
3946
+ END IF;
3947
+ SELECT s.last_seq, s.revision,
3948
+ encode(sha256(convert_to(s.header_json || E'\n' || s.summary_state, 'UTF8')), 'hex') AS digest
3949
+ INTO head FROM ${t.sessions} AS s WHERE s.id = p_session_id;
3950
+ IF NOT FOUND THEN
3951
+ RETURN QUERY SELECT 'missing'::text, NULL::text;
3952
+ RETURN;
3953
+ END IF;
3954
+ IF head.last_seq <> p_expect_seq THEN
3955
+ RETURN QUERY SELECT 'conflict'::text, head.last_seq::text;
3956
+ RETURN;
3957
+ END IF;
3958
+ IF head.revision <> p_revision OR head.digest <> p_digest THEN
3959
+ RETURN QUERY SELECT 'stale'::text, NULL::text;
3960
+ RETURN;
3961
+ END IF;
3962
+ IF p_blobs IS NOT NULL THEN
3963
+ SELECT array_agg(locked.hash) INTO stored_blobs FROM (${this.blobTable.storedBlobsQuery("p_blobs")}) AS locked;
3964
+ SELECT h.value INTO missing_blob FROM json_array_elements_text(p_blobs::json) WITH ORDINALITY AS h(value, ord)
3965
+ WHERE h.value <> ALL (coalesce(stored_blobs, '{}'::text[])) ORDER BY h.ord LIMIT 1;
3966
+ IF missing_blob IS NOT NULL THEN
3967
+ RETURN QUERY SELECT 'blob'::text, missing_blob;
3968
+ RETURN;
3969
+ END IF;
3970
+ END IF;
3971
+ INSERT INTO ${t.sessions}
3972
+ (id, cwd, created_at, header_json, internal, last_seq, modified_at, message_count,
3973
+ first_message, name, has_name, summary, summarized_through_id, summary_state, revision)
3974
+ VALUES (p_session_id, p_cwd, p_created_at, p_header_json, p_internal, p_last_seq, p_modified_at, p_message_count,
3975
+ p_first_message, p_name, p_has_name, p_summary, p_summarized_through_id, p_summary_state, p_new_revision)
3976
+ ON CONFLICT(id) DO UPDATE SET
3977
+ cwd = excluded.cwd, created_at = excluded.created_at, header_json = excluded.header_json,
3978
+ internal = excluded.internal, last_seq = excluded.last_seq, modified_at = excluded.modified_at,
3979
+ message_count = excluded.message_count, first_message = excluded.first_message, name = excluded.name,
3980
+ has_name = excluded.has_name, summary = excluded.summary,
3981
+ summarized_through_id = excluded.summarized_through_id,
3982
+ summary_state = excluded.summary_state, revision = excluded.revision;
3983
+ INSERT INTO ${t.entries} (session_id, seq, entry_id, entry_json, chunks)
3984
+ SELECT p_session_id, p_expect_seq + e.ord, e.value->>0, e.value->>1, 0
3985
+ FROM json_array_elements(p_entries::json) WITH ORDINALITY AS e(value, ord) ORDER BY e.ord;
3986
+ INSERT INTO ${t.searchTexts} (session_id, seq, text_json)
3987
+ SELECT p_session_id, (x.value->>0)::bigint, x.value->>1
3988
+ FROM json_array_elements(p_texts::json) WITH ORDINALITY AS x(value, ord) ORDER BY x.ord;
3989
+ RETURN QUERY SELECT 'appended'::text, NULL::text;
3990
+ END
3991
+ $append$`;
3992
+ }
3993
+ /**
3994
+ * Creates the session append function (#6599), once per revision, as the ledger records it, and lets every role that
3995
+ * may insert into the sessions table execute it: `atomic storage migrate` runs this as the owner role, and a
3996
+ * runtime role appends through the function from its next open on. PostgreSQL only; does nothing elsewhere.
3997
+ */
3998
+ async prepareAppendFunction() {
3999
+ this.assertOpen();
4000
+ if (this.dialect.name !== "postgres") return;
4001
+ const fn = renderStorageIdentifiers("sessions", { append: SESSION_APPEND_FUNCTION }, this.prefix).append;
4002
+ const ledger = storageMigrationTable(this.prefix);
4003
+ const physical = (name) => this.dialect.identifier(name).replaceAll("'", "''");
4004
+ await this.database.transaction(async (tx) => {
4005
+ await ensureStorageSchema(tx, this.dialect, {
4006
+ ledger,
4007
+ domain: SESSION_APPEND_FUNCTION_DOMAIN,
4008
+ revision: SESSION_APPEND_FUNCTION_REVISION
4009
+ }, () => tx.exec(this.appendFunctionSql(fn)));
4010
+ await tx.exec(`DO $grant$
4011
+ DECLARE grantee text;
4012
+ BEGIN
4013
+ FOR grantee IN SELECT DISTINCT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE quote_ident(pg_catalog.pg_get_userbyid(a.grantee)) END
4014
+ FROM pg_catalog.pg_class c, pg_catalog.aclexplode(c.relacl) AS a
4015
+ WHERE c.relnamespace = current_schema()::regnamespace AND c.relname = '${physical(this.tables.sessions)}'
4016
+ AND a.privilege_type = 'INSERT' AND a.grantee <> c.relowner
4017
+ LOOP
4018
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I TO %s', '${physical(fn)}', grantee);
4019
+ END LOOP;
4020
+ END
4021
+ $grant$`);
4022
+ }, {
4023
+ retryTransientFailures: true,
4024
+ concurrency: {
4025
+ kind: "serial",
4026
+ domain: ledger
4027
+ }
4028
+ });
2357
4029
  }
2358
4030
  async replace(sessionId, header, entries, options) {
4031
+ return this.writing(sessionId, this.writeReplace(sessionId, header, entries, options));
4032
+ }
4033
+ async writeReplace(sessionId, header, entries, options) {
2359
4034
  this.assertOpen();
2360
4035
  validateSessionText("sessionId", sessionId);
2361
- return this.transaction(async (tx) => {
2362
- await this.forWrite(tx, sessionId, options);
4036
+ this.writtenRows.delete(sessionId);
4037
+ let released = [];
4038
+ let entriesWritten = [];
4039
+ const pinReads = this.sharedHistorySeen ? forkPinReads(this.forkHost(), this.tables.sessions, sessionId, true) : void 0;
4040
+ const searchLock = this.searchIndex?.writeLock(sessionId);
4041
+ const run = (lockLate) => this.transactionCheckedAlongside(async (tx, checked) => {
4042
+ released = [];
4043
+ entriesWritten = [];
4044
+ const [, , pins] = await Promise.all([
4045
+ searchLock === void 0 ? void 0 : tx.get(searchLock.sql, ...searchLock.params),
4046
+ this.forWrite(tx, sessionId, options),
4047
+ this.readForkPinsWithin(tx, sessionId, pinReads, true)
4048
+ ]);
4049
+ await checked;
2363
4050
  validateSessionHeader(header);
2364
4051
  validateSessionEntries(entries);
2365
4052
  if (header.id !== sessionId) throw new SessionIdMismatchError$1(sessionId, header.id);
4053
+ if (pins !== void 0) released = await replaceForkedSessionWithin(this.forkHost(), tx, sessionId, pins, lockLate).catch((error) => {
4054
+ noteForkCopyRefusal(error, "replace");
4055
+ throw error;
4056
+ });
2366
4057
  await this.searchIndex?.forgetWithin(tx, sessionId);
2367
4058
  await tx.run(`DELETE FROM ${this.tables.searchTexts} WHERE session_id = ?`, sessionId);
2368
4059
  await tx.run(`DELETE FROM ${this.tables.entryChunks} WHERE session_id = ?`, sessionId);
@@ -2372,16 +4063,30 @@ var SqlSessionStore = class SqlSessionStore {
2372
4063
  entries,
2373
4064
  lastSeq: entries.length
2374
4065
  });
2375
- await this.insertEntries(tx, sessionId, entries, 0, texts);
4066
+ await this.insertEntries(tx, sessionId, entries, 0, texts, true, entriesWritten);
2376
4067
  return {
2377
4068
  lastSeq: entries.length,
2378
4069
  epoch
2379
4070
  };
2380
- }, this.sessionWrite(sessionId));
4071
+ }, this.sessionWrite(sessionId, ...searchLock === void 0 ? [] : [searchLock], ...pinReads === void 0 ? [] : [this.headRead(sessionId, options, false), ...pinReads]));
4072
+ let written;
4073
+ for (let attempt = 0;; attempt++) try {
4074
+ written = await run(attempt >= 3);
4075
+ break;
4076
+ } catch (error) {
4077
+ if (!(error instanceof ForkReadersMoved)) throw error;
4078
+ }
4079
+ this.noteWritten(sessionId, written.epoch, entriesWritten);
4080
+ await this.sweepReleasedForkRows(released);
4081
+ return written;
2381
4082
  }
2382
4083
  async updateHeader(header, options) {
4084
+ return this.writing(header.id, this.writeUpdateHeader(header, options));
4085
+ }
4086
+ async writeUpdateHeader(header, options) {
2383
4087
  this.assertOpen();
2384
4088
  validateSessionHeader(header);
4089
+ this.writtenRows.delete(header.id);
2385
4090
  return this.transaction(async (tx) => {
2386
4091
  const { row, state } = await this.forWrite(tx, header.id, options, true);
2387
4092
  const epoch = newRevision();
@@ -2411,7 +4116,7 @@ var SqlSessionStore = class SqlSessionStore {
2411
4116
  const row = await this.database.get(`SELECT last_seq FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
2412
4117
  if (row) announceHistoryLoad(row.last_seq);
2413
4118
  }
2414
- return this.readTransaction((tx) => this.read(tx, sessionId));
4119
+ return this.readTransaction(sessionId, (tx) => this.read(tx, sessionId));
2415
4120
  }
2416
4121
  async readEntryRange(sessionId, query) {
2417
4122
  this.assertOpen();
@@ -2421,15 +4126,19 @@ var SqlSessionStore = class SqlSessionStore {
2421
4126
  const skippedSet = query.skipTypes === void 0 ? void 0 : new Set(query.skipTypes);
2422
4127
  const skippedPrefixes = (query.skipTypes ?? []).map((type) => `{"type":${JSON.stringify(type)},`);
2423
4128
  const largeBytes = query.largeEntryBytes ?? 0x7fffffff;
2424
- const read = await this.database.all(`WITH sized AS (
2425
- SELECT seq, chunks, ${this.entryByteLength("entry_json")} AS raw_bytes,
4129
+ const selected = query.seqs === void 0 ? "" : ` AND seq IN (SELECT CAST(value AS ${this.dialect.types.int}) FROM ${this.dialect.jsonValues("?")})`;
4130
+ const fitted = query.seqs === void 0 ? "" : " AND (p.before_chars = 0 OR p.before_chars + p.bytes <= ?)";
4131
+ const maxChars = query.maxChars !== void 0 && query.maxChars <= 0 ? 0 : query.maxChars ?? Number.MAX_SAFE_INTEGER;
4132
+ const read = await this.outsideSessionRead(sessionId, (tables) => {
4133
+ const view = this.entriesView(tables, sessionId, fromSeq - 1, Math.min(query.toSeq, FORK_VIEW_END));
4134
+ return this.database.all(withForkViews([view], `WITH sized AS (
4135
+ SELECT seq, chunks, src_id, src_seq, ${this.entryByteLength("entry_json")} AS raw_bytes,
2426
4136
  ${this.entryByteLength("entry_json")} + chunks * ? AS bytes
2427
- FROM ${this.tables.entries}
2428
- WHERE session_id = ? AND seq >= ? AND seq <= ?
2429
- AND seq <= (SELECT last_seq FROM ${this.tables.sessions} WHERE id = ?)
4137
+ FROM ${view.name}
4138
+ WHERE seq <= (SELECT last_seq FROM ${this.tables.sessions} WHERE id = ?)${selected}
2430
4139
  ),
2431
4140
  paged AS (
2432
- SELECT seq, chunks, raw_bytes, count(*) OVER () AS remaining,
4141
+ SELECT seq, chunks, src_id, src_seq, raw_bytes, bytes, count(*) OVER () AS remaining,
2433
4142
  sum(bytes) OVER (ORDER BY seq) - bytes AS before_chars
2434
4143
  FROM sized
2435
4144
  ),
@@ -2439,13 +4148,19 @@ var SqlSessionStore = class SqlSessionStore {
2439
4148
  CASE WHEN p.chunks = 0 AND p.raw_bytes > ? AND substr(e.entry_json, 1, 8) <> '{"type":'
2440
4149
  THEN ${this.dialect.jsonText("e.entry_json", "type")} END AS entry_type
2441
4150
  FROM paged p
2442
- JOIN ${this.tables.entries} e ON e.session_id = ? AND e.seq = p.seq
2443
- WHERE p.before_chars < ?
4151
+ JOIN ${this.tables.entries} e ON e.session_id = p.src_id AND e.seq = p.src_seq
4152
+ WHERE p.before_chars < ?${fitted}
2444
4153
  )
2445
- SELECT s.last_seq, page.seq, page.entry_json, page.entry_head, page.chunks, page.remaining, page.entry_type
4154
+ SELECT s.last_seq, page.seq, page.entry_json, page.entry_head, page.chunks, page.remaining, page.entry_type${this.outsideForkedColumn("s.id")}
2446
4155
  FROM ${this.tables.sessions} s LEFT JOIN page ON 1 = 1
2447
4156
  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);
4157
+ ORDER BY page.seq`), ...view.params, SESSION_ENTRY_CHUNK_BYTES, sessionId, ...query.seqs === void 0 ? [] : [JSON.stringify(query.seqs)], largeBytes, largeBytes, maxChars, ...query.seqs === void 0 ? [] : [maxChars], sessionId);
4158
+ }, (found) => {
4159
+ const session = found[0];
4160
+ if (session === void 0 || maxChars <= 0) return true;
4161
+ if (fromSeq > Math.min(query.toSeq, Number(session.last_seq))) return true;
4162
+ return found.some((row) => row.seq !== null && row.seq !== void 0);
4163
+ }, (found) => found[0]?.forked);
2449
4164
  const session = read[0];
2450
4165
  if (!session) throw new SessionNotFoundError$1(sessionId);
2451
4166
  const lastSeq = Number(session.last_seq);
@@ -2468,7 +4183,7 @@ var SqlSessionStore = class SqlSessionStore {
2468
4183
  const seq = Number(row.seq);
2469
4184
  const chunks = Number(row.chunks);
2470
4185
  if (chunks > 0) {
2471
- const rawChunks = await this.readRawEntryChunks(this.database, sessionId, seq, chunks, query.signal);
4186
+ const rawChunks = await this.readRawEntryChunks(this.database, void 0, sessionId, seq, chunks, query.signal);
2472
4187
  if (rawChunks.reduce((total, chunk) => total + chunk.byteLength, 0) > largeBytes) entries.push({
2473
4188
  seq,
2474
4189
  entry: STUB_ENTRY,
@@ -2511,17 +4226,59 @@ var SqlSessionStore = class SqlSessionStore {
2511
4226
  return row ? JSON.parse(row.header_json) : void 0;
2512
4227
  }
2513
4228
  async delete(sessionId) {
4229
+ return this.writing(sessionId, this.writeDelete(sessionId));
4230
+ }
4231
+ async writeDelete(sessionId) {
2514
4232
  this.assertOpen();
2515
4233
  validateSessionText("sessionId", sessionId);
2516
- await this.transaction(async (tx) => {
4234
+ this.writtenRows.delete(sessionId);
4235
+ let released = [];
4236
+ const pinReads = this.sharedHistorySeen ? forkPinReads(this.forkHost(), this.tables.sessions, sessionId) : void 0;
4237
+ await this.transactionCheckedAlongside(async (tx, checked) => {
4238
+ released = [];
4239
+ const pins = await this.readForkPinsWithin(tx, sessionId, pinReads);
4240
+ await checked;
2517
4241
  await this.searchIndex?.forgetWithin(tx, sessionId);
4242
+ if (pins !== void 0) {
4243
+ const pinned = await deleteForkedSessionWithin(this.forkHost(), tx, sessionId, (/* @__PURE__ */ new Date()).toISOString(), pins);
4244
+ released = pinned.released;
4245
+ if (pinned.keepRows) {
4246
+ await tx.run(`DELETE FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
4247
+ return;
4248
+ }
4249
+ }
2518
4250
  await tx.run(`DELETE FROM ${this.tables.blobChunks} WHERE session_id = ?`, sessionId);
2519
4251
  await tx.run(`DELETE FROM ${this.tables.blobs} WHERE session_id = ?`, sessionId);
2520
4252
  await tx.run(`DELETE FROM ${this.tables.searchTexts} WHERE session_id = ?`, sessionId);
2521
4253
  await tx.run(`DELETE FROM ${this.tables.entryChunks} WHERE session_id = ?`, sessionId);
2522
4254
  await tx.run(`DELETE FROM ${this.tables.entries} WHERE session_id = ?`, sessionId);
2523
4255
  await tx.run(`DELETE FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
2524
- }, SESSION_TRANSACTION);
4256
+ }, pinReads === void 0 ? SESSION_TRANSACTION : {
4257
+ ...SESSION_TRANSACTION,
4258
+ leading: pinReads
4259
+ });
4260
+ await this.sweepReleasedForkRows(released);
4261
+ }
4262
+ /**
4263
+ * The fork history of `sessionId` where the transaction `tx` runs on shared history: through `reads`, the transaction's
4264
+ * leading reads, or, for a store that had not seen shared history when the transaction began, read now.
4265
+ */
4266
+ async readForkPinsWithin(tx, sessionId, reads, readers = false) {
4267
+ if (reads !== void 0) return readForkPins(tx, reads);
4268
+ if (!await this.sharedHistoryForks(tx)) return void 0;
4269
+ return readForkPins(tx, forkPinReads(this.forkHost(), this.tables.sessions, sessionId, readers));
4270
+ }
4271
+ /**
4272
+ * Removes the rows of deleted sessions no fork reads any more, among `released` and any an earlier sweep left, in
4273
+ * transactions of their own after the write that released them committed. A sweep that fails leaves tombstones the
4274
+ * next one finishes: the write it follows stands either way.
4275
+ */
4276
+ async sweepReleasedForkRows(released) {
4277
+ if (released.length === 0) return;
4278
+ const { sweepForkTombstones } = await import("../core/storage/session/fork-sweep.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
4279
+ try {
4280
+ await sweepForkTombstones(this.forkHost(), released);
4281
+ } catch {}
2525
4282
  }
2526
4283
  /**
2527
4284
  * Stores the blob as rows of at most {@link SESSION_BLOB_CHUNK_BYTES}, then publishes its header. Every statement
@@ -2538,7 +4295,13 @@ var SqlSessionStore = class SqlSessionStore {
2538
4295
  hash: await sha256Hex(stored),
2539
4296
  bytes: stored.byteLength
2540
4297
  };
2541
- const previous = await this.blobHeader(sessionId, blob.hash);
4298
+ const found = await this.database.get(`SELECT (SELECT max(schema_version) FROM ${this.tables.meta}) AS schema_version, b.bytes, b.chunks
4299
+ FROM (SELECT 1 AS one) AS probe LEFT JOIN ${this.tables.blobs} b ON b.session_id = ? AND b.hash = ?`, sessionId, blob.hash);
4300
+ assertStorageSchemaVersion("sessions", found?.schema_version ?? null, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
4301
+ const previous = found?.bytes === null || found?.bytes === void 0 ? void 0 : {
4302
+ bytes: Number(found.bytes),
4303
+ chunks: Number(found.chunks)
4304
+ };
2542
4305
  if (previous) {
2543
4306
  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));
2544
4307
  return blob;
@@ -2563,36 +4326,68 @@ var SqlSessionStore = class SqlSessionStore {
2563
4326
  async getBlob(sessionId, hash) {
2564
4327
  this.assertOpen();
2565
4328
  validateSessionText("sessionId", sessionId);
2566
- let header = await this.blobHeader(sessionId, hash);
2567
- if (header === void 0) return void 0;
2568
- if (header.chunks === -1) {
2569
- const row = await this.database.get(`SELECT data FROM ${this.tables.blobs} WHERE session_id = ? AND hash = ? AND chunks = -1`, sessionId, hash);
2570
- if (row) {
2571
- if (row.data.byteLength === header.bytes) return row.data;
2572
- throw new SessionBlobError("blob-incomplete", {
2573
- sessionId,
2574
- hash,
2575
- bytes: header.bytes
2576
- });
2577
- }
2578
- header = await this.blobHeader(sessionId, hash);
4329
+ for (let attempt = 0;; attempt++) {
4330
+ const header = await this.blobOwner(sessionId, hash);
2579
4331
  if (header === void 0) return void 0;
4332
+ const { owner } = header;
4333
+ if (header.chunks === -1) {
4334
+ const row = await this.database.get(`SELECT data FROM ${this.tables.blobs} WHERE session_id = ? AND hash = ? AND chunks = -1`, owner, hash);
4335
+ if (row) {
4336
+ if (row.data.byteLength === header.bytes) return row.data;
4337
+ throw new SessionBlobError("blob-incomplete", {
4338
+ sessionId,
4339
+ hash,
4340
+ bytes: header.bytes
4341
+ });
4342
+ }
4343
+ if (attempt < 2) continue;
4344
+ return;
4345
+ }
4346
+ const data = new Uint8Array(header.bytes);
4347
+ let offset = 0;
4348
+ for (let index = 0; index < header.chunks; index++) {
4349
+ const row = await this.database.get(`SELECT data FROM ${this.tables.blobChunks} WHERE idx = ? AND session_id = ? AND hash = ?`, index, owner, hash);
4350
+ if (row?.data == null || offset + row.data.byteLength > data.byteLength) break;
4351
+ data.set(row.data, offset);
4352
+ offset += row.data.byteLength;
4353
+ }
4354
+ if (offset === data.byteLength) return data;
4355
+ const again = await this.blobOwner(sessionId, hash);
4356
+ if (again === void 0) return void 0;
4357
+ if (again.owner !== owner && attempt < 2) continue;
4358
+ throw new SessionBlobError("blob-incomplete", {
4359
+ sessionId,
4360
+ hash,
4361
+ bytes: header.bytes
4362
+ });
2580
4363
  }
2581
- const data = new Uint8Array(header.bytes);
2582
- let offset = 0;
2583
- for (let index = 0; index < header.chunks; index++) {
2584
- const row = await this.database.get(`SELECT data FROM ${this.tables.blobChunks} WHERE idx = ? AND session_id = ? AND hash = ?`, index, sessionId, hash);
2585
- if (row?.data == null || offset + row.data.byteLength > data.byteLength) break;
2586
- data.set(row.data, offset);
2587
- offset += row.data.byteLength;
2588
- }
2589
- if (offset === data.byteLength) return data;
2590
- if (await this.blobHeader(sessionId, hash) === void 0) return void 0;
2591
- throw new SessionBlobError("blob-incomplete", {
2592
- sessionId,
2593
- hash,
2594
- bytes: header.bytes
2595
- });
4364
+ }
4365
+ /**
4366
+ * Where session `sessionId`'s blob `hash` is stored, with its header: its own, or the first of its fork sources' by
4367
+ * id, through the segments of a fork that shares its parent's history (#6560). Read outside a transaction.
4368
+ */
4369
+ async blobOwner(sessionId, hash) {
4370
+ const row = await this.outsideTransaction((tables) => this.database.get(tables.segments === void 0 ? `SELECT session_id AS owner, bytes, chunks FROM ${this.tables.blobs} WHERE session_id = ? AND hash = ?${tables.guard === void 0 ? "" : ` AND ${tables.guard}`}` : `SELECT b.session_id AS owner, b.bytes, b.chunks
4371
+ FROM ${this.blobPlaces(tables)} w JOIN ${this.tables.blobs} b ON b.session_id = w.owner AND b.hash = ?
4372
+ ${tables.guard === void 0 ? "" : `WHERE ${tables.guard}`}
4373
+ ORDER BY w.place, b.session_id LIMIT 1`, ...tables.segments === void 0 ? [sessionId, hash] : [...this.blobPlaceParams(tables, sessionId), hash]), (found) => found !== void 0);
4374
+ return row === void 0 ? void 0 : {
4375
+ owner: String(row.owner),
4376
+ bytes: Number(row.bytes),
4377
+ chunks: Number(row.chunks)
4378
+ };
4379
+ }
4380
+ /**
4381
+ * The sessions whose blobs a session reads (#6560), as a derived table of `owner` and `place`: the session itself,
4382
+ * place 0, and, with shared history, the sources its segments name, place 1. A blob is then looked up by its key in
4383
+ * each, never by a scan of the blobs of every session. Its parameters are {@link blobPlaceParams}.
4384
+ */
4385
+ blobPlaces(tables) {
4386
+ const own = `SELECT CAST(? AS ${this.dialect.types.text}) AS owner, 0 AS place`;
4387
+ return tables.segments === void 0 ? `(${own})` : `(${own} UNION ALL SELECT source_id, 1 FROM ${tables.segments} WHERE session_id = ?)`;
4388
+ }
4389
+ blobPlaceParams(tables, sessionId) {
4390
+ return tables.segments === void 0 ? [sessionId] : [sessionId, sessionId];
2596
4391
  }
2597
4392
  async blobHeader(sessionId, hash) {
2598
4393
  const row = await this.database.get(`SELECT bytes, chunks FROM ${this.tables.blobs} WHERE session_id = ? AND hash = ?`, sessionId, hash);
@@ -2662,6 +4457,7 @@ var SqlSessionStore = class SqlSessionStore {
2662
4457
  this.closed = true;
2663
4458
  this.scopes.clear();
2664
4459
  this.summaries.clear();
4460
+ dropStoredNotes(this);
2665
4461
  const reader = this.reader;
2666
4462
  this.reader = void 0;
2667
4463
  if (reader !== void 0) await (await reader.catch(() => void 0))?.close();
@@ -2775,10 +4571,10 @@ var SqlSessionStore = class SqlSessionStore {
2775
4571
  }
2776
4572
  const idPrefix = query.idPrefix?.toLowerCase();
2777
4573
  return {
2778
- where: `(? = 1 OR internal = 0)${projectCwds ? ` AND cwd IN (${projectCwds.map(() => "?").join(", ")})` : ""}${idPrefix === void 0 ? "" : " AND substr(lower(id), 1, ?) = ?"}`,
4574
+ where: `(? = 1 OR internal = 0)${projectCwds ? ` AND ${inJsonList(this.dialect, "cwd")}` : ""}${idPrefix === void 0 ? "" : " AND substr(lower(id), 1, ?) = ?"}`,
2779
4575
  params: [
2780
4576
  query.includeInternal ? 1 : 0,
2781
- ...projectCwds ?? [],
4577
+ ...projectCwds ? [JSON.stringify(projectCwds)] : [],
2782
4578
  ...idPrefix === void 0 ? [] : [idPrefix.length, idPrefix]
2783
4579
  ],
2784
4580
  inScope: (row) => !matchesCwd || matchesCwd(row.cwd)
@@ -2799,7 +4595,7 @@ var SqlSessionStore = class SqlSessionStore {
2799
4595
  if (stale.length <= rows.length / 4) {
2800
4596
  for (let start = 0; start < stale.length; start += 500) {
2801
4597
  const ids = stale.slice(start, start + 500).map((row) => row.id);
2802
- const fetched = new Set((await this.readSummaries(`id IN (${ids.map(() => "?").join(", ")})`, ids)).map((row) => row.id));
4598
+ const fetched = new Set((await this.readSummaries(inJsonList(this.dialect, "id"), [JSON.stringify(ids)])).map((row) => row.id));
2803
4599
  for (const id of ids) if (!fetched.has(id)) this.summaries.delete(id);
2804
4600
  this.assertListing(query);
2805
4601
  }
@@ -2846,17 +4642,25 @@ var SqlSessionStore = class SqlSessionStore {
2846
4642
  const order = this.dialect.rowOrder();
2847
4643
  const rows = [];
2848
4644
  for (let after = 0, limit = SESSION_READ_FETCH.first;;) {
4645
+ const seen = this.sharedHistorySeen;
4646
+ const texts = (session) => forkViewOf({
4647
+ segments: seen ? this.forkTables.forkSegments : void 0,
4648
+ dialect: this.dialect
4649
+ }, {
4650
+ table: this.tables.searchTexts,
4651
+ columns: ["text_json"]
4652
+ }, session);
2849
4653
  const page = await this.database.all(`WITH keyed AS MATERIALIZED (
2850
4654
  SELECT ${LISTING_COLUMNS}, ${order} AS ord, ${LISTING_SIZE} AS size
2851
4655
  FROM ${this.tables.sessions} AS s WHERE (${where}) AND ${order} > ? ORDER BY ord LIMIT ?
2852
4656
  ), sized AS MATERIALIZED (
2853
4657
  SELECT ${LISTING_COLUMNS}, ord, size,
2854
- (SELECT COALESCE(sum(length(text_json) + 1) + 1, 2) FROM ${this.tables.searchTexts} WHERE session_id = keyed.id) AS search_size
4658
+ (SELECT COALESCE(sum(length(text_json) + 1) + 1, 2) FROM ${texts("keyed.id")} AS t) AS search_size
2855
4659
  FROM keyed
2856
4660
  ) SELECT ${LISTING_COLUMNS}, ord, fetched, batch_chars, page_chars, CASE WHEN search_size <= ? THEN (
2857
4661
  SELECT COALESCE('[' || ${this.dialect.orderedConcat("text_json", "','", "seq")} || ']', '[]')
2858
- FROM (SELECT text_json, seq FROM ${this.tables.searchTexts} WHERE session_id = page.id ORDER BY seq)
2859
- ) END AS search_texts_json
4662
+ FROM (SELECT text_json, seq FROM ${texts("page.id")} AS t ORDER BY seq) AS ordered
4663
+ ) END AS search_texts_json, (SELECT max(schema_version) FROM ${this.tables.meta}) AS schema_version
2860
4664
  FROM (
2861
4665
  SELECT ${LISTING_COLUMNS}, ord, search_size, count(*) OVER () AS fetched,
2862
4666
  row_number() OVER (ORDER BY ord) AS page_row,
@@ -2864,6 +4668,11 @@ var SqlSessionStore = class SqlSessionStore {
2864
4668
  sum(size + search_size) OVER (ORDER BY ord) AS page_chars
2865
4669
  FROM sized
2866
4670
  ) AS page WHERE (page_chars <= ? OR page_row = 1) AND page_row <= ? ORDER BY ord`, ...params, after, limit + 1, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, limit);
4671
+ for (const row of page) {
4672
+ assertStorageSchemaVersion("sessions", row.schema_version, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
4673
+ this.noteSchemaVersion(row.schema_version);
4674
+ }
4675
+ if (this.sharedHistorySeen !== seen) continue;
2867
4676
  for (const row of page) {
2868
4677
  const summaryRow = row.search_texts_json === null ? {
2869
4678
  ...row,
@@ -2881,12 +4690,31 @@ var SqlSessionStore = class SqlSessionStore {
2881
4690
  limit = next.limit;
2882
4691
  }
2883
4692
  }
2884
- /** A session's search texts as one JSON array, read in pages of at most {@link SESSION_READ_PAGE_CHARS}. */
4693
+ /**
4694
+ * A session's search texts as one JSON array, read in pages of at most {@link SESSION_READ_PAGE_CHARS}, through its
4695
+ * view (#6560). Only a session with some text is read this way, so a read that finds none was held back.
4696
+ */
2885
4697
  async readSearchTexts(sessionId) {
2886
- const sizes = await this.database.all(`SELECT seq, length(text_json) AS size FROM ${this.tables.searchTexts} WHERE session_id = ? ORDER BY seq`, sessionId);
4698
+ const textsView = (tables, after, through) => {
4699
+ return forkView(tables, {
4700
+ name: "texts_view",
4701
+ table: this.tables.searchTexts,
4702
+ columns: ["text_json"],
4703
+ sessionId,
4704
+ after,
4705
+ through
4706
+ });
4707
+ };
4708
+ const sizes = await this.outsideTransaction((tables) => {
4709
+ const view = textsView(tables, 0, FORK_VIEW_END);
4710
+ return this.database.all(withForkViews([view], "SELECT seq, length(text_json) AS size FROM texts_view ORDER BY seq"), ...view.params);
4711
+ }, (found) => found.length > 0);
2887
4712
  const texts = [];
2888
4713
  for (const page of pagesOf(sizes)) {
2889
- const rows = await this.database.all(`SELECT text_json FROM ${this.tables.searchTexts} WHERE session_id = ? AND seq >= ? AND seq <= ? ORDER BY seq`, sessionId, page[0].seq, page.at(-1).seq);
4714
+ const rows = await this.outsideTransaction((tables) => {
4715
+ const view = textsView(tables, Number(page[0].seq) - 1, Number(page.at(-1).seq));
4716
+ return this.database.all(withForkViews([view], "SELECT text_json FROM texts_view ORDER BY seq"), ...view.params);
4717
+ }, (found) => found.length > 0);
2890
4718
  for (const row of rows) texts.push(row.text_json);
2891
4719
  }
2892
4720
  return `[${texts.join(",")}]`;
@@ -2907,8 +4735,18 @@ var SqlSessionStore = class SqlSessionStore {
2907
4735
  query.signal?.throwIfAborted();
2908
4736
  }
2909
4737
  async read(tx, 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)]);
4738
+ const generation = this.generation(sessionId);
4739
+ const shared = await this.viewTables(tx);
4740
+ const head = 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,${generation.sql} AS epoch${this.forkedColumn(shared.segments)} FROM ${this.tables.sessions} WHERE id = ?`, ...generation.params, sessionId);
4741
+ const guess = this.forkedSessions.get(sessionId) === false ? {
4742
+ ...shared,
4743
+ segments: void 0
4744
+ } : shared;
4745
+ const epoch = head.then((found) => found?.epoch);
4746
+ let [row, rows] = await Promise.all([head, this.readRows(tx, sessionId, void 0, void 0, epoch, guess)]);
2911
4747
  if (!row) throw new SessionNotFoundError$1(sessionId);
4748
+ this.noteForked(tx, sessionId, row.forked);
4749
+ if (guess.segments === void 0 && shared.segments !== void 0 && Number(row.forked) === 1) rows = await this.readRows(tx, sessionId, void 0, void 0, epoch, shared);
2912
4750
  const snapshot = {
2913
4751
  header: JSON.parse(row.header_json),
2914
4752
  entries: rows.map(({ entry }) => entry),
@@ -2917,35 +4755,49 @@ var SqlSessionStore = class SqlSessionStore {
2917
4755
  if (typeof row.chat_epoch === "string") bindChatEpoch(snapshot.header, row.chat_epoch);
2918
4756
  return noteSnapshotGeneration(this, snapshot, nativeLoad, row, "revision");
2919
4757
  }
2920
- async readRows(tx, sessionId, filter = "", params = []) {
4758
+ /**
4759
+ * The entries of session `sessionId` from `from` through `through`, in pages, through its view (#6560): only those
4760
+ * whose seq `seqs` lists, when it is given, which then lies in that range. With `epoch`, the session's generation in
4761
+ * the snapshot of `tx`, each entry is noted as stored at its seq in it, for a fork of the session to share its row.
4762
+ */
4763
+ async readRows(tx, sessionId, range = {}, seqs, epoch, viewTables) {
4764
+ const tables = viewTables ?? await this.viewTables(tx, sessionId);
4765
+ const through = range.through ?? FORK_VIEW_END;
4766
+ const filter = seqs === void 0 ? "" : ` AND ${inJsonList(this.dialect, "seq", true)}`;
2921
4767
  const entries = [];
2922
- for (let after = 0, limit = SESSION_READ_FETCH.first;;) {
2923
- const rows = await tx.all(`WITH sized AS MATERIALIZED (
2924
- SELECT seq, chunks, length(entry_json) AS size,
4768
+ for (let after = Math.max(0, (range.from ?? 1) - 1), limit = SESSION_READ_FETCH.first;;) {
4769
+ const view = this.entriesView(tables, sessionId, after, tables.segments === void 0 || seqs !== void 0 ? through : Math.min(through, after + limit + 1));
4770
+ const rows = await tx.all(withForkViews([view], `WITH sized AS MATERIALIZED (
4771
+ SELECT seq, chunks, src_id, src_seq, length(entry_json) AS size,
2925
4772
  CASE WHEN ${this.dialect.textByteLength("entry_json")} <= ? THEN entry_json END AS inline_json
2926
- FROM ${this.tables.entries} WHERE session_id = ? AND seq > ?${filter === "" ? "" : ` AND ${filter}`} ORDER BY seq LIMIT ?
4773
+ FROM ${view.name} WHERE seq > ?${filter} ORDER BY seq LIMIT ?
2927
4774
  ), batch AS MATERIALIZED (
2928
4775
  SELECT count(*) AS fetched, COALESCE(sum(size), 0) AS chars FROM sized
2929
4776
  ), page AS (
2930
- SELECT seq, chunks, inline_json, fetched, chars AS batch_chars, 0 AS page_chars
2931
- FROM (SELECT seq, chunks, inline_json FROM sized ORDER BY seq LIMIT ?) AS fitting CROSS JOIN batch
4777
+ SELECT seq, chunks, src_id, src_seq, inline_json, fetched, chars AS batch_chars, 0 AS page_chars
4778
+ FROM (SELECT seq, chunks, src_id, src_seq, inline_json FROM sized ORDER BY seq LIMIT ?) AS fitting CROSS JOIN batch
2932
4779
  WHERE batch.chars <= ?
2933
4780
  UNION ALL
2934
- SELECT seq, chunks, inline_json, fetched, batch_chars, page_chars FROM (
2935
- SELECT seq, chunks, inline_json, batch.fetched, batch.chars AS batch_chars,
4781
+ SELECT seq, chunks, src_id, src_seq, inline_json, fetched, batch_chars, page_chars FROM (
4782
+ SELECT seq, chunks, src_id, src_seq, inline_json, batch.fetched, batch.chars AS batch_chars,
2936
4783
  row_number() OVER (ORDER BY seq) AS page_row,
2937
4784
  sum(size) OVER (ORDER BY seq) AS page_chars
2938
4785
  FROM sized CROSS JOIN batch WHERE batch.chars > ?
2939
4786
  ) AS windowed WHERE (page_chars <= ? OR page_row = 1) AND page_row <= ?
2940
4787
  ) SELECT seq, COALESCE(inline_json, (
2941
- SELECT e.entry_json FROM ${this.tables.entries} AS e WHERE e.session_id = ? AND e.seq = page.seq
2942
- )) AS entry_json, chunks, fetched, batch_chars, page_chars FROM page ORDER BY seq`, SESSION_READ_INLINE_BYTES, sessionId, after, ...params, limit + 1, limit, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, limit, sessionId);
4788
+ SELECT e.entry_json FROM ${this.tables.entries} AS e WHERE e.session_id = page.src_id AND e.seq = page.src_seq
4789
+ )) AS entry_json, chunks, fetched, batch_chars, page_chars FROM page ORDER BY seq`), ...forkViewParams([view]), SESSION_READ_INLINE_BYTES, after, ...seqs === void 0 ? [] : [JSON.stringify(seqs)], limit + 1, limit, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, limit);
4790
+ const generation = await epoch;
4791
+ const note = generation === void 0 || !this.sharedHistorySeen ? void 0 : storedEntryNotes(this, sessionId, generation);
2943
4792
  for (const entry of rows) {
2944
4793
  const chunks = Number(entry.chunks);
2945
- const json = chunks === 0 ? entry.entry_json : await this.readEntryChunks(tx, sessionId, entry.seq, chunks);
4794
+ const seq = Number(entry.seq);
4795
+ const json = chunks === 0 ? entry.entry_json : await this.readEntryChunks(tx, tables, sessionId, seq, chunks);
4796
+ const parsed = JSON.parse(json);
4797
+ note?.(parsed, seq, json);
2946
4798
  entries.push({
2947
- seq: Number(entry.seq),
2948
- entry: JSON.parse(json)
4799
+ seq,
4800
+ entry: parsed
2949
4801
  });
2950
4802
  }
2951
4803
  const next = nextFetch(limit, rows);
@@ -2954,11 +4806,15 @@ var SqlSessionStore = class SqlSessionStore {
2954
4806
  limit = next.limit;
2955
4807
  }
2956
4808
  }
2957
- async readSeqs(tx, sessionId, seqs) {
4809
+ async readSeqs(tx, sessionId, seqs, epoch) {
2958
4810
  const entries = [];
2959
4811
  for (let start = 0; start < seqs.length; start += SEQ_BATCH) {
2960
4812
  const batch = seqs.slice(start, start + SEQ_BATCH);
2961
- entries.push(...await this.readRows(tx, sessionId, `seq IN (${batch.map(() => "?").join(", ")})`, batch));
4813
+ const range = {
4814
+ from: Math.min(...batch),
4815
+ through: Math.max(...batch)
4816
+ };
4817
+ entries.push(...await this.readRows(tx, sessionId, range, batch, epoch));
2962
4818
  }
2963
4819
  return entries;
2964
4820
  }
@@ -2968,14 +4824,36 @@ var SqlSessionStore = class SqlSessionStore {
2968
4824
  */
2969
4825
  resumeRow(sessionId) {
2970
4826
  return {
2971
- sql: `SELECT header_json,last_seq,summary_state,revision FROM ${this.tables.sessions} WHERE id = ?`,
4827
+ sql: `SELECT header_json,last_seq,summary_state,revision${this.forkedColumn(this.sharedHistorySeen ? this.forkTables.forkSegments : void 0)} FROM ${this.tables.sessions} WHERE id = ?`,
2972
4828
  params: [sessionId]
2973
4829
  };
2974
4830
  }
4831
+ /**
4832
+ * The view (#6560), as `name`, of session `sessionId`'s entries after seq `after` and through seq `through`, with
4833
+ * `entry_id`, `entry_json` and `chunks`, and where each is stored.
4834
+ */
4835
+ entriesView(tables, sessionId, after = 0, through = FORK_VIEW_END, name = "entries_view") {
4836
+ return {
4837
+ ...forkView(tables, {
4838
+ name,
4839
+ table: this.tables.entries,
4840
+ columns: [
4841
+ "entry_id",
4842
+ "entry_json",
4843
+ "chunks"
4844
+ ],
4845
+ sessionId,
4846
+ after,
4847
+ through
4848
+ }),
4849
+ name
4850
+ };
4851
+ }
2975
4852
  async resumeSource(tx, sessionId) {
2976
4853
  const read = this.resumeRow(sessionId);
2977
4854
  const row = await tx.get(read.sql, ...read.params);
2978
4855
  if (!row) throw new SessionNotFoundError$1(sessionId);
4856
+ this.noteForked(tx, sessionId, row.forked);
2979
4857
  const stored = windowIndex(JSON.parse(row.summary_state), Number(row.last_seq));
2980
4858
  const remembered = this.resumeIndexes.get(sessionId);
2981
4859
  const index = isSessionResumeIndex(stored, Number(row.last_seq)) ? stored : remembered?.revision === row.revision ? remembered.index : void 0;
@@ -3003,14 +4881,15 @@ var SqlSessionStore = class SqlSessionStore {
3003
4881
  }
3004
4882
  async prepareResume(sessionId, leafId, throughSeq) {
3005
4883
  attempts: for (let attempt = 0; attempt < 3; attempt++) {
3006
- const row = await this.database.get(`SELECT header_json,last_seq,summary_state,revision FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
4884
+ const row = await this.database.get(`SELECT header_json,last_seq,summary_state,revision${this.outsideForkedColumn("id")} FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
3007
4885
  if (!row) throw new SessionNotFoundError$1(sessionId);
4886
+ this.noteForked(void 0, sessionId, row.forked);
3008
4887
  const state = JSON.parse(row.summary_state);
3009
4888
  const remembered = this.resumeIndexes.get(sessionId);
3010
4889
  const currentIndex = windowIndex(state, Number(row.last_seq)) ?? (remembered?.revision === row.revision && isSessionResumeIndex(remembered.index, Number(row.last_seq)) ? remembered.index : void 0);
3011
4890
  const limit = throughSeq ?? Number(row.last_seq);
3012
4891
  if (limit > Number(row.last_seq)) throw new SessionConflictError$1(sessionId, limit, Number(row.last_seq));
3013
- const selected = leafId === void 0 ? void 0 : await this.seqOfEntry(this.database, sessionId, leafId) ?? 0;
4892
+ const selected = leafId === void 0 ? void 0 : await this.seqOfEntry(this.database, void 0, sessionId, leafId) ?? 0;
3014
4893
  const requested = selected !== void 0 && selected > limit ? 0 : selected;
3015
4894
  if (currentIndex && limit === currentIndex.seq && (requested === void 0 || requested === currentIndex.leafSeq)) return {
3016
4895
  index: currentIndex,
@@ -3139,12 +5018,18 @@ var SqlSessionStore = class SqlSessionStore {
3139
5018
  const lo = "(SELECT lo FROM bounds)";
3140
5019
  const hi = "(SELECT hi FROM bounds)";
3141
5020
  const pageWhere = sqlite ? `WHERE session_id = ${owner} AND seq > ${lo} AND seq <= ${hi}${sources}` : where;
5021
+ const viewed = this.outsideViewTables();
5022
+ const tables = Number(row.forked) === 0 ? {
5023
+ ...viewed,
5024
+ segments: void 0
5025
+ } : viewed;
5026
+ const shared = tables.segments !== void 0;
3142
5027
  const page = `WITH ${sqlite ? "bounds(id,lo,hi) AS NOT MATERIALIZED (VALUES (?,?,?)), " : ""}page AS (
3143
- SELECT ${sqlite ? "" : "CASE WHEN chunks > 0 THEN session_id END AS session_id,"}seq,entry_id,chunks,entry_json FROM ${this.tables.entries}
5028
+ SELECT ${sqlite && !shared ? "" : "CASE WHEN chunks > 0 THEN src_id END AS src_id,"}seq,src_seq,entry_id,chunks,entry_json FROM entries_view
3144
5029
  ${pageWhere} ORDER BY seq LIMIT ${SESSION_RESUME_REBUILD.pageEntries}
3145
5030
  )`;
3146
- const parts = (source) => `FROM ${this.tables.entryChunks} WHERE session_id = ${sqlite ? owner : `${source}.session_id`}
3147
- AND seq = ${source}.seq AND idx >= 0 AND idx < ${source}.chunks`;
5031
+ const parts = (source) => `FROM ${this.tables.entryChunks} WHERE session_id = ${sqlite && !shared ? owner : `${source}.src_id`}
5032
+ AND seq = ${source}.src_seq AND idx >= 0 AND idx < ${source}.chunks`;
3148
5033
  const projection = sqlite ? `SELECT seq,entry_id,chunks,${select} FROM payloads ORDER BY seq` : `SELECT seq,entry_id,chunks,${select} FROM payloads
3149
5034
  CROSS JOIN LATERAL (SELECT ${postgresJsonb("entry_json")} AS value OFFSET 0) AS parsed ORDER BY seq`;
3150
5035
  const fits = sqlite ? "length(zeroblob(sum(length(data)))) IS NOT NULL" : "sum(octet_length(data)) < 1073741824";
@@ -3159,7 +5044,7 @@ var SqlSessionStore = class SqlSessionStore {
3159
5044
  ) ${projection}`;
3160
5045
  const keysPerEntry = 64;
3161
5046
  const through = `${lo} + ${SESSION_RESUME_REBUILD.pageEntries}`;
3162
- const wide = sqlite && Number(row.last_seq) > 0 && Buffer.byteLength(sessionId) >= 512;
5047
+ const wide = sqlite && !shared && Number(row.last_seq) > 0 && Buffer.byteLength(sessionId) >= 512;
3163
5048
  let inlinePage = wide && this.chunkRowids === void 0 ? `${page}, chunked AS MATERIALIZED (SELECT 1 FROM page WHERE chunks > 0 LIMIT 1),
3164
5049
  payloads AS MATERIALIZED (SELECT seq,entry_id,chunks,entry_json FROM page WHERE NOT EXISTS (SELECT 1 FROM chunked)
3165
5050
  UNION ALL SELECT 0,'',0,'{}' FROM chunked) ${projection}` : void 0;
@@ -3186,14 +5071,16 @@ var SqlSessionStore = class SqlSessionStore {
3186
5071
  let topology = currentIndex && requested !== void 0 ? branchRanges(currentIndex, requested) : void 0;
3187
5072
  for (let pass = topology === void 0 ? 0 : 1; pass < 2; pass++) {
3188
5073
  for (let after = 0; after < limit;) {
5074
+ const view = this.entriesView(tables, sessionId, after, Math.min(limit, after + SESSION_RESUME_REBUILD.pageEntries));
3189
5075
  const args = [
5076
+ ...view.params,
3190
5077
  sessionId,
3191
5078
  after,
3192
5079
  limit
3193
5080
  ];
3194
5081
  let rows;
3195
5082
  try {
3196
- rows = await this.database.all(inlinePage ?? (this.chunkRowids ? rowidPage : directPage), ...args);
5083
+ rows = await this.database.all(withForkViews([view], inlinePage ?? (this.chunkRowids ? rowidPage : directPage)), ...args);
3197
5084
  if (inlinePage && Number(rows[0]?.seq) === 0) {
3198
5085
  inlinePage = void 0;
3199
5086
  try {
@@ -3204,12 +5091,15 @@ var SqlSessionStore = class SqlSessionStore {
3204
5091
  }
3205
5092
  } catch (error) {
3206
5093
  if (!(error instanceof Error && "code" in error && error.code === "payload-too-large")) throw error;
3207
- if (!await this.database.get(`SELECT 1 FROM ${this.tables.entryChunks}
3208
- WHERE session_id = ? AND seq IN (SELECT seq FROM ${this.tables.entries} ${where}
3209
- ORDER BY seq LIMIT ${SESSION_RESUME_REBUILD.pageEntries}) LIMIT 1`, sessionId, ...args).catch(() => void 0)) throw error;
3210
- rows = await this.database.all(stubPage, ...args);
5094
+ if (!await this.database.get(withForkViews([view], `SELECT 1 FROM (SELECT src_id, src_seq FROM ${view.name} ${where}
5095
+ ORDER BY seq LIMIT ${SESSION_RESUME_REBUILD.pageEntries}) AS p
5096
+ JOIN ${this.tables.entryChunks} c ON c.session_id = p.src_id AND c.seq = p.src_seq LIMIT 1`), ...view.params, sessionId, after, limit).catch(() => void 0)) throw error;
5097
+ rows = await this.database.all(withForkViews([view], stubPage), ...args);
5098
+ }
5099
+ if (rows.length === 0) {
5100
+ if (await this.schemaNowShared(viewed.segments !== void 0)) continue attempts;
5101
+ break;
3211
5102
  }
3212
- if (rows.length === 0) break;
3213
5103
  const batch = [];
3214
5104
  let toolCalls = 0;
3215
5105
  for (const entry of rows) {
@@ -3283,7 +5173,7 @@ var SqlSessionStore = class SqlSessionStore {
3283
5173
  const old = index ?? foldSessionResume(void 0, []);
3284
5174
  const seqs = /* @__PURE__ */ new Map();
3285
5175
  for (const id of foreignResumeIds(old, batch)) {
3286
- const seq = await this.seqOfEntry(this.database, sessionId, id);
5176
+ const seq = await this.seqOfEntry(this.database, void 0, sessionId, id);
3287
5177
  if (seq !== void 0) seqs.set(id, seq);
3288
5178
  }
3289
5179
  index = foldSessionResume(index, batch, (id) => seqs.get(id), (seq) => topology === void 0 || topology.some(([a, b]) => seq >= a && seq <= b));
@@ -3337,11 +5227,11 @@ var SqlSessionStore = class SqlSessionStore {
3337
5227
  this.assertOpen();
3338
5228
  validateSessionText("sessionId", sessionId);
3339
5229
  const start = Math.max(1, fromSeq);
3340
- const { tail } = await this.withResumeIndex(sessionId, () => this.readTransaction(async (tx) => {
5230
+ const { tail } = await this.withResumeIndex(sessionId, () => this.readTransaction(sessionId, async (tx) => {
3341
5231
  const source = await this.resumeSource(tx, sessionId);
3342
5232
  const stateSeqs = stateSeqsBefore(source.index, start);
3343
5233
  if (hasHistoryLoadObserver()) announceHistoryLoad(stateSeqs.length + Math.max(0, source.index.seq - start + 1));
3344
- const [state, rows] = await Promise.all([this.readSeqs(tx, sessionId, stateSeqs), this.readRows(tx, sessionId, "seq >= ?", [start])]);
5234
+ const [state, rows] = await Promise.all([this.readSeqs(tx, sessionId, stateSeqs), this.readRows(tx, sessionId, { from: start })]);
3345
5235
  const entries = rows.map(({ entry }) => entry);
3346
5236
  return {
3347
5237
  tail: sessionTailFrom(source.index, source.header, start, state, entries),
@@ -3354,41 +5244,55 @@ var SqlSessionStore = class SqlSessionStore {
3354
5244
  this.assertOpen();
3355
5245
  validateSessionText("sessionId", sessionId);
3356
5246
  const start = Math.max(1, startSeq);
3357
- return this.readTransaction(async (tx) => {
5247
+ return this.readTransaction(sessionId, async (tx) => {
3358
5248
  const head = await this.historyHead(tx, sessionId, true);
3359
5249
  if (expectedEpoch !== void 0 && expectedEpoch !== head.epoch) throw new SessionConflictError$1(sessionId, endSeq, head.lastSeq);
3360
- const entries = endSeq < start ? [] : await this.readRows(tx, sessionId, "seq >= ? AND seq <= ?", [start, endSeq]);
5250
+ const entries = endSeq < start ? [] : await this.readRows(tx, sessionId, {
5251
+ from: start,
5252
+ through: endSeq
5253
+ }, void 0, head.epoch);
3361
5254
  return {
3362
5255
  startSeq: start,
3363
5256
  entries: entries.map(({ entry }) => entry),
3364
5257
  seqs: entries.map(({ seq }) => seq),
3365
- ...head
5258
+ lastSeq: head.lastSeq,
5259
+ epoch: head.epoch
3366
5260
  };
3367
5261
  });
3368
5262
  }
5263
+ /**
5264
+ * The session's watermark and generation; with `segments`, the fork segments table of a database with shared
5265
+ * history, also whether the session has segments (#6560), in the same statement: a read that leaves a session without
5266
+ * them to its tables' own keyed lookups costs no read of its own to learn it.
5267
+ */
3369
5268
  async historyHead(tx, sessionId, readOnly = false) {
3370
5269
  const generation = this.generation(sessionId);
3371
- const row = await tx.get(`SELECT last_seq, revision, ${generation.sql} AS epoch FROM ${this.tables.sessions} WHERE id = ?${readOnly ? "" : this.dialect.lockClause("share")}`, ...generation.params, sessionId);
5270
+ const { segments } = await this.viewTables(tx);
5271
+ const row = await tx.get(`SELECT last_seq, revision, ${generation.sql} AS epoch${this.forkedColumn(segments)} FROM ${this.tables.sessions} WHERE id = ?${readOnly ? "" : this.dialect.lockClause("share")}`, ...generation.params, sessionId);
3372
5272
  if (!row) throw new SessionNotFoundError$1(sessionId);
3373
5273
  this.noteGeneration(sessionId, row.revision, Number(row.last_seq), row.epoch);
5274
+ this.noteForked(tx, sessionId, row.forked);
3374
5275
  return {
3375
5276
  lastSeq: Number(row.last_seq),
3376
- epoch: row.epoch
5277
+ epoch: row.epoch,
5278
+ forked: Number(row.forked) === 1
3377
5279
  };
3378
5280
  }
3379
5281
  /** Size at most one page and return only fitting bodies, in the same snapshot as the header. The first
3380
5282
  * oversized row is a chunk reference; its full inline value never crosses the driver boundary. */
3381
5283
  async historyPacket(tx, sessionId, epoch, from, through, backward) {
3382
5284
  const edge = backward ? through : from;
3383
- const rows = await tx.all(`WITH sizes AS MATERIALIZED (
3384
- SELECT e.seq, e.chunks, CASE WHEN e.chunks = 0 THEN ${this.entryByteLength("e.entry_json")} ELSE (e.chunks - 1) * ? +
3385
- (SELECT length(c.data) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx = e.chunks - 1) END AS bytes
3386
- FROM ${this.tables.entries} e WHERE e.session_id = ? AND e.seq BETWEEN ? AND ?
5285
+ const tables = await this.viewTables(tx, sessionId);
5286
+ const view = this.entriesView(tables, sessionId, from - 1, through);
5287
+ const rows = await tx.all(withForkViews([view], `WITH sizes AS MATERIALIZED (
5288
+ SELECT e.seq, e.chunks, e.src_id, e.src_seq, CASE WHEN e.chunks = 0 THEN ${this.entryByteLength("e.entry_json")} ELSE (e.chunks - 1) * ? +
5289
+ (SELECT length(c.data) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.src_id AND c.seq = e.src_seq AND c.idx = e.chunks - 1) END AS bytes
5290
+ FROM ${view.name} e
3387
5291
  ), sized_page AS (
3388
- SELECT seq, chunks, bytes, sum(bytes) OVER (ORDER BY seq ${backward ? "DESC" : "ASC"}) AS cumulative FROM sizes
5292
+ SELECT seq, chunks, src_id, src_seq, bytes, sum(bytes) OVER (ORDER BY seq ${backward ? "DESC" : "ASC"}) AS cumulative FROM sizes
3389
5293
  ) SELECT p.seq, p.chunks, p.bytes, CASE WHEN p.chunks = 0 AND p.bytes <= ? THEN e.entry_json END AS body
3390
- FROM sized_page p JOIN ${this.tables.entries} e ON e.session_id = ? AND e.seq = p.seq
3391
- WHERE p.bytes IS NULL OR p.cumulative <= ? OR p.seq = ? ORDER BY p.seq`, SESSION_ENTRY_CHUNK_BYTES, sessionId, from, through, SESSION_HISTORY_PAGE_BYTES, sessionId, SESSION_HISTORY_PAGE_BYTES, edge);
5294
+ FROM sized_page p JOIN ${this.tables.entries} e ON e.session_id = p.src_id AND e.seq = p.src_seq
5295
+ WHERE p.bytes IS NULL OR p.cumulative <= ? OR p.seq = ? ORDER BY p.seq`), ...view.params, SESSION_ENTRY_CHUNK_BYTES, SESSION_HISTORY_PAGE_BYTES, SESSION_HISTORY_PAGE_BYTES, edge);
3392
5296
  const items = [];
3393
5297
  for (const row of rows) {
3394
5298
  const seq = Number(row.seq);
@@ -3403,7 +5307,7 @@ var SqlSessionStore = class SqlSessionStore {
3403
5307
  });
3404
5308
  else items.push({
3405
5309
  seq,
3406
- entry: JSON.parse(row.body ?? await this.readEntryChunks(tx, sessionId, seq, Number(row.chunks)))
5310
+ entry: JSON.parse(row.body ?? await this.readEntryChunks(tx, tables, sessionId, seq, Number(row.chunks)))
3407
5311
  });
3408
5312
  }
3409
5313
  return items;
@@ -3412,10 +5316,22 @@ var SqlSessionStore = class SqlSessionStore {
3412
5316
  const { childDisplayCut } = await import("../core/storage/session/card-view.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
3413
5317
  const { index } = await this.prepareResume(sessionId);
3414
5318
  if (typeof launch.launchLeafId !== "string") return childDisplayCut(index, launch);
3415
- return this.readTransaction(async (tx) => {
5319
+ return this.readTransaction(sessionId, async (tx) => {
3416
5320
  const head = await this.historyHead(tx, sessionId, true);
3417
5321
  if (head.epoch !== index.epoch || head.lastSeq < index.seq) throw new SessionConflictError$1(sessionId, index.seq, head.lastSeq);
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);
5322
+ const view = forkView(await this.viewTables(tx, sessionId), {
5323
+ name: "launched",
5324
+ table: this.tables.entries,
5325
+ columns: ["entry_id"],
5326
+ sessionId,
5327
+ after: 0,
5328
+ through: index.seq,
5329
+ match: {
5330
+ column: "entry_id",
5331
+ value: launch.launchLeafId
5332
+ }
5333
+ });
5334
+ const row = await tx.get(withForkViews([view], "SELECT seq FROM launched ORDER BY seq DESC LIMIT 1"), ...view.params);
3419
5335
  return childDisplayCut(index, launch, row === void 0 ? void 0 : Number(row.seq));
3420
5336
  });
3421
5337
  }
@@ -3455,7 +5371,7 @@ var SqlSessionStore = class SqlSessionStore {
3455
5371
  * timestamp; its caller streams those fields instead of joining or decoding the stored body. */
3456
5372
  async readTreeOutline(sessionId, fromSeq, toSeq, epoch) {
3457
5373
  this.assertOpen();
3458
- return this.readTransaction(async (tx) => {
5374
+ return this.readTransaction(sessionId, async (tx) => {
3459
5375
  const head = await this.historyHead(tx, sessionId, true);
3460
5376
  if (epoch !== void 0 && head.epoch !== epoch || head.lastSeq < toSeq) throw new SessionConflictError$1(sessionId, toSeq, head.lastSeq);
3461
5377
  const sqlite = this.dialect.name === "sqlite";
@@ -3467,12 +5383,13 @@ var SqlSessionStore = class SqlSessionStore {
3467
5383
  const trim = sqlite ? "trim" : "btrim";
3468
5384
  const hasText = sqlite ? `EXISTS(SELECT 1 FROM json_each(entry_json,'$.message.content') b WHERE CASE WHEN b.type='object' AND json_extract(b.value,'$.type')='text' THEN length(trim(json_extract(b.value,'$.text'),?))>0 END)` : `EXISTS(SELECT 1 FROM jsonb_array_elements((${content})::jsonb) b WHERE b->>'type'='text' AND length(btrim(b->>'text',?))>0)`;
3469
5385
  const callIds = sqlite ? `(SELECT json_group_array(json_extract(b.value,'$.id')) FROM json_each(entry_json,'$.message.content') b WHERE CASE WHEN b.type='object' THEN json_extract(b.value,'$.type')='toolCall' AND json_type(b.value,'$.id')='text' END)` : `(SELECT json_agg(b->>'id')::text FROM jsonb_array_elements((${content})::jsonb) b WHERE b->>'type'='toolCall' AND jsonb_typeof(b->'id')='string')`;
3470
- return (await tx.all(`SELECT CASE WHEN ${role}='assistant' AND ${ctype}='array' THEN ${callIds} END calls,seq,entry_id,chunks,${j("type")} kind,${j("parentId")} parent,${j("timestamp")} stamp,${role} role,
5386
+ const view = this.entriesView(await this.viewTables(tx, sessionId), sessionId, fromSeq - 1, toSeq);
5387
+ return (await tx.all(withForkViews([view], `SELECT CASE WHEN ${role}='assistant' AND ${ctype}='array' THEN ${callIds} END calls,seq,entry_id,chunks,${j("type")} kind,${j("parentId")} parent,${j("timestamp")} stamp,${role} role,
3471
5388
  CASE WHEN ${role}='assistant' AND COALESCE(${j("message", "stopReason")},'') IN ('','toolUse','stop') AND CASE WHEN ${ctype}='array' THEN NOT ${hasText} WHEN ${ctype}='${sqlite ? "text" : "string"}' THEN length(${trim}(${content},?))=0 ELSE TRUE END THEN 1 ELSE 0 END hidden,
3472
5389
  CASE WHEN ${j("type")}='custom' AND ${j("customType")}='atomic.leaf' THEN 1 ELSE 0 END leaf_move,
3473
5390
  CASE WHEN ${j("type")}='custom' AND ${j("customType")}='subagent-child' THEN 1 ELSE 0 END child_record,
3474
5391
  CASE WHEN ${j("type")}='label' THEN ${j("targetId")} END target,CASE WHEN ${j("type")}='label' THEN substr(${j("label")},1,128) END label
3475
- FROM ${this.tables.entries} WHERE session_id=? AND seq BETWEEN ? AND ? ORDER BY seq LIMIT ?`, whites, whites, sessionId, fromSeq, toSeq, 64)).map((row) => Number(row.chunks) > 0 ? {
5392
+ FROM ${view.name} WHERE session_id=? AND seq BETWEEN ? AND ? ORDER BY seq LIMIT ?`), ...view.params, whites, whites, sessionId, fromSeq, toSeq, 64)).map((row) => Number(row.chunks) > 0 ? {
3476
5393
  seq: Number(row.seq),
3477
5394
  streamed: true
3478
5395
  } : {
@@ -3499,11 +5416,12 @@ var SqlSessionStore = class SqlSessionStore {
3499
5416
  const limit = entrySizeLimit(options.limit);
3500
5417
  const wanted = options.backward ? seqs.slice(-limit) : seqs.slice(0, limit);
3501
5418
  if (!wanted.length) return { items: [] };
3502
- return this.readTransaction(async (tx) => {
5419
+ return this.readTransaction(sessionId, async (tx) => {
3503
5420
  const head = await this.historyHead(tx, sessionId, true);
3504
5421
  if (head.epoch !== epoch || head.lastSeq < wanted.at(-1)) throw new SessionConflictError$1(sessionId, wanted.at(-1), head.lastSeq);
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)`;
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);
5422
+ const tail = `(SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id=e.src_id AND c.seq=e.src_seq AND c.idx=e.chunks-1)`;
5423
+ const view = this.entriesView(await this.viewTables(tx, sessionId), sessionId, Math.min(...wanted) - 1, Math.max(...wanted));
5424
+ const rows = await tx.all(withForkViews([view], `SELECT seq,CASE WHEN chunks=0 THEN ${this.entryByteLength("entry_json")} ELSE (chunks-1)*?+${tail} END bytes FROM ${view.name} e WHERE session_id=? AND ${inJsonList(this.dialect, "seq", true)} ORDER BY seq`), ...view.params, SESSION_ENTRY_CHUNK_BYTES, sessionId, JSON.stringify(wanted));
3507
5425
  const sizes = new Map(rows.map((row) => [Number(row.seq), row.bytes == null ? void 0 : Number(row.bytes)]));
3508
5426
  const plan = selectedPagePlan(sessionId, wanted, head.lastSeq, (seq) => {
3509
5427
  const bytes = sizes.get(seq);
@@ -3537,12 +5455,16 @@ var SqlSessionStore = class SqlSessionStore {
3537
5455
  async readEntrySizes(sessionId, startSeq, endSeq, limit) {
3538
5456
  this.assertOpen();
3539
5457
  validateSessionText("sessionId", sessionId);
3540
- return this.readTransaction(async (tx) => {
5458
+ return this.readTransaction(sessionId, async (tx) => {
3541
5459
  const head = await this.historyHead(tx, sessionId, true);
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)`;
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));
5460
+ const lastChunk = `(SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.src_id AND c.seq = e.src_seq AND c.idx = e.chunks - 1)`;
5461
+ const tables = await this.viewTables(tx, sessionId);
5462
+ const after = Math.max(1, startSeq) - 1;
5463
+ const view = this.entriesView(tables, sessionId, after, tables.segments === void 0 ? endSeq : Math.min(endSeq, after + entrySizeLimit(limit)));
5464
+ const rows = await tx.all(withForkViews([view], `SELECT seq, CASE WHEN chunks = 0 THEN ${this.entryByteLength("entry_json")} ELSE (chunks - 1) * ? + ${lastChunk} END AS bytes FROM ${view.name} e WHERE session_id = ? AND seq BETWEEN ? AND ? ORDER BY seq LIMIT ?`), ...view.params, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, endSeq, entrySizeLimit(limit));
3544
5465
  return {
3545
- ...head,
5466
+ lastSeq: head.lastSeq,
5467
+ epoch: head.epoch,
3546
5468
  sizes: rows.map((row) => {
3547
5469
  if (row.bytes === null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing final chunk of session entry ${row.seq}`));
3548
5470
  return {
@@ -3567,29 +5489,39 @@ var SqlSessionStore = class SqlSessionStore {
3567
5489
  const { select, trailingReference, referencePrefix } = options;
3568
5490
  const generation = this.generation(sessionId);
3569
5491
  const count = entrySizeLimit(limit);
3570
- const bytes = (row) => `CASE WHEN ${row}.chunks = 0 THEN ${this.entryByteLength(`${row}.entry_json`)} ELSE (${row}.chunks - 1) * ? + (SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id = ${row}.session_id AND c.seq = ${row}.seq AND c.idx = ${row}.chunks - 1) END`;
5492
+ const shared = this.sharedHistorySeen;
5493
+ const plain = shared && this.forkedSessions.get(sessionId) === false;
5494
+ const tables = {
5495
+ segments: shared && !plain ? this.forkTables.forkSegments : void 0,
5496
+ dialect: this.dialect
5497
+ };
5498
+ const scanEnd = tables.segments === void 0 ? endSeq : Math.min(endSeq, Math.max(1, startSeq) - 1 + (select === void 0 ? count : SCAN_SELECT_WINDOW));
5499
+ const view = this.entriesView(tables, sessionId, startSeq - 1, scanEnd, "scan_view");
5500
+ const bytes = (row) => `CASE WHEN ${row}.chunks = 0 THEN ${this.entryByteLength(`${row}.entry_json`)} ELSE (${row}.chunks - 1) * ? + (SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id = ${row}.src_id AND c.seq = ${row}.src_seq AND c.idx = ${row}.chunks - 1) END`;
5501
+ const forked = this.outsideForkedColumn("id");
5502
+ const forkedNull = forked === "" ? "" : ", NULL";
3571
5503
  const head = `SELECT 0 AS seq, NULL AS bytes, NULL AS chunks, header_json AS entry_json, last_seq, revision,
3572
- ${generation.sql} AS epoch, (SELECT schema_version FROM ${this.tables.meta} LIMIT 1) AS schema_version`;
5504
+ ${generation.sql} AS epoch, (SELECT schema_version FROM ${this.tables.meta} LIMIT 1) AS schema_version${forked}`;
3573
5505
  const filter = (row) => select ? ` AND ${this.selected(row, select)}` : "";
3574
5506
  const selectParams = select === void 0 ? [] : this.selectedParams(select);
3575
5507
  const json = this.dialect.name === "sqlite" ? "CAST(entry_json AS BLOB)" : "convert_to(entry_json, 'UTF8')";
3576
5508
  const prefixLength = Math.max(1, Math.trunc(referencePrefix ?? 1) || 1);
3577
- const rows = !select && !trailingReference && referencePrefix === void 0 ? await this.database.all(`${head} FROM ${this.tables.sessions} WHERE id = ?
5509
+ const rows = !select && !trailingReference && referencePrefix === void 0 ? await this.database.all(withForkViews([view], `${head} FROM ${this.tables.sessions} WHERE id = ?
3578
5510
  UNION ALL
3579
- SELECT seq, bytes, chunks, CASE WHEN bytes <= ? AND chunks = 0 THEN entry_json END, NULL, NULL, NULL, NULL FROM (
3580
- SELECT e.seq, e.chunks, e.entry_json, ${bytes("e")} AS bytes FROM ${this.tables.entries} e
5511
+ SELECT seq, bytes, chunks, CASE WHEN bytes <= ? AND chunks = 0 THEN entry_json END, NULL, NULL, NULL, NULL${forkedNull} FROM (
5512
+ SELECT e.seq, e.chunks, e.entry_json, ${bytes("e")} AS bytes FROM ${view.name} e
3581
5513
  -- The cut bounds the range itself, so the read stops there, however far the range goes.
3582
5514
  WHERE e.session_id = ? AND e.seq BETWEEN ? AND (
3583
5515
  SELECT COALESCE(max(CASE WHEN total <= ? THEN seq END), min(seq)) FROM (
3584
5516
  SELECT seq, sum(bytes) OVER (ORDER BY seq) AS total FROM (
3585
- SELECT s.seq, ${bytes("s")} AS bytes FROM ${this.tables.entries} s
5517
+ SELECT s.seq, ${bytes("s")} AS bytes FROM ${view.name} s
3586
5518
  WHERE s.session_id = ? AND s.seq BETWEEN ? AND ? ORDER BY s.seq LIMIT ?
3587
5519
  ) AS sized
3588
5520
  ) AS run
3589
5521
  )
3590
5522
  ) AS page
3591
- ORDER BY seq`, ...generation.params, sessionId, SESSION_HISTORY_PAGE_BYTES, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, SESSION_HISTORY_PAGE_BYTES, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, endSeq, count) : await this.database.all(`WITH sized AS MATERIALIZED (
3592
- SELECT s.seq, ${bytes("s")} AS bytes FROM ${this.tables.entries} s
5523
+ ORDER BY seq`), ...view.params, ...generation.params, sessionId, SESSION_HISTORY_PAGE_BYTES, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, SESSION_HISTORY_PAGE_BYTES, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, scanEnd, count) : await this.database.all(withForkViews([view], `WITH sized AS MATERIALIZED (
5524
+ SELECT s.seq, ${bytes("s")} AS bytes FROM ${view.name} s
3593
5525
  WHERE s.session_id = ? AND s.seq BETWEEN ? AND ?${filter("s")} ORDER BY s.seq LIMIT ?
3594
5526
  ), cut AS (
3595
5527
  SELECT COALESCE(
@@ -3604,26 +5536,28 @@ var SqlSessionStore = class SqlSessionStore {
3604
5536
  ${head}, (SELECT count(*) FROM sized) AS sized, (SELECT max(seq) FROM sized) AS sized_last, NULL AS prefix
3605
5537
  FROM ${this.tables.sessions} WHERE id = ?
3606
5538
  UNION ALL
3607
- SELECT seq, bytes, chunks, CASE WHEN bytes <= ? AND chunks = 0 THEN entry_json END, NULL, NULL, NULL, NULL, NULL, NULL,
5539
+ SELECT seq, bytes, chunks, CASE WHEN bytes <= ? AND chunks = 0 THEN entry_json END, NULL, NULL, NULL, NULL${forkedNull}, NULL, NULL,
3608
5540
  ${referencePrefix === void 0 ? "NULL" : `CASE WHEN bytes > ? THEN CASE WHEN chunks > 0
3609
- THEN (SELECT substr(c.data, 1, CAST(? AS INTEGER)) FROM ${this.tables.entryChunks} c WHERE c.session_id = ? AND c.seq = page.seq AND c.idx = 0)
5541
+ THEN (SELECT substr(c.data, 1, CAST(? AS INTEGER)) FROM ${this.tables.entryChunks} c WHERE c.session_id = page.src_id AND c.seq = page.src_seq AND c.idx = 0)
3610
5542
  ELSE substr(${json}, 1, CAST(? AS INTEGER)) END END`}
3611
5543
  FROM (
3612
- SELECT e.seq, e.chunks, e.entry_json, ${bytes("e")} AS bytes FROM ${this.tables.entries} e
5544
+ SELECT e.seq, e.chunks, e.entry_json, e.src_id, e.src_seq, ${bytes("e")} AS bytes FROM ${view.name} e
3613
5545
  WHERE e.session_id = ? AND e.seq BETWEEN ? AND (SELECT seq FROM cut)${filter("e")}
3614
5546
  UNION ALL
3615
- SELECT e.seq, e.chunks, e.entry_json, ${bytes("e")} AS bytes FROM ${this.tables.entries} e
5547
+ SELECT e.seq, e.chunks, e.entry_json, e.src_id, e.src_seq, ${bytes("e")} AS bytes FROM ${view.name} e
3616
5548
  WHERE e.session_id = ? AND e.seq = (SELECT seq FROM tail)
3617
5549
  ) AS page
3618
- ORDER BY seq`, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, endSeq, ...selectParams, count, SESSION_HISTORY_PAGE_BYTES, SESSION_HISTORY_PAGE_BYTES, SESSION_HISTORY_PAGE_BYTES, ...generation.params, sessionId, SESSION_HISTORY_PAGE_BYTES, ...referencePrefix === void 0 ? [] : [
5550
+ ORDER BY seq`), ...view.params, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, scanEnd, ...selectParams, count, SESSION_HISTORY_PAGE_BYTES, SESSION_HISTORY_PAGE_BYTES, SESSION_HISTORY_PAGE_BYTES, ...generation.params, sessionId, SESSION_HISTORY_PAGE_BYTES, ...referencePrefix === void 0 ? [] : [
3619
5551
  SESSION_HISTORY_PAGE_BYTES,
3620
5552
  prefixLength,
3621
- sessionId,
3622
5553
  prefixLength
3623
5554
  ], SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, ...selectParams, SESSION_ENTRY_CHUNK_BYTES, sessionId);
3624
5555
  const first = rows[0];
3625
5556
  if (first === void 0 || Number(first.seq) !== 0) throw new SessionNotFoundError$1(sessionId);
3626
- assertStorageSchemaVersion("sessions", first.schema_version, 2, SESSION_SCHEMA_VERSION_UNCHUNKED);
5557
+ assertStorageSchemaVersion("sessions", first.schema_version, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
5558
+ this.noteSchemaVersion(first.schema_version);
5559
+ this.noteForked(void 0, sessionId, first.forked);
5560
+ if (this.sharedHistorySeen !== shared || plain && Number(first.forked) === 1) return SqlSessionStore.prototype.readScanPage.call(this, sessionId, startSeq, endSeq, epoch, limit, options);
3627
5561
  const lastSeq = Number(first.last_seq);
3628
5562
  this.noteGeneration(sessionId, first.revision, lastSeq, first.epoch);
3629
5563
  if (epoch !== void 0 && first.epoch !== epoch) throw new SessionConflictError$1(sessionId, endSeq, lastSeq);
@@ -3637,10 +5571,10 @@ var SqlSessionStore = class SqlSessionStore {
3637
5571
  const top = page.at(-1);
3638
5572
  if (top === void 0) return {
3639
5573
  ...read,
3640
- throughSeq: endSeq,
5574
+ throughSeq: scanEnd,
3641
5575
  items: []
3642
5576
  };
3643
- const throughSeq = first.sized !== void 0 && Number(first.sized) < count && Number(first.sized_last) <= Number(top.seq) ? endSeq : Number(top.seq);
5577
+ const throughSeq = first.sized !== void 0 && Number(first.sized) < count && Number(first.sized_last) <= Number(top.seq) ? scanEnd : Number(top.seq);
3644
5578
  const prefixes = /* @__PURE__ */ new Map();
3645
5579
  const reference = (row) => {
3646
5580
  if (row.prefix) prefixes.set(Number(row.seq), row.prefix);
@@ -3686,7 +5620,7 @@ var SqlSessionStore = class SqlSessionStore {
3686
5620
  }
3687
5621
  /**
3688
5622
  * A condition on an entries row that holds for every entry `select` selects (and more): an entry larger than a page;
3689
- * on SQLite and libSQL, a message whose stored type and role say it is a tool result, or an assistant message with a
5623
+ * on SQLite, a message whose stored type and role say it is a tool result, or an assistant message with a
3690
5624
  * tool call named other than `exceptCalls`, and any row that is not valid JSON; on Postgres, which would parse each
3691
5625
  * row's JSON to read those, any row whose JSON holds a tool call block's `"toolCall"` or a result's `"toolResult"`,
3692
5626
  * which `JSON.stringify`, the only writer of a row, always writes as such (it never escapes a letter).
@@ -3715,15 +5649,24 @@ var SqlSessionStore = class SqlSessionStore {
3715
5649
  const length = Math.min(Math.max(1, Math.trunc(bytes) || 1), SESSION_HISTORY_PAGE_BYTES);
3716
5650
  const generation = this.generation(sessionId);
3717
5651
  const json = this.dialect.name === "sqlite" ? "CAST(e.entry_json AS BLOB)" : "convert_to(e.entry_json, 'UTF8')";
3718
- const row = await this.database.get(`SELECT s.last_seq, s.revision, ${generation.sql} AS epoch,
5652
+ const shared = this.sharedHistorySeen;
5653
+ const plain = shared && this.forkedSessions.get(sessionId) === false;
5654
+ const view = this.entriesView({
5655
+ segments: shared && !plain ? this.forkTables.forkSegments : void 0,
5656
+ dialect: this.dialect
5657
+ }, sessionId, seq - 1, seq);
5658
+ const row = await this.database.get(withForkViews([view], `SELECT s.last_seq, s.revision, ${generation.sql} AS epoch,
3719
5659
  (SELECT schema_version FROM ${this.tables.meta} LIMIT 1) AS schema_version, e.chunks,
3720
5660
  CASE WHEN e.chunks > 0
3721
- THEN (SELECT substr(c.data, CAST(? AS INTEGER), CAST(? AS INTEGER)) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx = ?)
3722
- ELSE substr(${json}, CAST(? AS INTEGER), CAST(? AS INTEGER)) END AS data
3723
- FROM ${this.tables.sessions} s LEFT JOIN ${this.tables.entries} e ON e.session_id = s.id AND e.seq = ?
3724
- WHERE s.id = ?`, ...generation.params, offset % SESSION_ENTRY_CHUNK_BYTES + 1, length, Math.floor(offset / SESSION_ENTRY_CHUNK_BYTES), offset + 1, length, seq, sessionId);
5661
+ THEN (SELECT substr(c.data, CAST(? AS INTEGER), CAST(? AS INTEGER)) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.src_id AND c.seq = e.src_seq AND c.idx = ?)
5662
+ ELSE substr(${json}, CAST(? AS INTEGER), CAST(? AS INTEGER)) END AS data${this.outsideForkedColumn("s.id")}
5663
+ FROM ${this.tables.sessions} s LEFT JOIN ${view.name} e ON e.session_id = s.id
5664
+ WHERE s.id = ?`), ...view.params, ...generation.params, offset % SESSION_ENTRY_CHUNK_BYTES + 1, length, Math.floor(offset / SESSION_ENTRY_CHUNK_BYTES), offset + 1, length, sessionId);
3725
5665
  if (!row) throw new SessionNotFoundError$1(sessionId);
3726
- assertStorageSchemaVersion("sessions", row.schema_version, 2, SESSION_SCHEMA_VERSION_UNCHUNKED);
5666
+ assertStorageSchemaVersion("sessions", row.schema_version, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
5667
+ this.noteSchemaVersion(row.schema_version);
5668
+ this.noteForked(void 0, sessionId, row.forked);
5669
+ if (this.sharedHistorySeen !== shared || plain && Number(row.forked) === 1) return SqlSessionStore.prototype.readEntryChunk.call(this, reference, offset, bytes);
3727
5670
  this.noteGeneration(sessionId, row.revision, Number(row.last_seq), row.epoch);
3728
5671
  if (row.epoch !== epoch) throw new SessionConflictError$1(sessionId, seq, Number(row.last_seq));
3729
5672
  if (row.chunks === null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing session entry ${seq}`));
@@ -3735,7 +5678,7 @@ var SqlSessionStore = class SqlSessionStore {
3735
5678
  validateSessionText("sessionId", sessionId);
3736
5679
  validateSessionText("entry.id", entryId);
3737
5680
  if (!await this.readHeader(sessionId)) throw new SessionNotFoundError$1(sessionId);
3738
- return this.seqOfEntry(this.database, sessionId, entryId);
5681
+ return this.seqOfEntry(this.database, void 0, sessionId, entryId);
3739
5682
  }
3740
5683
  /**
3741
5684
  * Earlier entries that may save the same task reference as each candidate (#5593), in one statement on the session
@@ -3746,12 +5689,21 @@ var SqlSessionStore = class SqlSessionStore {
3746
5689
  this.assertOpen();
3747
5690
  validateSessionText("sessionId", sessionId);
3748
5691
  const { candidates, afterSeq, limit } = taskReferenceDuplicateQuery(query);
3749
- return this.readTransaction(async (tx) => {
5692
+ return this.readTransaction(sessionId, async (tx) => {
5693
+ const tables = await this.viewTables(tx, sessionId);
3750
5694
  const head = await this.historyHead(tx, sessionId, true);
3751
5695
  if (head.epoch !== query.epoch || head.lastSeq < query.throughSeq) throw new SessionConflictError$1(sessionId, query.throughSeq, head.lastSeq);
3752
5696
  if (candidates.length === 0) return { seqs: [] };
3753
5697
  const t = snapshotIndexTables$1(this.prefix);
3754
- const links = t.sessionLinks;
5698
+ const view = !head.forked ? void 0 : forkView(tables, {
5699
+ name: "links_view",
5700
+ table: t.sessionLinks,
5701
+ columns: ["entry_id"],
5702
+ sessionId,
5703
+ after: 0,
5704
+ through: query.throughSeq
5705
+ });
5706
+ const links = view === void 0 ? t.sessionLinks : "links_view";
3755
5707
  /**
3756
5708
  * For each candidate `c`, the links row `s` at its sequence and then, with `earlier`, the rows `e` before it
3757
5709
  * under an ID, each found through an index, never by walking the session. Postgres plans a lateral subquery
@@ -3776,11 +5728,11 @@ var SqlSessionStore = class SqlSessionStore {
3776
5728
  WHEN c.suffix > 0 AND c.suffix <= length(s.entry_id) AND substr(s.entry_id, length(s.entry_id) - c.suffix + 1, 1) = ':'
3777
5729
  THEN substr(s.entry_id, 1, length(s.entry_id) - c.suffix) END`;
3778
5730
  const values = candidates.map(() => `(CAST(? AS ${this.dialect.types.int}), CAST(? AS INTEGER), CAST(? AS INTEGER))`);
3779
- const rows = await tx.all(`WITH c(seq, idx, suffix) AS (VALUES ${values.join(", ")}),
5731
+ const rows = await tx.all(withForkViews(view === void 0 ? [] : [view], `WITH c(seq, idx, suffix) AS (VALUES ${values.join(", ")}),
3780
5732
  hits AS (SELECT e.seq AS seq FROM ${rowsOf("s.entry_id")} UNION SELECT e.seq FROM ${rowsOf(other)})
3781
5733
  SELECT 0 AS kind, (SELECT CASE WHEN backfilled_through >= watermark THEN 1 ELSE 0 END FROM ${t.sources} WHERE source = 'session-entries') AS seq
3782
5734
  UNION ALL SELECT 1, count(*) FROM ${rowsOf()}
3783
- UNION ALL SELECT 2, page.seq FROM (SELECT seq FROM hits ORDER BY seq LIMIT ?) page`, ...candidates.flat(), ...[
5735
+ UNION ALL SELECT 2, page.seq FROM (SELECT seq FROM hits ORDER BY seq LIMIT ?) page`), ...view?.params ?? [], ...candidates.flat(), ...[
3784
5736
  sessionId,
3785
5737
  sessionId,
3786
5738
  afterSeq,
@@ -3809,12 +5761,36 @@ var SqlSessionStore = class SqlSessionStore {
3809
5761
  this.assertOpen();
3810
5762
  validateSessionText("sessionId", sessionId);
3811
5763
  const { indexedForkWindow, forkMetadata, byteMetadata, locateFork } = await import("../core/storage/session/fork-window.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
3812
- return this.readTransaction(async (tx) => {
5764
+ return this.readTransaction(sessionId, async (tx) => {
3813
5765
  const snapshots = snapshotIndexTables$1(this.prefix);
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);
5766
+ const shared = await this.viewTables(tx);
5767
+ const headRead = (leafTables) => {
5768
+ const leafViews = [snapshots.sessionLinks, this.tables.entries].map((table, index) => forkView(leafTables, {
5769
+ name: `leaf_${index}`,
5770
+ table,
5771
+ columns: ["entry_id"],
5772
+ sessionId,
5773
+ after: 0,
5774
+ through: FORK_VIEW_END,
5775
+ match: {
5776
+ column: "entry_id",
5777
+ value: entryId
5778
+ }
5779
+ }));
5780
+ return tx.get(withForkViews(leafViews, `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 leaf_0) ELSE (SELECT max(seq) FROM leaf_1) END AS leaf_seq${this.forkedColumn(shared.segments, "s.id")} FROM ${this.tables.sessions} s WHERE s.id=?`), ...forkViewParams(leafViews), sessionId);
5781
+ };
5782
+ const guessPlain = shared.segments !== void 0 && this.forkedSessions.get(sessionId) === false;
5783
+ let row = await headRead(guessPlain ? {
5784
+ ...shared,
5785
+ segments: void 0
5786
+ } : shared);
5787
+ if (row && guessPlain && Number(row.forked) === 1) row = await headRead(shared);
5788
+ if (row) this.noteForked(tx, sessionId, row.forked);
5789
+ const tables = await this.viewTables(tx, sessionId);
3815
5790
  if (!row) throw new SessionNotFoundError$1(sessionId);
3816
5791
  const header = JSON.parse(row.header_json);
3817
5792
  const state = JSON.parse(row.summary_state);
5793
+ const generation = state.epoch ?? row.revision;
3818
5794
  const count = Number(row.last_seq);
3819
5795
  const cached = this.resumeIndexes.get(sessionId);
3820
5796
  const ready = windowIndex(state, count) ?? (cached?.revision === row.revision ? cached.index : void 0);
@@ -3825,23 +5801,32 @@ var SqlSessionStore = class SqlSessionStore {
3825
5801
  if (!seqs.length) return result;
3826
5802
  const raw = this.dialect.name === "sqlite" ? "CAST(entry_json AS BLOB)" : "convert_to(entry_json,'UTF8')";
3827
5803
  const size = this.dialect.textByteLength("entry_json");
3828
- const rows = await tx.all(`SELECT seq,chunks,${size} AS bytes,CASE WHEN chunks=0 AND ${size}<=512 THEN entry_json END AS body FROM ${this.tables.entries} WHERE session_id=? AND seq IN (${seqs.map(() => "?").join(",")}) ORDER BY seq`, sessionId, ...seqs);
5804
+ const view = this.entriesView(tables, sessionId, Math.min(...seqs) - 1, Math.max(...seqs));
5805
+ const rows = await tx.all(withForkViews([view], `SELECT seq,chunks,${size} AS bytes,CASE WHEN chunks=0 AND ${size}<=512 THEN entry_json END AS body FROM ${view.name} WHERE session_id=? AND ${inJsonList(this.dialect, "seq", true)} ORDER BY seq`), ...view.params, sessionId, JSON.stringify(seqs));
3829
5806
  for (const row of rows) {
3830
5807
  const seq = Number(row.seq);
3831
5808
  if (row.body !== null) result.push(forkMetadata(seq, JSON.parse(row.body)));
3832
5809
  else if (Number(row.chunks) > 0) {
3833
5810
  const { projectForkMetadata } = await import("../core/storage/session/chunked-resume-projection.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
3834
- result.push(await projectForkMetadata(seq, this.forkEntryChunks(tx, sessionId, seq, Number(row.chunks))));
5811
+ result.push(await projectForkMetadata(seq, this.forkEntryChunks(tx, tables, sessionId, seq, Number(row.chunks))));
3835
5812
  } else result.push(await byteMetadata(seq, Number(row.bytes), async (offset, n) => {
3836
- const piece = await tx.get(`SELECT substr(${raw},?,?) AS part FROM ${this.tables.entries} WHERE session_id=? AND seq=?`, offset + 1, n, sessionId, seq);
5813
+ const one = this.entriesView(tables, sessionId, seq - 1, seq);
5814
+ const piece = await tx.get(withForkViews([one], `SELECT substr(${raw},?,?) AS part FROM ${one.name}`), ...one.params, offset + 1, n);
3837
5815
  if (!piece) throw new StorageError(`Session ${sessionId} entry ${seq} disappeared during its fork`);
3838
5816
  return piece.part;
3839
5817
  }));
3840
5818
  }
3841
5819
  return result;
3842
5820
  };
3843
- const entries = this.tables.entries;
3844
5821
  const j = (field) => this.dialect.jsonText("entry_json", field);
5822
+ const dialect = this.dialect;
5823
+ const scanWindow = (from, through) => {
5824
+ const end = tables.segments === void 0 ? through : Math.min(through, from - 1 + SCAN_SELECT_WINDOW);
5825
+ return {
5826
+ end,
5827
+ view: this.entriesView(tables, sessionId, from - 1, end)
5828
+ };
5829
+ };
3845
5830
  const selected = ready ? {
3846
5831
  index: ready,
3847
5832
  leaf,
@@ -3849,7 +5834,7 @@ var SqlSessionStore = class SqlSessionStore {
3849
5834
  } : await locateFork({
3850
5835
  ...foldSessionResume(void 0, []),
3851
5836
  seq: count,
3852
- epoch: state.epoch ?? row.revision,
5837
+ epoch: generation,
3853
5838
  needsBranchRebuild: true
3854
5839
  }, entryId, async (seqs) => {
3855
5840
  const pg = this.dialect.name === "postgres";
@@ -3871,7 +5856,8 @@ var SqlSessionStore = class SqlSessionStore {
3871
5856
  } : { column: "entry_json" }, "data", "completionId")} THEN ${key("data", "completionId")} END`,
3872
5857
  key("message", "role")
3873
5858
  ]);
3874
- const parsed = (await tx.all(`WITH projected AS MATERIALIZED (SELECT seq,chunks,CAST(${projection} AS TEXT) AS link FROM ${entries} ${pg ? `CROSS JOIN LATERAL (SELECT ${postgresJsonb("entry_json")} AS value OFFSET 0) AS parsed` : ""} WHERE session_id=? AND seq BETWEEN ? AND ?) SELECT seq,chunks,CASE WHEN ${this.dialect.textByteLength("link")}<=512 THEN link END AS link FROM projected ORDER BY seq`, sessionId, seqs[0], seqs.at(-1))).map((r) => ({
5859
+ const view = this.entriesView(tables, sessionId, seqs[0] - 1, seqs.at(-1));
5860
+ const parsed = (await tx.all(withForkViews([view], `WITH projected AS MATERIALIZED (SELECT seq,chunks,CAST(${projection} AS TEXT) AS link FROM ${view.name} ${pg ? `CROSS JOIN LATERAL (SELECT ${postgresJsonb("entry_json")} AS value OFFSET 0) AS parsed` : ""} WHERE session_id=? AND seq BETWEEN ? AND ?) SELECT seq,chunks,CASE WHEN ${this.dialect.textByteLength("link")}<=512 THEN link END AS link FROM projected ORDER BY seq`), ...view.params, sessionId, seqs[0], seqs.at(-1))).map((r) => ({
3875
5861
  seq: Number(r.seq),
3876
5862
  chunked: Number(r.chunks) > 0,
3877
5863
  link: r.link === null ? void 0 : JSON.parse(r.link)
@@ -3882,7 +5868,8 @@ var SqlSessionStore = class SqlSessionStore {
3882
5868
  const { messageRoleIn } = await import("../core/storage/session/chunked-resume-projection.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
3883
5869
  for (let i = 0; i < chunkedMessages.length; i += SEQ_BATCH) {
3884
5870
  const batch = chunkedMessages.slice(i, i + SEQ_BATCH);
3885
- const prefixes = await tx.all(`SELECT seq,substr(data,1,${FORK_ROLE_PREFIX_BYTES}) AS prefix FROM ${this.tables.entryChunks} WHERE session_id=? AND idx=0 AND seq IN (${batch.map(() => "?").join(",")})`, sessionId, ...batch);
5871
+ const view = this.entriesView(tables, sessionId, Math.min(...batch) - 1, Math.max(...batch));
5872
+ const prefixes = await tx.all(withForkViews([view], `SELECT v.seq,substr(c.data,1,${FORK_ROLE_PREFIX_BYTES}) AS prefix FROM ${view.name} v JOIN ${this.tables.entryChunks} c ON c.session_id=v.src_id AND c.seq=v.src_seq AND c.idx=0 WHERE ${inJsonList(this.dialect, "v.seq", true)}`), ...view.params, JSON.stringify(batch));
3886
5873
  for (const row of prefixes) roles.set(Number(row.seq), messageRoleIn(row.prefix));
3887
5874
  }
3888
5875
  }
@@ -3910,14 +5897,18 @@ var SqlSessionStore = class SqlSessionStore {
3910
5897
  return page;
3911
5898
  }, true, SESSION_READ_FETCH.max);
3912
5899
  const labelBody = `CASE WHEN chunks=0 AND ${this.dialect.textByteLength("entry_json")}<=512 THEN entry_json END`;
3913
- return indexedForkWindow(header, selected.index, selected.leaf, (lo, hi) => this.readRows(tx, sessionId, "seq BETWEEN ? AND ?", [lo, hi]), (seqs) => this.readSeqs(tx, sessionId, seqs), metadata, async function* (ranges, kinds, types = []) {
5900
+ return indexedForkWindow(header, selected.index, selected.leaf, (lo, hi) => this.readRows(tx, sessionId, {
5901
+ from: lo,
5902
+ through: hi
5903
+ }, void 0, generation), (seqs) => this.readSeqs(tx, sessionId, seqs, generation), metadata, async function* (ranges, kinds, types = []) {
3914
5904
  const filters = [];
3915
- if (types.length) filters.push(`${j("type")} IN (${types.map(() => "?").join(",")})`);
3916
- if (kinds.length) filters.push(`(${j("type")}='custom' AND (chunks>0 OR ${j("customType")} IN (${kinds.map(() => "?").join(",")})))`);
5905
+ if (types.length) filters.push(inJsonList(dialect, j("type")));
5906
+ if (kinds.length) filters.push(`(${j("type")}='custom' AND (chunks>0 OR ${inJsonList(dialect, j("customType"))}))`);
3917
5907
  for (const [lo, hi] of ranges) for (let seq = lo; seq <= hi;) {
3918
5908
  const labels = types.length === 1 && types[0] === "label";
3919
5909
  const limit = labels ? SESSION_READ_FETCH.first : SESSION_READ_FETCH.max;
3920
- const rows = await tx.all(`SELECT seq,${j("type")} AS kind${labels ? `,${labelBody} AS body` : ""} FROM ${entries} WHERE session_id=? AND seq BETWEEN ? AND ? AND (${filters.join(" OR ")}) ORDER BY seq LIMIT ${limit}`, sessionId, seq, hi, ...types, ...kinds);
5910
+ const { end, view } = scanWindow(seq, hi);
5911
+ const rows = await tx.all(withForkViews([view], `SELECT seq,${j("type")} AS kind${labels ? `,${labelBody} AS body` : ""} FROM ${view.name} WHERE session_id=? AND seq BETWEEN ? AND ? AND (${filters.join(" OR ")}) ORDER BY seq LIMIT ${limit}`), ...view.params, sessionId, seq, end, ...types.length ? [JSON.stringify(types)] : [], ...kinds.length ? [JSON.stringify(kinds)] : []);
3921
5912
  const deferred = rows.filter((r) => r.kind === "custom" || r.kind === "label" && !r.body).map((r) => Number(r.seq));
3922
5913
  const projected = /* @__PURE__ */ new Map();
3923
5914
  for (let i = 0; i < deferred.length; i += SEQ_BATCH) for (const m of await metadata(deferred.slice(i, i + SEQ_BATCH))) projected.set(m.seq, m);
@@ -3925,8 +5916,10 @@ var SqlSessionStore = class SqlSessionStore {
3925
5916
  type: row.kind,
3926
5917
  seq: Number(row.seq)
3927
5918
  });
3928
- if (rows.length < limit) break;
3929
- seq = Number(rows.at(-1).seq) + 1;
5919
+ if (rows.length < limit) {
5920
+ if (end >= hi) break;
5921
+ seq = end + 1;
5922
+ } else seq = Number(rows.at(-1).seq) + 1;
3930
5923
  }
3931
5924
  }, {
3932
5925
  ...selected.extras,
@@ -3934,9 +5927,10 @@ var SqlSessionStore = class SqlSessionStore {
3934
5927
  });
3935
5928
  });
3936
5929
  }
3937
- async *forkEntryChunks(tx, id, seq, count) {
5930
+ async *forkEntryChunks(tx, tables, id, seq, count) {
3938
5931
  for (let i = 0; i < count; i++) {
3939
- const row = await tx.get(`SELECT data FROM ${this.tables.entryChunks} WHERE session_id=? AND seq=? AND idx=?`, id, seq, i);
5932
+ const read = this.entryChunkRead(tables, id, seq, i);
5933
+ const row = await tx.get(read.sql, ...read.params);
3940
5934
  if (!row) throw new StorageError(`Session ${id} entry ${seq} is missing chunk ${i} of ${count}`);
3941
5935
  yield row.data;
3942
5936
  }
@@ -3956,7 +5950,7 @@ var SqlSessionStore = class SqlSessionStore {
3956
5950
  validateSessionText("sessionId", sessionId);
3957
5951
  if (leafId !== void 0) validateSessionText("entry.id", leafId);
3958
5952
  if (leafId === void 0 && throughSeq === void 0) try {
3959
- return await this.readTransaction(async (tx) => {
5953
+ return await this.readTransaction(sessionId, async (tx) => {
3960
5954
  const { header, index } = await this.resumeSource(tx, sessionId);
3961
5955
  return this.resumeIn(tx, sessionId, header, index, options);
3962
5956
  }, [this.resumeRow(sessionId)]);
@@ -3965,9 +5959,11 @@ var SqlSessionStore = class SqlSessionStore {
3965
5959
  }
3966
5960
  for (let attempt = 0; attempt < 3; attempt++) {
3967
5961
  const { index, revision } = await this.prepareResume(sessionId, leafId, throughSeq);
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);
5962
+ const resume = await this.readTransaction(sessionId, async (tx) => {
5963
+ const { segments } = await this.viewTables(tx);
5964
+ const head = await tx.get(`SELECT header_json,revision${this.forkedColumn(segments)} FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
3970
5965
  if (!head) throw new SessionNotFoundError$1(sessionId);
5966
+ this.noteForked(tx, sessionId, head.forked);
3971
5967
  if (revision !== head.revision) return void 0;
3972
5968
  return this.resumeIn(tx, sessionId, JSON.parse(head.header_json), index, options);
3973
5969
  });
@@ -3981,9 +5977,12 @@ var SqlSessionStore = class SqlSessionStore {
3981
5977
  const plan = sessionResumePlan(index, index.leafSeq, options?.deferChildRecords);
3982
5978
  announceHistoryLoad(plan.state.length + plan.branch.reduce((sum, [a, b]) => sum + b - a + 1, 0));
3983
5979
  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)
5980
+ Promise.all(plan.branch.map(([start, end]) => this.readRows(tx, sessionId, {
5981
+ from: start,
5982
+ through: end
5983
+ }, void 0, index.epoch))),
5984
+ this.readSeqs(tx, sessionId, plan.state, index.epoch),
5985
+ leafSeq <= 0 ? void 0 : this.entryIdAt(tx, sessionId, leafSeq)
3987
5986
  ]);
3988
5987
  const branch = ranges.flat();
3989
5988
  const resume = sessionResumeFrom(index, header, branch, state, leaf?.entry_id ?? null, plan.children);
@@ -3994,16 +5993,16 @@ var SqlSessionStore = class SqlSessionStore {
3994
5993
  this.assertOpen();
3995
5994
  validateSessionText("sessionId", sessionId);
3996
5995
  if (leafId !== void 0) validateSessionText("entry.id", leafId);
3997
- const { point } = await this.withResumeIndex(sessionId, () => this.readTransaction(async (tx) => {
5996
+ const { point } = await this.withResumeIndex(sessionId, () => this.readTransaction(sessionId, async (tx) => {
3998
5997
  const source = await this.resumeSource(tx, sessionId);
3999
5998
  const { index } = source;
4000
- const leafSeq = leafId === void 0 ? index.leafSeq : await this.seqOfEntry(tx, sessionId, leafId) ?? -1;
5999
+ const leafSeq = leafId === void 0 ? index.leafSeq : await this.seqOfEntry(tx, await this.viewTables(tx, sessionId), sessionId, leafId) ?? -1;
4001
6000
  const found = latestCompactionOf(index, leafSeq);
4002
6001
  if (found === void 0) return {
4003
6002
  point: void 0,
4004
6003
  source
4005
6004
  };
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)]);
6005
+ const [[boundary], leaf] = await Promise.all([this.readSeqs(tx, sessionId, [found.seq]), this.entryIdAt(tx, sessionId, leafSeq)]);
4007
6006
  if (boundary === void 0 || leaf === void 0) return {
4008
6007
  point: void 0,
4009
6008
  source
@@ -4020,15 +6019,44 @@ var SqlSessionStore = class SqlSessionStore {
4020
6019
  }, [this.resumeRow(sessionId)]));
4021
6020
  return point;
4022
6021
  }
6022
+ /** The ID of the entry at view seq `seq` of session `sessionId`, read in transaction `tx` (#6560). */
6023
+ async entryIdAt(tx, sessionId, seq) {
6024
+ const view = this.entriesView(await this.viewTables(tx, sessionId), sessionId, seq - 1, seq);
6025
+ return tx.get(withForkViews([view], `SELECT entry_id FROM ${view.name}`), ...view.params);
6026
+ }
4023
6027
  /** The JSON of a long entry, from its chunks, one statement each. */
4024
- async readEntryChunks(tx, sessionId, seq, count) {
4025
- return Buffer.concat(await this.readRawEntryChunks(tx, sessionId, seq, count)).toString("utf8");
6028
+ async readEntryChunks(tx, tables, sessionId, seq, count) {
6029
+ return Buffer.concat(await this.readRawEntryChunks(tx, tables, sessionId, seq, count)).toString("utf8");
6030
+ }
6031
+ /**
6032
+ * The read of chunk `index` of the entry at view seq `seq` of session `sessionId` (#6560), found through the view in
6033
+ * the statement itself, on the condition `condition` with `params` when given.
6034
+ */
6035
+ entryChunkRead(tables, sessionId, seq, index, condition) {
6036
+ const view = this.entriesView(tables, sessionId, seq - 1, seq);
6037
+ return {
6038
+ sql: withForkViews([view], `SELECT c.data FROM ${view.name} v JOIN ${this.tables.entryChunks} c
6039
+ ON c.session_id = v.src_id AND c.seq = v.src_seq AND c.idx = ?${condition === void 0 ? "" : ` WHERE ${condition.sql}`}`),
6040
+ params: [
6041
+ ...view.params,
6042
+ index,
6043
+ ...condition?.params ?? []
6044
+ ]
6045
+ };
4026
6046
  }
4027
- async readRawEntryChunks(tx, sessionId, seq, count, signal) {
6047
+ /**
6048
+ * The chunks of the entry at view seq `seq`: in transaction `tx` with `tables`, or, with `tables` undefined, each
6049
+ * read outside a transaction through `outsideTransaction`.
6050
+ */
6051
+ async readRawEntryChunks(tx, tables, sessionId, seq, count, signal) {
4028
6052
  const chunks = [];
4029
6053
  for (let index = 0; index < count; index++) {
4030
6054
  signal?.throwIfAborted();
4031
- const chunk = await tx.get(`SELECT data FROM ${this.tables.entryChunks} WHERE session_id = ? AND seq = ? AND idx = ?`, sessionId, seq, index);
6055
+ const read = (viewTables) => {
6056
+ const statement = this.entryChunkRead(viewTables, sessionId, seq, index);
6057
+ return tx.get(statement.sql, ...statement.params);
6058
+ };
6059
+ const chunk = tables === void 0 ? await this.outsideTransaction(read, (row) => row !== void 0) : await read(tables);
4032
6060
  if (chunk === void 0) throw new StorageError(`Session ${sessionId} entry ${seq} is missing chunk ${index} of ${count}`);
4033
6061
  chunks.push(chunk.data);
4034
6062
  if (signal !== void 0 && index + 1 < count) await yieldTurn();
@@ -4037,23 +6065,30 @@ var SqlSessionStore = class SqlSessionStore {
4037
6065
  }
4038
6066
  async *entryChunks(sessionId, seq, count, revision) {
4039
6067
  for (let index = 0; index < count; index++) {
4040
- const chunk = await this.database.get(`SELECT data FROM ${this.tables.entryChunks} WHERE session_id = ? AND seq = ? AND idx = ?
4041
- AND EXISTS (SELECT 1 FROM ${this.tables.sessions} WHERE id = ? AND revision = ?)`, sessionId, seq, index, sessionId, revision);
6068
+ const chunk = await this.outsideTransaction((tables) => {
6069
+ const statement = this.entryChunkRead(tables, sessionId, seq, index, {
6070
+ sql: `EXISTS (SELECT 1 FROM ${this.tables.sessions} WHERE id = ? AND revision = ?)`,
6071
+ params: [sessionId, revision]
6072
+ });
6073
+ return this.database.get(statement.sql, ...statement.params);
6074
+ }, (row) => row !== void 0);
4042
6075
  if (chunk === void 0) throw new StorageError(`Session ${sessionId} entry ${seq} is missing chunk ${index} of ${count}`);
4043
6076
  yield chunk.data;
4044
6077
  if (index + 1 < count) await yieldTurn();
4045
6078
  }
4046
6079
  }
6080
+ /** The JSON bytes of the entry stored whole at view seq `seq`, read outside a transaction. */
4047
6081
  async readInlineEntryBytes(sessionId, seq) {
4048
- if (this.dialect.name === "sqlite") {
4049
- const row = await this.database.get(`SELECT CAST(entry_json AS BLOB) AS data FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, seq);
4050
- return row ? [row.data] : [];
4051
- }
4052
- const row = await this.database.get(`SELECT entry_json FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, seq);
4053
- return row ? [new TextEncoder().encode(row.entry_json)] : [];
4054
- }
4055
- async forWrite(tx, sessionId, options, includeSummaryState = false) {
4056
- const read = this.headRead(sessionId, options, includeSummaryState);
6082
+ const sqlite = this.dialect.name === "sqlite";
6083
+ const row = await this.outsideTransaction((tables) => {
6084
+ const view = this.entriesView(tables, sessionId, seq - 1, seq);
6085
+ return this.database.get(withForkViews([view], `SELECT ${sqlite ? "CAST(entry_json AS BLOB)" : "entry_json"} AS data FROM ${view.name}`), ...view.params);
6086
+ }, (found) => found !== void 0);
6087
+ if (row === void 0) return [];
6088
+ return [typeof row.data === "string" ? new TextEncoder().encode(row.data) : row.data];
6089
+ }
6090
+ async forWrite(tx, sessionId, options, includeSummaryState = false, forked = false) {
6091
+ const read = this.headRead(sessionId, options, includeSummaryState, forked);
4057
6092
  const row = await tx.get(read.sql, ...read.params);
4058
6093
  if (!row) throw new SessionNotFoundError$1(sessionId);
4059
6094
  const state = row.summary_state === void 0 ? void 0 : JSON.parse(String(row.summary_state));
@@ -4063,32 +6098,56 @@ var SqlSessionStore = class SqlSessionStore {
4063
6098
  state
4064
6099
  };
4065
6100
  }
4066
- /** The read of the session's row that `forWrite` checks a write against. */
4067
- headRead(sessionId, options, includeSummaryState) {
6101
+ /**
6102
+ * The read of the session's row that `forWrite` checks a write against; with `forked`, once this store has seen
6103
+ * shared history, it also reads whether the session has fork segments (#6560).
6104
+ */
6105
+ headRead(sessionId, options, includeSummaryState, forked = false) {
4068
6106
  return {
4069
- sql: `SELECT header_json, last_seq${includeSummaryState || options.epoch !== void 0 ? ", summary_state" : ""}
6107
+ sql: `SELECT header_json, last_seq${includeSummaryState || options.epoch !== void 0 ? ", summary_state" : ""}${forked ? this.outsideForkedColumn("id") : ""}
4070
6108
  FROM ${this.tables.sessions} WHERE id = ?`,
4071
6109
  params: [sessionId]
4072
6110
  };
4073
6111
  }
6112
+ /** Whether session `sessionId` has fork segments, read in `tx`, whose database has shared history (#6560). */
6113
+ async hasForkSegments(tx, sessionId) {
6114
+ return await tx.get(`SELECT 1 AS found FROM ${this.forkTables.forkSegments} WHERE session_id = ? LIMIT 1`, sessionId) !== void 0;
6115
+ }
4074
6116
  async appendedResume(tx, sessionId, previous, lastSeq, entries) {
4075
6117
  if (!isSessionResumeIndex(previous, lastSeq)) return void 0;
4076
6118
  const seqs = /* @__PURE__ */ new Map();
4077
6119
  for (const id of foreignResumeIds(previous, entries)) {
4078
- const seq = await this.seqOfEntry(tx, sessionId, id);
6120
+ const seq = await this.seqOfEntry(tx, await this.viewTables(tx), sessionId, id);
4079
6121
  if (seq !== void 0) seqs.set(id, seq);
4080
6122
  }
4081
6123
  return foldSessionResume(previous, entries, (id) => seqs.get(id));
4082
6124
  }
4083
- async seqOfEntry(executor, sessionId, entryId) {
4084
- const tables = snapshotIndexTables$1(this.prefix);
4085
- const source = await executor.get(`SELECT CASE WHEN backfilled_through >= watermark THEN 1 ELSE 0 END AS complete FROM ${tables.sources} WHERE source = 'session-entries'`);
4086
- if (Number(source?.complete) === 1) {
4087
- const linked = await executor.get(`SELECT seq FROM ${tables.sessionLinks} WHERE session_id = ? AND entry_id = ? ORDER BY seq DESC LIMIT 1`, sessionId, entryId);
4088
- return linked === void 0 ? void 0 : Number(linked.seq);
4089
- }
4090
- const row = await executor.get(`SELECT seq FROM ${this.tables.entries} WHERE session_id = ? AND entry_id = ? ORDER BY seq DESC LIMIT 1`, sessionId, entryId);
4091
- return row === void 0 ? void 0 : Number(row.seq);
6125
+ /**
6126
+ * The latest seq of session `sessionId` that holds entry `entryId`, through its view (#6560): in transaction
6127
+ * `executor` with `tables`, or, with `tables` undefined, outside a transaction through `outsideTransaction`. A fork's
6128
+ * inherited entries are linked under the sessions that store them, at their seqs there, which the view renumbers.
6129
+ */
6130
+ async seqOfEntry(executor, tables, sessionId, entryId) {
6131
+ const index = snapshotIndexTables$1(this.prefix);
6132
+ const source = await executor.get(`SELECT CASE WHEN backfilled_through >= watermark THEN 1 ELSE 0 END AS complete FROM ${index.sources} WHERE source = 'session-entries'`);
6133
+ const table = Number(source?.complete) === 1 ? index.sessionLinks : this.tables.entries;
6134
+ const read = (viewTables, forked = "") => {
6135
+ const view = forkView(viewTables, {
6136
+ name: "linked",
6137
+ table,
6138
+ columns: ["entry_id"],
6139
+ sessionId,
6140
+ after: 0,
6141
+ through: FORK_VIEW_END,
6142
+ match: {
6143
+ column: "entry_id",
6144
+ value: entryId
6145
+ }
6146
+ });
6147
+ return executor.get(withForkViews([view], `SELECT (SELECT seq FROM linked ORDER BY seq DESC LIMIT 1) AS seq${forked}`), ...view.params, ...forked === "" ? [] : [sessionId]);
6148
+ };
6149
+ const row = tables === void 0 ? await this.outsideSessionRead(sessionId, (viewTables) => read(viewTables, this.outsideForkedColumn("?")), (found) => found?.seq != null, (found) => found?.forked) : await read(tables);
6150
+ return row?.seq == null ? void 0 : Number(row.seq);
4092
6151
  }
4093
6152
  async saveSummary(tx, sessionId, snapshot, previous, appendedResume) {
4094
6153
  const { statement, texts, epoch } = this.summaryWrite(sessionId, snapshot, previous, appendedResume);
@@ -4110,6 +6169,12 @@ var SqlSessionStore = class SqlSessionStore {
4110
6169
  epoch
4111
6170
  };
4112
6171
  const summary = materializeSessionSummaryMetadata(header, state);
6172
+ const row = {
6173
+ header_json: this.encode(header),
6174
+ summary_state: this.encode(state),
6175
+ revision: newRevision(),
6176
+ last_seq: lastSeq
6177
+ };
4113
6178
  return {
4114
6179
  statement: {
4115
6180
  sql: `INSERT INTO ${this.tables.sessions}
@@ -4127,7 +6192,7 @@ var SqlSessionStore = class SqlSessionStore {
4127
6192
  sessionId,
4128
6193
  header.cwd,
4129
6194
  header.createdAt,
4130
- this.encode(header),
6195
+ row.header_json,
4131
6196
  header.internal ? 1 : 0,
4132
6197
  lastSeq,
4133
6198
  summary.modifiedAt,
@@ -4137,17 +6202,28 @@ var SqlSessionStore = class SqlSessionStore {
4137
6202
  summary.hasName ? 1 : 0,
4138
6203
  summary.summary === void 0 ? null : this.encode(summary.summary),
4139
6204
  summary.summarizedThroughId ?? null,
4140
- this.encode(state),
4141
- newRevision()
6205
+ row.summary_state,
6206
+ row.revision
4142
6207
  ]
4143
6208
  },
4144
6209
  texts,
4145
- epoch
6210
+ epoch,
6211
+ row
4146
6212
  };
4147
6213
  }
4148
- async insertEntries(tx, sessionId, entries, lastSeq, texts, versionStep = true) {
6214
+ async insertEntries(tx, sessionId, entries, lastSeq, texts, versionStep = true, written) {
4149
6215
  const writes = new SentWrites(tx);
4150
- await writes.around(() => writes.send(this.entryWrites(sessionId, entries, lastSeq, texts, versionStep)));
6216
+ await writes.around(() => writes.send(this.entryWrites(sessionId, entries, lastSeq, texts, versionStep, written)));
6217
+ }
6218
+ /**
6219
+ * Notes `written`, the entries a committed write of session `sessionId` stored in generation `epoch`, as stored there
6220
+ * (#6560): a manager keeps the very objects it appended, so a fork of it shares their rows without reading them back.
6221
+ * Only where this store has seen shared history, for which alone the notes count.
6222
+ */
6223
+ noteWritten(sessionId, epoch, written) {
6224
+ if (!this.sharedHistorySeen) return;
6225
+ const note = storedEntryNotes(this, sessionId, epoch);
6226
+ for (const { entry, seq, json } of written) note(entry, seq, json);
4151
6227
  }
4152
6228
  /**
4153
6229
  * A fork's version step, once every entry of the child is in, as the transaction's last write: the same row order as
@@ -4155,7 +6231,12 @@ var SqlSessionStore = class SqlSessionStore {
4155
6231
  * so the two never deadlock (#6560). The body makes no call after it.
4156
6232
  */
4157
6233
  async finishFork(tx, child) {
4158
- const step = {
6234
+ const step = this.forkVersionStep(child);
6235
+ if (transactionFinisher(tx)?.([step]) !== true) await tx.run(step.sql, ...step.params);
6236
+ }
6237
+ /** The statement of {@link finishFork}. */
6238
+ forkVersionStep(child) {
6239
+ return {
4159
6240
  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
6241
  params: [
4161
6242
  2,
@@ -4163,21 +6244,40 @@ var SqlSessionStore = class SqlSessionStore {
4163
6244
  child
4164
6245
  ]
4165
6246
  };
4166
- if (transactionFinisher(tx)?.([step]) !== true) await tx.run(step.sql, ...step.params);
4167
6247
  }
4168
6248
  /**
4169
6249
  * The statements that store `entries` after `lastSeq`, in order, each entry encoded only when its statements are
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.
6250
+ * taken: the entries' rows, several to a statement (see {@link rowInserts}), each chunked entry's own row and its
6251
+ * chunks in their place among them, the version step a first chunked entry takes unless `versionStep` is false (a
6252
+ * fork takes it once its last entry is in), then the entries' search texts. With `written`, each entry is added to it
6253
+ * with its seq and its JSON as it is encoded, for {@link noteWritten} once the write commits.
4172
6254
  */
4173
- *entryWrites(sessionId, entries, lastSeq, texts, versionStep = true) {
6255
+ *entryWrites(sessionId, entries, lastSeq, texts, versionStep = true, written) {
4174
6256
  let chunked = false;
6257
+ const rows = new RowInserts(this.tables.entries, ENTRY_COLUMNS);
4175
6258
  for (const [index, entry] of entries.entries()) {
4176
6259
  const seq = lastSeq + index + 1;
4177
- const stored = storedEntry(entry, this.encode(entry));
4178
- chunked ||= stored.chunks.length > 0;
6260
+ const json = this.encode(entry);
6261
+ written?.push({
6262
+ entry,
6263
+ seq,
6264
+ json
6265
+ });
6266
+ const stored = storedEntry(entry, json);
6267
+ if (stored.chunks.length === 0) {
6268
+ yield* rows.add([
6269
+ sessionId,
6270
+ seq,
6271
+ entry.id,
6272
+ stored.json,
6273
+ 0
6274
+ ]);
6275
+ continue;
6276
+ }
6277
+ chunked = true;
6278
+ yield* rows.drain();
4179
6279
  yield {
4180
- sql: `INSERT INTO ${this.tables.entries} (session_id, seq, entry_id, entry_json, chunks) VALUES (?, ?, ?, ?, ?)`,
6280
+ sql: rows.sql(1),
4181
6281
  params: [
4182
6282
  sessionId,
4183
6283
  seq,
@@ -4186,7 +6286,7 @@ var SqlSessionStore = class SqlSessionStore {
4186
6286
  stored.chunks.length
4187
6287
  ]
4188
6288
  };
4189
- if (stored.chunks.length > 0) yield {
6289
+ yield {
4190
6290
  sql: `DELETE FROM ${this.tables.entryChunks} WHERE session_id = ? AND seq = ?`,
4191
6291
  params: [sessionId, seq]
4192
6292
  };
@@ -4200,40 +6300,53 @@ var SqlSessionStore = class SqlSessionStore {
4200
6300
  ]
4201
6301
  };
4202
6302
  }
6303
+ yield* rows.drain();
4203
6304
  if (chunked && versionStep) yield {
4204
6305
  sql: `UPDATE ${this.tables.meta} SET schema_version = ? WHERE schema_version = ?`,
4205
6306
  params: [2, SESSION_SCHEMA_VERSION_UNCHUNKED]
4206
6307
  };
4207
- for (const { index, text } of texts) yield {
4208
- sql: `INSERT INTO ${this.tables.searchTexts} (session_id, seq, text_json) VALUES (?, ?, ?)`,
4209
- params: [
4210
- sessionId,
4211
- lastSeq + index + 1,
4212
- this.encode(text)
4213
- ]
4214
- };
6308
+ const searchTexts = new RowInserts(this.tables.searchTexts, TEXT_COLUMNS);
6309
+ for (const { index, text } of texts) yield* searchTexts.add([
6310
+ sessionId,
6311
+ lastSeq + index + 1,
6312
+ this.encode(text)
6313
+ ]);
6314
+ yield* searchTexts.drain();
4215
6315
  }
4216
6316
  /**
4217
- * Runs the session row's statement, then `entries`' statements, in order. A write of up to
4218
- * {@link STATEMENT_BATCH_BYTES}, as an ordinary message is, goes to a connection thread as one batch that waits for
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
4220
- * about that much of them, or sends it, at once.
6317
+ * Runs the session row's statement, then `entries`' statements, in order, as the transaction's last calls: the body
6318
+ * makes none after them. A write of up to {@link STATEMENT_BATCH_BYTES}, as an ordinary message is, goes with the
6319
+ * commit where the connection is pipelined, or to a connection thread as one batch that waits for it once, or a
6320
+ * request's worth at a time when it has more statements than one takes. A larger one is sent as it is made, without
6321
+ * waiting for each statement's answer, so it never holds more than about that much of them, or sends it, at once.
4221
6322
  */
4222
- /** Writes the session's row and its entries as the transaction's last calls: the body makes none after them. */
4223
6323
  async writeEntries(tx, summary, entries) {
4224
6324
  const batch = [summary];
4225
6325
  let bytes = statementBytes(summary);
4226
6326
  const pending = entries[Symbol.iterator]();
6327
+ let whole = true;
4227
6328
  for (let next = pending.next(); next.done !== true; next = pending.next()) {
4228
6329
  batch.push(next.value);
4229
6330
  bytes += statementBytes(next.value);
4230
- if (bytes <= STATEMENT_BATCH_BYTES) continue;
4231
- for (const { sql, params } of batch) await tx.run(sql, ...params);
4232
- for (let rest = pending.next(); rest.done !== true; rest = pending.next()) await tx.run(rest.value.sql, ...rest.value.params);
6331
+ if (bytes > STATEMENT_BATCH_BYTES) {
6332
+ whole = false;
6333
+ break;
6334
+ }
6335
+ }
6336
+ if (whole) {
6337
+ if (transactionFinisher(tx)?.(batch) === true) return;
6338
+ if (batch.length <= MAX_SEQUENCE_REQUEST_STATEMENTS) {
6339
+ await statementBatch(tx, batch, []);
6340
+ return;
6341
+ }
6342
+ }
6343
+ const runSequence = whole ? sequenceRunner(tx) : void 0;
6344
+ if (runSequence !== void 0) {
6345
+ await runSequence({ statements: batch });
4233
6346
  return;
4234
6347
  }
4235
- if (transactionFinisher(tx)?.(batch) === true) return;
4236
- await statementBatch(tx, batch, []);
6348
+ const writes = new SentWrites(tx);
6349
+ await writes.around(() => writes.send(whole ? batch : withRest(batch, pending)));
4237
6350
  }
4238
6351
  encode(value) {
4239
6352
  try {
@@ -4244,14 +6357,21 @@ var SqlSessionStore = class SqlSessionStore {
4244
6357
  }
4245
6358
  };
4246
6359
  const nativeLoad = registerArchiveLoad(SqlSessionStore.prototype.load);
6360
+ /** The markers among `markers` whose processes `live` judges to be running. */
6361
+ async function liveMarkers(markers, live) {
6362
+ const running = [];
6363
+ for (const marker of markers) if (await live(marker)) running.push(marker);
6364
+ return running;
6365
+ }
4247
6366
  /** The running sessions that have a SQL store's sessions open, in a table every host sharing the store reads (#4971). */
4248
6367
  var SqlSessionOpenMarkers = class {
6368
+ /** A new table already has the columns the later steps add, so on a new database they find them and alter nothing. */
4249
6369
  static async createTable(tx, dialect, table) {
4250
6370
  const { int, text } = dialect.types;
4251
6371
  await tx.exec(`
4252
6372
  CREATE TABLE IF NOT EXISTS ${table} (
4253
6373
  session_id ${text} NOT NULL, token ${text} NOT NULL, pid ${int} NOT NULL, host ${text} NOT NULL,
4254
- heartbeat_at ${int} NOT NULL, PRIMARY KEY(session_id, token)
6374
+ heartbeat_at ${int} NOT NULL, schema_version ${int}, build ${text}, PRIMARY KEY(session_id, token)
4255
6375
  )${dialect.tableOptions};
4256
6376
  `);
4257
6377
  }
@@ -4264,6 +6384,14 @@ var SqlSessionOpenMarkers = class {
4264
6384
  const probe = dialect.columnExists(table, "schema_version");
4265
6385
  if (await tx.get(probe.sql, ...probe.params) === void 0) await tx.exec(`ALTER TABLE ${table} ADD COLUMN schema_version ${dialect.types.int}`);
4266
6386
  }
6387
+ /**
6388
+ * Each marker records the Atomic version of its process, so a command refused while older processes run names the
6389
+ * version each must be upgraded from (#6560). Null for markers of builds before it. Additive.
6390
+ */
6391
+ static async addBuild(tx, dialect, table) {
6392
+ const probe = dialect.columnExists(table, "build");
6393
+ if (await tx.get(probe.sql, ...probe.params) === void 0) await tx.exec(`ALTER TABLE ${table} ADD COLUMN build ${dialect.types.text}`);
6394
+ }
4267
6395
  database;
4268
6396
  table;
4269
6397
  assertOpen;
@@ -4275,9 +6403,26 @@ var SqlSessionOpenMarkers = class {
4275
6403
  async put(sessionId, marker) {
4276
6404
  this.assertOpen();
4277
6405
  const now = dialectOf(this.database).nowMs;
4278
- await this.database.run(`INSERT INTO ${this.table} (session_id, token, pid, host, heartbeat_at, schema_version) VALUES (?, ?, ?, ?, ${now}, ?)
6406
+ await this.database.run(`INSERT INTO ${this.table} (session_id, token, pid, host, heartbeat_at, schema_version, build) VALUES (?, ?, ?, ?, ${now}, ?, ?)
4279
6407
  ON CONFLICT(session_id, token) DO UPDATE SET pid = excluded.pid, host = excluded.host,
4280
- heartbeat_at = excluded.heartbeat_at, schema_version = excluded.schema_version`, sessionId, marker.token, marker.pid, marker.host, 2);
6408
+ heartbeat_at = excluded.heartbeat_at, schema_version = excluded.schema_version, build = excluded.build`, sessionId, marker.token, marker.pid, marker.host, 3, marker.build ?? null);
6409
+ }
6410
+ /**
6411
+ * The markers, through `tx`, of processes that do not read sessions schema `version`: those that record an older
6412
+ * one, and those of builds that record none.
6413
+ */
6414
+ async olderThan(tx, version) {
6415
+ const now = dialectOf(this.database).nowMs;
6416
+ return (await tx.all(`SELECT session_id, token, pid, host, ${now} - heartbeat_at AS age_ms, schema_version, build FROM ${this.table}
6417
+ WHERE schema_version IS NULL OR schema_version < ? ORDER BY host, pid, session_id`, version)).map((row) => ({
6418
+ sessionId: row.session_id,
6419
+ token: row.token,
6420
+ pid: Number(row.pid),
6421
+ host: row.host,
6422
+ ageMs: Number(row.age_ms),
6423
+ schemaVersion: row.schema_version === null ? void 0 : Number(row.schema_version),
6424
+ build: row.build ?? void 0
6425
+ }));
4281
6426
  }
4282
6427
  async remove(sessionId, token) {
4283
6428
  this.assertOpen();
@@ -10801,16 +12946,16 @@ var ThemeSelectorComponent = class extends FramedSelector {
10801
12946
  * update without an ESM missing-export error.
10802
12947
  */
10803
12948
  const COMPACTOR_COMPRESSION_RATIO = .5;
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 };
12949
+ 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_APPEND_FUNCTION_DOMAIN, 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_SCHEMA_VERSION_CHUNKED, SESSION_SCHEMA_VERSION_SHARED_HISTORY, SESSION_TABLES, SNAPSHOT_COLLECTION_BATCH, SessionConflictError, SessionExistsError, SessionFormatVersionError, SessionIdMismatchError, SessionInvalidTextError, SessionInvalidTimestampError, SessionNotFoundError, SessionStartConfigError, SessionStartError, SessionStartTimeoutError, ShowImagesSelectorComponent, SqlSessionStore, SqlSnapshotBlobStore, TEAM_JOIN_COMMAND, 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 };
10805
12950
 
10806
- //# sourceMappingURL=sdk-AVFII7NK.js.map
12951
+ //# sourceMappingURL=sdk-B5LEWGGI.js.map
10807
12952
  // __atomicOnDemandFailed: written by the build (scripts/in-place-update-gate.mjs). An import of this release's code on
10808
12953
  // demand that fails in a process an in-place update left running says to restart.
10809
12954
  function __atomicOnDemandFailed(error, feature) {
10810
12955
  return (async () => {
10811
12956
  const root = new URL("../", import.meta.url);
10812
12957
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
10813
- const key = `${root.href}#0.10.11-alpha.1`;
12958
+ const key = `${root.href}#0.10.11-alpha.3`;
10814
12959
  let release = releases.get(key);
10815
12960
  if (release === undefined) {
10816
12961
  const current = (async () => {
@@ -10838,7 +12983,7 @@ function __atomicOnDemandFailed(error, feature) {
10838
12983
  } catch {
10839
12984
  // No installation to read, as in a bundle of the package: the release the process runs decides.
10840
12985
  }
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;
12986
+ const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.3" ? installed : running !== undefined && running.version !== "0.10.11-alpha.3" ? "0.10.11-alpha.3" : undefined;
10842
12987
  if (updatedTo === undefined) throw error;
10843
12988
  const application = typeof running?.name === "string" ? running.name : "atomic";
10844
12989
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {