@bastani/atomic 0.10.11-alpha.2 → 0.10.11

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 (447) hide show
  1. package/CHANGELOG.md +307 -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 +6 -6
  7. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +5 -5
  8. package/dist/_shared/mode-shared-2QJSCUM6.js +6 -6
  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} +36 -8
  14. package/dist/_shared/p1b-elig-TVB5CBLL.js.map +1 -0
  15. package/dist/_shared/p2-shell-main-B2WIALFD.js +6 -3
  16. package/dist/_shared/p2-shell-main-B2WIALFD.js.map +1 -1
  17. package/dist/_shared/runtime-O4KCSG4C.js +3 -3
  18. package/dist/_shared/{sdk-IQMULKFU.js → sdk-B5LEWGGI.js} +1218 -657
  19. package/dist/_shared/sdk-B5LEWGGI.js.map +1 -0
  20. package/dist/_shared/session-data-AHTU7IS6.js +2 -2
  21. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  22. package/dist/_shared/{startup-0-0-3IXNMFM2.js → startup-0-0-XJJDOIEC.js} +50 -48
  23. package/dist/_shared/startup-0-0-XJJDOIEC.js.map +1 -0
  24. package/dist/_shared/{startup-0-1-7T2IAE7J.js → startup-0-1-M6OWAYHH.js} +540 -136
  25. package/dist/_shared/startup-0-1-M6OWAYHH.js.map +1 -0
  26. package/dist/_shared/startup-0-2-5QHPCEON.js +47 -48
  27. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -1
  28. package/dist/_shared/startup-0-3-4ZYBYQNM.js +5 -5
  29. package/dist/_shared/startup-0-4-ZMJV547D.js +12 -7
  30. package/dist/_shared/startup-0-4-ZMJV547D.js.map +1 -1
  31. package/dist/_shared/startup-0-5-YDW47QX6.js +7 -7
  32. package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -1
  33. package/dist/_shared/startup-10-0-TDQNBDDL.js +6 -6
  34. package/dist/_shared/startup-12-0-55AAXBJZ.js +2 -2
  35. package/dist/_shared/startup-14-0-MLX36RBG.js +4 -5
  36. package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
  37. package/dist/_shared/startup-15-0-YUKGAC63.js +4 -4
  38. package/dist/_shared/startup-15-1-4S7FLMNG.js +19 -27
  39. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  40. package/dist/_shared/startup-8-0-34CBHPZH.js +2144 -249
  41. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  42. package/dist/_shared/{startup-8-1-X32CYSXB.js → startup-8-1-LZFXSD3Z.js} +98 -1184
  43. package/dist/_shared/startup-8-1-LZFXSD3Z.js.map +1 -0
  44. package/dist/_shared/storage-command-7MGXLJGZ.js +188 -37
  45. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  46. package/dist/_shared/storage-status-K7PX2RXA.js +557 -0
  47. package/dist/_shared/storage-status-K7PX2RXA.js.map +1 -0
  48. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  49. package/dist/_shared/team-DOQKICG2.js +376 -0
  50. package/dist/_shared/team-DOQKICG2.js.map +1 -0
  51. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  52. package/dist/builtin/intercom/CHANGELOG.md +88 -0
  53. package/dist/builtin/intercom/README.md +2 -2
  54. package/dist/builtin/intercom/broker/broker.bundle.mjs +1917 -381
  55. package/dist/builtin/intercom/broker/client.ts +8 -0
  56. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +324 -68
  57. package/dist/builtin/intercom/broker/multinode-router.ts +256 -39
  58. package/dist/builtin/intercom/broker/multinode-state-store.ts +71 -5
  59. package/dist/builtin/intercom/broker/open-broker-state.ts +14 -0
  60. package/dist/builtin/intercom/broker/send-order-gate.ts +5 -2
  61. package/dist/builtin/intercom/broker/sql-add-column.ts +50 -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 +473 -121
  66. package/dist/builtin/intercom/broker/sql-outbox-store.ts +821 -79
  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 +256 -8
  70. package/dist/builtin/intercom/broker/sql-retention.ts +150 -0
  71. package/dist/builtin/intercom/broker/sql-schema.ts +175 -24
  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 +14 -4
  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 +20 -0
  79. package/dist/builtin/subagents/package.json +1 -1
  80. package/dist/builtin/subagents/skills/skill-creator/eval-viewer/generate_review.py +8 -1
  81. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  82. package/dist/builtin/web-access/index.bundle.mjs +2 -10
  83. package/dist/builtin/web-access/package.json +1 -1
  84. package/dist/bun/bundled-sqlite.js +41 -0
  85. package/dist/bun/bundled-sqlite.js.map +1 -0
  86. package/dist/cli/args.js +2 -2
  87. package/dist/cli/auth-cli.code.js +4 -4
  88. package/dist/cli/auth-cli.impl.js +3 -3
  89. package/dist/cli/auth-cli.js +3 -3
  90. package/dist/cli/blueprint-command.code.js +3 -3
  91. package/dist/cli/blueprint-command.impl.js +3 -3
  92. package/dist/cli/blueprint-command.js +3 -3
  93. package/dist/cli/intercom-command.code.js +3 -3
  94. package/dist/cli/intercom-command.code.js.map +1 -1
  95. package/dist/cli/intercom-command.impl.js +3 -3
  96. package/dist/cli/intercom-command.js +3 -3
  97. package/dist/cli/list-models.code.js +2 -2
  98. package/dist/cli/list-models.impl.js +3 -3
  99. package/dist/cli/list-models.js +3 -3
  100. package/dist/cli/session-picker.code.js +1 -1
  101. package/dist/cli/session-picker.impl.js +3 -3
  102. package/dist/cli/session-picker.js +3 -3
  103. package/dist/cli/startup-ui.code.js +1 -1
  104. package/dist/cli/startup-ui.impl.js +3 -3
  105. package/dist/cli/startup-ui.js +3 -3
  106. package/dist/cli/storage-command.impl.js +3 -3
  107. package/dist/cli/storage-command.js +3 -3
  108. package/dist/cli/storage-search-session.code.js +3 -3
  109. package/dist/cli/storage-search-session.impl.js +3 -3
  110. package/dist/cli/storage-search-session.js +3 -3
  111. package/dist/cli/team-command.code.js +19 -113
  112. package/dist/cli/team-command.code.js.map +1 -1
  113. package/dist/cli/team-command.impl.js +3 -3
  114. package/dist/cli/team-command.js +3 -3
  115. package/dist/cli.js +5 -18
  116. package/dist/cli.js.map +1 -1
  117. package/dist/core/agent-rehydrate-errors.d.ts +4 -9
  118. package/dist/core/compaction/compactor.d.ts +3 -3
  119. package/dist/core/debug.code.js +1 -1
  120. package/dist/core/debug.impl.js +3 -3
  121. package/dist/core/debug.js +3 -3
  122. package/dist/core/export-html/card-projection.impl.js +3 -3
  123. package/dist/core/export-html/card-projection.js +3 -3
  124. package/dist/core/export-html/index.code.js +4 -4
  125. package/dist/core/export-html/index.code.js.map +1 -1
  126. package/dist/core/export-html/index.impl.js +3 -3
  127. package/dist/core/export-html/index.js +3 -3
  128. package/dist/core/export-html/json-spans.impl.js +3 -3
  129. package/dist/core/export-html/json-spans.js +3 -3
  130. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  131. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  132. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  133. package/dist/core/export-html/tool-renderer.js +3 -3
  134. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  135. package/dist/core/extensions/jiti-loader.js +3 -3
  136. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  137. package/dist/core/extensions/jiti-static-loader.js +3 -3
  138. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  139. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  140. package/dist/core/extensions/loader-host-modules.js +3 -3
  141. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  142. package/dist/core/extensions/runner-context.js +2 -2
  143. package/dist/core/intercom-broker-control-host.code.js +2 -2
  144. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  145. package/dist/core/intercom-broker-control-host.js +3 -3
  146. package/dist/core/intercom-broker-control.code.js +3 -3
  147. package/dist/core/intercom-broker-control.impl.js +3 -3
  148. package/dist/core/intercom-broker-control.js +3 -3
  149. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  150. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  151. package/dist/core/package-manager-storage-adapters.js +3 -3
  152. package/dist/core/process-start-token.d.ts +12 -3
  153. package/dist/core/process-tree-containment.d.ts +16 -0
  154. package/dist/core/sdk-types.d.ts +1 -2
  155. package/dist/core/sdk-types.js.map +1 -1
  156. package/dist/core/sdk.code.js +3 -3
  157. package/dist/core/sdk.impl.js +3 -3
  158. package/dist/core/sdk.js +3 -3
  159. package/dist/core/session-manager-core.js +5 -5
  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 +1 -1
  163. package/dist/core/session-manager.impl.js +3 -3
  164. package/dist/core/session-manager.js +3 -3
  165. package/dist/core/session-storage.code.js +1 -1
  166. package/dist/core/session-storage.impl.js +3 -3
  167. package/dist/core/session-storage.js +3 -3
  168. package/dist/core/settings-schema.d.ts +0 -3
  169. package/dist/core/storage/added-exports-0-10-11.js +19 -0
  170. package/dist/core/storage/added-exports-0-10-11.js.map +1 -0
  171. package/dist/core/storage/creation-time.js +105 -0
  172. package/dist/core/storage/creation-time.js.map +1 -0
  173. package/dist/core/storage/database.d.ts +25 -5
  174. package/dist/core/storage/database.js.map +1 -1
  175. package/dist/core/storage/dialect.d.ts +1 -1
  176. package/dist/core/storage/dialect.js +1 -1
  177. package/dist/core/storage/dialect.js.map +1 -1
  178. package/dist/core/storage/errors.d.ts +13 -13
  179. package/dist/core/storage/errors.js +10 -16
  180. package/dist/core/storage/errors.js.map +1 -1
  181. package/dist/core/storage/fenced-paths.d.ts +18 -6
  182. package/dist/core/storage/fenced-paths.js +18 -6
  183. package/dist/core/storage/fenced-paths.js.map +1 -1
  184. package/dist/core/storage/file-identity.d.ts +2 -0
  185. package/dist/core/storage/file-identity.js +24 -8
  186. package/dist/core/storage/file-identity.js.map +1 -1
  187. package/dist/core/storage/index.d.ts +3 -2
  188. package/dist/core/storage/index.js +5 -3
  189. package/dist/core/storage/index.js.map +1 -1
  190. package/dist/core/storage/libsql-removed.d.ts +71 -0
  191. package/dist/core/storage/libsql-removed.js +123 -0
  192. package/dist/core/storage/libsql-removed.js.map +1 -0
  193. package/dist/core/storage/migrations.d.ts +78 -14
  194. package/dist/core/storage/migrations.js +375 -49
  195. package/dist/core/storage/migrations.js.map +1 -1
  196. package/dist/core/storage/node-sqlite-file-gate.js +0 -15
  197. package/dist/core/storage/node-sqlite-file-gate.js.map +1 -1
  198. package/dist/core/storage/node-sqlite-thread.js +215 -30
  199. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  200. package/dist/core/storage/node-sqlite.js +484 -72
  201. package/dist/core/storage/node-sqlite.js.map +1 -1
  202. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  203. package/dist/core/storage/offline-snapshot-file.js +3 -3
  204. package/dist/core/storage/prefix.d.ts +1 -1
  205. package/dist/core/storage/prefix.js +9 -2
  206. package/dist/core/storage/prefix.js.map +1 -1
  207. package/dist/core/storage/process-selection.d.ts +5 -5
  208. package/dist/core/storage/provider.js +2 -2
  209. package/dist/core/storage/schema-catalog.d.ts +76 -15
  210. package/dist/core/storage/schema-catalog.js +359 -68
  211. package/dist/core/storage/schema-catalog.js.map +1 -1
  212. package/dist/core/storage/selection.d.ts +7 -82
  213. package/dist/core/storage/selection.js +20 -235
  214. package/dist/core/storage/selection.js.map +1 -1
  215. package/dist/core/storage/session/branch-fork-source.code.js +2 -2
  216. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  217. package/dist/core/storage/session/branch-fork-source.js +3 -3
  218. package/dist/core/storage/session/card-view.impl.js +3 -3
  219. package/dist/core/storage/session/card-view.js +3 -3
  220. package/dist/core/storage/session/child-reader.code.js +3 -3
  221. package/dist/core/storage/session/child-reader.impl.js +3 -3
  222. package/dist/core/storage/session/child-reader.js +3 -3
  223. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  224. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  225. package/dist/core/storage/session/expanded-child-details.code.js +2 -2
  226. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  227. package/dist/core/storage/session/expanded-child-details.js +3 -3
  228. package/dist/core/storage/session/fork-detach.d.ts +11 -1
  229. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  230. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  231. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  232. package/dist/core/storage/session/fork-row-index.js +3 -3
  233. package/dist/core/storage/session/fork-staging.code.js +4 -7
  234. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  235. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  236. package/dist/core/storage/session/fork-staging.js +3 -3
  237. package/dist/core/storage/session/fork-sweep.js +31 -7
  238. package/dist/core/storage/session/fork-sweep.js.map +1 -1
  239. package/dist/core/storage/session/fork-window.code.js +3 -3
  240. package/dist/core/storage/session/fork-window.impl.js +3 -3
  241. package/dist/core/storage/session/fork-window.js +3 -3
  242. package/dist/core/storage/session/history-pages.impl.js +3 -3
  243. package/dist/core/storage/session/history-pages.js +3 -3
  244. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  245. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  246. package/dist/core/storage/session/jsonl-session-lock.d.ts +100 -0
  247. package/dist/core/storage/session/jsonl-session-store.d.ts +46 -24
  248. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  249. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  250. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  251. package/dist/core/storage/session/memory-session-store.js +3 -3
  252. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  253. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  254. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  255. package/dist/core/storage/session/released-history-files.code.js +9 -9
  256. package/dist/core/storage/session/released-history-files.code.js.map +1 -1
  257. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  258. package/dist/core/storage/session/released-history-files.js +3 -3
  259. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  260. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  261. package/dist/core/storage/session/session-resume.impl.js +3 -3
  262. package/dist/core/storage/session/session-resume.js +3 -3
  263. package/dist/core/storage/session/session-search-index.d.ts +52 -5
  264. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  265. package/dist/core/storage/session/snapshot-cut.js +3 -3
  266. package/dist/core/storage/session/snapshot-history.code.js +3 -3
  267. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  268. package/dist/core/storage/session/snapshot-history.js +3 -3
  269. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  270. package/dist/core/storage/session/sql-session-store.d.ts +99 -18
  271. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  272. package/dist/core/storage/session/sql-session-store.js +3 -3
  273. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  274. package/dist/core/storage/session/tree-outline.js +3 -3
  275. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  276. package/dist/core/storage/session/tree-presentation.js +3 -3
  277. package/dist/core/storage/sqlite-facade.d.ts +12 -1
  278. package/dist/core/storage/sqlite-facade.js +310 -33
  279. package/dist/core/storage/sqlite-facade.js.map +1 -1
  280. package/dist/core/storage/sqlite-open-batch.js +10 -0
  281. package/dist/core/storage/sqlite-open-batch.js.map +1 -0
  282. package/dist/core/storage/storage-status.code.js +1 -1
  283. package/dist/core/storage/storage-status.impl.js +3 -3
  284. package/dist/core/storage/storage-status.js +3 -3
  285. package/dist/core/storage/team.code.js +1 -1
  286. package/dist/core/storage/team.d.ts +26 -115
  287. package/dist/core/storage/team.impl.js +3 -3
  288. package/dist/core/storage/team.js +3 -3
  289. package/dist/core/structured-output/index.code.js +1 -1
  290. package/dist/core/structured-output/index.impl.js +3 -3
  291. package/dist/core/structured-output/index.js +3 -3
  292. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  293. package/dist/core/tasks/task-completion-entry.js +3 -3
  294. package/dist/core/tasks/task-file-history.code.js +3 -3
  295. package/dist/core/tasks/task-file-history.impl.js +3 -3
  296. package/dist/core/tasks/task-file-history.js +3 -3
  297. package/dist/core/tasks/task-reference-archive.code.js +4 -4
  298. package/dist/core/tasks/task-reference-archive.js +3 -3
  299. package/dist/core/tasks/task-reference-identity.js +3 -3
  300. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  301. package/dist/core/tasks/task-reference-stream.js +3 -3
  302. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  303. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  304. package/dist/core/tasks/task-view-source.code.js +1 -1
  305. package/dist/core/tasks/task-view-source.impl.js +3 -3
  306. package/dist/core/tasks/task-view-source.js +3 -3
  307. package/dist/core/tools/history-tasks.d.ts +3 -2
  308. package/dist/core/tools/read-url.code.js +4 -4
  309. package/dist/core/tools/read-url.impl.js +3 -3
  310. package/dist/core/tools/read-url.js +3 -3
  311. package/dist/core/worktree-snapshot/blob-store.d.ts +44 -5
  312. package/dist/core/worktree-snapshot/blob-store.js +553 -30
  313. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  314. package/dist/core/worktree-snapshot/errors.code.js +2 -2
  315. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  316. package/dist/core/worktree-snapshot/errors.js +3 -3
  317. package/dist/core/worktree-snapshot/fork-blob-guard.js +81 -0
  318. package/dist/core/worktree-snapshot/fork-blob-guard.js.map +1 -0
  319. package/dist/core/worktree-snapshot/fork-snapshot-index.js +208 -50
  320. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -1
  321. package/dist/core/worktree-snapshot/session-index-reset.code.js +4 -0
  322. package/dist/core/worktree-snapshot/session-index-reset.code.js.map +1 -1
  323. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  324. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  325. package/dist/extensions/codemode/execute.code.js +1 -1
  326. package/dist/extensions/codemode/execute.impl.js +3 -3
  327. package/dist/extensions/codemode/execute.js +3 -3
  328. package/dist/extensions/codemode/renderer.code.js +2 -2
  329. package/dist/extensions/codemode/renderer.impl.js +3 -3
  330. package/dist/extensions/codemode/renderer.js +3 -3
  331. package/dist/extensions/mcp/cli.code.js +3 -3
  332. package/dist/extensions/mcp/cli.impl.js +3 -3
  333. package/dist/extensions/mcp/cli.js +3 -3
  334. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  335. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  336. package/dist/extensions/mcp/cli.lazy.js +3 -3
  337. package/dist/extensions/mcp/runtime.code.js +1 -1
  338. package/dist/extensions/mcp/runtime.impl.js +3 -3
  339. package/dist/extensions/mcp/runtime.js +3 -3
  340. package/dist/index.d.ts +3 -1
  341. package/dist/index.js +5 -5
  342. package/dist/main-first-time-setup.code.js +1 -1
  343. package/dist/main-first-time-setup.impl.js +3 -3
  344. package/dist/main-first-time-setup.js +3 -3
  345. package/dist/main.js +1 -1
  346. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  347. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  348. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  349. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  350. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  351. package/dist/modes/interactive/startup-shell-eligibility.js +1 -1
  352. package/dist/modes/interactive-engine/engine-prewarm.d.ts +1 -1
  353. package/dist/modes/print-mode.js +1 -1
  354. package/dist/package-manager-cli.code.js +6 -6
  355. package/dist/package-manager-cli.impl.js +3 -3
  356. package/dist/package-manager-cli.js +3 -3
  357. package/dist/rpc-entry.js +1 -1
  358. package/dist/startup-files.json +1 -1
  359. package/dist/startup-stages/10.js +1 -1
  360. package/dist/startup-stages/11.js +1 -1
  361. package/dist/startup-stages/12.js +1 -1
  362. package/dist/startup-stages/2.js +2 -4
  363. package/dist/startup-stages/3.js +1 -3
  364. package/dist/startup-stages/4.js +1 -2
  365. package/dist/startup-stages/5.js +1 -1
  366. package/dist/startup-stages/6.js +5 -7
  367. package/dist/startup-stages/7.js +3 -10
  368. package/dist/startup-stages/8.js +7 -2
  369. package/dist/startup-stages/9.js +1 -7
  370. package/dist/startup-stages/stages.json +1 -1
  371. package/dist/utils/compile-cache-deferral.js +8 -13
  372. package/dist/utils/compile-cache-deferral.js.map +1 -1
  373. package/dist/utils/compile-cache-warmup-host.js +3 -4
  374. package/dist/utils/compile-cache-warmup-host.js.map +1 -1
  375. package/dist/utils/compile-cache.js +12 -100
  376. package/dist/utils/compile-cache.js.map +1 -1
  377. package/dist/utils/startup-database-spare.code.js +2 -2
  378. package/dist/utils/startup-database-spare.impl.js +3 -3
  379. package/dist/utils/startup-database-spare.js +3 -3
  380. package/dist/utils/tools-manager.code.js +1 -1
  381. package/dist/utils/tools-manager.impl.js +3 -3
  382. package/dist/utils/tools-manager.js +3 -3
  383. package/dist/utils/worker-threads.js +2 -15
  384. package/dist/utils/worker-threads.js.map +1 -1
  385. package/docs/build.md +3 -3
  386. package/docs/changelog.mdx +1498 -69
  387. package/docs/compaction/reference.md +5 -5
  388. package/docs/compaction.md +7 -9
  389. package/docs/containerization.md +2 -2
  390. package/docs/custom-provider/api-reference.md +1 -1
  391. package/docs/docs.json +37 -10
  392. package/docs/environment-variables.md +0 -2
  393. package/docs/extensions/api-reference.md +4 -4
  394. package/docs/getting-started/installation.md +3 -0
  395. package/docs/guides/configuration.md +1 -1
  396. package/docs/guides/non-interactive.md +1 -1
  397. package/docs/guides/resume-on-any-machine.md +14 -22
  398. package/docs/guides/team-setup.md +56 -83
  399. package/docs/guides.md +2 -4
  400. package/docs/herdr.md +1 -1
  401. package/docs/index.md +1 -1
  402. package/docs/intercom/operations.md +26 -21
  403. package/docs/intercom/reference.md +2 -2
  404. package/docs/intercom.md +1 -1
  405. package/docs/libraries/storage-postgres.md +9 -9
  406. package/docs/libraries.md +2 -3
  407. package/docs/models-configuration.md +2 -2
  408. package/docs/models.md +2 -3
  409. package/docs/packages/authoring.md +7 -7
  410. package/docs/packages.md +1 -1
  411. package/docs/programmatic.md +2 -2
  412. package/docs/quickstart.md +1 -1
  413. package/docs/reference/cli.md +6 -11
  414. package/docs/reference.md +2 -2
  415. package/docs/rpc/extension-ui.md +2 -2
  416. package/docs/sdk/reference.md +5 -4
  417. package/docs/sdk/storage.md +8 -92
  418. package/docs/sdk/structured-decisions.md +1 -1
  419. package/docs/sdk/web-server.md +3 -3
  420. package/docs/sdk.md +14 -4
  421. package/docs/security.md +1 -1
  422. package/docs/session-format.md +5 -5
  423. package/docs/sessions.md +29 -49
  424. package/docs/settings.md +7 -8
  425. package/docs/storage/custom-adapters.md +255 -0
  426. package/docs/storage/jsonl.md +117 -0
  427. package/docs/{guides/postgres-pgbouncer.md → storage/postgres/pgbouncer.md} +66 -68
  428. package/docs/storage/postgres/tuning.md +337 -0
  429. package/docs/storage/postgres.md +556 -0
  430. package/docs/storage/sqlite.md +99 -0
  431. package/docs/storage.md +326 -990
  432. package/docs/subagents/authoring.md +1 -1
  433. package/docs/subagents.md +2 -2
  434. package/docs/tools.md +1 -1
  435. package/docs/worktree-snapshots.md +2 -2
  436. package/package.json +9 -9
  437. package/schemas/models.schema.json +2 -2
  438. package/schemas/settings.schema.json +0 -14
  439. package/dist/_shared/p1b-elig-ENCUPKKJ.js.map +0 -1
  440. package/dist/_shared/sdk-IQMULKFU.js.map +0 -1
  441. package/dist/_shared/startup-0-0-3IXNMFM2.js.map +0 -1
  442. package/dist/_shared/startup-0-1-7T2IAE7J.js.map +0 -1
  443. package/dist/_shared/startup-8-1-X32CYSXB.js.map +0 -1
  444. package/dist/core/intercom-broker-control.d.ts +0 -129
  445. package/dist/startup-stages/13.js +0 -1
  446. package/docs/guides/postgres-tuning.md +0 -311
  447. 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, 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, sessionWriteTransaction, sha256Hex, sharedHistorySwitchHost, sharedWakeDispatcher, sliceHead, storedEntryNotes, storedRows, stripUrlUserinfoAndHash, whenAborted, withinDecisionDeadline, writeRawStdout, yieldTurn } from "./startup-0-0-3IXNMFM2.js";
4
- import { CommandDeliveries, SqlSessionSearchIndex, WorkspacePublicationError, collectCommandDeliveries, normalizeModelFailureSignal, reportDiagnostics, requireTimerMs } from "./startup-0-1-7T2IAE7J.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-XJJDOIEC.js";
4
+ import { CommandDeliveries, SqlSessionSearchIndex, WorkspacePublicationError, collectCommandDeliveries, normalizeModelFailureSignal, reportDiagnostics, requireTimerMs } from "./startup-0-1-M6OWAYHH.js";
5
5
  import { getAvailableThemes, keyHint } from "./p2-shell-main-B2WIALFD.js";
6
- import { releaseLock, reportDebugAsync, waitForLock } from "./p1b-elig-ENCUPKKJ.js";
6
+ import { releaseLock, reportDebugAsync, waitForLock } from "./p1b-elig-TVB5CBLL.js";
7
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
8
  import { CODEMODE_TOOL_NAME, assistantRetryAttempt, runWorkspaceProcess } from "./startup-0-3-4ZYBYQNM.js";
9
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,20 +35,23 @@ 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
- import * as schemaCatalog from "../core/storage/schema-catalog.js";
45
46
  import { schemaCatalogOf, withStorageSchemaCatalog } from "../core/storage/schema-catalog.js";
46
- import * as statementSequence from "../core/storage/statement-sequence.js";
47
+ import { flushStorageSchemaSetups, queueSqliteSchemaSetup } from "../core/storage/sqlite-open-batch.js";
47
48
  import { sequenceRunner } from "../core/storage/statement-sequence.js";
48
49
  import { createServer } from "node:http";
49
50
  import { Check, Errors } from "@bastani/atomic-ai/utils/typebox/value";
51
+ import { TEAM_JOIN_COMMAND } from "../core/storage/libsql-removed.js";
52
+ import { ensureForkInheritedBlobGuard, installForkInheritedBlobGuard } from "../core/worktree-snapshot/fork-blob-guard.js";
50
53
  import { forkLinkWrites, legacyForkLinksTriggerName } from "../core/worktree-snapshot/fork-snapshot-index.js";
51
- import { ensureTableFillfactor, storageSchemaCurrent, transactionFinisher } from "../core/storage/added-exports.js";
54
+ import { MAX_SEQUENCE_REQUEST_STATEMENTS, noteStorageSchemaTables, refreshStorageSchemaCatalog } from "../core/storage/added-exports-0-10-11.js";
52
55
  import { assertStorageSchemaVersion, assertStoredSchemaVersion } from "../core/storage/schema.js";
53
56
  import { applyStorageMigrationsTogether, statementBatch } from "../core/storage/statement-batches.js";
54
57
  import { createSharedHistoryTables, sessionForkTables, sharedHistoryTablesScript } from "../core/storage/session/fork-schema.js";
@@ -921,22 +924,18 @@ async function restoreRunWorktree(remotes, restore, options = {}) {
921
924
  }], options);
922
925
  return root;
923
926
  }
924
- // dist/core/storage/added-exports-0-10-11.js
927
+ // dist/core/storage/session/json-list.js
925
928
  /**
926
- * `noteStorageSchemaTables` and `refreshStorageSchemaCatalog` of `schema-catalog.ts`, which the copy 0.10.11-alpha.1
927
- * loaded lacks, and `MAX_SEQUENCE_REQUEST_STATEMENTS` of `statement-sequence.ts`, which the copies 0.10.3 and 0.10.4's
928
- * prereleases loaded lack. A process that loaded those copies, or 0.10.11-alpha.1's `added-exports.js`, before an
929
- * in-place update replaced the installation keeps them, and can load the modules that use these from the update: a
930
- * named import of any of them would fail to link there, so they take them from here, a path no earlier release has
931
- * (#6560). With 0.10.11-alpha.1's catalog, which knows nothing of fork tables, an open keeps the catalog it read, as
932
- * there.
929
+ * `expression IN (…)` over a list bound as one parameter, the list as a JSON array (`JSON.stringify(values)`): the
930
+ * statement's text is the same however many values the list holds, so a server that keeps prepared statements, and
931
+ * pg_stat_statements, see one statement instead of one per length (#6560). On PostgreSQL the list becomes an array the
932
+ * comparison takes whole (`= ANY`), so an index on `expression` is searched for each value, as for a list of
933
+ * parameters. With `int`, PostgreSQL's text elements are compared as integers.
933
934
  */
934
- const catalogUpdates = schemaCatalog;
935
- const sequences = statementSequence;
936
- const noteStorageSchemaTables = catalogUpdates.noteStorageSchemaTables ?? (() => {});
937
- const refreshStorageSchemaCatalog = catalogUpdates.refreshStorageSchemaCatalog ?? (() => {});
938
- /** The most statements one request of a sequence carries (#6560). */
939
- const MAX_SEQUENCE_REQUEST_STATEMENTS = sequences.MAX_SEQUENCE_REQUEST_STATEMENTS ?? 256;
935
+ function inJsonList(dialect, expression, int = false) {
936
+ const values = `SELECT ${int ? `CAST(value AS ${dialect.types.int})` : "value"} FROM ${dialect.jsonValues("?")}`;
937
+ return dialect.name === "postgres" ? `${expression} = ANY(ARRAY(${values}))` : `${expression} IN (${values})`;
938
+ }
940
939
  // dist/core/storage/session/fork-row-copy.js
941
940
  /** How many entry IDs a run builder holds for lookups before it sends its runs, bounding what a fork holds. */
942
941
  const HELD_RUN_ROWS = 4096;
@@ -1035,7 +1034,7 @@ function incompleteEntryRead(tables, child) {
1035
1034
  * as `copyForkBlob` copied each one, a blob the child already holds is kept, one in the legacy one-row layout is copied
1036
1035
  * only with all its bytes, and each chunk only at its full length.
1037
1036
  */
1038
- function forkBlobCopy(tables, options, source, child, hashes) {
1037
+ function forkBlobCopy(dialect, tables, options, source, child, hashes) {
1039
1038
  const { blobs, blobChunks } = tables;
1040
1039
  const columns = options.legacyBlobData ? ", data" : "";
1041
1040
  const sourceColumns = options.legacyBlobData ? ", p.data" : "";
@@ -1045,33 +1044,33 @@ function forkBlobCopy(tables, options, source, child, hashes) {
1045
1044
  const groups = [];
1046
1045
  for (let start = 0; start < hashes.length; start += BLOB_HASHES_PER_STATEMENT) groups.push(hashes.slice(start, start + BLOB_HASHES_PER_STATEMENT));
1047
1046
  for (const group of groups) {
1048
- const named = group.map(() => "?").join(", ");
1047
+ const named = JSON.stringify(group);
1049
1048
  statements.push({
1050
- 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`,
1049
+ 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`,
1051
1050
  params: [
1052
1051
  child,
1053
1052
  source,
1054
- ...group,
1053
+ named,
1055
1054
  child
1056
1055
  ]
1057
1056
  }, {
1058
- 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`,
1057
+ 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`,
1059
1058
  params: [
1060
1059
  child,
1061
1060
  source,
1062
- ...group,
1061
+ named,
1063
1062
  options.chunkBytes,
1064
1063
  options.chunkBytes,
1065
1064
  child
1066
1065
  ]
1067
1066
  });
1068
1067
  checks.push({
1069
- 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})`,
1068
+ 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")}`,
1070
1069
  params: [
1071
1070
  child,
1072
1071
  child,
1073
1072
  source,
1074
- ...group
1073
+ named
1075
1074
  ]
1076
1075
  });
1077
1076
  }
@@ -1175,7 +1174,7 @@ async function forkChildren(tx, tables, sourceId) {
1175
1174
  async function lockForkSources(tx, dialect, tables, ids, mode) {
1176
1175
  const sorted = [...new Set(ids)].sort();
1177
1176
  if (dialect.name === "sqlite" || sorted.length === 0) return;
1178
- await tx.all(`SELECT id FROM ${tables.sessions} WHERE id IN (${sorted.map(() => "?").join(", ")}) ORDER BY id${dialect.lockClause(mode)}`, ...sorted);
1177
+ await tx.all(`SELECT id FROM ${tables.sessions} WHERE ${inJsonList(dialect, "id")} ORDER BY id${dialect.lockClause(mode)}`, JSON.stringify(sorted));
1179
1178
  }
1180
1179
  /**
1181
1180
  * The segments of a fork that shares its parent's history, gathered as the fork's rows stream past (#6560): each row the
@@ -1268,9 +1267,11 @@ async function firstIncomplete(tx, tables, piece) {
1268
1267
  }
1269
1268
  /**
1270
1269
  * Copies into session `childId`, a fork that shares history, the rows `pieces` of its segments name, with their chunks,
1271
- * search texts and the blobs their tool outputs name, and links them in the snapshot index with `links` (see
1272
- * `materializedForkLinks`), a statement a piece, then writes its segments without them, with a new generation, so
1273
- * its view stays as it was at every commit (#6560). Each piece lies within one of the child's segments: a sub-range of
1270
+ * search texts and the blobs their tool outputs name, and links them in the snapshot index with `links.materialized`
1271
+ * (see `materializedForkLinks`), a statement a piece, then writes its segments without them, with a new generation, so
1272
+ * its view stays as it was at every commit (#6560). `links.settle` writes the segments, and in the same request checks
1273
+ * the child's links from the first row copied on against the ones a save in seq order writes, linking them again where
1274
+ * they differ (`sessionEntryLinks`). Each piece lies within one of the child's segments: a sub-range of
1274
1275
  * it, or all of it. The caller holds the child's row locked `update`, and the sources' rows locked, so neither its
1275
1276
  * segments nor the rows they name change meanwhile; `length` is the child's last seq.
1276
1277
  */
@@ -1286,17 +1287,19 @@ async function materializeForkSegments(tx, dialect, tables, blobs, links, childI
1286
1287
  ];
1287
1288
  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
1289
  if (Number(copied.changes) !== segmentLength(piece)) throw new ForkSourceIncompleteError(childId, piece.sourceId, await firstIncomplete(tx, tables, piece));
1289
- await Promise.all([tx.run(links, 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 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
1291
  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
1292
  const named = await tx.all(`SELECT DISTINCT ${text("data", "hash")} AS hash FROM ${tables.entries} WHERE session_id = ? AND seq BETWEEN ? AND ?
1292
1293
  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(tables, blobs, piece.sourceId, childId, named.map((row) => String(row.hash)));
1294
+ const copy = forkBlobCopy(dialect, tables, blobs, piece.sourceId, childId, named.map((row) => String(row.hash)));
1294
1295
  for (const { sql, params } of copy.statements) await tx.run(sql, ...params);
1295
1296
  const answers = [];
1296
1297
  for (const { sql, params } of copy.checks) answers.push(await tx.all(sql, ...params));
1297
1298
  copy.remaining(answers);
1298
1299
  }
1299
- await writeForkSegments(tx, tables, childId, remaining, length);
1300
+ const writes = forkSegmentWrites(tables, childId, remaining, length);
1301
+ if (pieces.length === 0) for (const { sql, params } of writes) await tx.run(sql, ...params);
1302
+ else await links.settle(tx, childId, Math.min(...pieces.map((piece) => piece.baseSeq + 1)), writes, remaining.length > 0);
1300
1303
  }
1301
1304
  // dist/core/storage/session/fork-detach-host.js
1302
1305
  /**
@@ -1333,19 +1336,22 @@ function forkDetachHost(store) {
1333
1336
  forkLineage: forkTables.forkLineage
1334
1337
  },
1335
1338
  forkTransaction: (body) => store.transaction(body),
1339
+ ...store.readTransaction === void 0 ? {} : { forkReadTransaction: (body, leading, leadingOnly) => store.readTransaction(body, leading, leadingOnly) },
1340
+ ...store.sessionTransaction === void 0 ? {} : { forkSessionTransaction: (sessionId, body, leading) => store.sessionTransaction(sessionId, body, leading) },
1336
1341
  lockClause: (mode) => dialect.lockClause(mode),
1337
1342
  forkSegments: (tx, sessionId) => readForkSegments(tx, lineage, sessionId),
1338
1343
  forkChildren: (tx, sourceId) => forkChildren(tx, lineage, sourceId),
1339
1344
  async materializeForkSegments(tx, childId, pieces) {
1340
- await materializeForkSegments(tx, dialect, materialize, store.blobs, store.materializedLinks, childId, await length(tx, childId), pieces);
1345
+ await materializeForkSegments(tx, dialect, materialize, store.blobs, store.entryLinks, childId, await length(tx, childId), pieces);
1341
1346
  },
1342
1347
  async writeForkSegments(tx, sessionId, segments) {
1343
- if (segments.length > 0 || (await readForkSegments(tx, lineage, sessionId)).length > 0) await writeForkSegments(tx, lineage, sessionId, segments, await length(tx, sessionId));
1348
+ 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)));
1349
+ else if ((await readForkSegments(tx, lineage, sessionId)).length > 0) await writeForkSegments(tx, lineage, sessionId, segments, await length(tx, sessionId));
1344
1350
  },
1345
1351
  async lockForkSources(tx, ids, mode) {
1346
- await lockForkSources(tx, dialect, lineage, ids, mode);
1347
1352
  const sorted = [...new Set(ids)].sort();
1348
- if (dialect.name !== "sqlite" && sorted.length > 0) await tx.all(`SELECT session_id FROM ${forkTables.forkTombstones} WHERE session_id IN (${sorted.map(() => "?").join(", ")}) ORDER BY session_id${dialect.lockClause(mode)}`, ...sorted);
1353
+ 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));
1354
+ await lockForkSources(tx, dialect, lineage, sorted, mode);
1349
1355
  },
1350
1356
  async forkRewriteEpoch(tx, sessionId) {
1351
1357
  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;
@@ -1362,8 +1368,8 @@ function forkDetachHost(store) {
1362
1368
  * tombstone once nothing names them any more: when the last fork reading them is deleted, replaced or detached.
1363
1369
  * - Replacing a session that forks still read first gives each of them its own copy of the rows it read (detach),
1364
1370
  * since the replace deletes those rows.
1365
- * - Creating a session under the ID of a tombstone first detaches the forks that still read the old rows, then removes
1366
- * them, so the new session starts empty.
1371
+ * - Creating a session under the ID of a tombstone, by `create` or by any fork, first detaches the forks that still
1372
+ * read the old rows, then removes them, so the new session starts empty.
1367
1373
  *
1368
1374
  * A session's own segments go when it is deleted or replaced, which may leave a deleted source no fork reads; the caller
1369
1375
  * sweeps it once its transaction commits (fork-sweep.ts). A delete and a replace lock the session's row for update
@@ -1371,19 +1377,37 @@ function forkDetachHost(store) {
1371
1377
  * they drop its own segments and list the forks that name it only under that lock. A fork locks every session its
1372
1378
  * segments name for key share, tombstones included, so a fork being made either commits first and is listed, or waits
1373
1379
  * and finds the session gone.
1380
+ *
1381
+ * Every transaction locks tombstones before sessions rows, and the sessions rows it locks together in one statement,
1382
+ * in id order, so no two of them wait for each other in a cycle: a replace locks the forks reading the session with
1383
+ * the session itself, as a fork locks its donor with the sessions its segments name.
1374
1384
  */
1375
1385
  /**
1386
+ * A replace listed a fork of the session that its first read did not lock: a fork made while that read waited for its
1387
+ * locks. The replace runs again, locking it in order with the rest.
1388
+ */
1389
+ var ForkReadersMoved = class extends Error {
1390
+ constructor() {
1391
+ super("A fork of the session was made while its replace waited for its locks");
1392
+ }
1393
+ };
1394
+ /**
1376
1395
  * The statements a delete or a replace of `sessionId` reads its fork history with, as the first reads of its
1377
1396
  * transaction: where writers can run together, the session's row, locked for update so that no fork of it starts
1378
- * meanwhile, then the listing. Sent with the transaction's start, they cost no round trip of their own.
1397
+ * meanwhile, with `readers` also the rows of the forks reading it, which a replace detaches, all in id order; then
1398
+ * the listing. Sent with the transaction's start, they cost no round trip of their own.
1379
1399
  */
1380
- function forkPinReads(host, sessions, sessionId) {
1400
+ function forkPinReads(host, sessions, sessionId, readers = false) {
1381
1401
  const { forkSegments, forkLineage } = host.pinTables;
1382
1402
  const lock = host.lockClause("update");
1383
- return [...lock === "" ? [] : [{
1403
+ const locked = readers ? {
1404
+ sql: `SELECT id FROM ${sessions} WHERE id = ? OR id IN (SELECT session_id FROM ${forkSegments} WHERE source_id = ?) ORDER BY id${lock}`,
1405
+ params: [sessionId, sessionId]
1406
+ } : {
1384
1407
  sql: `SELECT id FROM ${sessions} WHERE id = ?${lock}`,
1385
1408
  params: [sessionId]
1386
- }], {
1409
+ };
1410
+ return [...lock === "" ? [] : [locked], {
1387
1411
  sql: `SELECT 's' AS kind, source_id AS id FROM ${forkSegments} WHERE session_id = ?
1388
1412
  UNION SELECT 'r', session_id FROM ${forkSegments} WHERE source_id = ? AND session_id <> ?
1389
1413
  UNION SELECT 'l', session_id FROM ${forkLineage} WHERE session_id = ?`,
@@ -1398,13 +1422,16 @@ function forkPinReads(host, sessions, sessionId) {
1398
1422
  /** Reads `sessionId`'s fork history through the statements of {@link forkPinReads}, in order. */
1399
1423
  async function readForkPins(tx, reads) {
1400
1424
  const listing = reads.at(-1);
1401
- for (const lock of reads.slice(0, -1)) await tx.get(lock.sql, ...lock.params);
1425
+ const locks = reads.slice(0, -1);
1426
+ const locked = /* @__PURE__ */ new Set();
1427
+ for (const lock of locks) for (const row of await tx.all(lock.sql, ...lock.params)) locked.add(String(row.id));
1402
1428
  const rows = await tx.all(listing.sql, ...listing.params);
1403
1429
  const of = (kind) => [...new Set(rows.filter((row) => row.kind === kind).map((row) => String(row.id)))].sort();
1404
1430
  return {
1405
1431
  sources: of("s"),
1406
1432
  readers: of("r"),
1407
- lineage: rows.some((row) => row.kind === "l")
1433
+ lineage: rows.some((row) => row.kind === "l"),
1434
+ ...locks.length === 0 ? {} : { locked }
1408
1435
  };
1409
1436
  }
1410
1437
  /**
@@ -1430,21 +1457,32 @@ async function deleteForkedSessionWithin(host, tx, sessionId, deletedAt, pins) {
1430
1457
  * In `replace`'s transaction, before the session's rows go, given what {@link readForkPins} read: each fork reading
1431
1458
  * them gets its own copy, and the session drops its own segments, as a replaced session holds every row of its view
1432
1459
  * itself. Resolves with the sources those segments named, to sweep once the transaction commits. A session no fork
1433
- * history names costs no statement.
1460
+ * history names costs no statement. Throws {@link ForkReadersMoved}, unless `lockLate`, when it lists a fork its first
1461
+ * read did not lock: locked now, after the session's row, a fork of that fork could wait for the replace while it
1462
+ * waits for the fork. `lockLate` locks it all the same, as a replace that ran again too often does.
1434
1463
  */
1435
- async function replaceForkedSessionWithin(host, tx, sessionId, pins) {
1464
+ async function replaceForkedSessionWithin(host, tx, sessionId, pins, lockLate = false) {
1465
+ const { locked } = pins;
1466
+ if (!lockLate && locked !== void 0 && pins.readers.some((reader) => !locked.has(reader))) throw new ForkReadersMoved();
1436
1467
  if (pins.sources.length > 0) await host.writeForkSegments(tx, sessionId, []);
1437
1468
  for (const child of pins.readers) await detachForkWithin(host, tx, sessionId, child, false);
1438
1469
  return pins.sources;
1439
1470
  }
1440
1471
  /**
1441
- * In `create`'s transaction, before the session is written: when a deleted session with this ID left a tombstone,
1442
- * the forks still reading its rows get their own copy, and the rows go.
1472
+ * In the transaction that writes a new session, by `create` or by a fork, before the session is written: when a
1473
+ * deleted session with this ID left a tombstone, the forks still reading its rows get their own copy, and the rows go.
1474
+ * Resolves with whether there was a tombstone.
1475
+ *
1476
+ * The tombstone is locked before the forks that read the rows, as every writer orders them: a fork locks the
1477
+ * tombstones among its sources before any session's row, so a fork that waits for this tombstone holds no row this
1478
+ * transaction locks next. Under the tombstone's lock no fork starts reading the rows, so the forks listed then are all
1479
+ * of them.
1443
1480
  */
1444
1481
  async function createOverTombstoneWithin(host, tx, sessionId) {
1445
- if (!await isTombstoned(host, tx, sessionId)) return;
1482
+ if (!await isTombstoned(host, tx, sessionId)) return false;
1446
1483
  for (const child of await lockedReferrers(host, tx, sessionId)) await detachForkWithin(host, tx, sessionId, child, false);
1447
1484
  await removeStoredRows(host, tx, sessionId);
1485
+ return true;
1448
1486
  }
1449
1487
  /** Never load the clone writer in an ordinary open. Fence a lapsed transfer before deleting so a paused donor
1450
1488
  * cannot publish a partially swept transfer. When more rows remain, the new token stays expired. */
@@ -1545,6 +1583,23 @@ function withForkViews(views, sql) {
1545
1583
  function forkViewParams(views) {
1546
1584
  return views.flatMap((view) => view.params);
1547
1585
  }
1586
+ // dist/core/storage/session/session-transactions.js
1587
+ /**
1588
+ * A write to the rows of the session `sessionId` of the sessions table `sessions`: on Postgres it is the only writer of
1589
+ * that session, while writers of other sessions run beside it; SQLite runs every write alone anyway. Every writer of a
1590
+ * session's rows names this one domain, whatever table it writes (the session store, its chat records, its search
1591
+ * index), so the checks each makes against the session's row hold until it commits. A transient failure runs it again
1592
+ * (#4383).
1593
+ */
1594
+ function sessionWriteTransaction(sessions, sessionId) {
1595
+ return {
1596
+ retryTransientFailures: true,
1597
+ concurrency: {
1598
+ kind: "serial",
1599
+ domain: `${sessions}:${sessionId}`
1600
+ }
1601
+ };
1602
+ }
1548
1603
  // dist/core/storage/session/sql-chat-records.js
1549
1604
  /** Rows one read fetches at most. */
1550
1605
  const READ_PAGE_ROWS = 64;
@@ -1640,9 +1695,9 @@ function sqlChatRecords(database, sessions, table, index, ledger) {
1640
1695
  row_number() OVER (ORDER BY position) AS page_row,
1641
1696
  sum(${bytes("anchor")}+${bytes("data")}) OVER (ORDER BY position) AS page_bytes
1642
1697
  FROM (SELECT position,anchor,data FROM ${table}
1643
- WHERE session_id=? AND epoch=? AND position>? AND anchor IN (${anchors.map(() => "?").join(",")})
1698
+ WHERE session_id=? AND epoch=? AND position>? AND ${inJsonList(dialect, "anchor")}
1644
1699
  ORDER BY position LIMIT ${READ_PAGE_ROWS}) AS candidates
1645
- ) AS page WHERE page_row=1 OR page_bytes<=? ORDER BY position`, owner.id, owner.epoch, after, ...anchors.map(lineKey), CHAT_READ_PAGE_BYTES);
1700
+ ) 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);
1646
1701
  for (const { anchor, data } of rows) {
1647
1702
  const record = decodeChatRecord(data);
1648
1703
  if (record) result.push({
@@ -1659,7 +1714,7 @@ function sqlChatRecords(database, sessions, table, index, ledger) {
1659
1714
  const orders = [];
1660
1715
  for (let i = 0; i < promptIds.length; i += ORDER_BATCH) {
1661
1716
  const keys = promptIds.slice(i, i + ORDER_BATCH).map(orderKey);
1662
- 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);
1717
+ 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));
1663
1718
  for (const { data } of rows) {
1664
1719
  const order = decodeChatOrder(data);
1665
1720
  if (order) orders.push(order);
@@ -1671,6 +1726,12 @@ function sqlChatRecords(database, sessions, table, index, ledger) {
1671
1726
  }
1672
1727
  // dist/core/storage/session/sql-session-store.js
1673
1728
  /**
1729
+ * `sessionEntryLinks` of `blob-store.ts`, which the copy a process of an earlier release loaded lacks. Such a process
1730
+ * keeps that copy after an in-place update, and can load this module from the update: a named import would fail to link
1731
+ * there. Without it, a materialization leaves the links the index's triggers wrote until the index is rebuilt (#6560).
1732
+ */
1733
+ const entryLinkers = blobStore;
1734
+ /**
1674
1735
  * The newest sessions schema this build reads and writes. Version 2 stores long entries in chunks (#4954), which a build
1675
1736
  * that knows only version 1 would read as stubs. A database stays at version 1, which older builds still open, until
1676
1737
  * this build writes its first chunked entry: that transaction moves the sessions meta to 2, and older builds refuse it
@@ -1763,6 +1824,24 @@ var ForkSourcesMoved = class extends Error {
1763
1824
  super("The fork's source moved its history while the fork read it");
1764
1825
  }
1765
1826
  };
1827
+ /**
1828
+ * A fork into the ID of a deleted session forks still read, whose reads did not lock that session's tombstone and the
1829
+ * forks reading it before the donor's row: the fork runs again with reads that do (#6560).
1830
+ */
1831
+ var ForkChildTombstoned = class extends Error {
1832
+ constructor() {
1833
+ super("The fork's child has the ID of a deleted session forks still read");
1834
+ }
1835
+ };
1836
+ /** The leading statements of a fork's transaction: its reads of {@link SharedForkReads}, in the order it makes them. */
1837
+ function sharedForkLeading(reads) {
1838
+ return [
1839
+ reads.exists,
1840
+ reads.tombstones,
1841
+ reads.lock,
1842
+ reads.segments
1843
+ ];
1844
+ }
1766
1845
  function windowIndex(state, seq) {
1767
1846
  return isSessionResumeIndex(state.windowResume, seq) ? state.windowResume : isSessionResumeIndex(state.resume, seq) ? state.resume : void 0;
1768
1847
  }
@@ -1902,6 +1981,14 @@ const SESSION_READ = {
1902
1981
  retryTransientFailures: true,
1903
1982
  readOnly: true
1904
1983
  };
1984
+ /**
1985
+ * A read-only gate transaction whose only statement is the leading schema version check, committed with the start on a
1986
+ * pipelined connection without acquiring any write lock.
1987
+ */
1988
+ const SESSION_READ_GATE = {
1989
+ ...SESSION_READ,
1990
+ leadingOnly: true
1991
+ };
1905
1992
  /** The largest content index or suffix length a task-reference query binds, an SQL `INTEGER` on every backend. */
1906
1993
  const TASK_REFERENCE_INTEGER = 2 ** 31 - 1;
1907
1994
  /**
@@ -2119,12 +2206,16 @@ var SqlSessionStore = class SqlSessionStore {
2119
2206
  chatStore;
2120
2207
  /** The database's reader handle, once a read opened it: see `readerDatabase`. */
2121
2208
  reader;
2209
+ /** Each session's writes this store started and has not finished, each settled as its write is: see `writing`. */
2210
+ unfinishedWrites = /* @__PURE__ */ new Map();
2122
2211
  /** The sessions schema version each transaction read first, by its handle: see `sharedHistoryForks`. */
2123
2212
  schemaVersions = /* @__PURE__ */ new WeakMap();
2124
2213
  /** The fork tables under this store's prefix, which exist once its sessions schema is version 3 (#6560). */
2125
2214
  forkTables;
2126
2215
  /** See {@link forkLinks}. */
2127
2216
  forkLinkStatements;
2217
+ /** See {@link entryLinks}. */
2218
+ entryLinkStatements;
2128
2219
  /**
2129
2220
  * Whether a read of this store found its sessions schema at {@link SESSION_SCHEMA_VERSION_SHARED_HISTORY}: one way,
2130
2221
  * as the switch is. A read outside a transaction reads sessions through their views once it is set, and before that
@@ -2137,14 +2228,7 @@ var SqlSessionStore = class SqlSessionStore {
2137
2228
  forkedSessions = /* @__PURE__ */ new Map();
2138
2229
  /** The sessions each recently forked session's segments named when this store last read them (#6560). */
2139
2230
  forkSources = /* @__PURE__ */ new Map();
2140
- /**
2141
- * Absent on a local libSQL file, which then behaves as before: @libsql/client waits for another process's write
2142
- * lock on the calling thread, even to begin a transaction, so a side write would stop the event loop where an
2143
- * ordinary turn-ending notice writes nothing (#5682).
2144
- */
2145
2231
  get chatRecords() {
2146
- const { adapter, location } = this.database.descriptor;
2147
- if (adapter === "libsql" && /^file:/i.test(location)) return void 0;
2148
2232
  if (!this.chatStore) {
2149
2233
  const names = renderStorageIdentifiers("sessions", {
2150
2234
  rows: "chat_v1",
@@ -2200,7 +2284,7 @@ var SqlSessionStore = class SqlSessionStore {
2200
2284
  registerHistorySnapshot(this, (sessionId, project) => {
2201
2285
  this.assertOpen();
2202
2286
  validateSessionText("sessionId", sessionId);
2203
- return this.readTransaction(async (tx) => {
2287
+ return this.readTransaction(sessionId, async (tx) => {
2204
2288
  const head = await this.historyHead(tx, sessionId, true);
2205
2289
  return project(head.epoch, head.lastSeq, (from, through, backward) => this.historyPacket(tx, sessionId, head.epoch, from, through, backward));
2206
2290
  });
@@ -2306,8 +2390,12 @@ var SqlSessionStore = class SqlSessionStore {
2306
2390
  await statementBatch(tx, [chunks === void 0 && `ALTER TABLE ${tables.entries} ADD COLUMN chunks ${int} NOT NULL DEFAULT 0`, database.readOnly !== true && removeOrphanedEntryChunks], []);
2307
2391
  };
2308
2392
  const presence = renderStorageIdentifiers("sessions", SESSION_PRESENCE_TABLES, options.prefix);
2393
+ const ledger = storageMigrationTable(options.prefix);
2394
+ const entryByteLengthPromise = entryByteLengthOf(database);
2309
2395
  const current = await SqlSessionStore.currentSchema(database, tables, presence.open, database.readOnly === true ? void 0 : orphanedEntryKeys);
2396
+ const dialect = dialectOf(database);
2310
2397
  let sharedHistory;
2398
+ let batchedSqliteSetup = false;
2311
2399
  if (current !== void 0) {
2312
2400
  legacyBlobData = current.legacyBlobData;
2313
2401
  sharedHistory = current.sharedHistory;
@@ -2317,7 +2405,97 @@ var SqlSessionStore = class SqlSessionStore {
2317
2405
  }).catch((error) => {
2318
2406
  if (error instanceof StorageSchemaVersionError) throw error;
2319
2407
  });
2320
- } else {
2408
+ } else if (!dialect.versionedMigrations) {
2409
+ const requiredTables = [...Object.values(tables), presence.open];
2410
+ const requiredColumns = [
2411
+ [tables.sessions, "revision"],
2412
+ [tables.entries, "chunks"],
2413
+ [tables.blobs, "chunks"],
2414
+ [presence.open, "schema_version"],
2415
+ [presence.open, "build"]
2416
+ ];
2417
+ batchedSqliteSetup = queueSqliteSchemaSetup(database, ledger, {
2418
+ reset() {
2419
+ createdShared = false;
2420
+ legacyBlobData = false;
2421
+ },
2422
+ done: async (freshCatalog) => {
2423
+ if (!(requiredTables.every((table) => freshCatalog.hasTable(table)) && requiredColumns.every(([table, column]) => freshCatalog.hasColumn(table, column)))) return false;
2424
+ const versions = await database.all(`SELECT schema_version FROM ${tables.meta}`);
2425
+ if (versions.length === 0) return false;
2426
+ for (const version of versions) assertStorageSchemaVersion("sessions", version.schema_version, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
2427
+ legacyBlobData = freshCatalog.hasColumn(tables.blobs, "data");
2428
+ createdShared = versions.every((row) => Number(row.schema_version) >= 3);
2429
+ return true;
2430
+ },
2431
+ run: async (ctx) => {
2432
+ if (ctx.catalog !== void 0 && !requiredTables.some((table) => ctx.tableExisted(table))) {
2433
+ const { int, text, blob } = dialect.types;
2434
+ const strict = dialect.tableOptions;
2435
+ const json = (column) => dialect.jsonValid(column);
2436
+ const tablesScript = `
2437
+ CREATE TABLE IF NOT EXISTS ${tables.sessions} (
2438
+ id ${text} PRIMARY KEY, cwd ${text} NOT NULL, created_at ${text} NOT NULL,
2439
+ header_json ${text} NOT NULL CHECK(${json("header_json")}), internal ${int} NOT NULL,
2440
+ last_seq ${int} NOT NULL, modified_at ${text} NOT NULL, message_count ${int} NOT NULL,
2441
+ first_message ${text} NOT NULL CHECK(${json("first_message")}),
2442
+ name ${text} CHECK(name IS NULL OR ${json("name")}), has_name ${int} NOT NULL,
2443
+ summary ${text} CHECK(summary IS NULL OR ${json("summary")}), summarized_through_id ${text},
2444
+ summary_state ${text} NOT NULL CHECK(${json("summary_state")}), revision ${text} NOT NULL DEFAULT ''${dialect.rowOrderColumn}
2445
+ )${strict};
2446
+ CREATE TABLE IF NOT EXISTS ${tables.entries} (
2447
+ session_id ${text} NOT NULL, seq ${int} NOT NULL, entry_id ${text} NOT NULL,
2448
+ entry_json ${text} NOT NULL CHECK(${json("entry_json")}), PRIMARY KEY(session_id, seq)${dialect.rowOrderColumn}
2449
+ )${strict};
2450
+ CREATE TABLE IF NOT EXISTS ${tables.searchTexts} (
2451
+ session_id ${text} NOT NULL, seq ${int} NOT NULL,
2452
+ text_json ${text} NOT NULL CHECK(${json("text_json")}), PRIMARY KEY(session_id, seq)
2453
+ )${strict};
2454
+ CREATE TABLE IF NOT EXISTS ${tables.blobs} (
2455
+ session_id ${text} NOT NULL, hash ${text} NOT NULL, bytes ${int} NOT NULL, chunks ${int} NOT NULL,
2456
+ PRIMARY KEY(session_id, hash)
2457
+ )${strict};
2458
+ CREATE TABLE IF NOT EXISTS ${tables.blobChunks} (
2459
+ session_id ${text} NOT NULL, hash ${text} NOT NULL, idx ${int} NOT NULL, data ${blob} NOT NULL,
2460
+ PRIMARY KEY(session_id, hash, idx)
2461
+ )${strict};
2462
+ `;
2463
+ ctx.enqueue(`CREATE TABLE IF NOT EXISTS ${tables.meta} (schema_version ${int} NOT NULL)${strict}`);
2464
+ ctx.enqueue({
2465
+ sql: `INSERT INTO ${tables.meta} VALUES (?)`,
2466
+ params: [3]
2467
+ });
2468
+ ctx.enqueue(`${tablesScript}\n${sharedHistoryTablesScript(dialect, forkTables)}`);
2469
+ ctx.enqueue(`
2470
+ CREATE TABLE IF NOT EXISTS ${tables.entryChunks} (
2471
+ session_id ${text} NOT NULL, seq ${int} NOT NULL, idx ${int} NOT NULL, data ${blob} NOT NULL,
2472
+ PRIMARY KEY(session_id, seq, idx)
2473
+ )${strict};
2474
+ `);
2475
+ ctx.enqueue(`ALTER TABLE ${tables.entries} ADD COLUMN chunks ${int} NOT NULL DEFAULT 0`);
2476
+ ctx.enqueue(`
2477
+ CREATE TABLE IF NOT EXISTS ${presence.open} (
2478
+ session_id ${text} NOT NULL, token ${text} NOT NULL, pid ${int} NOT NULL, host ${text} NOT NULL,
2479
+ heartbeat_at ${int} NOT NULL, schema_version ${int}, build ${text}, PRIMARY KEY(session_id, token)
2480
+ )${strict};
2481
+ `);
2482
+ for (const table of [...requiredTables, ...Object.values(forkTables)]) ctx.noteTableCreated(table);
2483
+ createdShared = true;
2484
+ legacyBlobData = false;
2485
+ return;
2486
+ }
2487
+ await ctx.flushWrites();
2488
+ await createTables(ctx.tx, dialect);
2489
+ await addEntryChunks(ctx.tx, dialect);
2490
+ await SqlSessionOpenMarkers.createTable(ctx.tx, dialect, presence.open);
2491
+ await SqlSessionOpenMarkers.addSchemaVersion(ctx.tx, dialect, presence.open);
2492
+ await SqlSessionOpenMarkers.addBuild(ctx.tx, dialect, presence.open);
2493
+ for (const table of requiredTables) ctx.noteTableCreated(table);
2494
+ if (createdShared) for (const table of Object.values(forkTables)) ctx.noteTableCreated(table);
2495
+ }
2496
+ });
2497
+ }
2498
+ if (current === void 0 && !batchedSqliteSetup) {
2321
2499
  const [sessionsSchema] = await applyStorageMigrationsTogether(database, [{
2322
2500
  domain: SESSION_DOMAIN,
2323
2501
  steps: [{
@@ -2328,8 +2506,8 @@ var SqlSessionStore = class SqlSessionStore {
2328
2506
  up: addEntryChunks
2329
2507
  }],
2330
2508
  options: {
2331
- table: storageMigrationTable(options.prefix),
2332
- recordedThrough: 3
2509
+ table: ledger,
2510
+ acceptNewer: true
2333
2511
  }
2334
2512
  }, {
2335
2513
  domain: SESSION_PRESENCE_DOMAIN,
@@ -2348,39 +2526,71 @@ var SqlSessionStore = class SqlSessionStore {
2348
2526
  }
2349
2527
  ],
2350
2528
  options: {
2351
- table: storageMigrationTable(options.prefix),
2529
+ table: ledger,
2352
2530
  acceptNewer: true
2353
2531
  }
2354
2532
  }]);
2533
+ if ((sessionsSchema?.version ?? 0) > 3) throw new StorageSchemaVersionError(SESSION_DOMAIN, sessionsSchema.version, 3);
2355
2534
  if (createdShared) {
2356
2535
  sharedHistory = true;
2357
2536
  noteStorageSchemaTables(database, Object.values(forkTables));
2358
- } else if (dialectOf(database).versionedMigrations) sharedHistory = (sessionsSchema?.version ?? 0) >= 3;
2537
+ } else if (dialect.versionedMigrations) sharedHistory = (sessionsSchema?.version ?? 0) >= 3;
2359
2538
  }
2360
2539
  await ensureTableFillfactor(database, {
2361
- ledger: storageMigrationTable(options.prefix),
2540
+ ledger,
2362
2541
  domain: SESSION_FILLFACTOR_DOMAIN,
2363
2542
  revision: 1,
2364
2543
  table: tables.sessions,
2365
2544
  fillfactor: SESSION_ROW_FILLFACTOR
2366
2545
  });
2367
2546
  const markers = new SqlSessionOpenMarkers(database, presence.open, () => store.assertOpen());
2547
+ const staging = renderStorageIdentifiers("sessions", SESSION_FORK_STAGING_TABLES, options.prefix).forkStaging;
2548
+ const stagingProbe = dialect.tableExists(staging);
2368
2549
  let shared = sharedHistory === true;
2369
- if (sharedHistory !== true && database.readOnly !== true) {
2370
- const switched = await SqlSessionStore.switchAtOpen(database, options.prefix ?? "", tables, markers, sharedHistory === false);
2371
- if (switched) refreshStorageSchemaCatalog(database);
2372
- shared = switched;
2550
+ let blobs;
2551
+ let searchIndex;
2552
+ let catalog;
2553
+ let staged;
2554
+ if (batchedSqliteSetup) {
2555
+ catalog = await schemaCatalogOf(database);
2556
+ staged = database.readOnly === true || !database.tryMaintenance ? Promise.resolve(false) : catalog !== void 0 ? Promise.resolve(catalog.hasTable(staging)) : database.get(stagingProbe.sql, ...stagingProbe.params).then((row) => row !== void 0, () => false);
2557
+ let searchUnavailable = false;
2558
+ blobs = await SqlSnapshotBlobStore$1.open(database, options.prefix);
2559
+ const openedSearch = await SqlSessionSearchIndex.open(database, tables, options.prefix, () => {
2560
+ searchUnavailable = true;
2561
+ });
2562
+ await Promise.allSettled([entryByteLengthPromise]);
2563
+ await flushStorageSchemaSetups(database, ledger);
2564
+ searchIndex = searchUnavailable ? void 0 : openedSearch;
2565
+ shared = createdShared;
2566
+ if (!shared && database.readOnly !== true) {
2567
+ if (await SqlSessionStore.switchAtOpen(database, options.prefix ?? "", tables, markers, false)) {
2568
+ refreshStorageSchemaCatalog(database);
2569
+ shared = true;
2570
+ blobs = await SqlSnapshotBlobStore$1.open(database, options.prefix);
2571
+ await ensureForkInheritedBlobGuard(database, snapshotIndexTables$1(options.prefix), forkTables.forkSegments, ledger);
2572
+ }
2573
+ }
2574
+ } else {
2575
+ if (sharedHistory !== true && database.readOnly !== true) {
2576
+ const switched = await SqlSessionStore.switchAtOpen(database, options.prefix ?? "", tables, markers, sharedHistory === false);
2577
+ if (switched) refreshStorageSchemaCatalog(database);
2578
+ shared = switched;
2579
+ }
2580
+ catalog = await schemaCatalogOf(database);
2581
+ staged = database.readOnly === true || !database.tryMaintenance ? Promise.resolve(false) : catalog !== void 0 ? Promise.resolve(catalog.hasTable(staging)) : database.get(stagingProbe.sql, ...stagingProbe.params).then((row) => row !== void 0, () => false);
2582
+ const opening = current === void 0 ? await SqlSnapshotBlobStore$1.open(database, options.prefix) : void 0;
2583
+ let searchUnavailable = false;
2584
+ const [openedBlobs, openedSearch] = await Promise.all([opening ?? SqlSnapshotBlobStore$1.open(database, options.prefix), SqlSessionSearchIndex.open(database, tables, options.prefix, () => {
2585
+ searchUnavailable = true;
2586
+ })]);
2587
+ await Promise.allSettled([entryByteLengthPromise]);
2588
+ await flushStorageSchemaSetups(database, ledger);
2589
+ blobs = openedBlobs;
2590
+ searchIndex = searchUnavailable ? void 0 : openedSearch;
2591
+ if (shared) await ensureForkInheritedBlobGuard(database, snapshotIndexTables$1(options.prefix), forkTables.forkSegments, ledger);
2373
2592
  }
2374
- const staging = renderStorageIdentifiers("sessions", SESSION_FORK_STAGING_TABLES, options.prefix).forkStaging;
2375
- const stagingProbe = dialectOf(database).tableExists(staging);
2376
- const catalog = await schemaCatalogOf(database);
2377
- const staged = database.readOnly === true || !database.tryMaintenance ? Promise.resolve(false) : catalog !== void 0 ? Promise.resolve(catalog.hasTable(staging)) : database.get(stagingProbe.sql, ...stagingProbe.params).then((row) => row !== void 0, () => false);
2378
- const opening = current === void 0 ? await SqlSnapshotBlobStore$1.open(database, options.prefix) : void 0;
2379
- const [blobs, searchIndex, entryByteLength] = await Promise.all([
2380
- opening ?? SqlSnapshotBlobStore$1.open(database, options.prefix),
2381
- SqlSessionSearchIndex.open(database, tables, options.prefix),
2382
- entryByteLengthOf(database)
2383
- ]);
2593
+ const entryByteLength = await entryByteLengthPromise;
2384
2594
  const appendFunction = renderStorageIdentifiers("sessions", { append: SESSION_APPEND_FUNCTION }, options.prefix).append;
2385
2595
  const appendsThroughFunction = catalog?.hasFunction?.(appendFunction) === true && database.autocommit !== void 0 && typeof blobs.storedBlobsQuery === "function";
2386
2596
  const store = new SqlSessionStore(database, tables, options.prefix, options.cwdMatcher, blobs, legacyBlobData, searchIndex, entryByteLength, appendsThroughFunction ? appendFunction : void 0);
@@ -2425,17 +2635,26 @@ var SqlSessionStore = class SqlSessionStore {
2425
2635
  let legacyBlobs;
2426
2636
  const catalog = await reading;
2427
2637
  if (catalog !== void 0) {
2428
- if (!(required.every((table) => catalog.hasTable(table)) && columns.every(([table, column]) => catalog.hasColumn(table, column)))) return void 0;
2638
+ if (!(required.every((table) => catalog.hasTable(table)) && columns.every(([table, column]) => catalog.hasColumn(table, column)))) {
2639
+ await Promise.allSettled([orphaned, versionsRead]);
2640
+ return;
2641
+ }
2429
2642
  legacyBlobs = catalog.hasColumn(tables.blobs, "data");
2430
2643
  } else {
2431
2644
  const probes = [...required.map((table) => dialect.tableExists(table)), ...columns.map(([table, column]) => dialect.columnExists(table, column))];
2432
2645
  const legacy = dialect.columnExists(tables.blobs, "data");
2433
2646
  const [legacyFound, ...found] = await Promise.all([legacy, ...probes].map((probe) => database.get(probe.sql, ...probe.params)));
2434
- if (!found.every((row) => row !== void 0)) return void 0;
2647
+ if (!found.every((row) => row !== void 0)) {
2648
+ await Promise.allSettled([orphaned, versionsRead]);
2649
+ return;
2650
+ }
2435
2651
  legacyBlobs = legacyFound !== void 0;
2436
2652
  }
2437
2653
  const versions = await versionsRead;
2438
- 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;
2654
+ 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)) {
2655
+ await Promise.allSettled([orphaned]);
2656
+ return;
2657
+ }
2439
2658
  return {
2440
2659
  legacyBlobData: legacyBlobs,
2441
2660
  orphaned: await orphaned !== void 0,
@@ -2474,19 +2693,57 @@ var SqlSessionStore = class SqlSessionStore {
2474
2693
  };
2475
2694
  }
2476
2695
  /**
2477
- * `transaction` for a body that only reads, in one read-only snapshot, on the database's reader handle when it
2478
- * offers one: its reads then wait for neither the writes queued on this store's connection nor their locks.
2696
+ * `transaction` for a body that only reads session `sessionId`, in one read-only snapshot, on the database's reader
2697
+ * handle when it offers one: its reads then wait for neither the writes queued on this store's connection nor their
2698
+ * locks. It first waits for the writes of that session this store started and has not finished (`writing`), so a
2699
+ * caller that starts a write and then reads, without awaiting the write, reads it as the store's own connection would
2700
+ * have; with none unfinished it waits for nothing.
2479
2701
  */
2480
- async readTransaction(body, leading = []) {
2481
- return (await this.readerDatabase()).transaction(async (tx) => {
2702
+ async readTransaction(sessionId, body, leading = []) {
2703
+ const unfinished = this.unfinishedWrites.get(sessionId);
2704
+ if (unfinished !== void 0) await Promise.all(unfinished);
2705
+ const database = await this.readerDatabase();
2706
+ const statements = typeof leading === "function" ? leading() : leading;
2707
+ return database.transaction(async (tx) => {
2482
2708
  await this.assertReadableSchema(tx);
2483
2709
  return body(tx);
2484
- }, this.checkedFirst(leading.length === 0 ? SESSION_READ : {
2710
+ }, this.checkedFirst(statements.length === 0 ? SESSION_READ : {
2485
2711
  ...SESSION_READ,
2486
- leading
2712
+ leading: statements
2487
2713
  }));
2488
2714
  }
2489
2715
  /**
2716
+ * Runs `firstRead` behind the sessions schema check in one read-only transaction: on a pipelined connection the
2717
+ * begin, schema check, read and commit go out in one round trip on one pool checkout, and an unsupported schema
2718
+ * version is always thrown before `firstRead`'s result or failure is observed.
2719
+ */
2720
+ readChecked(firstRead, run) {
2721
+ return this.database.transaction(async (tx) => {
2722
+ await this.assertReadableSchema(tx);
2723
+ return run(tx);
2724
+ }, {
2725
+ ...SESSION_READ,
2726
+ leading: [this.schemaCheck(), firstRead],
2727
+ leadingOnly: true
2728
+ });
2729
+ }
2730
+ /**
2731
+ * `write`, a write of session `sessionId` this store has just started, kept in `unfinishedWrites` until it settles,
2732
+ * for the reads of the session that start meanwhile to wait for (`readTransaction`). No write waits for a read, and
2733
+ * no write of this store reads through `readTransaction`, so the wait never comes back to the write.
2734
+ */
2735
+ writing(sessionId, write) {
2736
+ const writes = this.unfinishedWrites.get(sessionId) ?? /* @__PURE__ */ new Set();
2737
+ this.unfinishedWrites.set(sessionId, writes);
2738
+ const settled = write.then(() => {}, () => {});
2739
+ writes.add(settled);
2740
+ settled.then(() => {
2741
+ writes.delete(settled);
2742
+ if (writes.size === 0 && this.unfinishedWrites.get(sessionId) === writes) this.unfinishedWrites.delete(sessionId);
2743
+ });
2744
+ return write;
2745
+ }
2746
+ /**
2490
2747
  * The database's reader handle, opened at the first read and closed with the store; the database without one. A
2491
2748
  * reader that cannot open, such as when its file can no longer be opened anew, leaves the read on the store's own
2492
2749
  * connection, as every read ran before readers, and the next read tries to open one again.
@@ -2682,6 +2939,7 @@ var SqlSessionStore = class SqlSessionStore {
2682
2939
  holders
2683
2940
  };
2684
2941
  await createSharedHistoryTables(tx, dialect, sessionForkTables(prefix));
2942
+ await installForkInheritedBlobGuard(tx, dialect, snapshotIndexTables$1(prefix), sessionForkTables(prefix).forkSegments);
2685
2943
  await statementBatch(tx, [
2686
2944
  dialect.dropTrigger(legacyForkLinksTriggerName(tables.entries), tables.entries, true),
2687
2945
  dialect.versionedMigrations && {
@@ -2744,27 +3002,19 @@ var SqlSessionStore = class SqlSessionStore {
2744
3002
  };
2745
3003
  }
2746
3004
  async create(header, entries) {
3005
+ return this.writing(header.id, this.writeCreate(header, entries));
3006
+ }
3007
+ async writeCreate(header, entries) {
2747
3008
  this.assertOpen();
2748
3009
  validateSessionHeader(header);
2749
3010
  validateSessionEntries(entries);
2750
- const tombstones = this.sharedHistorySeen;
2751
- const existing = tombstones ? {
2752
- sql: `SELECT (SELECT id FROM ${this.tables.sessions} WHERE id = ?) AS id, (SELECT session_id FROM ${this.forkTables.forkTombstones} WHERE session_id = ?) AS tombstone`,
2753
- params: [header.id, header.id]
2754
- } : {
2755
- sql: `SELECT id FROM ${this.tables.sessions} WHERE id = ?`,
2756
- params: [header.id]
2757
- };
3011
+ const existing = this.newSessionRead(header.id);
2758
3012
  let written = [];
2759
3013
  let writtenRow;
2760
3014
  const created = await this.transactionCheckedAlongside(async (tx, checked) => {
2761
3015
  writtenRow = void 0;
2762
3016
  const found = await tx.get(existing.sql, ...existing.params);
2763
- if (found?.id != null) throw new SessionExistsError$1(header.id);
2764
- if (await this.sharedHistoryForks(tx) && (tombstones ? found?.tombstone != null : await this.hasForkTombstone(tx, header.id))) await createOverTombstoneWithin(this.forkHost(), tx, header.id).catch((error) => {
2765
- noteForkCopyRefusal(error, "create");
2766
- throw error;
2767
- });
3017
+ await this.startNewSession(tx, header.id, found, "create");
2768
3018
  const summary = this.summaryWrite(header.id, {
2769
3019
  header,
2770
3020
  entries,
@@ -2783,7 +3033,55 @@ var SqlSessionStore = class SqlSessionStore {
2783
3033
  this.rememberWritten(header.id, writtenRow);
2784
3034
  return created;
2785
3035
  }
3036
+ /**
3037
+ * The read that begins a transaction writing a new session `id`, by `create` or by a fork: whether it exists and, where
3038
+ * this store has seen shared history, whether a deleted session with this ID left rows forks still read, in the same
3039
+ * statement.
3040
+ */
3041
+ newSessionRead(id) {
3042
+ return this.sharedHistorySeen ? {
3043
+ sql: `SELECT (SELECT id FROM ${this.tables.sessions} WHERE id = ?) AS id, (SELECT session_id FROM ${this.forkTables.forkTombstones} WHERE session_id = ?) AS tombstone`,
3044
+ params: [id, id]
3045
+ } : {
3046
+ sql: `SELECT id FROM ${this.tables.sessions} WHERE id = ?`,
3047
+ params: [id]
3048
+ };
3049
+ }
3050
+ /**
3051
+ * In the transaction that writes a new session `id`, before its writes, given what {@link newSessionRead} found:
3052
+ * refuses a session that exists. Where a deleted session with this ID left rows forks still read, those forks get
3053
+ * their own copies first and the rows go, so the new session starts empty and their sweep never takes its rows. A
3054
+ * fork whose copy a missing source chunk refuses keeps the old rows, and the new session is refused with it.
3055
+ */
3056
+ async startNewSession(tx, id, found, operation) {
3057
+ if (found?.id != null) throw new SessionExistsError$1(id);
3058
+ if (!await this.sharedHistoryForks(tx)) return false;
3059
+ if (!(found?.tombstone === void 0 ? await this.hasForkTombstone(tx, id) : found.tombstone !== null)) return false;
3060
+ return createOverTombstoneWithin(this.forkHost(), tx, id).catch((error) => {
3061
+ noteForkCopyRefusal(error, operation);
3062
+ throw error;
3063
+ });
3064
+ }
3065
+ /**
3066
+ * {@link startNewSession} for a fork with shared history, once it has read its donor: resolves with the donor. A donor
3067
+ * that read the rows a deleted session with the child's ID left holds its own copy of them now, in segments of its
3068
+ * own, and is read again (#6560).
3069
+ */
3070
+ async startSharedFork(tx, child, donor, source, withState) {
3071
+ const found = donor.child;
3072
+ const tombstoned = found?.tombstone === void 0 ? await this.hasForkTombstone(tx, child) : found.tombstone !== null;
3073
+ if (tombstoned && !donor.ordered && this.dialect.lockClause("update") !== "") throw new ForkChildTombstoned();
3074
+ if (!await this.startNewSession(tx, child, {
3075
+ id: null,
3076
+ tombstone: tombstoned ? child : null
3077
+ }, "fork")) return donor;
3078
+ if (!donor.segments.some((segment) => segment.sourceId === child)) return donor;
3079
+ return this.sharedForkDonor(tx, child, source, this.sharedForkReads(child, source.sessionId, withState));
3080
+ }
2786
3081
  async createFork(header, entries, source) {
3082
+ return this.writing(header.id, this.writeCreateFork(header, entries, source));
3083
+ }
3084
+ async writeCreateFork(header, entries, source) {
2787
3085
  if (this.create !== SqlSessionStore.prototype.create) return void 0;
2788
3086
  if (!this.sharesTablesWith(source.store)) {
2789
3087
  if ("read" in entries) return entries.kind === "complete-session" ? this.createStagedFork(header, entries, source) : void 0;
@@ -2800,17 +3098,13 @@ var SqlSessionStore = class SqlSessionStore {
2800
3098
  validateSessionHeader(header);
2801
3099
  validateSessionEntries(entries);
2802
3100
  if (source.receipts.size === 0 && source.hashes.length === 0 && (!this.sharedHistorySeen || source.epoch === void 0)) return void 0;
2803
- for (let attempt = 0;; attempt++) {
2804
- const reads = this.sharedHistorySeen ? this.sharedForkReads(header.id, source.sessionId, false) : void 0;
3101
+ for (let attempt = 0, ordered = false;; attempt++) {
3102
+ const reads = this.sharedHistorySeen ? this.sharedForkReads(header.id, source.sessionId, false, ordered) : void 0;
2805
3103
  try {
2806
- return await this.transactionCheckedAlongside((tx, checked) => this.writeEntriesFork(tx, checked, header, entries, source, reads), this.sessionWrite(header.id, ...reads === void 0 ? [] : [
2807
- reads.exists,
2808
- reads.lock,
2809
- reads.tombstones,
2810
- reads.segments
2811
- ]));
3104
+ return await this.transactionCheckedAlongside((tx, checked) => this.writeEntriesFork(tx, checked, header, entries, source, reads), this.sessionWrite(header.id, ...reads === void 0 ? [] : sharedForkLeading(reads)));
2812
3105
  } catch (error) {
2813
- if (!(error instanceof ForkSourcesMoved) || attempt >= 3) throw error;
3106
+ if (error instanceof ForkChildTombstoned && !ordered) ordered = true;
3107
+ else if (!(error instanceof ForkSourcesMoved) || attempt >= 3) throw error;
2814
3108
  }
2815
3109
  }
2816
3110
  }
@@ -2850,6 +3144,7 @@ var SqlSessionStore = class SqlSessionStore {
2850
3144
  lastSeq: entries.length
2851
3145
  });
2852
3146
  await checked;
3147
+ if (shared !== void 0) shared = await this.startSharedFork(tx, header.id, shared, unchecked, false);
2853
3148
  const tables = await this.viewTables(tx);
2854
3149
  const writes = new SentWrites(tx);
2855
3150
  if (!sharing) {
@@ -3010,7 +3305,7 @@ var SqlSessionStore = class SqlSessionStore {
3010
3305
  */
3011
3306
  forkBlobCopy(source, child, hashes) {
3012
3307
  if (this.getBlob !== SqlSessionStore.prototype.getBlob || this.putBlob !== SqlSessionStore.prototype.putBlob) return void 0;
3013
- return forkBlobCopy(this.tables, {
3308
+ return forkBlobCopy(this.dialect, this.tables, {
3014
3309
  legacyBlobData: this.legacyBlobData,
3015
3310
  chunkBytes: SESSION_BLOB_CHUNK_BYTES
3016
3311
  }, source, child, [...new Set(hashes)]);
@@ -3042,6 +3337,9 @@ var SqlSessionStore = class SqlSessionStore {
3042
3337
  * `remainingBlobs` names the blobs left to copy with `copySessionBlobs`: those the source no longer holds.
3043
3338
  */
3044
3339
  async createStagedFork(header, stream, source) {
3340
+ return this.writing(header.id, this.writeCreateStagedFork(header, stream, source));
3341
+ }
3342
+ async writeCreateStagedFork(header, stream, source) {
3045
3343
  this.assertOpen();
3046
3344
  validateSessionHeader(header);
3047
3345
  const { createStagedFork } = await import("../core/storage/session/fork-staging.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
@@ -3080,8 +3378,14 @@ var SqlSessionStore = class SqlSessionStore {
3080
3378
  legacyBlobData: this.legacyBlobData,
3081
3379
  chunkBytes: SESSION_BLOB_CHUNK_BYTES
3082
3380
  },
3083
- materializedLinks: this.forkLinks().materialized,
3084
- transaction: (body) => this.transaction(body, SESSION_TRANSACTION)
3381
+ entryLinks: this.entryLinks(),
3382
+ transaction: (body) => this.transaction(body, SESSION_TRANSACTION),
3383
+ readTransaction: (body, leading, leadingOnly) => this.transaction(body, {
3384
+ ...SESSION_READ,
3385
+ ...leading === void 0 ? {} : { leading },
3386
+ ...leadingOnly === true ? { leadingOnly: true } : {}
3387
+ }),
3388
+ sessionTransaction: (sessionId, body, leading) => this.transaction(body, this.sessionWrite(sessionId, ...leading ?? []))
3085
3389
  });
3086
3390
  }
3087
3391
  /** The statements that link the entries a session with fork segments stores, as a copy links them (#6560). */
@@ -3095,6 +3399,13 @@ var SqlSessionStore = class SqlSessionStore {
3095
3399
  }, this.dialect);
3096
3400
  return this.forkLinkStatements;
3097
3401
  }
3402
+ /** How the snapshot index links a materialization's copies and a fork moved onto another copy (#6560). */
3403
+ entryLinks() {
3404
+ this.entryLinkStatements ??= entryLinkers.sessionEntryLinks?.(this.prefix, this.dialect, this.forkTables.forkSegments) ?? { async settle(tx, _sessionId, _fromSeq, before) {
3405
+ for (const { sql, params } of before) await tx.run(sql, ...params);
3406
+ } };
3407
+ return this.entryLinkStatements;
3408
+ }
3098
3409
  /**
3099
3410
  * @internal Gives every fork that shares history with `sessionId` its own copy of what it reads, so the session's
3100
3411
  * rows no longer stay for them; see fork-detach.ts. Detaches a crash stopped are finished first. Nothing to do where
@@ -3103,7 +3414,7 @@ var SqlSessionStore = class SqlSessionStore {
3103
3414
  async detachForks(sessionId, options = {}) {
3104
3415
  this.assertOpen();
3105
3416
  validateSessionText("sessionId", sessionId);
3106
- if (!await this.transaction((tx) => this.sharedHistoryForks(tx), SESSION_TRANSACTION)) return {
3417
+ if (!await this.transaction((tx) => this.sharedHistoryForks(tx), SESSION_READ_GATE)) return {
3107
3418
  detached: [],
3108
3419
  reparented: []
3109
3420
  };
@@ -3117,7 +3428,7 @@ var SqlSessionStore = class SqlSessionStore {
3117
3428
  /** @internal Finishes every detach a crash stopped. Nothing to do where shared-history forks are off. */
3118
3429
  async resumeForkDetaches() {
3119
3430
  this.assertOpen();
3120
- if (!await this.transaction((tx) => this.sharedHistoryForks(tx), SESSION_TRANSACTION)) return {
3431
+ if (!await this.transaction((tx) => this.sharedHistoryForks(tx), SESSION_READ_GATE)) return {
3121
3432
  detached: [],
3122
3433
  reparented: []
3123
3434
  };
@@ -3129,7 +3440,7 @@ var SqlSessionStore = class SqlSessionStore {
3129
3440
  */
3130
3441
  async sweepForkTombstones(sessionIds = [], batchEntries) {
3131
3442
  this.assertOpen();
3132
- if (!await this.transaction((tx) => this.sharedHistoryForks(tx), SESSION_TRANSACTION)) return [];
3443
+ if (!await this.transaction((tx) => this.sharedHistoryForks(tx), SESSION_READ_GATE)) return [];
3133
3444
  const { sweepForkTombstones } = await import("../core/storage/session/fork-sweep.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
3134
3445
  return sweepForkTombstones(this.forkHost(), sessionIds, batchEntries === void 0 ? {} : { batchEntries });
3135
3446
  }
@@ -3152,6 +3463,10 @@ var SqlSessionStore = class SqlSessionStore {
3152
3463
  lastSeq
3153
3464
  }, summary, index),
3154
3465
  create: (header, entries) => this.create(header, entries),
3466
+ newSessionRead: (id) => this.newSessionRead(id),
3467
+ startNewSession: async (tx, id, found) => {
3468
+ await this.startNewSession(tx, id, found, "fork");
3469
+ },
3155
3470
  sourceStoredEntryChunks: (source) => {
3156
3471
  const store = nativeForkReader(source, "entry");
3157
3472
  return store instanceof SqlSessionStore && store.readEntryChunk === SqlSessionStore.prototype.readEntryChunk ? (reference, index) => store.readStoredEntryChunk(reference, index) : void 0;
@@ -3181,7 +3496,7 @@ var SqlSessionStore = class SqlSessionStore {
3181
3496
  */
3182
3497
  async readStoredEntryChunk(reference, index) {
3183
3498
  this.assertOpen();
3184
- return this.readTransaction(async (tx) => {
3499
+ return this.readTransaction(reference.sessionId, async (tx) => {
3185
3500
  const { sessionId, epoch, seq } = reference;
3186
3501
  const head = await this.historyHead(tx, sessionId, true);
3187
3502
  if (head.epoch !== epoch) throw new SessionConflictError$1(sessionId, seq, head.lastSeq);
@@ -3197,7 +3512,7 @@ var SqlSessionStore = class SqlSessionStore {
3197
3512
  /** How many chunks the entry `reference` names is stored in, 0 when it is stored whole, in its generation. */
3198
3513
  async readStoredChunks(reference) {
3199
3514
  this.assertOpen();
3200
- return this.readTransaction(async (tx) => {
3515
+ return this.readTransaction(reference.sessionId, async (tx) => {
3201
3516
  const { sessionId, epoch, seq } = reference;
3202
3517
  const head = await this.historyHead(tx, sessionId, true);
3203
3518
  if (head.epoch !== epoch) throw new SessionConflictError$1(sessionId, seq, head.lastSeq);
@@ -3219,10 +3534,10 @@ var SqlSessionStore = class SqlSessionStore {
3219
3534
  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,
3220
3535
  CASE WHEN w.place = 0 THEN 1 ELSE 0 END AS own
3221
3536
  FROM ${this.blobPlaces(tables)} w JOIN ${this.tables.blobs} b
3222
- ON b.session_id = w.owner AND b.hash IN (${hashes.map(() => "?").join(", ")})
3537
+ ON b.session_id = w.owner AND ${inJsonList(this.dialect, "b.hash")}
3223
3538
  LEFT JOIN ${this.tables.blobChunks} c ON c.session_id = b.session_id AND c.hash = b.hash AND c.idx = 0
3224
3539
  ${tables.guard === void 0 ? "" : `WHERE ${tables.guard}`}
3225
- ORDER BY own DESC, b.session_id`, maxBytes, ...this.blobPlaceParams(tables, sessionId), ...hashes), (found) => found.length > 0);
3540
+ ORDER BY own DESC, b.session_id`, maxBytes, ...this.blobPlaceParams(tables, sessionId), JSON.stringify(hashes)), (found) => found.length > 0);
3226
3541
  for (const row of rows) if (!parts.has(String(row.hash))) parts.set(String(row.hash), {
3227
3542
  bytes: Number(row.bytes),
3228
3543
  chunks: Number(row.chunks),
@@ -3260,25 +3575,24 @@ var SqlSessionStore = class SqlSessionStore {
3260
3575
  async createStreamedFork(header, stream, source) {
3261
3576
  this.assertOpen();
3262
3577
  validateSessionHeader(header);
3263
- for (let attempt = 0;; attempt++) {
3264
- const reads = this.sharedHistorySeen ? this.sharedForkReads(header.id, source.sessionId, stream.prefix !== void 0) : void 0;
3578
+ for (let attempt = 0, ordered = false;; attempt++) {
3579
+ const reads = this.sharedHistorySeen ? this.sharedForkReads(header.id, source.sessionId, stream.prefix !== void 0, ordered) : void 0;
3265
3580
  try {
3266
- return await this.transactionCheckedAlongside((tx, checked) => this.writeStreamedFork(tx, checked, header, stream, source, reads), this.sessionWrite(header.id, ...reads === void 0 ? [] : [
3267
- reads.exists,
3268
- reads.lock,
3269
- reads.tombstones,
3270
- reads.segments
3271
- ]));
3581
+ return await this.transactionCheckedAlongside((tx, checked) => this.writeStreamedFork(tx, checked, header, stream, source, reads), this.sessionWrite(header.id, ...reads === void 0 ? [] : sharedForkLeading(reads)));
3272
3582
  } catch (error) {
3273
- if (!(error instanceof ForkSourcesMoved) || attempt >= 3) throw error;
3583
+ if (error instanceof ForkChildTombstoned && !ordered) ordered = true;
3584
+ else if (!(error instanceof ForkSourcesMoved) || attempt >= 3) throw error;
3274
3585
  }
3275
3586
  }
3276
3587
  }
3277
3588
  async writeStreamedFork(tx, checked, header, stream, source, reads) {
3278
3589
  const sharedRead = this.leadingForkDonor(tx, header.id, source, reads);
3279
- const shared = await this.sharedHistoryForks(tx) ? await (sharedRead ?? this.sharedForkDonor(tx, header.id, source, this.sharedForkReads(header.id, source.sessionId, stream.prefix !== void 0))) : void 0;
3280
- const head = shared ?? await this.forkDonor(tx, header.id, source);
3590
+ const withState = stream.prefix !== void 0;
3591
+ let shared = await this.sharedHistoryForks(tx) ? await (sharedRead ?? this.sharedForkDonor(tx, header.id, source, this.sharedForkReads(header.id, source.sessionId, withState))) : void 0;
3592
+ const read = shared ?? await this.forkDonor(tx, header.id, source);
3281
3593
  await checked;
3594
+ if (shared !== void 0) shared = await this.startSharedFork(tx, header.id, shared, source, withState);
3595
+ const head = shared ?? read;
3282
3596
  const { encodedForkRow } = await import("../core/storage/session/fork-row-bytes.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
3283
3597
  const { foldForkRow } = await import("../core/storage/session/fork-row-index.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
3284
3598
  const prefix = stream.prefix;
@@ -3466,37 +3780,38 @@ var SqlSessionStore = class SqlSessionStore {
3466
3780
  }
3467
3781
  /**
3468
3782
  * The reads that begin a fork of session `donor` into `child` with shared history (#6560), in order: whether the child
3469
- * exists; the rows of the donor and of the sessions its segments name, as the statement starts or as this store last
3470
- * saw them, each locked `key-share` in id order, unless the child exists, with the donor's watermark and generation,
3471
- * and with `withState` its summary state; then the donor's segments, read once those locks are held.
3783
+ * exists; the tombstones of the deleted sessions among the donor's sources, locked `key-share`; the rows of the donor
3784
+ * and of the sessions its segments name, as the statement starts or as this store last saw them, each locked
3785
+ * `key-share` in id order, unless the child exists, with the donor's watermark and generation, and with `withState`
3786
+ * its summary state; then the donor's segments, read once those locks are held.
3472
3787
  */
3473
- sharedForkReads(child, donor, withState) {
3788
+ sharedForkReads(child, donor, withState, ordered = false) {
3474
3789
  const ids = [.../* @__PURE__ */ new Set([donor, ...this.forkSources.get(donor) ?? []])].sort();
3790
+ const tombstoneIds = ordered ? [.../* @__PURE__ */ new Set([...ids, child])].sort() : ids;
3475
3791
  const epoch = `COALESCE(${this.dialect.jsonText("summary_state", "epoch")}, ${this.dialect.jsonText("summary_state", "resume", "epoch")}, revision)`;
3792
+ const readers = ordered ? ` OR id IN (SELECT session_id FROM ${this.forkTables.forkSegments} WHERE source_id = ?)` : "";
3476
3793
  return {
3477
- ids,
3478
- exists: {
3479
- sql: `SELECT id FROM ${this.tables.sessions} WHERE id = ?`,
3480
- params: [child]
3481
- },
3794
+ exists: this.newSessionRead(child),
3795
+ ordered,
3482
3796
  lock: {
3483
3797
  sql: `SELECT id, last_seq, CASE WHEN id = ? THEN ${epoch} END AS epoch${withState ? ", CASE WHEN id = ? THEN summary_state END AS summary_state" : ""}
3484
- FROM ${this.tables.sessions} WHERE (id IN (${ids.map(() => "?").join(", ")})
3485
- OR id IN (SELECT source_id FROM ${this.forkTables.forkSegments} WHERE session_id = ?))
3486
- AND NOT EXISTS (SELECT 1 FROM ${this.tables.sessions} c WHERE c.id = ?) ORDER BY id${this.dialect.lockClause("key-share")}`,
3798
+ FROM ${this.tables.sessions} WHERE (${inJsonList(this.dialect, "id")}
3799
+ OR id IN (SELECT source_id FROM ${this.forkTables.forkSegments} WHERE session_id = ?)${readers})
3800
+ AND NOT EXISTS (SELECT 1 FROM ${this.tables.sessions} c WHERE c.id = ?) ORDER BY id${this.dialect.lockClause(ordered ? "update" : "key-share")}`,
3487
3801
  params: [
3488
3802
  donor,
3489
3803
  ...withState ? [donor] : [],
3490
- ...ids,
3804
+ JSON.stringify(ids),
3491
3805
  donor,
3806
+ ...ordered ? [child] : [],
3492
3807
  child
3493
3808
  ]
3494
3809
  },
3495
3810
  tombstones: {
3496
- sql: `SELECT session_id FROM ${this.forkTables.forkTombstones} WHERE session_id IN (${ids.map(() => "?").join(", ")})
3811
+ sql: `SELECT session_id FROM ${this.forkTables.forkTombstones} WHERE ${inJsonList(this.dialect, "session_id")}
3497
3812
  OR session_id IN (SELECT source_id FROM ${this.forkTables.forkSegments} WHERE session_id = ?)
3498
- ORDER BY session_id${this.dialect.lockClause("key-share")}`,
3499
- params: [...ids, donor]
3813
+ ORDER BY session_id${this.dialect.lockClause(ordered ? "update" : "key-share")}`,
3814
+ params: [JSON.stringify(tombstoneIds), donor]
3500
3815
  },
3501
3816
  segments: {
3502
3817
  sql: `SELECT source_id, from_seq, to_seq, base_seq FROM ${this.forkTables.forkSegments} WHERE session_id = ? ORDER BY idx`,
@@ -3512,20 +3827,21 @@ var SqlSessionStore = class SqlSessionStore {
3512
3827
  async sharedForkDonor(tx, child, source, reads) {
3513
3828
  const settle = (read) => read.then((value) => ({ value }), (error) => ({ error }));
3514
3829
  const existing = settle(tx.get(reads.exists.sql, ...reads.exists.params));
3515
- const locked = settle(tx.all(reads.lock.sql, ...reads.lock.params));
3516
3830
  const tombstones = settle(tx.all(reads.tombstones.sql, ...reads.tombstones.params));
3831
+ const locked = settle(tx.all(reads.lock.sql, ...reads.lock.params));
3517
3832
  const segmentRows = settle(tx.all(reads.segments.sql, ...reads.segments.params));
3518
3833
  for (const read of [
3519
3834
  existing,
3520
- locked,
3521
3835
  tombstones,
3836
+ locked,
3522
3837
  segmentRows
3523
3838
  ]) {
3524
3839
  const answer = await read;
3525
3840
  if ("error" in answer) throw answer.error;
3526
3841
  }
3527
3842
  const answer = (read) => read.value;
3528
- if (answer(await existing)) throw new SessionExistsError$1(child);
3843
+ const found = answer(await existing);
3844
+ if (found?.id != null) throw new SessionExistsError$1(child);
3529
3845
  const row = answer(await locked).find((candidate) => String(candidate.id) === source.sessionId);
3530
3846
  if (row === void 0) throw new SessionNotFoundError$1(source.sessionId);
3531
3847
  const segments = answer(await segmentRows).map((segment) => ({
@@ -3536,11 +3852,7 @@ var SqlSessionStore = class SqlSessionStore {
3536
3852
  }));
3537
3853
  const sources = [...new Set(segments.map((segment) => segment.sourceId))].sort();
3538
3854
  this.noteForkSources(source.sessionId, sources);
3539
- const lockedIds = /* @__PURE__ */ new Set([
3540
- ...reads.ids,
3541
- ...answer(await locked).map((candidate) => String(candidate.id)),
3542
- ...answer(await tombstones).map((candidate) => String(candidate.session_id))
3543
- ]);
3855
+ const lockedIds = /* @__PURE__ */ new Set([...answer(await locked).map((candidate) => String(candidate.id)), ...answer(await tombstones).map((candidate) => String(candidate.session_id))]);
3544
3856
  if (sources.some((id) => !lockedIds.has(id))) throw new ForkSourcesMoved();
3545
3857
  const lastSeq = Number(row.last_seq);
3546
3858
  const epoch = String(row.epoch);
@@ -3549,6 +3861,8 @@ var SqlSessionStore = class SqlSessionStore {
3549
3861
  lastSeq,
3550
3862
  epoch,
3551
3863
  segments,
3864
+ child: found,
3865
+ ordered: reads.ordered,
3552
3866
  ...typeof row.summary_state === "string" ? { state: JSON.parse(row.summary_state) } : {}
3553
3867
  };
3554
3868
  }
@@ -3632,6 +3946,9 @@ var SqlSessionStore = class SqlSessionStore {
3632
3946
  } : original], seq, texts, false);
3633
3947
  }
3634
3948
  async append(sessionId, entries, options) {
3949
+ return this.writing(sessionId, this.writeAppend(sessionId, entries, options));
3950
+ }
3951
+ async writeAppend(sessionId, entries, options) {
3635
3952
  this.assertOpen();
3636
3953
  validateSessionText("sessionId", sessionId);
3637
3954
  const fast = await this.appendThroughFunction(sessionId, entries, options);
@@ -3873,44 +4190,59 @@ $grant$`);
3873
4190
  });
3874
4191
  }
3875
4192
  async replace(sessionId, header, entries, options) {
4193
+ return this.writing(sessionId, this.writeReplace(sessionId, header, entries, options));
4194
+ }
4195
+ async writeReplace(sessionId, header, entries, options) {
3876
4196
  this.assertOpen();
3877
4197
  validateSessionText("sessionId", sessionId);
3878
4198
  this.writtenRows.delete(sessionId);
3879
4199
  let released = [];
3880
4200
  let entriesWritten = [];
3881
- const pinReads = this.sharedHistorySeen ? forkPinReads(this.forkHost(), this.tables.sessions, sessionId) : void 0;
3882
- const written = await this.transactionCheckedAlongside(async (tx, checked) => {
4201
+ const pinReads = this.sharedHistorySeen ? forkPinReads(this.forkHost(), this.tables.sessions, sessionId, true) : void 0;
4202
+ const searchLock = this.searchIndex?.writeLock(sessionId);
4203
+ const run = (lockLate) => this.transactionCheckedAlongside(async (tx, checked) => {
3883
4204
  released = [];
3884
4205
  entriesWritten = [];
3885
- const [, pins] = await Promise.all([this.forWrite(tx, sessionId, options), this.readForkPinsWithin(tx, sessionId, pinReads)]);
4206
+ const [, , pins] = await Promise.all([
4207
+ searchLock === void 0 ? void 0 : tx.get(searchLock.sql, ...searchLock.params),
4208
+ this.forWrite(tx, sessionId, options),
4209
+ this.readForkPinsWithin(tx, sessionId, pinReads, true)
4210
+ ]);
3886
4211
  await checked;
3887
4212
  validateSessionHeader(header);
3888
4213
  validateSessionEntries(entries);
3889
4214
  if (header.id !== sessionId) throw new SessionIdMismatchError$1(sessionId, header.id);
3890
- if (pins !== void 0) released = await replaceForkedSessionWithin(this.forkHost(), tx, sessionId, pins).catch((error) => {
4215
+ if (pins !== void 0) released = await replaceForkedSessionWithin(this.forkHost(), tx, sessionId, pins, lockLate).catch((error) => {
3891
4216
  noteForkCopyRefusal(error, "replace");
3892
4217
  throw error;
3893
4218
  });
3894
4219
  await this.searchIndex?.forgetWithin(tx, sessionId);
3895
- await tx.run(`DELETE FROM ${this.tables.searchTexts} WHERE session_id = ?`, sessionId);
3896
- await tx.run(`DELETE FROM ${this.tables.entryChunks} WHERE session_id = ?`, sessionId);
3897
- await tx.run(`DELETE FROM ${this.tables.entries} WHERE session_id = ?`, sessionId);
3898
- const { texts, epoch } = await this.saveSummary(tx, sessionId, {
4220
+ const summary = this.summaryWrite(sessionId, {
3899
4221
  header,
3900
4222
  entries,
3901
4223
  lastSeq: entries.length
3902
4224
  });
3903
- await this.insertEntries(tx, sessionId, entries, 0, texts, true, entriesWritten);
4225
+ await this.writeEntries(tx, summary.statement, withRest(this.sessionRowDeletes(sessionId), this.entryWrites(sessionId, entries, 0, summary.texts, true, entriesWritten)));
3904
4226
  return {
3905
4227
  lastSeq: entries.length,
3906
- epoch
4228
+ epoch: summary.epoch
3907
4229
  };
3908
- }, this.sessionWrite(sessionId, ...pinReads === void 0 ? [] : [this.headRead(sessionId, options, false), ...pinReads]));
4230
+ }, this.sessionWrite(sessionId, ...searchLock === void 0 ? [] : [searchLock], ...pinReads === void 0 ? [] : [this.headRead(sessionId, options, false), ...pinReads]));
4231
+ let written;
4232
+ for (let attempt = 0;; attempt++) try {
4233
+ written = await run(attempt >= 3);
4234
+ break;
4235
+ } catch (error) {
4236
+ if (!(error instanceof ForkReadersMoved)) throw error;
4237
+ }
3909
4238
  this.noteWritten(sessionId, written.epoch, entriesWritten);
3910
4239
  await this.sweepReleasedForkRows(released);
3911
4240
  return written;
3912
4241
  }
3913
4242
  async updateHeader(header, options) {
4243
+ return this.writing(header.id, this.writeUpdateHeader(header, options));
4244
+ }
4245
+ async writeUpdateHeader(header, options) {
3914
4246
  this.assertOpen();
3915
4247
  validateSessionHeader(header);
3916
4248
  this.writtenRows.delete(header.id);
@@ -3943,7 +4275,18 @@ $grant$`);
3943
4275
  const row = await this.database.get(`SELECT last_seq FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
3944
4276
  if (row) announceHistoryLoad(row.last_seq);
3945
4277
  }
3946
- return this.readTransaction((tx) => this.read(tx, sessionId));
4278
+ let generation = this.generation(sessionId);
4279
+ let guessedPlain = false;
4280
+ return this.readTransaction(sessionId, (tx) => this.read(tx, sessionId, generation, guessedPlain), () => {
4281
+ generation = this.generation(sessionId);
4282
+ const segments = this.sharedHistorySeen ? this.forkTables.forkSegments : void 0;
4283
+ guessedPlain = segments !== void 0 && this.forkedSessions.get(sessionId) === false;
4284
+ const pageTables = {
4285
+ segments: guessedPlain ? void 0 : segments,
4286
+ dialect: this.dialect
4287
+ };
4288
+ return [this.loadHeadStatement(sessionId, generation, segments), this.readRowsPageStatement(pageTables, sessionId, 0, FORK_VIEW_END, SESSION_READ_FETCH.first)];
4289
+ });
3947
4290
  }
3948
4291
  async readEntryRange(sessionId, query) {
3949
4292
  this.assertOpen();
@@ -4053,44 +4396,50 @@ $grant$`);
4053
4396
  return row ? JSON.parse(row.header_json) : void 0;
4054
4397
  }
4055
4398
  async delete(sessionId) {
4399
+ return this.writing(sessionId, this.writeDelete(sessionId));
4400
+ }
4401
+ async writeDelete(sessionId) {
4056
4402
  this.assertOpen();
4057
4403
  validateSessionText("sessionId", sessionId);
4058
4404
  this.writtenRows.delete(sessionId);
4059
4405
  let released = [];
4060
4406
  const pinReads = this.sharedHistorySeen ? forkPinReads(this.forkHost(), this.tables.sessions, sessionId) : void 0;
4407
+ const updateLock = this.dialect.lockClause("update");
4408
+ const sessionLock = pinReads === void 0 && updateLock !== "" ? {
4409
+ sql: `SELECT id FROM ${this.tables.sessions} WHERE id = ?${updateLock}`,
4410
+ params: [sessionId]
4411
+ } : void 0;
4412
+ const searchLock = this.searchIndex?.writeLock(sessionId);
4061
4413
  await this.transactionCheckedAlongside(async (tx, checked) => {
4062
4414
  released = [];
4063
- const pins = await this.readForkPinsWithin(tx, sessionId, pinReads);
4415
+ const [, , leadingPins] = await Promise.all([
4416
+ searchLock === void 0 ? void 0 : tx.get(searchLock.sql, ...searchLock.params),
4417
+ sessionLock === void 0 ? void 0 : tx.get(sessionLock.sql, ...sessionLock.params),
4418
+ pinReads === void 0 ? void 0 : this.readForkPinsWithin(tx, sessionId, pinReads)
4419
+ ]);
4420
+ const pins = pinReads === void 0 ? await this.readForkPinsWithin(tx, sessionId, void 0) : leadingPins;
4064
4421
  await checked;
4065
4422
  await this.searchIndex?.forgetWithin(tx, sessionId);
4066
4423
  if (pins !== void 0) {
4067
4424
  const pinned = await deleteForkedSessionWithin(this.forkHost(), tx, sessionId, (/* @__PURE__ */ new Date()).toISOString(), pins);
4068
4425
  released = pinned.released;
4069
4426
  if (pinned.keepRows) {
4070
- await tx.run(`DELETE FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
4427
+ await this.finishWrites(tx, [this.sessionRowDelete(sessionId)]);
4071
4428
  return;
4072
4429
  }
4073
4430
  }
4074
- await tx.run(`DELETE FROM ${this.tables.blobChunks} WHERE session_id = ?`, sessionId);
4075
- await tx.run(`DELETE FROM ${this.tables.blobs} WHERE session_id = ?`, sessionId);
4076
- await tx.run(`DELETE FROM ${this.tables.searchTexts} WHERE session_id = ?`, sessionId);
4077
- await tx.run(`DELETE FROM ${this.tables.entryChunks} WHERE session_id = ?`, sessionId);
4078
- await tx.run(`DELETE FROM ${this.tables.entries} WHERE session_id = ?`, sessionId);
4079
- await tx.run(`DELETE FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
4080
- }, pinReads === void 0 ? SESSION_TRANSACTION : {
4081
- ...SESSION_TRANSACTION,
4082
- leading: pinReads
4083
- });
4431
+ await this.finishWrites(tx, [...this.sessionRowDeletes(sessionId, [this.tables.blobChunks, this.tables.blobs]), this.sessionRowDelete(sessionId)]);
4432
+ }, this.sessionWrite(sessionId, ...searchLock === void 0 ? [] : [searchLock], ...sessionLock === void 0 ? [] : [sessionLock], ...pinReads ?? []));
4084
4433
  await this.sweepReleasedForkRows(released);
4085
4434
  }
4086
4435
  /**
4087
4436
  * The fork history of `sessionId` where the transaction `tx` runs on shared history: through `reads`, the transaction's
4088
4437
  * leading reads, or, for a store that had not seen shared history when the transaction began, read now.
4089
4438
  */
4090
- async readForkPinsWithin(tx, sessionId, reads) {
4439
+ async readForkPinsWithin(tx, sessionId, reads, readers = false) {
4091
4440
  if (reads !== void 0) return readForkPins(tx, reads);
4092
4441
  if (!await this.sharedHistoryForks(tx)) return void 0;
4093
- return readForkPins(tx, forkPinReads(this.forkHost(), this.tables.sessions, sessionId));
4442
+ return readForkPins(tx, forkPinReads(this.forkHost(), this.tables.sessions, sessionId, readers));
4094
4443
  }
4095
4444
  /**
4096
4445
  * Removes the rows of deleted sessions no fork reads any more, among `released` and any an earlier sweep left, in
@@ -4250,8 +4599,13 @@ $grant$`);
4250
4599
  /** Revalidates one scope's cache and resolves its summaries; called for one listing at a time. */
4251
4600
  async listScope(query) {
4252
4601
  this.assertListing(query);
4253
- await this.assertReadableSchema(this.database);
4254
- const token = await this.changeToken();
4602
+ let token;
4603
+ let checkSchema = true;
4604
+ if (this.database.descriptor.adapter === "node-sqlite") {
4605
+ await this.assertReadableSchema(this.database);
4606
+ checkSchema = false;
4607
+ token = await this.changeToken();
4608
+ }
4255
4609
  const key = JSON.stringify([
4256
4610
  query.includeInternal === true,
4257
4611
  query.cwd ?? null,
@@ -4260,7 +4614,7 @@ $grant$`);
4260
4614
  const cached = this.scopes.get(key);
4261
4615
  const scope = token !== void 0 && cached?.token === token && cached.ids.every((id) => this.summaries.has(id)) ? cached : {
4262
4616
  token,
4263
- ids: await this.readScope(query, cached !== void 0)
4617
+ ids: await this.readScope(query, cached !== void 0, checkSchema)
4264
4618
  };
4265
4619
  this.scopes.delete(key);
4266
4620
  this.scopes.set(key, scope);
@@ -4303,11 +4657,15 @@ $grant$`);
4303
4657
  return JSON.stringify(Object.values(row ?? {}).map(String));
4304
4658
  }
4305
4659
  async *listWithoutSearchText(query) {
4306
- await this.assertReadableSchema(this.database);
4307
- const scope = await this.scopeOf(query, true);
4660
+ const checkInBound = query.cwd === void 0;
4661
+ const scope = await this.scopeOf(query, true, !checkInBound);
4308
4662
  if (scope === void 0) return;
4309
4663
  const order = this.dialect.rowOrder();
4310
- const bound = await this.database.get(`SELECT max(${order}) AS upper FROM ${this.tables.sessions}`);
4664
+ const boundStatement = {
4665
+ sql: `SELECT max(${order}) AS upper FROM ${this.tables.sessions}`,
4666
+ params: []
4667
+ };
4668
+ const bound = checkInBound ? await this.readChecked(boundStatement, (tx) => tx.get(boundStatement.sql, ...boundStatement.params)) : await this.database.get(boundStatement.sql, ...boundStatement.params);
4311
4669
  const upper = Number(bound?.upper ?? 0);
4312
4670
  const seen = /* @__PURE__ */ new Set();
4313
4671
  const scanRows = this.listingScanRows(SESSION_READ_FETCH.max);
@@ -4357,14 +4715,24 @@ $grant$`);
4357
4715
  }
4358
4716
  this.assertListing(query);
4359
4717
  }
4360
- async distinctCwds(paced, query) {
4361
- if (!paced) return (await this.database.all(`SELECT DISTINCT cwd FROM ${this.tables.sessions}`)).map((project) => project.cwd);
4718
+ async distinctCwds(paced, query, checkSchema) {
4719
+ if (!paced) {
4720
+ const statement = {
4721
+ sql: `SELECT DISTINCT cwd FROM ${this.tables.sessions}`,
4722
+ params: []
4723
+ };
4724
+ return (checkSchema ? await this.readChecked(statement, (tx) => tx.all(statement.sql, ...statement.params)) : await this.database.all(statement.sql, ...statement.params)).map((project) => project.cwd);
4725
+ }
4362
4726
  const order = this.dialect.rowOrder();
4363
4727
  const page = this.listingScanRows(LISTING_CWD_PAGE);
4364
4728
  const cwds = /* @__PURE__ */ new Set();
4365
- for (let after = 0;;) {
4729
+ for (let after = 0, first = true;; first = false) {
4366
4730
  this.assertListing(query);
4367
- const rows = await this.database.all(`SELECT ${order} AS ord, cwd FROM ${this.tables.sessions} WHERE ${order} > ? ORDER BY ${order} LIMIT ?`, after, page);
4731
+ const statement = {
4732
+ sql: `SELECT ${order} AS ord, cwd FROM ${this.tables.sessions} WHERE ${order} > ? ORDER BY ${order} LIMIT ?`,
4733
+ params: [after, page]
4734
+ };
4735
+ const rows = first && checkSchema ? await this.readChecked(statement, (tx) => tx.all(statement.sql, ...statement.params)) : await this.database.all(statement.sql, ...statement.params);
4368
4736
  for (const row of rows) cwds.add(row.cwd);
4369
4737
  await yieldTurn();
4370
4738
  if (rows.length < page) return [...cwds];
@@ -4375,11 +4743,11 @@ $grant$`);
4375
4743
  listingScanRows(overServer) {
4376
4744
  return this.database.descriptor.adapter === "node-sqlite" ? LISTING_SCAN_ROWS : overServer;
4377
4745
  }
4378
- async scopeOf(query, paced) {
4746
+ async scopeOf(query, paced, checkSchema = false) {
4379
4747
  const matchesCwd = query.cwd === void 0 ? void 0 : this.cwdMatcher?.(query.cwd) ?? ((candidate) => candidate === query.cwd);
4380
4748
  let projectCwds;
4381
4749
  if (matchesCwd) {
4382
- const distinct = await this.distinctCwds(paced, query);
4750
+ const distinct = await this.distinctCwds(paced, query, checkSchema);
4383
4751
  const slice = paced ? LISTING_CWD_MATCHES : Math.max(1, distinct.length);
4384
4752
  projectCwds = [];
4385
4753
  for (let start = 0; start < distinct.length; start += slice) {
@@ -4395,38 +4763,39 @@ $grant$`);
4395
4763
  }
4396
4764
  const idPrefix = query.idPrefix?.toLowerCase();
4397
4765
  return {
4398
- where: `(? = 1 OR internal = 0)${projectCwds ? ` AND cwd IN (${projectCwds.map(() => "?").join(", ")})` : ""}${idPrefix === void 0 ? "" : " AND substr(lower(id), 1, ?) = ?"}`,
4766
+ where: `(? = 1 OR internal = 0)${projectCwds ? ` AND ${inJsonList(this.dialect, "cwd")}` : ""}${idPrefix === void 0 ? "" : " AND substr(lower(id), 1, ?) = ?"}`,
4399
4767
  params: [
4400
4768
  query.includeInternal ? 1 : 0,
4401
- ...projectCwds ?? [],
4769
+ ...projectCwds ? [JSON.stringify(projectCwds)] : [],
4402
4770
  ...idPrefix === void 0 ? [] : [idPrefix.length, idPrefix]
4403
4771
  ],
4404
4772
  inScope: (row) => !matchesCwd || matchesCwd(row.cwd)
4405
4773
  };
4406
4774
  }
4407
4775
  /** The scope's session ids in store order, with a current summary cached for each. */
4408
- async readScope(query, listedBefore) {
4409
- const resolved = await this.scopeOf(query, false);
4776
+ async readScope(query, listedBefore, checkSchema = false) {
4777
+ const resolved = await this.scopeOf(query, false, checkSchema);
4410
4778
  if (resolved === void 0) return [];
4779
+ const checkOnPage = checkSchema && query.cwd === void 0;
4411
4780
  const { where: scope, params, inScope } = resolved;
4412
4781
  const filterInScope = async (rows) => {
4413
4782
  return (await Promise.all(rows.map(async (row) => await inScope(row) ? row : void 0))).filter((row) => row !== void 0);
4414
4783
  };
4415
4784
  if (listedBefore) {
4416
- const rows = await filterInScope(await this.readListingRows(scope, params));
4785
+ const rows = await filterInScope(await this.readListingRows(scope, params, checkOnPage));
4417
4786
  this.assertListing(query);
4418
4787
  const stale = rows.filter((row) => this.summaries.get(row.id)?.version !== listingVersion(row));
4419
4788
  if (stale.length <= rows.length / 4) {
4420
4789
  for (let start = 0; start < stale.length; start += 500) {
4421
4790
  const ids = stale.slice(start, start + 500).map((row) => row.id);
4422
- const fetched = new Set((await this.readSummaries(`id IN (${ids.map(() => "?").join(", ")})`, ids)).map((row) => row.id));
4791
+ const fetched = new Set((await this.readSummaries(inJsonList(this.dialect, "id"), [JSON.stringify(ids)])).map((row) => row.id));
4423
4792
  for (const id of ids) if (!fetched.has(id)) this.summaries.delete(id);
4424
4793
  this.assertListing(query);
4425
4794
  }
4426
4795
  return rows.flatMap((row) => this.summaries.has(row.id) ? [row.id] : []);
4427
4796
  }
4428
4797
  }
4429
- const rows = await filterInScope(await this.readSummaries(scope, params));
4798
+ const rows = await filterInScope(await this.readSummaries(scope, params, checkOnPage && !listedBefore));
4430
4799
  this.assertListing(query);
4431
4800
  return rows.map((row) => row.id);
4432
4801
  }
@@ -4436,11 +4805,12 @@ $grant$`);
4436
4805
  * {@link SESSION_READ_PAGE_CHARS}, the first always, so that no response passes a libSQL server's limit however many
4437
4806
  * sessions there are (#4954) and no statement reads more than its batch.
4438
4807
  */
4439
- async readListingRows(where, params) {
4808
+ async readListingRows(where, params, checkSchema = false) {
4440
4809
  const order = this.dialect.rowOrder();
4441
4810
  const rows = [];
4442
- for (let after = 0, limit = SESSION_READ_FETCH.first;;) {
4443
- const page = await this.database.all(`WITH sized AS MATERIALIZED (
4811
+ for (let after = 0, limit = SESSION_READ_FETCH.first, check = checkSchema;; check = false) {
4812
+ const statement = {
4813
+ sql: `WITH sized AS MATERIALIZED (
4444
4814
  SELECT ${LISTING_COLUMNS}, ${order} AS ord, ${LISTING_SIZE} AS size
4445
4815
  FROM ${this.tables.sessions} WHERE (${where}) AND ${order} > ? ORDER BY ord LIMIT ?
4446
4816
  ) SELECT ${LISTING_COLUMNS}, ord, fetched, batch_chars, page_chars FROM (
@@ -4449,7 +4819,16 @@ $grant$`);
4449
4819
  sum(size) OVER () AS batch_chars,
4450
4820
  sum(size) OVER (ORDER BY ord) AS page_chars
4451
4821
  FROM sized
4452
- ) AS page WHERE (page_chars <= ? OR page_row = 1) AND page_row <= ? ORDER BY ord`, ...params, after, limit + 1, SESSION_READ_PAGE_CHARS, limit);
4822
+ ) AS page WHERE (page_chars <= ? OR page_row = 1) AND page_row <= ? ORDER BY ord`,
4823
+ params: [
4824
+ ...params,
4825
+ after,
4826
+ limit + 1,
4827
+ SESSION_READ_PAGE_CHARS,
4828
+ limit
4829
+ ]
4830
+ };
4831
+ const page = check ? await this.readChecked(statement, (tx) => tx.all(statement.sql, ...statement.params)) : await this.database.all(statement.sql, ...statement.params);
4453
4832
  rows.push(...page);
4454
4833
  const next = nextFetch(limit, page);
4455
4834
  if (!next.more) return rows;
@@ -4462,10 +4841,10 @@ $grant$`);
4462
4841
  * {@link readListingRows} reads, search text counted. A session whose search text alone is longer than a page has
4463
4842
  * it read in pages of its own and joined here rather than by the database, whose string limit it may pass (#4954).
4464
4843
  */
4465
- async readSummaries(where, params) {
4844
+ async readSummaries(where, params, checkSchema = false) {
4466
4845
  const order = this.dialect.rowOrder();
4467
4846
  const rows = [];
4468
- for (let after = 0, limit = SESSION_READ_FETCH.first;;) {
4847
+ for (let after = 0, limit = SESSION_READ_FETCH.first, check = checkSchema;;) {
4469
4848
  const seen = this.sharedHistorySeen;
4470
4849
  const texts = (session) => forkViewOf({
4471
4850
  segments: seen ? this.forkTables.forkSegments : void 0,
@@ -4474,7 +4853,8 @@ $grant$`);
4474
4853
  table: this.tables.searchTexts,
4475
4854
  columns: ["text_json"]
4476
4855
  }, session);
4477
- const page = await this.database.all(`WITH keyed AS MATERIALIZED (
4856
+ const statement = {
4857
+ sql: `WITH keyed AS MATERIALIZED (
4478
4858
  SELECT ${LISTING_COLUMNS}, ${order} AS ord, ${LISTING_SIZE} AS size
4479
4859
  FROM ${this.tables.sessions} AS s WHERE (${where}) AND ${order} > ? ORDER BY ord LIMIT ?
4480
4860
  ), sized AS MATERIALIZED (
@@ -4491,7 +4871,18 @@ $grant$`);
4491
4871
  sum(size + search_size) OVER () AS batch_chars,
4492
4872
  sum(size + search_size) OVER (ORDER BY ord) AS page_chars
4493
4873
  FROM sized
4494
- ) 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);
4874
+ ) AS page WHERE (page_chars <= ? OR page_row = 1) AND page_row <= ? ORDER BY ord`,
4875
+ params: [
4876
+ ...params,
4877
+ after,
4878
+ limit + 1,
4879
+ SESSION_READ_PAGE_CHARS,
4880
+ SESSION_READ_PAGE_CHARS,
4881
+ limit
4882
+ ]
4883
+ };
4884
+ const page = check ? await this.readChecked(statement, (tx) => tx.all(statement.sql, ...statement.params)) : await this.database.all(statement.sql, ...statement.params);
4885
+ check = false;
4495
4886
  for (const row of page) {
4496
4887
  assertStorageSchemaVersion("sessions", row.schema_version, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
4497
4888
  this.noteSchemaVersion(row.schema_version);
@@ -4558,19 +4949,65 @@ $grant$`);
4558
4949
  this.assertOpen();
4559
4950
  query.signal?.throwIfAborted();
4560
4951
  }
4561
- async read(tx, sessionId) {
4562
- const generation = this.generation(sessionId);
4952
+ /** The session-row read that `read` makes first, shared with `load`'s leading statements. */
4953
+ loadHeadStatement(sessionId, generation, segments) {
4954
+ return {
4955
+ sql: `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(segments)} FROM ${this.tables.sessions} WHERE id = ?`,
4956
+ params: [...generation.params, sessionId]
4957
+ };
4958
+ }
4959
+ /** One page read of `readRows`, shared with `load`'s leading statements. */
4960
+ readRowsPageStatement(tables, sessionId, after, through, limit, seqs) {
4961
+ const filter = seqs === void 0 ? "" : ` AND ${inJsonList(this.dialect, "seq", true)}`;
4962
+ const view = this.entriesView(tables, sessionId, after, tables.segments === void 0 || seqs !== void 0 ? through : Math.min(through, after + limit + 1));
4963
+ return {
4964
+ sql: withForkViews([view], `WITH sized AS MATERIALIZED (
4965
+ SELECT seq, chunks, src_id, src_seq, length(entry_json) AS size,
4966
+ CASE WHEN ${this.dialect.textByteLength("entry_json")} <= ? THEN entry_json END AS inline_json
4967
+ FROM ${view.name} WHERE seq > ?${filter} ORDER BY seq LIMIT ?
4968
+ ), batch AS MATERIALIZED (
4969
+ SELECT count(*) AS fetched, COALESCE(sum(size), 0) AS chars FROM sized
4970
+ ), page AS (
4971
+ SELECT seq, chunks, src_id, src_seq, inline_json, fetched, chars AS batch_chars, 0 AS page_chars
4972
+ FROM (SELECT seq, chunks, src_id, src_seq, inline_json FROM sized ORDER BY seq LIMIT ?) AS fitting CROSS JOIN batch
4973
+ WHERE batch.chars <= ?
4974
+ UNION ALL
4975
+ SELECT seq, chunks, src_id, src_seq, inline_json, fetched, batch_chars, page_chars FROM (
4976
+ SELECT seq, chunks, src_id, src_seq, inline_json, batch.fetched, batch.chars AS batch_chars,
4977
+ row_number() OVER (ORDER BY seq) AS page_row,
4978
+ sum(size) OVER (ORDER BY seq) AS page_chars
4979
+ FROM sized CROSS JOIN batch WHERE batch.chars > ?
4980
+ ) AS windowed WHERE (page_chars <= ? OR page_row = 1) AND page_row <= ?
4981
+ ) SELECT seq, COALESCE(inline_json, (
4982
+ SELECT e.entry_json FROM ${this.tables.entries} AS e WHERE e.session_id = page.src_id AND e.seq = page.src_seq
4983
+ )) AS entry_json, chunks, fetched, batch_chars, page_chars FROM page ORDER BY seq`),
4984
+ params: [
4985
+ ...forkViewParams([view]),
4986
+ SESSION_READ_INLINE_BYTES,
4987
+ after,
4988
+ ...seqs === void 0 ? [] : [JSON.stringify(seqs)],
4989
+ limit + 1,
4990
+ limit,
4991
+ SESSION_READ_PAGE_CHARS,
4992
+ SESSION_READ_PAGE_CHARS,
4993
+ SESSION_READ_PAGE_CHARS,
4994
+ limit
4995
+ ]
4996
+ };
4997
+ }
4998
+ async read(tx, sessionId, generation = this.generation(sessionId), guessedPlain = this.forkedSessions.get(sessionId) === false) {
4563
4999
  const shared = await this.viewTables(tx);
4564
- 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);
4565
- const guess = this.forkedSessions.get(sessionId) === false ? {
5000
+ const headStatement = this.loadHeadStatement(sessionId, generation, shared.segments);
5001
+ const head = tx.get(headStatement.sql, ...headStatement.params);
5002
+ const guess = shared.segments !== void 0 && guessedPlain ? {
4566
5003
  ...shared,
4567
5004
  segments: void 0
4568
5005
  } : shared;
4569
- const epoch = head.then((found) => found?.epoch);
5006
+ const epoch = head.then((found) => guess.segments === void 0 && shared.segments !== void 0 && Number(found?.forked) === 1 ? void 0 : found?.epoch);
4570
5007
  let [row, rows] = await Promise.all([head, this.readRows(tx, sessionId, void 0, void 0, epoch, guess)]);
4571
5008
  if (!row) throw new SessionNotFoundError$1(sessionId);
4572
5009
  this.noteForked(tx, sessionId, row.forked);
4573
- 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);
5010
+ if (guess.segments === void 0 && shared.segments !== void 0 && Number(row.forked) === 1) rows = await this.readRows(tx, sessionId, void 0, void 0, row.epoch, shared);
4574
5011
  const snapshot = {
4575
5012
  header: JSON.parse(row.header_json),
4576
5013
  entries: rows.map(({ entry }) => entry),
@@ -4587,30 +5024,10 @@ $grant$`);
4587
5024
  async readRows(tx, sessionId, range = {}, seqs, epoch, viewTables) {
4588
5025
  const tables = viewTables ?? await this.viewTables(tx, sessionId);
4589
5026
  const through = range.through ?? FORK_VIEW_END;
4590
- const filter = seqs === void 0 ? "" : ` AND seq IN (${seqs.map(() => "?").join(", ")})`;
4591
5027
  const entries = [];
4592
5028
  for (let after = Math.max(0, (range.from ?? 1) - 1), limit = SESSION_READ_FETCH.first;;) {
4593
- const view = this.entriesView(tables, sessionId, after, tables.segments === void 0 || seqs !== void 0 ? through : Math.min(through, after + limit + 1));
4594
- const rows = await tx.all(withForkViews([view], `WITH sized AS MATERIALIZED (
4595
- SELECT seq, chunks, src_id, src_seq, length(entry_json) AS size,
4596
- CASE WHEN ${this.dialect.textByteLength("entry_json")} <= ? THEN entry_json END AS inline_json
4597
- FROM ${view.name} WHERE seq > ?${filter} ORDER BY seq LIMIT ?
4598
- ), batch AS MATERIALIZED (
4599
- SELECT count(*) AS fetched, COALESCE(sum(size), 0) AS chars FROM sized
4600
- ), page AS (
4601
- SELECT seq, chunks, src_id, src_seq, inline_json, fetched, chars AS batch_chars, 0 AS page_chars
4602
- FROM (SELECT seq, chunks, src_id, src_seq, inline_json FROM sized ORDER BY seq LIMIT ?) AS fitting CROSS JOIN batch
4603
- WHERE batch.chars <= ?
4604
- UNION ALL
4605
- SELECT seq, chunks, src_id, src_seq, inline_json, fetched, batch_chars, page_chars FROM (
4606
- SELECT seq, chunks, src_id, src_seq, inline_json, batch.fetched, batch.chars AS batch_chars,
4607
- row_number() OVER (ORDER BY seq) AS page_row,
4608
- sum(size) OVER (ORDER BY seq) AS page_chars
4609
- FROM sized CROSS JOIN batch WHERE batch.chars > ?
4610
- ) AS windowed WHERE (page_chars <= ? OR page_row = 1) AND page_row <= ?
4611
- ) SELECT seq, COALESCE(inline_json, (
4612
- SELECT e.entry_json FROM ${this.tables.entries} AS e WHERE e.session_id = page.src_id AND e.seq = page.src_seq
4613
- )) AS entry_json, chunks, fetched, batch_chars, page_chars FROM page ORDER BY seq`), ...forkViewParams([view]), SESSION_READ_INLINE_BYTES, after, ...seqs ?? [], limit + 1, limit, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, limit);
5029
+ const pageStatement = this.readRowsPageStatement(tables, sessionId, after, through, limit, seqs);
5030
+ const rows = await tx.all(pageStatement.sql, ...pageStatement.params);
4614
5031
  const generation = await epoch;
4615
5032
  const note = generation === void 0 || !this.sharedHistorySeen ? void 0 : storedEntryNotes(this, sessionId, generation);
4616
5033
  for (const entry of rows) {
@@ -4673,192 +5090,291 @@ $grant$`);
4673
5090
  name
4674
5091
  };
4675
5092
  }
4676
- async resumeSource(tx, sessionId) {
4677
- const read = this.resumeRow(sessionId);
4678
- const row = await tx.get(read.sql, ...read.params);
4679
- if (!row) throw new SessionNotFoundError$1(sessionId);
4680
- this.noteForked(tx, sessionId, row.forked);
4681
- const stored = windowIndex(JSON.parse(row.summary_state), Number(row.last_seq));
4682
- const remembered = this.resumeIndexes.get(sessionId);
4683
- const index = isSessionResumeIndex(stored, Number(row.last_seq)) ? stored : remembered?.revision === row.revision ? remembered.index : void 0;
4684
- if (!index || !isSessionResumeIndex(index, Number(row.last_seq))) throw new SessionConflictError$1(sessionId, Number(row.last_seq), Number(row.last_seq));
4685
- return {
4686
- header: JSON.parse(row.header_json),
4687
- index,
4688
- row
4689
- };
5093
+ cacheResumeIndex(sessionId, revision, index) {
5094
+ this.resumeIndexes.set(sessionId, {
5095
+ revision,
5096
+ index
5097
+ });
5098
+ while (this.resumeIndexes.size > 16) this.resumeIndexes.delete(this.resumeIndexes.keys().next().value);
4690
5099
  }
4691
5100
  /**
4692
- * Runs `read`, a read transaction that finds the session's index with `resumeSource`, at once; only when that index is
4693
- * missing or stale (`resumeSource` rejects with `SessionConflictError`) does it compute the index with
4694
- * `prepareResume` and run `read` again. A current index, the usual case, then costs no read before the transaction:
4695
- * on a server, one round trip fewer (#6560).
5101
+ * Persists a freshly rebuilt current-leaf resume index through one conditional `UPDATE ... RETURNING` guarded by
5102
+ * `(id, revision, last_seq)`, so a concurrent write can never have a stale index marked current. Returns whether the
5103
+ * row still stood at `(row.revision, row.last_seq)`. On a read-only connection where the update cannot run, verifies
5104
+ * `(revision, last_seq)` when `verifyOnReadOnly` is set and caches the index in memory only.
4696
5105
  */
4697
- async withResumeIndex(sessionId, read) {
5106
+ async persistRebuiltResumeIndex(sessionId, row, state, index, verifyOnReadOnly) {
5107
+ const checkReadOnly = async () => {
5108
+ if (verifyOnReadOnly) {
5109
+ const current = await this.database.get(`SELECT revision,last_seq FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
5110
+ if (current?.revision !== row.revision || Number(current.last_seq) !== Number(row.last_seq)) return false;
5111
+ }
5112
+ this.cacheResumeIndex(sessionId, row.revision, index);
5113
+ return true;
5114
+ };
5115
+ if (this.database.readOnly === true) return checkReadOnly();
5116
+ const updatedState = JSON.stringify({
5117
+ ...state,
5118
+ ...windowFields(state, index, index.seq, index.epoch),
5119
+ epoch: index.epoch
5120
+ });
5121
+ let updated;
4698
5122
  try {
4699
- return await read();
4700
- } catch (error) {
4701
- if (!(error instanceof SessionConflictError$1)) throw error;
5123
+ updated = await this.database.get(`UPDATE ${this.tables.sessions} SET summary_state = ? WHERE id = ? AND revision = ? AND last_seq = ? RETURNING revision`, updatedState, sessionId, row.revision, row.last_seq);
5124
+ } catch {
5125
+ return checkReadOnly();
4702
5126
  }
4703
- await this.prepareResume(sessionId);
4704
- return read();
5127
+ if (updated === void 0) return false;
5128
+ this.cacheResumeIndex(sessionId, row.revision, index);
5129
+ this.generations.delete(sessionId);
5130
+ this.writtenRows.delete(sessionId);
5131
+ return true;
5132
+ }
5133
+ /**
5134
+ * Runs `read` inside a read-only snapshot transaction with a current resume index. For the session's current leaf
5135
+ * (`cut` absent), reads the session row with the transaction's start so a current index costs no read before it
5136
+ * (#6560). When the index is missing or stale (or a historical cut is requested), passes the already-read row into
5137
+ * `prepareResume` to rebuild without re-reading it, then runs `read` in a transaction whose leading read verifies
5138
+ * `(revision, last_seq)` still matches.
5139
+ */
5140
+ async withResumeIndex(sessionId, read, cut) {
5141
+ const leafId = cut?.leafId;
5142
+ const throughSeq = cut?.throughSeq;
5143
+ let initialRow;
5144
+ if (leafId === void 0 && throughSeq === void 0) {
5145
+ const fast = await this.readTransaction(sessionId, async (tx) => {
5146
+ const rowRead = this.resumeRow(sessionId);
5147
+ const row = await tx.get(rowRead.sql, ...rowRead.params);
5148
+ if (!row) throw new SessionNotFoundError$1(sessionId);
5149
+ this.noteForked(tx, sessionId, row.forked);
5150
+ const stored = windowIndex(JSON.parse(row.summary_state), Number(row.last_seq));
5151
+ const remembered = this.resumeIndexes.get(sessionId);
5152
+ const index = isSessionResumeIndex(stored, Number(row.last_seq)) ? stored : remembered?.revision === row.revision ? remembered.index : void 0;
5153
+ if (!index || !isSessionResumeIndex(index, Number(row.last_seq))) return {
5154
+ kind: "stale",
5155
+ row
5156
+ };
5157
+ return {
5158
+ kind: "value",
5159
+ value: await read(tx, {
5160
+ header: JSON.parse(row.header_json),
5161
+ index,
5162
+ row
5163
+ })
5164
+ };
5165
+ }, [this.resumeRow(sessionId)]);
5166
+ if (fast.kind === "value") return fast.value;
5167
+ initialRow = fast.row;
5168
+ }
5169
+ for (let attempt = 0; attempt < 3; attempt++) {
5170
+ const prepared = await this.prepareResume(sessionId, leafId, throughSeq, {
5171
+ initialRow: attempt === 0 ? initialRow : void 0,
5172
+ deferRequestedCheck: true
5173
+ });
5174
+ const result = await this.readTransaction(sessionId, async (tx) => {
5175
+ const rowRead = this.resumeRow(sessionId);
5176
+ const row = await tx.get(rowRead.sql, ...rowRead.params);
5177
+ if (!row) throw new SessionNotFoundError$1(sessionId);
5178
+ this.noteForked(tx, sessionId, row.forked);
5179
+ if (prepared.revision !== row.revision || prepared.lastSeq !== Number(row.last_seq)) return void 0;
5180
+ return { value: await read(tx, {
5181
+ header: JSON.parse(row.header_json),
5182
+ index: prepared.index,
5183
+ row
5184
+ }) };
5185
+ }, [this.resumeRow(sessionId)]);
5186
+ if (result !== void 0) return result.value;
5187
+ }
5188
+ throw new SessionConflictError$1(sessionId, 0, 0);
4705
5189
  }
4706
- async prepareResume(sessionId, leafId, throughSeq) {
4707
- attempts: for (let attempt = 0; attempt < 3; attempt++) {
4708
- const row = await this.database.get(`SELECT header_json,last_seq,summary_state,revision${this.outsideForkedColumn("id")} FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
5190
+ async prepareResume(sessionId, leafId, throughSeq, options) {
5191
+ for (let attempt = 0; attempt < 3; attempt++) {
5192
+ const row = attempt === 0 && options?.initialRow !== void 0 ? options.initialRow : await this.database.get(`SELECT header_json,last_seq,summary_state,revision${this.outsideForkedColumn("id")} FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
4709
5193
  if (!row) throw new SessionNotFoundError$1(sessionId);
4710
5194
  this.noteForked(void 0, sessionId, row.forked);
5195
+ const lastSeq = Number(row.last_seq);
4711
5196
  const state = JSON.parse(row.summary_state);
4712
5197
  const remembered = this.resumeIndexes.get(sessionId);
4713
- const currentIndex = windowIndex(state, Number(row.last_seq)) ?? (remembered?.revision === row.revision && isSessionResumeIndex(remembered.index, Number(row.last_seq)) ? remembered.index : void 0);
4714
- const limit = throughSeq ?? Number(row.last_seq);
4715
- if (limit > Number(row.last_seq)) throw new SessionConflictError$1(sessionId, limit, Number(row.last_seq));
5198
+ const currentIndex = windowIndex(state, lastSeq) ?? (remembered?.revision === row.revision && isSessionResumeIndex(remembered.index, lastSeq) ? remembered.index : void 0);
5199
+ const limit = throughSeq ?? lastSeq;
5200
+ if (limit > lastSeq) throw new SessionConflictError$1(sessionId, limit, lastSeq);
4716
5201
  const selected = leafId === void 0 ? void 0 : await this.seqOfEntry(this.database, void 0, sessionId, leafId) ?? 0;
4717
5202
  const requested = selected !== void 0 && selected > limit ? 0 : selected;
4718
5203
  if (currentIndex && limit === currentIndex.seq && (requested === void 0 || requested === currentIndex.leafSeq)) return {
4719
5204
  index: currentIndex,
4720
- revision: row.revision
5205
+ revision: row.revision,
5206
+ lastSeq
4721
5207
  };
4722
- let index;
4723
- const sqlite = this.dialect.name === "sqlite";
4724
- const j = (...path) => sqlite ? this.dialect.jsonText("entry_json", ...path) : this.dialect.jsonAt({
4725
- column: "entry_json",
4726
- element: "parsed"
4727
- }, ...path);
4728
- const jsonType = (...path) => sqlite ? this.dialect.jsonType("entry_json", ...path) : `jsonb_typeof(parsed.value #> '{${path.join(",")}}')`;
4729
- const projected = [
4730
- "type",
4731
- "parentId",
4732
- "timestamp",
4733
- "customType",
4734
- "firstKeptEntryId",
4735
- "coveredThroughEntryId",
4736
- "provider",
4737
- "modelId",
4738
- "thinkingLevel",
4739
- "targetId",
4740
- "label",
4741
- "stageAdmissionKey",
4742
- "root",
4743
- "snapshotId",
4744
- "degradedFrom",
4745
- "captureMs"
4746
- ].map((key) => [key, j(key)]);
4747
- const messageKeys = [
4748
- "role",
4749
- "provider",
4750
- "model",
4751
- "usage",
4752
- "toolCallId"
4753
- ];
4754
- const dataKeys = [
4755
- "childId",
5208
+ const index = await this.foldResumeIndex(sessionId, row, state, currentIndex, limit, requested);
5209
+ if (index === void 0) continue;
5210
+ if (requested !== void 0) {
5211
+ if (options?.deferRequestedCheck !== true) {
5212
+ const current = await this.database.get(`SELECT revision,last_seq FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
5213
+ if (current?.revision !== row.revision || Number(current.last_seq) !== lastSeq) continue;
5214
+ }
5215
+ return {
5216
+ index: {
5217
+ ...index,
5218
+ leafSeq: requested
5219
+ },
5220
+ revision: row.revision,
5221
+ lastSeq
5222
+ };
5223
+ }
5224
+ if (!await this.persistRebuiltResumeIndex(sessionId, row, state, index, true)) continue;
5225
+ return {
5226
+ index,
5227
+ revision: row.revision,
5228
+ lastSeq
5229
+ };
5230
+ }
5231
+ throw new SessionConflictError$1(sessionId, 0, 0);
5232
+ }
5233
+ /**
5234
+ * Folds the entries of `sessionId` through `limit` into a resume index on `this.database`. Returns `undefined` when a
5235
+ * concurrent schema switch or session replacement requires restarting the rebuild attempt.
5236
+ */
5237
+ async foldResumeIndex(sessionId, row, state, currentIndex, limit, requested) {
5238
+ let index;
5239
+ const sqlite = this.dialect.name === "sqlite";
5240
+ const j = (...path) => sqlite ? this.dialect.jsonText("entry_json", ...path) : this.dialect.jsonAt({
5241
+ column: "entry_json",
5242
+ element: "parsed"
5243
+ }, ...path);
5244
+ const jsonType = (...path) => sqlite ? this.dialect.jsonType("entry_json", ...path) : `jsonb_typeof(parsed.value #> '{${path.join(",")}}')`;
5245
+ const projected = [
5246
+ "type",
5247
+ "parentId",
5248
+ "timestamp",
5249
+ "customType",
5250
+ "firstKeptEntryId",
5251
+ "coveredThroughEntryId",
5252
+ "provider",
5253
+ "modelId",
5254
+ "thinkingLevel",
5255
+ "targetId",
5256
+ "label",
5257
+ "stageAdmissionKey",
5258
+ "root",
5259
+ "snapshotId",
5260
+ "degradedFrom",
5261
+ "captureMs"
5262
+ ].map((key) => [key, j(key)]);
5263
+ const messageKeys = [
5264
+ "role",
5265
+ "provider",
5266
+ "model",
5267
+ "usage",
5268
+ "toolCallId"
5269
+ ];
5270
+ const dataKeys = [
5271
+ "childId",
5272
+ "version",
5273
+ "index",
5274
+ "agent",
5275
+ "cwd",
5276
+ "state",
5277
+ "intercomSessionId",
5278
+ "homeGroup",
5279
+ "kind",
5280
+ "worktree",
5281
+ "type",
5282
+ "timestamp",
5283
+ "completionId",
5284
+ "sessionId",
5285
+ "askId",
5286
+ "messageId",
5287
+ "attemptId",
5288
+ "runId",
5289
+ "requestId",
5290
+ "id",
5291
+ "protectedReconciliationOf",
5292
+ "historyOnly",
5293
+ "toolCallId",
5294
+ "ownerId",
5295
+ "taskId",
5296
+ "terminalStatus"
5297
+ ];
5298
+ const op = `CASE WHEN ${jsonType("data", "op")} = '${sqlite ? "text" : "string"}' THEN ${j("data", "op")} END`;
5299
+ const deliveryOp = `chunks > 0 AND ${j("type")} = 'custom' AND ${j("customType")} = 'atomic-pooled-delivery-op'`;
5300
+ const dataExpr = this.dialect.jsonObject([
5301
+ ...dataKeys.map((key) => [key, [
4756
5302
  "version",
4757
5303
  "index",
4758
- "agent",
4759
- "cwd",
4760
- "state",
4761
- "intercomSessionId",
4762
- "homeGroup",
4763
- "kind",
4764
- "worktree",
4765
- "type",
4766
- "timestamp",
4767
- "completionId",
4768
- "sessionId",
4769
- "askId",
4770
- "messageId",
4771
- "attemptId",
4772
- "runId",
4773
- "requestId",
4774
- "id",
4775
- "protectedReconciliationOf",
4776
- "historyOnly",
4777
- "toolCallId",
4778
- "ownerId",
4779
- "taskId",
4780
- "terminalStatus"
4781
- ];
4782
- const op = `CASE WHEN ${jsonType("data", "op")} = '${sqlite ? "text" : "string"}' THEN ${j("data", "op")} END`;
4783
- const deliveryOp = `chunks > 0 AND ${j("type")} = 'custom' AND ${j("customType")} = 'atomic-pooled-delivery-op'`;
4784
- const dataExpr = this.dialect.jsonObject([
4785
- ...dataKeys.map((key) => [key, [
4786
- "version",
4787
- "index",
4788
- "timestamp"
4789
- ].includes(key) ? `CASE WHEN ${jsonType("data", key)} IN ('integer','real','number') THEN CAST(${j("data", key)} AS ${this.dialect.types.real}) END` : key === "runId" ? `CASE WHEN ${j("customType")} NOT IN ('workflow.run.start','workflow.run.end') OR ${jsonType("data", key)} = '${sqlite ? "text" : "string"}' THEN ${j("data", key)} END` : j("data", key)]),
4790
- ["name", `CASE WHEN ${jsonType("data", "name")} = '${sqlite ? "text" : "string"}' THEN '' END`],
4791
- ["ts", `CASE WHEN ${jsonType("data", "ts")} IN ('integer','real','number') THEN 0 END`],
4792
- ["message", this.dialect.jsonObject([
4793
- "id",
4794
- "replyTo",
4795
- "expectsReply"
4796
- ].map((key) => [key, j("data", "message", key)]))],
4797
- ["op", op],
4798
- ...[
4799
- ["owner", "object"],
4800
- ["tasks", "array"],
4801
- ["groups", "array"]
4802
- ].map(([key, type]) => [key, `CASE WHEN ${jsonType("data", key)} = '${type}' THEN ${j("data", key)} WHEN ${jsonType("data", key)} IS NULL OR ${jsonType("data", key)} = 'null' THEN NULL ELSE '' END`]),
4803
- ...["messageIds", "askIds"].map((key) => [key, `CASE WHEN ${jsonType("data", key)} = 'array' THEN ${j("data", key)} END`]),
4804
- ...["queries", "urls"].map((key) => [key, `CASE WHEN ${jsonType("data", key)} = 'array' THEN '[]' ELSE NULL END`])
4805
- ]);
4806
- const detailsExpr = this.dialect.jsonObject([...dataKeys.map((key) => [key, j("details", key)]), ["message", this.dialect.jsonObject([
5304
+ "timestamp"
5305
+ ].includes(key) ? `CASE WHEN ${jsonType("data", key)} IN ('integer','real','number') THEN CAST(${j("data", key)} AS ${this.dialect.types.real}) END` : key === "runId" ? `CASE WHEN ${j("customType")} NOT IN ('workflow.run.start','workflow.run.end') OR ${jsonType("data", key)} = '${sqlite ? "text" : "string"}' THEN ${j("data", key)} END` : j("data", key)]),
5306
+ ["name", `CASE WHEN ${jsonType("data", "name")} = '${sqlite ? "text" : "string"}' THEN '' END`],
5307
+ ["ts", `CASE WHEN ${jsonType("data", "ts")} IN ('integer','real','number') THEN 0 END`],
5308
+ ["message", this.dialect.jsonObject([
4807
5309
  "id",
4808
5310
  "replyTo",
4809
5311
  "expectsReply"
4810
- ].map((key) => [key, j("details", "message", key)]))]]);
4811
- const dataFieldNames = this.dialect.name === "sqlite" ? `(SELECT COALESCE(json_group_array(key),'[]') FROM json_each(entry_json,'$.data'))` : `(SELECT COALESCE(json_agg(key)::text,'[]') FROM jsonb_object_keys(CASE WHEN jsonb_typeof(parsed.value->'data')='object' THEN parsed.value->'data' ELSE '{}'::jsonb END) AS key)`;
4812
- const binaryContent = sqlite && Number(row.last_seq) > 0 && this.database.supportsJsonbExtract && await this.database.supportsJsonbExtract();
4813
- const toolBlocks = sqlite ? this.dialect.jsonValues(binaryContent ? "jsonb_extract(entry_json, '$.message.content')" : j("message", "content")) : "jsonb_array_elements_text(parsed.value #> '{message,content}') AS blocks(value)";
4814
- const blockType = this.dialect.jsonText("value", "type");
4815
- const toolType = `CASE WHEN chunks > 0 AND ${sqlite ? "type = 'text' AND instr(value, '{')" : "strpos(value, '{')"} = 0 THEN NULL ELSE ${blockType} END`;
4816
- const columns = [
4817
- ["dataFields", `CASE WHEN ${deliveryOp} THEN '["op"]' WHEN ${j("type")} = 'custom' THEN ${dataFieldNames} ELSE '[]' END`],
4818
- ...projected,
4819
- ["message", this.dialect.jsonObject([...messageKeys.map((key) => [key, j("message", key)]), ...["toolsAdded", "toolsRemoved"].map((key) => [key, `CASE WHEN ${jsonType("message", key)}='array' THEN 1 END`])])],
4820
- ["data", `CASE WHEN ${deliveryOp} THEN ${this.dialect.jsonObject([["op", op]])} ELSE ${dataExpr} END`],
4821
- ["details", detailsExpr],
4822
- ["usage", j("usage")],
4823
- ["protectedReconciliation", j("protectedReconciliation")],
4824
- ["snapshot", `CASE WHEN ${jsonType("snapshot")} = 'object' THEN '{}' ELSE NULL END`],
4825
- ["restore", `CASE WHEN ${jsonType("restore")} = 'object' THEN 1 END`],
4826
- ["unrestored", `CASE WHEN ${jsonType("unrestored")} = 'object' THEN 1 END`],
4827
- ["compactionDetails", j("details", "strategy")],
4828
- ["toolCalls", `CASE WHEN ${j("message", "role")} = 'assistant' AND ${jsonType("message", "content")} = 'array' THEN
5312
+ ].map((key) => [key, j("data", "message", key)]))],
5313
+ ["op", op],
5314
+ ...[
5315
+ ["owner", "object"],
5316
+ ["tasks", "array"],
5317
+ ["groups", "array"]
5318
+ ].map(([key, type]) => [key, `CASE WHEN ${jsonType("data", key)} = '${type}' THEN ${j("data", key)} WHEN ${jsonType("data", key)} IS NULL OR ${jsonType("data", key)} = 'null' THEN NULL ELSE '' END`]),
5319
+ ...["messageIds", "askIds"].map((key) => [key, `CASE WHEN ${jsonType("data", key)} = 'array' THEN ${j("data", key)} END`]),
5320
+ ...["queries", "urls"].map((key) => [key, `CASE WHEN ${jsonType("data", key)} = 'array' THEN '[]' ELSE NULL END`])
5321
+ ]);
5322
+ const detailsExpr = this.dialect.jsonObject([...dataKeys.map((key) => [key, j("details", key)]), ["message", this.dialect.jsonObject([
5323
+ "id",
5324
+ "replyTo",
5325
+ "expectsReply"
5326
+ ].map((key) => [key, j("details", "message", key)]))]]);
5327
+ const dataFieldNames = this.dialect.name === "sqlite" ? `(SELECT COALESCE(json_group_array(key),'[]') FROM json_each(entry_json,'$.data'))` : `(SELECT COALESCE(json_agg(key)::text,'[]') FROM jsonb_object_keys(CASE WHEN jsonb_typeof(parsed.value->'data')='object' THEN parsed.value->'data' ELSE '{}'::jsonb END) AS key)`;
5328
+ const binaryContent = sqlite && Number(row.last_seq) > 0 && this.database.supportsJsonbExtract && await this.database.supportsJsonbExtract();
5329
+ const toolBlocks = sqlite ? this.dialect.jsonValues(binaryContent ? "jsonb_extract(entry_json, '$.message.content')" : j("message", "content")) : "jsonb_array_elements_text(parsed.value #> '{message,content}') AS blocks(value)";
5330
+ const blockType = this.dialect.jsonText("value", "type");
5331
+ const toolType = `CASE WHEN chunks > 0 AND ${sqlite ? "type = 'text' AND instr(value, '{')" : "strpos(value, '{')"} = 0 THEN NULL ELSE ${blockType} END`;
5332
+ const columns = [
5333
+ ["dataFields", `CASE WHEN ${deliveryOp} THEN '["op"]' WHEN ${j("type")} = 'custom' THEN ${dataFieldNames} ELSE '[]' END`],
5334
+ ...projected,
5335
+ ["message", this.dialect.jsonObject([...messageKeys.map((key) => [key, j("message", key)]), ...["toolsAdded", "toolsRemoved"].map((key) => [key, `CASE WHEN ${jsonType("message", key)}='array' THEN 1 END`])])],
5336
+ ["data", `CASE WHEN ${deliveryOp} THEN ${this.dialect.jsonObject([["op", op]])} ELSE ${dataExpr} END`],
5337
+ ["details", detailsExpr],
5338
+ ["usage", j("usage")],
5339
+ ["protectedReconciliation", j("protectedReconciliation")],
5340
+ ["snapshot", `CASE WHEN ${jsonType("snapshot")} = 'object' THEN '{}' ELSE NULL END`],
5341
+ ["restore", `CASE WHEN ${jsonType("restore")} = 'object' THEN 1 END`],
5342
+ ["unrestored", `CASE WHEN ${jsonType("unrestored")} = 'object' THEN 1 END`],
5343
+ ["compactionDetails", j("details", "strategy")],
5344
+ ["toolCalls", `CASE WHEN ${j("message", "role")} = 'assistant' AND ${jsonType("message", "content")} = 'array' THEN
4829
5345
  (SELECT count(*) FROM ${toolBlocks}
4830
5346
  WHERE ${toolType} = 'toolCall') ELSE 0 END`]
4831
- ];
4832
- const select = columns.map(([key, expr]) => `${expr} AS ${this.dialect.identifier(`resume_${key.toLowerCase()}`)}`).join(", ");
4833
- const upgrade = requested === void 0 && limit === Number(row.last_seq) && isUpgradableSessionResumeIndex(state.resume, limit) ? sessionResumeUpgrade(state.resume) : void 0;
4834
- const list = (values) => values.map((value) => `'${value.replaceAll("'", "''")}'`).join(",");
4835
- const source = `chunks > 0 OR ${j("type")} IN (${list(RESUME_UPGRADE_SOURCES.types)})
5347
+ ];
5348
+ const select = columns.map(([key, expr]) => `${expr} AS ${this.dialect.identifier(`resume_${key.toLowerCase()}`)}`).join(", ");
5349
+ const upgrade = requested === void 0 && limit === Number(row.last_seq) && isUpgradableSessionResumeIndex(state.resume, limit) ? sessionResumeUpgrade(state.resume) : void 0;
5350
+ const list = (values) => values.map((value) => `'${value.replaceAll("'", "''")}'`).join(",");
5351
+ const source = `chunks > 0 OR ${j("type")} IN (${list(RESUME_UPGRADE_SOURCES.types)})
4836
5352
  OR (${j("type")} = 'message' AND ${j("message", "role")} = 'system')
4837
5353
  OR (${j("type")} = 'custom' AND (${j("customType")} IN (${list(RESUME_UPGRADE_SOURCES.customTypes)})
4838
5354
  OR ${j("customType")} NOT IN (${list(RESUME_UPGRADE_SOURCES.atomicCustomTypes)})))`;
4839
- const sources = !upgrade ? "" : sqlite ? ` AND (${source})` : ` AND EXISTS (SELECT 1 FROM (SELECT ${postgresJsonb("entry_json")} AS value OFFSET 0) AS parsed WHERE ${source})`;
4840
- const where = `WHERE session_id = ? AND seq > ? AND seq <= ?${sources}`;
4841
- const owner = "(SELECT id FROM bounds)";
4842
- const lo = "(SELECT lo FROM bounds)";
4843
- const hi = "(SELECT hi FROM bounds)";
4844
- const pageWhere = sqlite ? `WHERE session_id = ${owner} AND seq > ${lo} AND seq <= ${hi}${sources}` : where;
4845
- const viewed = this.outsideViewTables();
4846
- const tables = Number(row.forked) === 0 ? {
4847
- ...viewed,
4848
- segments: void 0
4849
- } : viewed;
4850
- const shared = tables.segments !== void 0;
4851
- const page = `WITH ${sqlite ? "bounds(id,lo,hi) AS NOT MATERIALIZED (VALUES (?,?,?)), " : ""}page AS (
5355
+ const sources = !upgrade ? "" : sqlite ? ` AND (${source})` : ` AND EXISTS (SELECT 1 FROM (SELECT ${postgresJsonb("entry_json")} AS value OFFSET 0) AS parsed WHERE ${source})`;
5356
+ const where = `WHERE session_id = ? AND seq > ? AND seq <= ?${sources}`;
5357
+ const owner = "(SELECT id FROM bounds)";
5358
+ const lo = "(SELECT lo FROM bounds)";
5359
+ const hi = "(SELECT hi FROM bounds)";
5360
+ const pageWhere = sqlite ? `WHERE session_id = ${owner} AND seq > ${lo} AND seq <= ${hi}${sources}` : where;
5361
+ const viewed = this.outsideViewTables();
5362
+ const tables = Number(row.forked) === 0 ? {
5363
+ ...viewed,
5364
+ segments: void 0
5365
+ } : viewed;
5366
+ const shared = tables.segments !== void 0;
5367
+ const page = `WITH ${sqlite ? "bounds(id,lo,hi) AS NOT MATERIALIZED (VALUES (?,?,?)), " : ""}page AS (
4852
5368
  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
4853
5369
  ${pageWhere} ORDER BY seq LIMIT ${SESSION_RESUME_REBUILD.pageEntries}
4854
5370
  )`;
4855
- const parts = (source) => `FROM ${this.tables.entryChunks} WHERE session_id = ${sqlite && !shared ? owner : `${source}.src_id`}
5371
+ const parts = (source) => `FROM ${this.tables.entryChunks} WHERE session_id = ${sqlite && !shared ? owner : `${source}.src_id`}
4856
5372
  AND seq = ${source}.src_seq AND idx >= 0 AND idx < ${source}.chunks`;
4857
- const projection = sqlite ? `SELECT seq,entry_id,chunks,${select} FROM payloads ORDER BY seq` : `SELECT seq,entry_id,chunks,${select} FROM payloads
5373
+ const projection = sqlite ? `SELECT seq,entry_id,chunks,${select} FROM payloads ORDER BY seq` : `SELECT seq,entry_id,chunks,${select} FROM payloads
4858
5374
  CROSS JOIN LATERAL (SELECT ${postgresJsonb("entry_json")} AS value OFFSET 0) AS parsed ORDER BY seq`;
4859
- const fits = sqlite ? "length(zeroblob(sum(length(data)))) IS NOT NULL" : "sum(octet_length(data)) < 1073741824";
4860
- const joined = sqlite ? `(SELECT group_concat(text, '') FROM (SELECT CAST(data AS TEXT) AS text ${parts("sized")} ORDER BY idx))` : `(SELECT convert_from(string_agg(data, ''::bytea ORDER BY idx), 'UTF8') ${parts("sized")})`;
4861
- const directPage = `${page}, sized AS ${sqlite ? "NOT MATERIALIZED" : "MATERIALIZED"} (
5375
+ const fits = sqlite ? "length(zeroblob(sum(length(data)))) IS NOT NULL" : "sum(octet_length(data)) < 1073741824";
5376
+ const joined = sqlite ? `(SELECT group_concat(text, '') FROM (SELECT CAST(data AS TEXT) AS text ${parts("sized")} ORDER BY idx))` : `(SELECT convert_from(string_agg(data, ''::bytea ORDER BY idx), 'UTF8') ${parts("sized")})`;
5377
+ const directPage = `${page}, sized AS ${sqlite ? "NOT MATERIALIZED" : "MATERIALIZED"} (
4862
5378
  SELECT page.*, CASE WHEN chunks = 0 OR EXISTS (SELECT 1 ${parts("page")} GROUP BY seq
4863
5379
  HAVING count(*) = page.chunks AND ${fits}) THEN 0 ELSE chunks END AS remaining FROM page${sqlite ? " LIMIT -1 OFFSET 0" : ""}
4864
5380
  ), payloads AS MATERIALIZED (
@@ -4866,13 +5382,13 @@ $grant$`);
4866
5382
  CASE WHEN chunks > 0 AND remaining = 0 THEN ${joined} ELSE entry_json END AS entry_json
4867
5383
  FROM sized
4868
5384
  ) ${projection}`;
4869
- const keysPerEntry = 64;
4870
- const through = `${lo} + ${SESSION_RESUME_REBUILD.pageEntries}`;
4871
- const wide = sqlite && !shared && Number(row.last_seq) > 0 && Buffer.byteLength(sessionId) >= 512;
4872
- let inlinePage = wide && this.chunkRowids === void 0 ? `${page}, chunked AS MATERIALIZED (SELECT 1 FROM page WHERE chunks > 0 LIMIT 1),
5385
+ const keysPerEntry = 64;
5386
+ const through = `${lo} + ${SESSION_RESUME_REBUILD.pageEntries}`;
5387
+ const wide = sqlite && !shared && Number(row.last_seq) > 0 && Buffer.byteLength(sessionId) >= 512;
5388
+ let inlinePage = wide && this.chunkRowids === void 0 ? `${page}, chunked AS MATERIALIZED (SELECT 1 FROM page WHERE chunks > 0 LIMIT 1),
4873
5389
  payloads AS MATERIALIZED (SELECT seq,entry_id,chunks,entry_json FROM page WHERE NOT EXISTS (SELECT 1 FROM chunked)
4874
5390
  UNION ALL SELECT 0,'',0,'{}' FROM chunked) ${projection}` : void 0;
4875
- const rowidPage = wide && this.chunkRowids !== false ? `${page},
5391
+ const rowidPage = wide && this.chunkRowids !== false ? `${page},
4876
5392
  keys AS MATERIALIZED (SELECT seq,idx,rowid AS rid FROM ${this.tables.entryChunks}
4877
5393
  WHERE session_id = ${owner} AND seq > ${lo} AND seq <= ${hi} AND seq <= ${through} AND idx >= 0 AND idx < ${keysPerEntry}
4878
5394
  ORDER BY seq,idx),
@@ -4891,184 +5407,153 @@ $grant$`);
4891
5407
  FROM (SELECT rid FROM keys k WHERE k.seq = sized.seq AND k.idx < sized.chunks ORDER BY k.idx LIMIT -1 OFFSET 0) ids)
4892
5408
  END AS entry_json FROM sized)
4893
5409
  ${projection}` : directPage;
4894
- const stubPage = `${page}, payloads AS (SELECT seq,entry_id,-chunks AS chunks,entry_json FROM page) ${projection}`;
4895
- let topology = currentIndex && requested !== void 0 ? branchRanges(currentIndex, requested) : void 0;
4896
- for (let pass = topology === void 0 ? 0 : 1; pass < 2; pass++) {
4897
- for (let after = 0; after < limit;) {
4898
- const view = this.entriesView(tables, sessionId, after, Math.min(limit, after + SESSION_RESUME_REBUILD.pageEntries));
4899
- const args = [
4900
- ...view.params,
4901
- sessionId,
4902
- after,
4903
- limit
4904
- ];
4905
- let rows;
4906
- try {
4907
- rows = await this.database.all(withForkViews([view], inlinePage ?? (this.chunkRowids ? rowidPage : directPage)), ...args);
4908
- if (inlinePage && Number(rows[0]?.seq) === 0) {
4909
- inlinePage = void 0;
4910
- try {
4911
- this.chunkRowids = await this.database.get(`SELECT 1 WHERE NOT EXISTS (SELECT 1 FROM pragma_index_xinfo(?))
5410
+ const stubPage = `${page}, payloads AS (SELECT seq,entry_id,-chunks AS chunks,entry_json FROM page) ${projection}`;
5411
+ let topology = currentIndex && requested !== void 0 ? branchRanges(currentIndex, requested) : void 0;
5412
+ for (let pass = topology === void 0 ? 0 : 1; pass < 2; pass++) {
5413
+ for (let after = 0; after < limit;) {
5414
+ const view = this.entriesView(tables, sessionId, after, Math.min(limit, after + SESSION_RESUME_REBUILD.pageEntries));
5415
+ const args = [
5416
+ ...view.params,
5417
+ sessionId,
5418
+ after,
5419
+ limit
5420
+ ];
5421
+ let rows;
5422
+ try {
5423
+ rows = await this.database.all(withForkViews([view], inlinePage ?? (this.chunkRowids ? rowidPage : directPage)), ...args);
5424
+ if (inlinePage && Number(rows[0]?.seq) === 0) {
5425
+ inlinePage = void 0;
5426
+ try {
5427
+ this.chunkRowids = await this.database.get(`SELECT 1 WHERE NOT EXISTS (SELECT 1 FROM pragma_index_xinfo(?))
4912
5428
  AND NOT EXISTS (SELECT 1 FROM pragma_table_xinfo(?) WHERE name = 'rowid' COLLATE NOCASE)`, this.tables.entryChunks, this.tables.entryChunks) !== void 0;
4913
- } catch {}
4914
- continue;
4915
- }
4916
- } catch (error) {
4917
- if (!(error instanceof Error && "code" in error && error.code === "payload-too-large")) throw error;
4918
- if (!await this.database.get(withForkViews([view], `SELECT 1 FROM (SELECT src_id, src_seq FROM ${view.name} ${where}
5429
+ } catch {}
5430
+ continue;
5431
+ }
5432
+ } catch (error) {
5433
+ if (!(error instanceof Error && "code" in error && error.code === "payload-too-large")) throw error;
5434
+ if (!await this.database.get(withForkViews([view], `SELECT 1 FROM (SELECT src_id, src_seq FROM ${view.name} ${where}
4919
5435
  ORDER BY seq LIMIT ${SESSION_RESUME_REBUILD.pageEntries}) AS p
4920
5436
  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;
4921
- rows = await this.database.all(withForkViews([view], stubPage), ...args);
4922
- }
4923
- if (rows.length === 0) {
4924
- if (await this.schemaNowShared(viewed.segments !== void 0)) continue attempts;
4925
- break;
5437
+ rows = await this.database.all(withForkViews([view], stubPage), ...args);
5438
+ }
5439
+ if (rows.length === 0) {
5440
+ if (await this.schemaNowShared(viewed.segments !== void 0)) return void 0;
5441
+ break;
5442
+ }
5443
+ const batch = [];
5444
+ let toolCalls = 0;
5445
+ for (const entry of rows) {
5446
+ const chunks = Number(entry.chunks);
5447
+ let projected = entry;
5448
+ if (chunks < 0) try {
5449
+ const { chunkedResumeProjection } = await import("../core/storage/session/chunked-resume-projection.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
5450
+ projected = await chunkedResumeProjection(entry, this.dialect.name === "postgres", () => this.entryChunks(sessionId, Number(entry.seq), -chunks, row.revision));
5451
+ } catch (error) {
5452
+ if ((await this.database.get(`SELECT revision FROM ${this.tables.sessions} WHERE id = ?`, sessionId))?.revision !== row.revision) return void 0;
5453
+ throw error;
4926
5454
  }
4927
- const batch = [];
4928
- let toolCalls = 0;
4929
- for (const entry of rows) {
4930
- const chunks = Number(entry.chunks);
4931
- let projected = entry;
4932
- if (chunks < 0) try {
4933
- const { chunkedResumeProjection } = await import("../core/storage/session/chunked-resume-projection.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
4934
- projected = await chunkedResumeProjection(entry, this.dialect.name === "postgres", () => this.entryChunks(sessionId, Number(entry.seq), -chunks, row.revision));
4935
- } catch (error) {
4936
- if ((await this.database.get(`SELECT revision FROM ${this.tables.sessions} WHERE id = ?`, sessionId))?.revision !== row.revision) continue attempts;
4937
- throw error;
4938
- }
4939
- const parsed = { id: entry.entry_id };
4940
- const decode = (value) => typeof value === "string" && (value.startsWith("{") || value.startsWith("[")) ? JSON.parse(value) : value;
4941
- for (const [key] of columns) {
4942
- const value = projected[`resume_${key.toLowerCase()}`];
4943
- parsed[key] = [
4944
- "dataFields",
4945
- "message",
4946
- "data",
4947
- "details",
4948
- "usage",
4949
- "snapshot",
4950
- "protectedReconciliation"
4951
- ].includes(key) ? decode(value) : value;
4952
- }
4953
- const message = parsed.message;
4954
- if (message && typeof message === "object") {
4955
- message.usage = decode(message.usage);
4956
- if (parsed.type === "message" && message.role === "assistant") toolCalls += Number(parsed.toolCalls ?? 0);
4957
- }
4958
- if (parsed.snapshot === null) delete parsed.snapshot;
4959
- if (parsed.type === "compaction") parsed.details = { strategy: parsed.compactionDetails };
4960
- if (parsed.type === "custom") {
4961
- const data = parsed.data;
4962
- const keys = parsed.dataFields ?? [];
4963
- for (const key of Object.keys(data)) if (!keys.includes(key)) delete data[key];
4964
- for (const key of keys) if (!(key in data)) data[key] = null;
4965
- }
4966
- for (const key of ["data", "details"]) {
4967
- const data = parsed[key];
4968
- if (data && typeof data === "object") {
4969
- data.message = decode(data.message);
4970
- data.owner = decode(data.owner);
4971
- data.tasks = decode(data.tasks);
4972
- for (const field of [
4973
- "groups",
4974
- "queries",
4975
- "urls",
4976
- "messageIds",
4977
- "askIds"
4978
- ]) if (field in data) data[field] = decode(data[field]);
4979
- if (data.timestamp !== null && data.timestamp !== void 0 && typeof data.timestamp === "string") data.timestamp = Number(data.timestamp);
4980
- if (parsed.type === "custom" && parsed.customType === "subagent-child") {
4981
- if (data.version !== null && data.version !== void 0) data.version = Number(data.version);
4982
- if (data.index !== null && data.index !== void 0) data.index = Number(data.index);
4983
- }
4984
- const message = data.message;
4985
- if (message?.expectsReply === 1 || message?.expectsReply === "true") message.expectsReply = true;
4986
- if (data.historyOnly === 1 || data.historyOnly === "true") data.historyOnly = true;
4987
- }
4988
- }
4989
- if (upgrade) upgrade.add(parsed, Number(entry.seq));
4990
- else batch.push(parsed);
5455
+ const parsed = { id: entry.entry_id };
5456
+ const decode = (value) => typeof value === "string" && (value.startsWith("{") || value.startsWith("[")) ? JSON.parse(value) : value;
5457
+ for (const [key] of columns) {
5458
+ const value = projected[`resume_${key.toLowerCase()}`];
5459
+ parsed[key] = [
5460
+ "dataFields",
5461
+ "message",
5462
+ "data",
5463
+ "details",
5464
+ "usage",
5465
+ "snapshot",
5466
+ "protectedReconciliation"
5467
+ ].includes(key) ? decode(value) : value;
4991
5468
  }
4992
- if (upgrade) {
4993
- after = Number(rows.at(-1).seq);
4994
- if (after < limit) await yieldTurn();
4995
- continue;
5469
+ const message = parsed.message;
5470
+ if (message && typeof message === "object") {
5471
+ message.usage = decode(message.usage);
5472
+ if (parsed.type === "message" && message.role === "assistant") toolCalls += Number(parsed.toolCalls ?? 0);
4996
5473
  }
4997
- const old = index ?? foldSessionResume(void 0, []);
4998
- const seqs = /* @__PURE__ */ new Map();
4999
- for (const id of foreignResumeIds(old, batch)) {
5000
- const seq = await this.seqOfEntry(this.database, void 0, sessionId, id);
5001
- if (seq !== void 0) seqs.set(id, seq);
5474
+ if (parsed.snapshot === null) delete parsed.snapshot;
5475
+ if (parsed.type === "compaction") parsed.details = { strategy: parsed.compactionDetails };
5476
+ if (parsed.type === "custom") {
5477
+ const data = parsed.data;
5478
+ const keys = parsed.dataFields ?? [];
5479
+ for (const key of Object.keys(data)) if (!keys.includes(key)) delete data[key];
5480
+ for (const key of keys) if (!(key in data)) data[key] = null;
5002
5481
  }
5003
- index = foldSessionResume(index, batch, (id) => seqs.get(id), (seq) => topology === void 0 || topology.some(([a, b]) => seq >= a && seq <= b));
5004
- if (toolCalls > 0) index = {
5005
- ...index,
5006
- totals: {
5007
- ...index.totals,
5008
- toolCalls: index.totals.toolCalls + toolCalls
5482
+ for (const key of ["data", "details"]) {
5483
+ const data = parsed[key];
5484
+ if (data && typeof data === "object") {
5485
+ data.message = decode(data.message);
5486
+ data.owner = decode(data.owner);
5487
+ data.tasks = decode(data.tasks);
5488
+ for (const field of [
5489
+ "groups",
5490
+ "queries",
5491
+ "urls",
5492
+ "messageIds",
5493
+ "askIds"
5494
+ ]) if (field in data) data[field] = decode(data[field]);
5495
+ if (data.timestamp !== null && data.timestamp !== void 0 && typeof data.timestamp === "string") data.timestamp = Number(data.timestamp);
5496
+ if (parsed.type === "custom" && parsed.customType === "subagent-child") {
5497
+ if (data.version !== null && data.version !== void 0) data.version = Number(data.version);
5498
+ if (data.index !== null && data.index !== void 0) data.index = Number(data.index);
5499
+ }
5500
+ const message = data.message;
5501
+ if (message?.expectsReply === 1 || message?.expectsReply === "true") message.expectsReply = true;
5502
+ if (data.historyOnly === 1 || data.historyOnly === "true") data.historyOnly = true;
5009
5503
  }
5010
- };
5504
+ }
5505
+ if (upgrade) upgrade.add(parsed, Number(entry.seq));
5506
+ else batch.push(parsed);
5507
+ }
5508
+ if (upgrade) {
5011
5509
  after = Number(rows.at(-1).seq);
5012
- if (after < Number(row.last_seq)) await yieldTurn();
5510
+ if (after < limit) await yieldTurn();
5511
+ continue;
5013
5512
  }
5014
- if (pass !== 0 || !index || index.jumps.length === 0 && (requested === void 0 || requested === index.leafSeq)) break;
5015
- topology = branchRanges(index, requested ?? index.leafSeq);
5016
- index = void 0;
5017
- }
5018
- if (upgrade) index = upgrade.finish();
5019
- index = {
5020
- ...index ?? foldSessionResume(void 0, []),
5021
- epoch: state.epoch ?? row.revision
5022
- };
5023
- const current = await this.database.get(`SELECT revision,last_seq FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
5024
- if (current?.revision !== row.revision || Number(current.last_seq) !== Number(row.last_seq)) continue;
5025
- if (requested !== void 0) return {
5026
- index: {
5513
+ const old = index ?? foldSessionResume(void 0, []);
5514
+ const seqs = /* @__PURE__ */ new Map();
5515
+ for (const id of foreignResumeIds(old, batch)) {
5516
+ const seq = await this.seqOfEntry(this.database, void 0, sessionId, id);
5517
+ if (seq !== void 0) seqs.set(id, seq);
5518
+ }
5519
+ index = foldSessionResume(index, batch, (id) => seqs.get(id), (seq) => topology === void 0 || topology.some(([a, b]) => seq >= a && seq <= b));
5520
+ if (toolCalls > 0) index = {
5027
5521
  ...index,
5028
- leafSeq: requested
5029
- },
5030
- revision: row.revision
5031
- };
5032
- this.resumeIndexes.set(sessionId, {
5033
- revision: row.revision,
5034
- index
5035
- });
5036
- while (this.resumeIndexes.size > 16) this.resumeIndexes.delete(this.resumeIndexes.keys().next().value);
5037
- await this.database.run(`UPDATE ${this.tables.sessions} SET summary_state = ? WHERE id = ? AND revision = ? AND last_seq = ?`, JSON.stringify({
5038
- ...state,
5039
- ...windowFields(state, index, index.seq, index.epoch),
5040
- epoch: index.epoch
5041
- }), sessionId, row.revision, row.last_seq).catch(() => void 0);
5042
- this.generations.delete(sessionId);
5043
- return {
5044
- index,
5045
- revision: row.revision
5046
- };
5522
+ totals: {
5523
+ ...index.totals,
5524
+ toolCalls: index.totals.toolCalls + toolCalls
5525
+ }
5526
+ };
5527
+ after = Number(rows.at(-1).seq);
5528
+ if (after < Number(row.last_seq)) await yieldTurn();
5529
+ }
5530
+ if (pass !== 0 || !index || index.jumps.length === 0 && (requested === void 0 || requested === index.leafSeq)) break;
5531
+ topology = branchRanges(index, requested ?? index.leafSeq);
5532
+ index = void 0;
5047
5533
  }
5048
- throw new SessionConflictError$1(sessionId, 0, 0);
5534
+ if (upgrade) index = upgrade.finish();
5535
+ return {
5536
+ ...index ?? foldSessionResume(void 0, []),
5537
+ epoch: state.epoch ?? row.revision
5538
+ };
5049
5539
  }
5050
5540
  async readTail(sessionId, fromSeq) {
5051
5541
  this.assertOpen();
5052
5542
  validateSessionText("sessionId", sessionId);
5053
5543
  const start = Math.max(1, fromSeq);
5054
- const { tail } = await this.withResumeIndex(sessionId, () => this.readTransaction(async (tx) => {
5055
- const source = await this.resumeSource(tx, sessionId);
5544
+ return this.withResumeIndex(sessionId, async (tx, source) => {
5056
5545
  const stateSeqs = stateSeqsBefore(source.index, start);
5057
5546
  if (hasHistoryLoadObserver()) announceHistoryLoad(stateSeqs.length + Math.max(0, source.index.seq - start + 1));
5058
5547
  const [state, rows] = await Promise.all([this.readSeqs(tx, sessionId, stateSeqs), this.readRows(tx, sessionId, { from: start })]);
5059
5548
  const entries = rows.map(({ entry }) => entry);
5060
- return {
5061
- tail: sessionTailFrom(source.index, source.header, start, state, entries),
5062
- source
5063
- };
5064
- }, [this.resumeRow(sessionId)]));
5065
- return tail;
5549
+ return sessionTailFrom(source.index, source.header, start, state, entries);
5550
+ });
5066
5551
  }
5067
5552
  async readRange(sessionId, startSeq, endSeq, expectedEpoch) {
5068
5553
  this.assertOpen();
5069
5554
  validateSessionText("sessionId", sessionId);
5070
5555
  const start = Math.max(1, startSeq);
5071
- return this.readTransaction(async (tx) => {
5556
+ return this.readTransaction(sessionId, async (tx) => {
5072
5557
  const head = await this.historyHead(tx, sessionId, true);
5073
5558
  if (expectedEpoch !== void 0 && expectedEpoch !== head.epoch) throw new SessionConflictError$1(sessionId, endSeq, head.lastSeq);
5074
5559
  const entries = endSeq < start ? [] : await this.readRows(tx, sessionId, {
@@ -5084,15 +5569,22 @@ $grant$`);
5084
5569
  };
5085
5570
  });
5086
5571
  }
5572
+ /** The statement of {@link historyHead}, shared with leading reads. */
5573
+ historyHeadStatement(sessionId, readOnly, generation, segments) {
5574
+ return {
5575
+ sql: `SELECT last_seq, revision, ${generation.sql} AS epoch${this.forkedColumn(segments)} FROM ${this.tables.sessions} WHERE id = ?${readOnly ? "" : this.dialect.lockClause("share")}`,
5576
+ params: [...generation.params, sessionId]
5577
+ };
5578
+ }
5087
5579
  /**
5088
5580
  * The session's watermark and generation; with `segments`, the fork segments table of a database with shared
5089
5581
  * history, also whether the session has segments (#6560), in the same statement: a read that leaves a session without
5090
5582
  * them to its tables' own keyed lookups costs no read of its own to learn it.
5091
5583
  */
5092
- async historyHead(tx, sessionId, readOnly = false) {
5093
- const generation = this.generation(sessionId);
5584
+ async historyHead(tx, sessionId, readOnly = false, generation = this.generation(sessionId)) {
5094
5585
  const { segments } = await this.viewTables(tx);
5095
- 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);
5586
+ const statement = this.historyHeadStatement(sessionId, readOnly, generation, segments);
5587
+ const row = await tx.get(statement.sql, ...statement.params);
5096
5588
  if (!row) throw new SessionNotFoundError$1(sessionId);
5097
5589
  this.noteGeneration(sessionId, row.revision, Number(row.last_seq), row.epoch);
5098
5590
  this.noteForked(tx, sessionId, row.forked);
@@ -5140,7 +5632,7 @@ $grant$`);
5140
5632
  const { childDisplayCut } = await import("../core/storage/session/card-view.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
5141
5633
  const { index } = await this.prepareResume(sessionId);
5142
5634
  if (typeof launch.launchLeafId !== "string") return childDisplayCut(index, launch);
5143
- return this.readTransaction(async (tx) => {
5635
+ return this.readTransaction(sessionId, async (tx) => {
5144
5636
  const head = await this.historyHead(tx, sessionId, true);
5145
5637
  if (head.epoch !== index.epoch || head.lastSeq < index.seq) throw new SessionConflictError$1(sessionId, index.seq, head.lastSeq);
5146
5638
  const view = forkView(await this.viewTables(tx, sessionId), {
@@ -5195,7 +5687,7 @@ $grant$`);
5195
5687
  * timestamp; its caller streams those fields instead of joining or decoding the stored body. */
5196
5688
  async readTreeOutline(sessionId, fromSeq, toSeq, epoch) {
5197
5689
  this.assertOpen();
5198
- return this.readTransaction(async (tx) => {
5690
+ return this.readTransaction(sessionId, async (tx) => {
5199
5691
  const head = await this.historyHead(tx, sessionId, true);
5200
5692
  if (epoch !== void 0 && head.epoch !== epoch || head.lastSeq < toSeq) throw new SessionConflictError$1(sessionId, toSeq, head.lastSeq);
5201
5693
  const sqlite = this.dialect.name === "sqlite";
@@ -5240,12 +5732,12 @@ $grant$`);
5240
5732
  const limit = entrySizeLimit(options.limit);
5241
5733
  const wanted = options.backward ? seqs.slice(-limit) : seqs.slice(0, limit);
5242
5734
  if (!wanted.length) return { items: [] };
5243
- return this.readTransaction(async (tx) => {
5735
+ return this.readTransaction(sessionId, async (tx) => {
5244
5736
  const head = await this.historyHead(tx, sessionId, true);
5245
5737
  if (head.epoch !== epoch || head.lastSeq < wanted.at(-1)) throw new SessionConflictError$1(sessionId, wanted.at(-1), head.lastSeq);
5246
5738
  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)`;
5247
5739
  const view = this.entriesView(await this.viewTables(tx, sessionId), sessionId, Math.min(...wanted) - 1, Math.max(...wanted));
5248
- 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 seq IN (${wanted.map(() => "?").join(",")}) ORDER BY seq`), ...view.params, SESSION_ENTRY_CHUNK_BYTES, sessionId, ...wanted);
5740
+ 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));
5249
5741
  const sizes = new Map(rows.map((row) => [Number(row.seq), row.bytes == null ? void 0 : Number(row.bytes)]));
5250
5742
  const plan = selectedPagePlan(sessionId, wanted, head.lastSeq, (seq) => {
5251
5743
  const bytes = sizes.get(seq);
@@ -5279,8 +5771,9 @@ $grant$`);
5279
5771
  async readEntrySizes(sessionId, startSeq, endSeq, limit) {
5280
5772
  this.assertOpen();
5281
5773
  validateSessionText("sessionId", sessionId);
5282
- return this.readTransaction(async (tx) => {
5283
- const head = await this.historyHead(tx, sessionId, true);
5774
+ let generation = this.generation(sessionId);
5775
+ return this.readTransaction(sessionId, async (tx) => {
5776
+ const head = await this.historyHead(tx, sessionId, true, generation);
5284
5777
  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)`;
5285
5778
  const tables = await this.viewTables(tx, sessionId);
5286
5779
  const after = Math.max(1, startSeq) - 1;
@@ -5297,6 +5790,9 @@ $grant$`);
5297
5790
  };
5298
5791
  })
5299
5792
  };
5793
+ }, () => {
5794
+ generation = this.generation(sessionId);
5795
+ return [this.historyHeadStatement(sessionId, true, generation, this.sharedHistorySeen ? this.forkTables.forkSegments : void 0)];
5300
5796
  });
5301
5797
  }
5302
5798
  /**
@@ -5444,7 +5940,7 @@ $grant$`);
5444
5940
  }
5445
5941
  /**
5446
5942
  * A condition on an entries row that holds for every entry `select` selects (and more): an entry larger than a page;
5447
- * on SQLite and libSQL, a message whose stored type and role say it is a tool result, or an assistant message with a
5943
+ * on SQLite, a message whose stored type and role say it is a tool result, or an assistant message with a
5448
5944
  * tool call named other than `exceptCalls`, and any row that is not valid JSON; on Postgres, which would parse each
5449
5945
  * row's JSON to read those, any row whose JSON holds a tool call block's `"toolCall"` or a result's `"toolResult"`,
5450
5946
  * which `JSON.stringify`, the only writer of a row, always writes as such (it never escapes a letter).
@@ -5501,8 +5997,31 @@ $grant$`);
5501
5997
  this.assertOpen();
5502
5998
  validateSessionText("sessionId", sessionId);
5503
5999
  validateSessionText("entry.id", entryId);
5504
- if (!await this.readHeader(sessionId)) throw new SessionNotFoundError$1(sessionId);
5505
- return this.seqOfEntry(this.database, void 0, sessionId, entryId);
6000
+ for (let attempt = 0; attempt < 2; attempt++) {
6001
+ const guessedShared = this.sharedHistorySeen;
6002
+ const guessedPlain = attempt === 0 && guessedShared && this.forkedSessions.get(sessionId) === false;
6003
+ const viewTables = {
6004
+ segments: guessedShared && !guessedPlain ? this.forkTables.forkSegments : void 0,
6005
+ dialect: this.dialect
6006
+ };
6007
+ const forked = this.forkedColumn(guessedShared ? this.forkTables.forkSegments : void 0, "s.id");
6008
+ const lookup = this.entrySeqStatement(viewTables, sessionId, entryId, {
6009
+ requireSession: true,
6010
+ forked
6011
+ });
6012
+ const { actualShared, row } = await this.readChecked(lookup, async (tx) => {
6013
+ return {
6014
+ actualShared: await this.sharedHistoryForks(tx),
6015
+ row: await tx.get(lookup.sql, ...lookup.params)
6016
+ };
6017
+ });
6018
+ if (!row) throw new SessionNotFoundError$1(sessionId);
6019
+ this.noteForked(void 0, sessionId, row.forked);
6020
+ if (actualShared !== guessedShared) continue;
6021
+ if (guessedPlain && Number(row.forked) === 1) continue;
6022
+ return row.seq == null ? void 0 : Number(row.seq);
6023
+ }
6024
+ throw new SessionNotFoundError$1(sessionId);
5506
6025
  }
5507
6026
  /**
5508
6027
  * Earlier entries that may save the same task reference as each candidate (#5593), in one statement on the session
@@ -5513,7 +6032,7 @@ $grant$`);
5513
6032
  this.assertOpen();
5514
6033
  validateSessionText("sessionId", sessionId);
5515
6034
  const { candidates, afterSeq, limit } = taskReferenceDuplicateQuery(query);
5516
- return this.readTransaction(async (tx) => {
6035
+ return this.readTransaction(sessionId, async (tx) => {
5517
6036
  const tables = await this.viewTables(tx, sessionId);
5518
6037
  const head = await this.historyHead(tx, sessionId, true);
5519
6038
  if (head.epoch !== query.epoch || head.lastSeq < query.throughSeq) throw new SessionConflictError$1(sessionId, query.throughSeq, head.lastSeq);
@@ -5585,25 +6104,34 @@ $grant$`);
5585
6104
  this.assertOpen();
5586
6105
  validateSessionText("sessionId", sessionId);
5587
6106
  const { indexedForkWindow, forkMetadata, byteMetadata, locateFork } = await import("../core/storage/session/fork-window.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
5588
- return this.readTransaction(async (tx) => {
5589
- const snapshots = snapshotIndexTables$1(this.prefix);
6107
+ const snapshots = snapshotIndexTables$1(this.prefix);
6108
+ const headStatement = (sharedSegments, leafTables) => {
6109
+ const leafViews = [snapshots.sessionLinks, this.tables.entries].map((table, index) => forkView(leafTables, {
6110
+ name: `leaf_${index}`,
6111
+ table,
6112
+ columns: ["entry_id"],
6113
+ sessionId,
6114
+ after: 0,
6115
+ through: FORK_VIEW_END,
6116
+ match: {
6117
+ column: "entry_id",
6118
+ value: entryId
6119
+ }
6120
+ }));
6121
+ return {
6122
+ sql: 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(sharedSegments, "s.id")} FROM ${this.tables.sessions} s WHERE s.id=?`),
6123
+ params: [...forkViewParams(leafViews), sessionId]
6124
+ };
6125
+ };
6126
+ let guessedSharedSegments;
6127
+ let guessedPlain = false;
6128
+ return this.readTransaction(sessionId, async (tx) => {
5590
6129
  const shared = await this.viewTables(tx);
5591
6130
  const headRead = (leafTables) => {
5592
- const leafViews = [snapshots.sessionLinks, this.tables.entries].map((table, index) => forkView(leafTables, {
5593
- name: `leaf_${index}`,
5594
- table,
5595
- columns: ["entry_id"],
5596
- sessionId,
5597
- after: 0,
5598
- through: FORK_VIEW_END,
5599
- match: {
5600
- column: "entry_id",
5601
- value: entryId
5602
- }
5603
- }));
5604
- 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);
6131
+ const statement = headStatement(shared.segments, leafTables);
6132
+ return tx.get(statement.sql, ...statement.params);
5605
6133
  };
5606
- const guessPlain = shared.segments !== void 0 && this.forkedSessions.get(sessionId) === false;
6134
+ const guessPlain = shared.segments !== void 0 && (shared.segments === guessedSharedSegments ? guessedPlain : this.forkedSessions.get(sessionId) === false);
5607
6135
  let row = await headRead(guessPlain ? {
5608
6136
  ...shared,
5609
6137
  segments: void 0
@@ -5626,7 +6154,7 @@ $grant$`);
5626
6154
  const raw = this.dialect.name === "sqlite" ? "CAST(entry_json AS BLOB)" : "convert_to(entry_json,'UTF8')";
5627
6155
  const size = this.dialect.textByteLength("entry_json");
5628
6156
  const view = this.entriesView(tables, sessionId, Math.min(...seqs) - 1, Math.max(...seqs));
5629
- 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 seq IN (${seqs.map(() => "?").join(",")}) ORDER BY seq`), ...view.params, sessionId, ...seqs);
6157
+ 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));
5630
6158
  for (const row of rows) {
5631
6159
  const seq = Number(row.seq);
5632
6160
  if (row.body !== null) result.push(forkMetadata(seq, JSON.parse(row.body)));
@@ -5643,6 +6171,7 @@ $grant$`);
5643
6171
  return result;
5644
6172
  };
5645
6173
  const j = (field) => this.dialect.jsonText("entry_json", field);
6174
+ const dialect = this.dialect;
5646
6175
  const scanWindow = (from, through) => {
5647
6176
  const end = tables.segments === void 0 ? through : Math.min(through, from - 1 + SCAN_SELECT_WINDOW);
5648
6177
  return {
@@ -5692,7 +6221,7 @@ $grant$`);
5692
6221
  for (let i = 0; i < chunkedMessages.length; i += SEQ_BATCH) {
5693
6222
  const batch = chunkedMessages.slice(i, i + SEQ_BATCH);
5694
6223
  const view = this.entriesView(tables, sessionId, Math.min(...batch) - 1, Math.max(...batch));
5695
- 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 v.seq IN (${batch.map(() => "?").join(",")})`), ...view.params, ...batch);
6224
+ 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));
5696
6225
  for (const row of prefixes) roles.set(Number(row.seq), messageRoleIn(row.prefix));
5697
6226
  }
5698
6227
  }
@@ -5725,13 +6254,13 @@ $grant$`);
5725
6254
  through: hi
5726
6255
  }, void 0, generation), (seqs) => this.readSeqs(tx, sessionId, seqs, generation), metadata, async function* (ranges, kinds, types = []) {
5727
6256
  const filters = [];
5728
- if (types.length) filters.push(`${j("type")} IN (${types.map(() => "?").join(",")})`);
5729
- if (kinds.length) filters.push(`(${j("type")}='custom' AND (chunks>0 OR ${j("customType")} IN (${kinds.map(() => "?").join(",")})))`);
6257
+ if (types.length) filters.push(inJsonList(dialect, j("type")));
6258
+ if (kinds.length) filters.push(`(${j("type")}='custom' AND (chunks>0 OR ${inJsonList(dialect, j("customType"))}))`);
5730
6259
  for (const [lo, hi] of ranges) for (let seq = lo; seq <= hi;) {
5731
6260
  const labels = types.length === 1 && types[0] === "label";
5732
6261
  const limit = labels ? SESSION_READ_FETCH.first : SESSION_READ_FETCH.max;
5733
6262
  const { end, view } = scanWindow(seq, hi);
5734
- 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, ...kinds);
6263
+ 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)] : []);
5735
6264
  const deferred = rows.filter((r) => r.kind === "custom" || r.kind === "label" && !r.body).map((r) => Number(r.seq));
5736
6265
  const projected = /* @__PURE__ */ new Map();
5737
6266
  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);
@@ -5748,6 +6277,14 @@ $grant$`);
5748
6277
  ...selected.extras,
5749
6278
  ...options
5750
6279
  });
6280
+ }, () => {
6281
+ guessedSharedSegments = this.sharedHistorySeen ? this.forkTables.forkSegments : void 0;
6282
+ guessedPlain = guessedSharedSegments !== void 0 && this.forkedSessions.get(sessionId) === false;
6283
+ const guessedLeafTables = {
6284
+ segments: guessedPlain ? void 0 : guessedSharedSegments,
6285
+ dialect: this.dialect
6286
+ };
6287
+ return [headStatement(guessedSharedSegments, guessedLeafTables)];
5751
6288
  });
5752
6289
  }
5753
6290
  async *forkEntryChunks(tx, tables, id, seq, count) {
@@ -5772,27 +6309,10 @@ $grant$`);
5772
6309
  this.assertOpen();
5773
6310
  validateSessionText("sessionId", sessionId);
5774
6311
  if (leafId !== void 0) validateSessionText("entry.id", leafId);
5775
- if (leafId === void 0 && throughSeq === void 0) try {
5776
- return await this.readTransaction(async (tx) => {
5777
- const { header, index } = await this.resumeSource(tx, sessionId);
5778
- return this.resumeIn(tx, sessionId, header, index, options);
5779
- }, [this.resumeRow(sessionId)]);
5780
- } catch (error) {
5781
- if (!(error instanceof SessionConflictError$1)) throw error;
5782
- }
5783
- for (let attempt = 0; attempt < 3; attempt++) {
5784
- const { index, revision } = await this.prepareResume(sessionId, leafId, throughSeq);
5785
- const resume = await this.readTransaction(async (tx) => {
5786
- const { segments } = await this.viewTables(tx);
5787
- const head = await tx.get(`SELECT header_json,revision${this.forkedColumn(segments)} FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
5788
- if (!head) throw new SessionNotFoundError$1(sessionId);
5789
- this.noteForked(tx, sessionId, head.forked);
5790
- if (revision !== head.revision) return void 0;
5791
- return this.resumeIn(tx, sessionId, JSON.parse(head.header_json), index, options);
5792
- });
5793
- if (resume !== void 0) return resume;
5794
- }
5795
- throw new SessionConflictError$1(sessionId, 0, 0);
6312
+ return this.withResumeIndex(sessionId, (tx, { header, index }) => this.resumeIn(tx, sessionId, header, index, options), leafId === void 0 && throughSeq === void 0 ? void 0 : {
6313
+ leafId,
6314
+ throughSeq
6315
+ });
5796
6316
  }
5797
6317
  /** The resume of `index`, the session's index as of the snapshot of `tx`, with `header`. */
5798
6318
  async resumeIn(tx, sessionId, header, index, options) {
@@ -5816,31 +6336,20 @@ $grant$`);
5816
6336
  this.assertOpen();
5817
6337
  validateSessionText("sessionId", sessionId);
5818
6338
  if (leafId !== void 0) validateSessionText("entry.id", leafId);
5819
- const { point } = await this.withResumeIndex(sessionId, () => this.readTransaction(async (tx) => {
5820
- const source = await this.resumeSource(tx, sessionId);
6339
+ return this.withResumeIndex(sessionId, async (tx, source) => {
5821
6340
  const { index } = source;
5822
6341
  const leafSeq = leafId === void 0 ? index.leafSeq : await this.seqOfEntry(tx, await this.viewTables(tx, sessionId), sessionId, leafId) ?? -1;
5823
6342
  const found = latestCompactionOf(index, leafSeq);
5824
- if (found === void 0) return {
5825
- point: void 0,
5826
- source
5827
- };
6343
+ if (found === void 0) return void 0;
5828
6344
  const [[boundary], leaf] = await Promise.all([this.readSeqs(tx, sessionId, [found.seq]), this.entryIdAt(tx, sessionId, leafSeq)]);
5829
- if (boundary === void 0 || leaf === void 0) return {
5830
- point: void 0,
5831
- source
5832
- };
6345
+ if (boundary === void 0 || leaf === void 0) return void 0;
5833
6346
  return {
5834
- point: {
5835
- ...found,
5836
- entry: boundary.entry,
5837
- leafId: leaf.entry_id,
5838
- lastSeq: index.seq
5839
- },
5840
- source
6347
+ ...found,
6348
+ entry: boundary.entry,
6349
+ leafId: leaf.entry_id,
6350
+ lastSeq: index.seq
5841
6351
  };
5842
- }, [this.resumeRow(sessionId)]));
5843
- return point;
6352
+ });
5844
6353
  }
5845
6354
  /** The ID of the entry at view seq `seq` of session `sessionId`, read in transaction `tx` (#6560). */
5846
6355
  async entryIdAt(tx, sessionId, seq) {
@@ -5946,41 +6455,62 @@ $grant$`);
5946
6455
  return foldSessionResume(previous, entries, (id) => seqs.get(id));
5947
6456
  }
5948
6457
  /**
6458
+ * Single-statement lookup of the latest seq of `entryId` in session `sessionId` through `viewTables`: checks
6459
+ * whether `snapshot_index_sources` has a complete `'session-entries'` backfill in the same snapshot and reads
6460
+ * `sessionLinks` when complete or `entries` otherwise. With `requireSession`, anchors the row on `sessions` so a
6461
+ * missing session returns no row.
6462
+ */
6463
+ entrySeqStatement(viewTables, sessionId, entryId, options = {}) {
6464
+ const index = snapshotIndexTables$1(this.prefix);
6465
+ const linked = forkView(viewTables, {
6466
+ name: "linked",
6467
+ table: index.sessionLinks,
6468
+ columns: ["entry_id"],
6469
+ sessionId,
6470
+ after: 0,
6471
+ through: FORK_VIEW_END,
6472
+ match: {
6473
+ column: "entry_id",
6474
+ value: entryId
6475
+ }
6476
+ });
6477
+ const entries = forkView(viewTables, {
6478
+ name: "entries",
6479
+ table: this.tables.entries,
6480
+ columns: ["entry_id"],
6481
+ sessionId,
6482
+ after: 0,
6483
+ through: FORK_VIEW_END,
6484
+ match: {
6485
+ column: "entry_id",
6486
+ value: entryId
6487
+ }
6488
+ });
6489
+ const seqExpr = `CASE WHEN EXISTS (SELECT 1 FROM ${index.sources} WHERE source = 'session-entries' AND backfilled_through >= watermark) THEN (SELECT seq FROM linked ORDER BY seq DESC LIMIT 1) ELSE (SELECT seq FROM entries ORDER BY seq DESC LIMIT 1) END`;
6490
+ const forked = options.forked ?? "";
6491
+ if (options.requireSession === true) return {
6492
+ sql: withForkViews([linked, entries], `SELECT 1 AS present, ${seqExpr} AS seq${forked} FROM ${this.tables.sessions} s WHERE s.id = ?`),
6493
+ params: [...forkViewParams([linked, entries]), sessionId]
6494
+ };
6495
+ return {
6496
+ sql: withForkViews([linked, entries], `SELECT ${seqExpr} AS seq${forked}`),
6497
+ params: [...forkViewParams([linked, entries]), ...forked === "" ? [] : [sessionId]]
6498
+ };
6499
+ }
6500
+ /**
5949
6501
  * The latest seq of session `sessionId` that holds entry `entryId`, through its view (#6560): in transaction
5950
6502
  * `executor` with `tables`, or, with `tables` undefined, outside a transaction through `outsideTransaction`. A fork's
5951
6503
  * inherited entries are linked under the sessions that store them, at their seqs there, which the view renumbers.
5952
6504
  */
5953
6505
  async seqOfEntry(executor, tables, sessionId, entryId) {
5954
- const index = snapshotIndexTables$1(this.prefix);
5955
- 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'`);
5956
- const table = Number(source?.complete) === 1 ? index.sessionLinks : this.tables.entries;
5957
6506
  const read = (viewTables, forked = "") => {
5958
- const view = forkView(viewTables, {
5959
- name: "linked",
5960
- table,
5961
- columns: ["entry_id"],
5962
- sessionId,
5963
- after: 0,
5964
- through: FORK_VIEW_END,
5965
- match: {
5966
- column: "entry_id",
5967
- value: entryId
5968
- }
5969
- });
5970
- return executor.get(withForkViews([view], `SELECT (SELECT seq FROM linked ORDER BY seq DESC LIMIT 1) AS seq${forked}`), ...view.params, ...forked === "" ? [] : [sessionId]);
6507
+ const statement = this.entrySeqStatement(viewTables, sessionId, entryId, { forked });
6508
+ return executor.get(statement.sql, ...statement.params);
5971
6509
  };
5972
6510
  const row = tables === void 0 ? await this.outsideSessionRead(sessionId, (viewTables) => read(viewTables, this.outsideForkedColumn("?")), (found) => found?.seq != null, (found) => found?.forked) : await read(tables);
5973
6511
  return row?.seq == null ? void 0 : Number(row.seq);
5974
6512
  }
5975
- async saveSummary(tx, sessionId, snapshot, previous, appendedResume) {
5976
- const { statement, texts, epoch } = this.summaryWrite(sessionId, snapshot, previous, appendedResume);
5977
- await tx.run(statement.sql, ...statement.params);
5978
- return {
5979
- texts,
5980
- epoch
5981
- };
5982
- }
5983
- /** The statement that saves the session's row as `saveSummary` saves it, with what `saveSummary` returns. */
6513
+ /** The statement that saves the session's row, with the search texts of `snapshot`'s entries and its generation. */
5984
6514
  summaryWrite(sessionId, snapshot, previous, appendedResume) {
5985
6515
  const { header, lastSeq } = snapshot;
5986
6516
  const { state: listed, texts } = applySessionSummaryEntries(previous, snapshot.entries);
@@ -6171,6 +6701,37 @@ $grant$`);
6171
6701
  const writes = new SentWrites(tx);
6172
6702
  await writes.around(() => writes.send(whole ? batch : withRest(batch, pending)));
6173
6703
  }
6704
+ /**
6705
+ * The deletes of session `sessionId`'s rows in `before` (the tables of rows only `delete` removes), then in its search
6706
+ * texts, entry chunks and entries, in that order: what a delete or a replace removes ahead of the session's row.
6707
+ */
6708
+ sessionRowDeletes(sessionId, before = []) {
6709
+ return [
6710
+ ...before,
6711
+ this.tables.searchTexts,
6712
+ this.tables.entryChunks,
6713
+ this.tables.entries
6714
+ ].map((table) => ({
6715
+ sql: `DELETE FROM ${table} WHERE session_id = ?`,
6716
+ params: [sessionId]
6717
+ }));
6718
+ }
6719
+ /** The delete of session `sessionId`'s row. */
6720
+ sessionRowDelete(sessionId) {
6721
+ return {
6722
+ sql: `DELETE FROM ${this.tables.sessions} WHERE id = ?`,
6723
+ params: [sessionId]
6724
+ };
6725
+ }
6726
+ /**
6727
+ * Runs `statements` as the last calls of transaction `tx`: where its connection is pipelined, they go out with the
6728
+ * commit, in one round trip, and commit together or, when one fails, not at all; on a connection thread, as one
6729
+ * request; otherwise one after another. The first that fails ends them with its failure.
6730
+ */
6731
+ async finishWrites(tx, statements) {
6732
+ if (transactionFinisher(tx)?.(statements) === true) return;
6733
+ await statementBatch(tx, statements, []);
6734
+ }
6174
6735
  encode(value) {
6175
6736
  try {
6176
6737
  return JSON.stringify(value);
@@ -12769,16 +13330,16 @@ var ThemeSelectorComponent = class extends FramedSelector {
12769
13330
  * update without an ESM missing-export error.
12770
13331
  */
12771
13332
  const COMPACTOR_COMPRESSION_RATIO = .5;
12772
- 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, 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 };
13333
+ 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 };
12773
13334
 
12774
- //# sourceMappingURL=sdk-IQMULKFU.js.map
13335
+ //# sourceMappingURL=sdk-B5LEWGGI.js.map
12775
13336
  // __atomicOnDemandFailed: written by the build (scripts/in-place-update-gate.mjs). An import of this release's code on
12776
13337
  // demand that fails in a process an in-place update left running says to restart.
12777
13338
  function __atomicOnDemandFailed(error, feature) {
12778
13339
  return (async () => {
12779
13340
  const root = new URL("../", import.meta.url);
12780
13341
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
12781
- const key = `${root.href}#0.10.11-alpha.2`;
13342
+ const key = `${root.href}#0.10.11`;
12782
13343
  let release = releases.get(key);
12783
13344
  if (release === undefined) {
12784
13345
  const current = (async () => {
@@ -12806,7 +13367,7 @@ function __atomicOnDemandFailed(error, feature) {
12806
13367
  } catch {
12807
13368
  // No installation to read, as in a bundle of the package: the release the process runs decides.
12808
13369
  }
12809
- const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.2" ? installed : running !== undefined && running.version !== "0.10.11-alpha.2" ? "0.10.11-alpha.2" : undefined;
13370
+ const updatedTo = typeof installed === "string" && installed !== "0.10.11" ? installed : running !== undefined && running.version !== "0.10.11" ? "0.10.11" : undefined;
12810
13371
  if (updatedTo === undefined) throw error;
12811
13372
  const application = typeof running?.name === "string" ? running.name : "atomic";
12812
13373
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {