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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (432) hide show
  1. package/CHANGELOG.md +99 -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} +14 -2
  14. package/dist/_shared/{p1b-elig-ENCUPKKJ.js.map → p1b-elig-TVB5CBLL.js.map} +1 -1
  15. package/dist/_shared/runtime-O4KCSG4C.js +3 -3
  16. package/dist/_shared/{sdk-IQMULKFU.js → sdk-B5LEWGGI.js} +340 -163
  17. package/dist/_shared/sdk-B5LEWGGI.js.map +1 -0
  18. package/dist/_shared/session-data-AHTU7IS6.js +2 -2
  19. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  20. package/dist/_shared/{startup-0-0-3IXNMFM2.js → startup-0-0-EZUKEP4Q.js} +48 -40
  21. package/dist/_shared/startup-0-0-EZUKEP4Q.js.map +1 -0
  22. package/dist/_shared/{startup-0-1-7T2IAE7J.js → startup-0-1-RTOHJFDJ.js} +195 -42
  23. package/dist/_shared/startup-0-1-RTOHJFDJ.js.map +1 -0
  24. package/dist/_shared/startup-0-2-5QHPCEON.js +33 -43
  25. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -1
  26. package/dist/_shared/startup-0-3-4ZYBYQNM.js +5 -5
  27. package/dist/_shared/startup-0-4-ZMJV547D.js +12 -7
  28. package/dist/_shared/startup-0-4-ZMJV547D.js.map +1 -1
  29. package/dist/_shared/startup-0-5-YDW47QX6.js +7 -7
  30. package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -1
  31. package/dist/_shared/startup-10-0-TDQNBDDL.js +6 -6
  32. package/dist/_shared/startup-12-0-55AAXBJZ.js +2 -2
  33. package/dist/_shared/startup-14-0-MLX36RBG.js +4 -5
  34. package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
  35. package/dist/_shared/startup-15-0-YUKGAC63.js +4 -4
  36. package/dist/_shared/startup-15-1-4S7FLMNG.js +19 -27
  37. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  38. package/dist/_shared/startup-8-0-34CBHPZH.js +39 -23
  39. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  40. package/dist/_shared/{startup-8-1-X32CYSXB.js → startup-8-1-LZFXSD3Z.js} +90 -1176
  41. package/dist/_shared/startup-8-1-LZFXSD3Z.js.map +1 -0
  42. package/dist/_shared/storage-command-7MGXLJGZ.js +186 -35
  43. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  44. package/dist/_shared/storage-status-K7PX2RXA.js +557 -0
  45. package/dist/_shared/storage-status-K7PX2RXA.js.map +1 -0
  46. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  47. package/dist/_shared/team-DOQKICG2.js +376 -0
  48. package/dist/_shared/team-DOQKICG2.js.map +1 -0
  49. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  50. package/dist/builtin/intercom/CHANGELOG.md +23 -0
  51. package/dist/builtin/intercom/README.md +2 -2
  52. package/dist/builtin/intercom/broker/broker.bundle.mjs +913 -289
  53. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +243 -64
  54. package/dist/builtin/intercom/broker/multinode-router.ts +154 -22
  55. package/dist/builtin/intercom/broker/multinode-state-store.ts +30 -3
  56. package/dist/builtin/intercom/broker/open-broker-state.ts +14 -0
  57. package/dist/builtin/intercom/broker/sql-add-column.ts +29 -5
  58. package/dist/builtin/intercom/broker/sql-ended-child-queue-store.ts +3 -2
  59. package/dist/builtin/intercom/broker/sql-held-send-store.ts +2 -2
  60. package/dist/builtin/intercom/broker/sql-known-session-store.ts +43 -19
  61. package/dist/builtin/intercom/broker/sql-lease-store.ts +170 -74
  62. package/dist/builtin/intercom/broker/sql-outbox-store.ts +298 -47
  63. package/dist/builtin/intercom/broker/sql-pending-ask-store.ts +8 -5
  64. package/dist/builtin/intercom/broker/sql-released-ask-store.ts +12 -5
  65. package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +24 -7
  66. package/dist/builtin/intercom/broker/sql-retention.ts +141 -0
  67. package/dist/builtin/intercom/broker/sql-schema.ts +136 -19
  68. package/dist/builtin/intercom/broker/sql-sent-message-authority.ts +74 -19
  69. package/dist/builtin/intercom/broker/wake-up-bus.ts +6 -0
  70. package/dist/builtin/intercom/index.bundle.mjs +2 -3
  71. package/dist/builtin/intercom/package.json +1 -1
  72. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  73. package/dist/builtin/mcp/package.json +1 -1
  74. package/dist/builtin/subagents/package.json +1 -1
  75. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  76. package/dist/builtin/web-access/index.bundle.mjs +2 -10
  77. package/dist/builtin/web-access/package.json +1 -1
  78. package/dist/bun/bundled-sqlite.js +41 -0
  79. package/dist/bun/bundled-sqlite.js.map +1 -0
  80. package/dist/cli/args.js +2 -2
  81. package/dist/cli/auth-cli.code.js +4 -4
  82. package/dist/cli/auth-cli.impl.js +3 -3
  83. package/dist/cli/auth-cli.js +3 -3
  84. package/dist/cli/blueprint-command.code.js +3 -3
  85. package/dist/cli/blueprint-command.impl.js +3 -3
  86. package/dist/cli/blueprint-command.js +3 -3
  87. package/dist/cli/intercom-command.code.js +3 -3
  88. package/dist/cli/intercom-command.code.js.map +1 -1
  89. package/dist/cli/intercom-command.impl.js +3 -3
  90. package/dist/cli/intercom-command.js +3 -3
  91. package/dist/cli/list-models.code.js +2 -2
  92. package/dist/cli/list-models.impl.js +3 -3
  93. package/dist/cli/list-models.js +3 -3
  94. package/dist/cli/session-picker.code.js +1 -1
  95. package/dist/cli/session-picker.impl.js +3 -3
  96. package/dist/cli/session-picker.js +3 -3
  97. package/dist/cli/startup-ui.code.js +1 -1
  98. package/dist/cli/startup-ui.impl.js +3 -3
  99. package/dist/cli/startup-ui.js +3 -3
  100. package/dist/cli/storage-command.impl.js +3 -3
  101. package/dist/cli/storage-command.js +3 -3
  102. package/dist/cli/storage-search-session.code.js +3 -3
  103. package/dist/cli/storage-search-session.impl.js +3 -3
  104. package/dist/cli/storage-search-session.js +3 -3
  105. package/dist/cli/team-command.code.js +19 -113
  106. package/dist/cli/team-command.code.js.map +1 -1
  107. package/dist/cli/team-command.impl.js +3 -3
  108. package/dist/cli/team-command.js +3 -3
  109. package/dist/cli.js +5 -18
  110. package/dist/cli.js.map +1 -1
  111. package/dist/core/agent-rehydrate-errors.d.ts +4 -9
  112. package/dist/core/compaction/compactor.d.ts +3 -3
  113. package/dist/core/debug.code.js +1 -1
  114. package/dist/core/debug.impl.js +3 -3
  115. package/dist/core/debug.js +3 -3
  116. package/dist/core/export-html/card-projection.impl.js +3 -3
  117. package/dist/core/export-html/card-projection.js +3 -3
  118. package/dist/core/export-html/index.code.js +2 -2
  119. package/dist/core/export-html/index.impl.js +3 -3
  120. package/dist/core/export-html/index.js +3 -3
  121. package/dist/core/export-html/json-spans.impl.js +3 -3
  122. package/dist/core/export-html/json-spans.js +3 -3
  123. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  124. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  125. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  126. package/dist/core/export-html/tool-renderer.js +3 -3
  127. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  128. package/dist/core/extensions/jiti-loader.js +3 -3
  129. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  130. package/dist/core/extensions/jiti-static-loader.js +3 -3
  131. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  132. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  133. package/dist/core/extensions/loader-host-modules.js +3 -3
  134. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  135. package/dist/core/extensions/runner-context.js +2 -2
  136. package/dist/core/intercom-broker-control-host.code.js +2 -2
  137. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  138. package/dist/core/intercom-broker-control-host.js +3 -3
  139. package/dist/core/intercom-broker-control.code.js +3 -3
  140. package/dist/core/intercom-broker-control.impl.js +3 -3
  141. package/dist/core/intercom-broker-control.js +3 -3
  142. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  143. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  144. package/dist/core/package-manager-storage-adapters.js +3 -3
  145. package/dist/core/process-start-token.d.ts +8 -0
  146. package/dist/core/process-tree-containment.d.ts +16 -0
  147. package/dist/core/sdk-types.d.ts +1 -2
  148. package/dist/core/sdk-types.js.map +1 -1
  149. package/dist/core/sdk.code.js +3 -3
  150. package/dist/core/sdk.impl.js +3 -3
  151. package/dist/core/sdk.js +3 -3
  152. package/dist/core/session-manager-core.js +5 -5
  153. package/dist/core/session-manager-list.impl.js +3 -3
  154. package/dist/core/session-manager-list.js +3 -3
  155. package/dist/core/session-manager.code.js +1 -1
  156. package/dist/core/session-manager.impl.js +3 -3
  157. package/dist/core/session-manager.js +3 -3
  158. package/dist/core/session-storage.code.js +1 -1
  159. package/dist/core/session-storage.impl.js +3 -3
  160. package/dist/core/session-storage.js +3 -3
  161. package/dist/core/settings-schema.d.ts +0 -3
  162. package/dist/core/storage/added-exports-0-10-11.js +19 -0
  163. package/dist/core/storage/added-exports-0-10-11.js.map +1 -0
  164. package/dist/core/storage/creation-time.js +105 -0
  165. package/dist/core/storage/creation-time.js.map +1 -0
  166. package/dist/core/storage/database.d.ts +19 -5
  167. package/dist/core/storage/database.js.map +1 -1
  168. package/dist/core/storage/dialect.d.ts +1 -1
  169. package/dist/core/storage/dialect.js +1 -1
  170. package/dist/core/storage/dialect.js.map +1 -1
  171. package/dist/core/storage/errors.d.ts +13 -13
  172. package/dist/core/storage/errors.js +10 -16
  173. package/dist/core/storage/errors.js.map +1 -1
  174. package/dist/core/storage/fenced-paths.d.ts +11 -0
  175. package/dist/core/storage/fenced-paths.js +11 -0
  176. package/dist/core/storage/fenced-paths.js.map +1 -1
  177. package/dist/core/storage/file-identity.d.ts +2 -0
  178. package/dist/core/storage/file-identity.js +24 -8
  179. package/dist/core/storage/file-identity.js.map +1 -1
  180. package/dist/core/storage/index.d.ts +3 -2
  181. package/dist/core/storage/index.js +5 -3
  182. package/dist/core/storage/index.js.map +1 -1
  183. package/dist/core/storage/libsql-removed.d.ts +71 -0
  184. package/dist/core/storage/libsql-removed.js +123 -0
  185. package/dist/core/storage/libsql-removed.js.map +1 -0
  186. package/dist/core/storage/migrations.d.ts +78 -14
  187. package/dist/core/storage/migrations.js +375 -49
  188. package/dist/core/storage/migrations.js.map +1 -1
  189. package/dist/core/storage/node-sqlite-file-gate.js +0 -15
  190. package/dist/core/storage/node-sqlite-file-gate.js.map +1 -1
  191. package/dist/core/storage/node-sqlite-thread.js +8 -13
  192. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  193. package/dist/core/storage/node-sqlite.js +51 -3
  194. package/dist/core/storage/node-sqlite.js.map +1 -1
  195. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  196. package/dist/core/storage/offline-snapshot-file.js +3 -3
  197. package/dist/core/storage/prefix.d.ts +1 -1
  198. package/dist/core/storage/prefix.js +9 -2
  199. package/dist/core/storage/prefix.js.map +1 -1
  200. package/dist/core/storage/process-selection.d.ts +5 -5
  201. package/dist/core/storage/provider.js +2 -2
  202. package/dist/core/storage/schema-catalog.d.ts +7 -8
  203. package/dist/core/storage/schema-catalog.js +8 -8
  204. package/dist/core/storage/schema-catalog.js.map +1 -1
  205. package/dist/core/storage/selection.d.ts +7 -82
  206. package/dist/core/storage/selection.js +20 -235
  207. package/dist/core/storage/selection.js.map +1 -1
  208. package/dist/core/storage/session/branch-fork-source.code.js +2 -2
  209. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  210. package/dist/core/storage/session/branch-fork-source.js +3 -3
  211. package/dist/core/storage/session/card-view.impl.js +3 -3
  212. package/dist/core/storage/session/card-view.js +3 -3
  213. package/dist/core/storage/session/child-reader.code.js +3 -3
  214. package/dist/core/storage/session/child-reader.impl.js +3 -3
  215. package/dist/core/storage/session/child-reader.js +3 -3
  216. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  217. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  218. package/dist/core/storage/session/expanded-child-details.code.js +2 -2
  219. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  220. package/dist/core/storage/session/expanded-child-details.js +3 -3
  221. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  222. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  223. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  224. package/dist/core/storage/session/fork-row-index.js +3 -3
  225. package/dist/core/storage/session/fork-staging.code.js +4 -7
  226. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  227. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  228. package/dist/core/storage/session/fork-staging.js +3 -3
  229. package/dist/core/storage/session/fork-window.code.js +3 -3
  230. package/dist/core/storage/session/fork-window.impl.js +3 -3
  231. package/dist/core/storage/session/fork-window.js +3 -3
  232. package/dist/core/storage/session/history-pages.impl.js +3 -3
  233. package/dist/core/storage/session/history-pages.js +3 -3
  234. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  235. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  236. package/dist/core/storage/session/jsonl-session-store.d.ts +5 -1
  237. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  238. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  239. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  240. package/dist/core/storage/session/memory-session-store.js +3 -3
  241. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  242. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  243. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  244. package/dist/core/storage/session/released-history-files.code.js +3 -3
  245. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  246. package/dist/core/storage/session/released-history-files.js +3 -3
  247. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  248. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  249. package/dist/core/storage/session/session-resume.impl.js +3 -3
  250. package/dist/core/storage/session/session-resume.js +3 -3
  251. package/dist/core/storage/session/session-search-index.d.ts +43 -4
  252. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  253. package/dist/core/storage/session/snapshot-cut.js +3 -3
  254. package/dist/core/storage/session/snapshot-history.code.js +3 -3
  255. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  256. package/dist/core/storage/session/snapshot-history.js +3 -3
  257. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  258. package/dist/core/storage/session/sql-session-store.d.ts +48 -11
  259. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  260. package/dist/core/storage/session/sql-session-store.js +3 -3
  261. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  262. package/dist/core/storage/session/tree-outline.js +3 -3
  263. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  264. package/dist/core/storage/session/tree-presentation.js +3 -3
  265. package/dist/core/storage/sqlite-facade.d.ts +6 -1
  266. package/dist/core/storage/sqlite-facade.js +1 -0
  267. package/dist/core/storage/sqlite-facade.js.map +1 -1
  268. package/dist/core/storage/storage-status.code.js +1 -1
  269. package/dist/core/storage/storage-status.impl.js +3 -3
  270. package/dist/core/storage/storage-status.js +3 -3
  271. package/dist/core/storage/team.code.js +1 -1
  272. package/dist/core/storage/team.d.ts +26 -115
  273. package/dist/core/storage/team.impl.js +3 -3
  274. package/dist/core/storage/team.js +3 -3
  275. package/dist/core/structured-output/index.code.js +1 -1
  276. package/dist/core/structured-output/index.impl.js +3 -3
  277. package/dist/core/structured-output/index.js +3 -3
  278. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  279. package/dist/core/tasks/task-completion-entry.js +3 -3
  280. package/dist/core/tasks/task-file-history.code.js +3 -3
  281. package/dist/core/tasks/task-file-history.impl.js +3 -3
  282. package/dist/core/tasks/task-file-history.js +3 -3
  283. package/dist/core/tasks/task-reference-archive.code.js +4 -4
  284. package/dist/core/tasks/task-reference-archive.js +3 -3
  285. package/dist/core/tasks/task-reference-identity.js +3 -3
  286. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  287. package/dist/core/tasks/task-reference-stream.js +3 -3
  288. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  289. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  290. package/dist/core/tasks/task-view-source.code.js +1 -1
  291. package/dist/core/tasks/task-view-source.impl.js +3 -3
  292. package/dist/core/tasks/task-view-source.js +3 -3
  293. package/dist/core/tools/history-tasks.d.ts +3 -2
  294. package/dist/core/tools/read-url.code.js +4 -4
  295. package/dist/core/tools/read-url.impl.js +3 -3
  296. package/dist/core/tools/read-url.js +3 -3
  297. package/dist/core/worktree-snapshot/blob-store.d.ts +40 -3
  298. package/dist/core/worktree-snapshot/blob-store.js +414 -21
  299. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  300. package/dist/core/worktree-snapshot/errors.code.js +2 -2
  301. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  302. package/dist/core/worktree-snapshot/errors.js +3 -3
  303. package/dist/core/worktree-snapshot/fork-blob-guard.js +81 -0
  304. package/dist/core/worktree-snapshot/fork-blob-guard.js.map +1 -0
  305. package/dist/core/worktree-snapshot/fork-snapshot-index.js +79 -38
  306. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -1
  307. package/dist/core/worktree-snapshot/session-index-reset.code.js +4 -0
  308. package/dist/core/worktree-snapshot/session-index-reset.code.js.map +1 -1
  309. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  310. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  311. package/dist/extensions/codemode/execute.code.js +1 -1
  312. package/dist/extensions/codemode/execute.impl.js +3 -3
  313. package/dist/extensions/codemode/execute.js +3 -3
  314. package/dist/extensions/codemode/renderer.code.js +2 -2
  315. package/dist/extensions/codemode/renderer.impl.js +3 -3
  316. package/dist/extensions/codemode/renderer.js +3 -3
  317. package/dist/extensions/mcp/cli.code.js +3 -3
  318. package/dist/extensions/mcp/cli.impl.js +3 -3
  319. package/dist/extensions/mcp/cli.js +3 -3
  320. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  321. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  322. package/dist/extensions/mcp/cli.lazy.js +3 -3
  323. package/dist/extensions/mcp/runtime.code.js +1 -1
  324. package/dist/extensions/mcp/runtime.impl.js +3 -3
  325. package/dist/extensions/mcp/runtime.js +3 -3
  326. package/dist/index.d.ts +3 -1
  327. package/dist/index.js +5 -5
  328. package/dist/main-first-time-setup.code.js +1 -1
  329. package/dist/main-first-time-setup.impl.js +3 -3
  330. package/dist/main-first-time-setup.js +3 -3
  331. package/dist/main.js +1 -1
  332. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  333. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  334. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  335. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  336. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  337. package/dist/modes/interactive/startup-shell-eligibility.js +1 -1
  338. package/dist/modes/interactive-engine/engine-prewarm.d.ts +1 -1
  339. package/dist/modes/print-mode.js +1 -1
  340. package/dist/package-manager-cli.code.js +6 -6
  341. package/dist/package-manager-cli.impl.js +3 -3
  342. package/dist/package-manager-cli.js +3 -3
  343. package/dist/rpc-entry.js +1 -1
  344. package/dist/startup-files.json +1 -1
  345. package/dist/startup-stages/10.js +1 -1
  346. package/dist/startup-stages/11.js +1 -1
  347. package/dist/startup-stages/12.js +1 -1
  348. package/dist/startup-stages/2.js +2 -4
  349. package/dist/startup-stages/3.js +1 -3
  350. package/dist/startup-stages/4.js +1 -2
  351. package/dist/startup-stages/5.js +1 -1
  352. package/dist/startup-stages/6.js +5 -7
  353. package/dist/startup-stages/7.js +3 -10
  354. package/dist/startup-stages/8.js +7 -2
  355. package/dist/startup-stages/9.js +1 -7
  356. package/dist/startup-stages/stages.json +1 -1
  357. package/dist/utils/compile-cache-deferral.js +8 -13
  358. package/dist/utils/compile-cache-deferral.js.map +1 -1
  359. package/dist/utils/compile-cache-warmup-host.js +3 -4
  360. package/dist/utils/compile-cache-warmup-host.js.map +1 -1
  361. package/dist/utils/compile-cache.js +12 -100
  362. package/dist/utils/compile-cache.js.map +1 -1
  363. package/dist/utils/startup-database-spare.code.js +2 -2
  364. package/dist/utils/startup-database-spare.impl.js +3 -3
  365. package/dist/utils/startup-database-spare.js +3 -3
  366. package/dist/utils/tools-manager.code.js +1 -1
  367. package/dist/utils/tools-manager.impl.js +3 -3
  368. package/dist/utils/tools-manager.js +3 -3
  369. package/dist/utils/worker-threads.js +2 -15
  370. package/dist/utils/worker-threads.js.map +1 -1
  371. package/docs/build.md +3 -3
  372. package/docs/changelog.mdx +1421 -69
  373. package/docs/compaction/reference.md +5 -5
  374. package/docs/compaction.md +7 -9
  375. package/docs/containerization.md +2 -2
  376. package/docs/custom-provider/api-reference.md +1 -1
  377. package/docs/docs.json +37 -10
  378. package/docs/environment-variables.md +0 -2
  379. package/docs/extensions/api-reference.md +4 -4
  380. package/docs/getting-started/installation.md +3 -0
  381. package/docs/guides/configuration.md +1 -1
  382. package/docs/guides/non-interactive.md +1 -1
  383. package/docs/guides/resume-on-any-machine.md +14 -22
  384. package/docs/guides/team-setup.md +56 -83
  385. package/docs/guides.md +2 -4
  386. package/docs/herdr.md +1 -1
  387. package/docs/index.md +1 -1
  388. package/docs/intercom/operations.md +26 -21
  389. package/docs/intercom/reference.md +2 -2
  390. package/docs/intercom.md +1 -1
  391. package/docs/libraries/storage-postgres.md +9 -9
  392. package/docs/libraries.md +2 -3
  393. package/docs/models-configuration.md +2 -2
  394. package/docs/models.md +2 -3
  395. package/docs/packages/authoring.md +7 -7
  396. package/docs/packages.md +1 -1
  397. package/docs/programmatic.md +2 -2
  398. package/docs/quickstart.md +1 -1
  399. package/docs/reference/cli.md +6 -11
  400. package/docs/reference.md +2 -2
  401. package/docs/rpc/extension-ui.md +2 -2
  402. package/docs/sdk/reference.md +5 -4
  403. package/docs/sdk/storage.md +8 -92
  404. package/docs/sdk/structured-decisions.md +1 -1
  405. package/docs/sdk/web-server.md +3 -3
  406. package/docs/sdk.md +14 -4
  407. package/docs/security.md +1 -1
  408. package/docs/session-format.md +5 -5
  409. package/docs/sessions.md +29 -49
  410. package/docs/settings.md +7 -8
  411. package/docs/storage/custom-adapters.md +255 -0
  412. package/docs/storage/jsonl.md +117 -0
  413. package/docs/{guides/postgres-pgbouncer.md → storage/postgres/pgbouncer.md} +66 -68
  414. package/docs/storage/postgres/tuning.md +337 -0
  415. package/docs/storage/postgres.md +556 -0
  416. package/docs/storage/sqlite.md +99 -0
  417. package/docs/storage.md +326 -990
  418. package/docs/subagents/authoring.md +1 -1
  419. package/docs/subagents.md +2 -2
  420. package/docs/tools.md +1 -1
  421. package/docs/worktree-snapshots.md +2 -2
  422. package/package.json +9 -9
  423. package/schemas/models.schema.json +2 -2
  424. package/schemas/settings.schema.json +0 -14
  425. package/dist/_shared/sdk-IQMULKFU.js.map +0 -1
  426. package/dist/_shared/startup-0-0-3IXNMFM2.js.map +0 -1
  427. package/dist/_shared/startup-0-1-7T2IAE7J.js.map +0 -1
  428. package/dist/_shared/startup-8-1-X32CYSXB.js.map +0 -1
  429. package/dist/core/intercom-broker-control.d.ts +0 -129
  430. package/dist/startup-stages/13.js +0 -1
  431. package/docs/guides/postgres-tuning.md +0 -311
  432. 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-EZUKEP4Q.js";
4
+ import { CommandDeliveries, SqlSessionSearchIndex, WorkspacePublicationError, collectCommandDeliveries, normalizeModelFailureSignal, reportDiagnostics, requireTimerMs } from "./startup-0-1-RTOHJFDJ.js";
5
5
  import { getAvailableThemes, keyHint } from "./p2-shell-main-B2WIALFD.js";
6
- import { releaseLock, reportDebugAsync, waitForLock } from "./p1b-elig-ENCUPKKJ.js";
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,22 @@ 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
47
  import { sequenceRunner } from "../core/storage/statement-sequence.js";
48
48
  import { createServer } from "node:http";
49
49
  import { Check, Errors } from "@bastani/atomic-ai/utils/typebox/value";
50
+ import { TEAM_JOIN_COMMAND } from "../core/storage/libsql-removed.js";
51
+ import { ensureForkInheritedBlobGuard, installForkInheritedBlobGuard } from "../core/worktree-snapshot/fork-blob-guard.js";
50
52
  import { forkLinkWrites, legacyForkLinksTriggerName } from "../core/worktree-snapshot/fork-snapshot-index.js";
51
- import { ensureTableFillfactor, storageSchemaCurrent, transactionFinisher } from "../core/storage/added-exports.js";
53
+ import { MAX_SEQUENCE_REQUEST_STATEMENTS, noteStorageSchemaTables, refreshStorageSchemaCatalog } from "../core/storage/added-exports-0-10-11.js";
52
54
  import { assertStorageSchemaVersion, assertStoredSchemaVersion } from "../core/storage/schema.js";
53
55
  import { applyStorageMigrationsTogether, statementBatch } from "../core/storage/statement-batches.js";
54
56
  import { createSharedHistoryTables, sessionForkTables, sharedHistoryTablesScript } from "../core/storage/session/fork-schema.js";
@@ -921,22 +923,18 @@ async function restoreRunWorktree(remotes, restore, options = {}) {
921
923
  }], options);
922
924
  return root;
923
925
  }
924
- // dist/core/storage/added-exports-0-10-11.js
926
+ // dist/core/storage/session/json-list.js
925
927
  /**
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.
928
+ * `expression IN (…)` over a list bound as one parameter, the list as a JSON array (`JSON.stringify(values)`): the
929
+ * statement's text is the same however many values the list holds, so a server that keeps prepared statements, and
930
+ * pg_stat_statements, see one statement instead of one per length (#6560). On PostgreSQL the list becomes an array the
931
+ * comparison takes whole (`= ANY`), so an index on `expression` is searched for each value, as for a list of
932
+ * parameters. With `int`, PostgreSQL's text elements are compared as integers.
933
933
  */
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;
934
+ function inJsonList(dialect, expression, int = false) {
935
+ const values = `SELECT ${int ? `CAST(value AS ${dialect.types.int})` : "value"} FROM ${dialect.jsonValues("?")}`;
936
+ return dialect.name === "postgres" ? `${expression} = ANY(ARRAY(${values}))` : `${expression} IN (${values})`;
937
+ }
940
938
  // dist/core/storage/session/fork-row-copy.js
941
939
  /** How many entry IDs a run builder holds for lookups before it sends its runs, bounding what a fork holds. */
942
940
  const HELD_RUN_ROWS = 4096;
@@ -1035,7 +1033,7 @@ function incompleteEntryRead(tables, child) {
1035
1033
  * as `copyForkBlob` copied each one, a blob the child already holds is kept, one in the legacy one-row layout is copied
1036
1034
  * only with all its bytes, and each chunk only at its full length.
1037
1035
  */
1038
- function forkBlobCopy(tables, options, source, child, hashes) {
1036
+ function forkBlobCopy(dialect, tables, options, source, child, hashes) {
1039
1037
  const { blobs, blobChunks } = tables;
1040
1038
  const columns = options.legacyBlobData ? ", data" : "";
1041
1039
  const sourceColumns = options.legacyBlobData ? ", p.data" : "";
@@ -1045,33 +1043,33 @@ function forkBlobCopy(tables, options, source, child, hashes) {
1045
1043
  const groups = [];
1046
1044
  for (let start = 0; start < hashes.length; start += BLOB_HASHES_PER_STATEMENT) groups.push(hashes.slice(start, start + BLOB_HASHES_PER_STATEMENT));
1047
1045
  for (const group of groups) {
1048
- const named = group.map(() => "?").join(", ");
1046
+ const named = JSON.stringify(group);
1049
1047
  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`,
1048
+ sql: `INSERT INTO ${blobs} (session_id, hash, bytes, chunks${columns}) SELECT ?, p.hash, p.bytes, p.chunks${sourceColumns} FROM ${blobs} p WHERE p.session_id = ? AND ${inJsonList(dialect, "p.hash")}${whole} AND NOT EXISTS (SELECT 1 FROM ${blobs} c WHERE c.session_id = ? AND c.hash = p.hash) ORDER BY p.hash`,
1051
1049
  params: [
1052
1050
  child,
1053
1051
  source,
1054
- ...group,
1052
+ named,
1055
1053
  child
1056
1054
  ]
1057
1055
  }, {
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`,
1056
+ sql: `INSERT INTO ${blobChunks} (session_id, hash, idx, data) SELECT ?, k.hash, k.idx, k.data FROM ${blobChunks} k JOIN ${blobs} p ON p.session_id = k.session_id AND p.hash = k.hash WHERE k.session_id = ? AND ${inJsonList(dialect, "k.hash")} AND k.idx < p.chunks AND length(k.data) = CASE WHEN k.idx = p.chunks - 1 THEN p.bytes - k.idx * ? ELSE ? END AND NOT EXISTS (SELECT 1 FROM ${blobChunks} x WHERE x.session_id = ? AND x.hash = k.hash AND x.idx = k.idx) ORDER BY k.hash, k.idx`,
1059
1057
  params: [
1060
1058
  child,
1061
1059
  source,
1062
- ...group,
1060
+ named,
1063
1061
  options.chunkBytes,
1064
1062
  options.chunkBytes,
1065
1063
  child
1066
1064
  ]
1067
1065
  });
1068
1066
  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})`,
1067
+ sql: `SELECT p.hash, p.bytes, p.chunks, (SELECT count(*) FROM ${blobs} c WHERE c.session_id = ? AND c.hash = p.hash) AS copied, (SELECT count(*) FROM ${blobChunks} k WHERE k.session_id = ? AND k.hash = p.hash) AS parts FROM ${blobs} p WHERE p.session_id = ? AND ${inJsonList(dialect, "p.hash")}`,
1070
1068
  params: [
1071
1069
  child,
1072
1070
  child,
1073
1071
  source,
1074
- ...group
1072
+ named
1075
1073
  ]
1076
1074
  });
1077
1075
  }
@@ -1175,7 +1173,7 @@ async function forkChildren(tx, tables, sourceId) {
1175
1173
  async function lockForkSources(tx, dialect, tables, ids, mode) {
1176
1174
  const sorted = [...new Set(ids)].sort();
1177
1175
  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);
1176
+ await tx.all(`SELECT id FROM ${tables.sessions} WHERE ${inJsonList(dialect, "id")} ORDER BY id${dialect.lockClause(mode)}`, JSON.stringify(sorted));
1179
1177
  }
1180
1178
  /**
1181
1179
  * 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 +1266,11 @@ async function firstIncomplete(tx, tables, piece) {
1268
1266
  }
1269
1267
  /**
1270
1268
  * 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
1269
+ * search texts and the blobs their tool outputs name, and links them in the snapshot index with `links.materialized`
1270
+ * (see `materializedForkLinks`), a statement a piece, then writes its segments without them, with a new generation, so
1271
+ * its view stays as it was at every commit (#6560). `links.settle` writes the segments, and in the same request checks
1272
+ * the child's links from the first row copied on against the ones a save in seq order writes, linking them again where
1273
+ * they differ (`sessionEntryLinks`). Each piece lies within one of the child's segments: a sub-range of
1274
1274
  * it, or all of it. The caller holds the child's row locked `update`, and the sources' rows locked, so neither its
1275
1275
  * segments nor the rows they name change meanwhile; `length` is the child's last seq.
1276
1276
  */
@@ -1286,17 +1286,19 @@ async function materializeForkSegments(tx, dialect, tables, blobs, links, childI
1286
1286
  ];
1287
1287
  const copied = await tx.run(`INSERT INTO ${tables.entries} (session_id, seq, entry_id, entry_json, chunks) SELECT ?, e.seq + ?, e.entry_id, e.entry_json, e.chunks FROM ${tables.entries} e WHERE e.session_id = ? AND e.seq BETWEEN ? AND ? AND (e.chunks = 0 OR e.chunks = (SELECT count(*) FROM ${tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx >= 0 AND c.idx < e.chunks)) ORDER BY e.seq`, childId, shift, ...range);
1288
1288
  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)]);
1289
+ await Promise.all([links.materialized === void 0 ? void 0 : tx.run(links.materialized, childId, shift, ...range, childId), tx.run(`INSERT INTO ${tables.entryChunks} (session_id, seq, idx, data) SELECT ?, c.seq + ?, c.idx, c.data FROM ${tables.entryChunks} c JOIN ${tables.entries} e ON e.session_id = c.session_id AND e.seq = c.seq WHERE c.session_id = ? AND c.seq BETWEEN ? AND ? AND c.idx >= 0 AND c.idx < e.chunks ORDER BY c.seq, c.idx`, childId, shift, ...range)]);
1290
1290
  await tx.run(`INSERT INTO ${tables.searchTexts} (session_id, seq, text_json) SELECT ?, seq + ?, text_json FROM ${tables.searchTexts} WHERE session_id = ? AND seq BETWEEN ? AND ? ORDER BY seq`, childId, shift, ...range);
1291
1291
  const named = await tx.all(`SELECT DISTINCT ${text("data", "hash")} AS hash FROM ${tables.entries} WHERE session_id = ? AND seq BETWEEN ? AND ?
1292
1292
  AND chunks = 0 AND ${text("type")} = 'custom' AND ${text("customType")} = 'atomic.tool-output' AND ${text("data", "hash")} IS NOT NULL`, ...range);
1293
- const copy = forkBlobCopy(tables, blobs, piece.sourceId, childId, named.map((row) => String(row.hash)));
1293
+ const copy = forkBlobCopy(dialect, tables, blobs, piece.sourceId, childId, named.map((row) => String(row.hash)));
1294
1294
  for (const { sql, params } of copy.statements) await tx.run(sql, ...params);
1295
1295
  const answers = [];
1296
1296
  for (const { sql, params } of copy.checks) answers.push(await tx.all(sql, ...params));
1297
1297
  copy.remaining(answers);
1298
1298
  }
1299
- await writeForkSegments(tx, tables, childId, remaining, length);
1299
+ const writes = forkSegmentWrites(tables, childId, remaining, length);
1300
+ if (pieces.length === 0) for (const { sql, params } of writes) await tx.run(sql, ...params);
1301
+ else await links.settle(tx, childId, Math.min(...pieces.map((piece) => piece.baseSeq + 1)), writes);
1300
1302
  }
1301
1303
  // dist/core/storage/session/fork-detach-host.js
1302
1304
  /**
@@ -1337,15 +1339,16 @@ function forkDetachHost(store) {
1337
1339
  forkSegments: (tx, sessionId) => readForkSegments(tx, lineage, sessionId),
1338
1340
  forkChildren: (tx, sourceId) => forkChildren(tx, lineage, sourceId),
1339
1341
  async materializeForkSegments(tx, childId, pieces) {
1340
- await materializeForkSegments(tx, dialect, materialize, store.blobs, store.materializedLinks, childId, await length(tx, childId), pieces);
1342
+ await materializeForkSegments(tx, dialect, materialize, store.blobs, store.entryLinks, childId, await length(tx, childId), pieces);
1341
1343
  },
1342
1344
  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));
1345
+ if (segments.length > 0) await store.entryLinks.settle(tx, sessionId, Math.min(...segments.map((segment) => segment.baseSeq + 1)), forkSegmentWrites(lineage, sessionId, segments, await length(tx, sessionId)));
1346
+ else if ((await readForkSegments(tx, lineage, sessionId)).length > 0) await writeForkSegments(tx, lineage, sessionId, segments, await length(tx, sessionId));
1344
1347
  },
1345
1348
  async lockForkSources(tx, ids, mode) {
1346
1349
  await lockForkSources(tx, dialect, lineage, ids, mode);
1347
1350
  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);
1351
+ if (dialect.name !== "sqlite" && sorted.length > 0) await tx.all(`SELECT session_id FROM ${forkTables.forkTombstones} WHERE ${inJsonList(dialect, "session_id")} ORDER BY session_id${dialect.lockClause(mode)}`, JSON.stringify(sorted));
1349
1352
  },
1350
1353
  async forkRewriteEpoch(tx, sessionId) {
1351
1354
  return (await tx.get(`SELECT COALESCE(${dialect.jsonText("summary_state", "epoch")}, ${dialect.jsonText("summary_state", "resume", "epoch")}) AS epoch FROM ${tables.sessions} WHERE id = ?`, sessionId))?.epoch ?? void 0;
@@ -1362,8 +1365,8 @@ function forkDetachHost(store) {
1362
1365
  * tombstone once nothing names them any more: when the last fork reading them is deleted, replaced or detached.
1363
1366
  * - Replacing a session that forks still read first gives each of them its own copy of the rows it read (detach),
1364
1367
  * 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.
1368
+ * - Creating a session under the ID of a tombstone, by `create` or by any fork, first detaches the forks that still
1369
+ * read the old rows, then removes them, so the new session starts empty.
1367
1370
  *
1368
1371
  * A session's own segments go when it is deleted or replaced, which may leave a deleted source no fork reads; the caller
1369
1372
  * sweeps it once its transaction commits (fork-sweep.ts). A delete and a replace lock the session's row for update
@@ -1371,19 +1374,37 @@ function forkDetachHost(store) {
1371
1374
  * they drop its own segments and list the forks that name it only under that lock. A fork locks every session its
1372
1375
  * segments name for key share, tombstones included, so a fork being made either commits first and is listed, or waits
1373
1376
  * and finds the session gone.
1377
+ *
1378
+ * Every transaction locks tombstones before sessions rows, and the sessions rows it locks together in one statement,
1379
+ * in id order, so no two of them wait for each other in a cycle: a replace locks the forks reading the session with
1380
+ * the session itself, as a fork locks its donor with the sessions its segments name.
1381
+ */
1382
+ /**
1383
+ * A replace listed a fork of the session that its first read did not lock: a fork made while that read waited for its
1384
+ * locks. The replace runs again, locking it in order with the rest.
1374
1385
  */
1386
+ var ForkReadersMoved = class extends Error {
1387
+ constructor() {
1388
+ super("A fork of the session was made while its replace waited for its locks");
1389
+ }
1390
+ };
1375
1391
  /**
1376
1392
  * The statements a delete or a replace of `sessionId` reads its fork history with, as the first reads of its
1377
1393
  * 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.
1394
+ * meanwhile, with `readers` also the rows of the forks reading it, which a replace detaches, all in id order; then
1395
+ * the listing. Sent with the transaction's start, they cost no round trip of their own.
1379
1396
  */
1380
- function forkPinReads(host, sessions, sessionId) {
1397
+ function forkPinReads(host, sessions, sessionId, readers = false) {
1381
1398
  const { forkSegments, forkLineage } = host.pinTables;
1382
1399
  const lock = host.lockClause("update");
1383
- return [...lock === "" ? [] : [{
1400
+ const locked = readers ? {
1401
+ sql: `SELECT id FROM ${sessions} WHERE id = ? OR id IN (SELECT session_id FROM ${forkSegments} WHERE source_id = ?) ORDER BY id${lock}`,
1402
+ params: [sessionId, sessionId]
1403
+ } : {
1384
1404
  sql: `SELECT id FROM ${sessions} WHERE id = ?${lock}`,
1385
1405
  params: [sessionId]
1386
- }], {
1406
+ };
1407
+ return [...lock === "" ? [] : [locked], {
1387
1408
  sql: `SELECT 's' AS kind, source_id AS id FROM ${forkSegments} WHERE session_id = ?
1388
1409
  UNION SELECT 'r', session_id FROM ${forkSegments} WHERE source_id = ? AND session_id <> ?
1389
1410
  UNION SELECT 'l', session_id FROM ${forkLineage} WHERE session_id = ?`,
@@ -1398,13 +1419,16 @@ function forkPinReads(host, sessions, sessionId) {
1398
1419
  /** Reads `sessionId`'s fork history through the statements of {@link forkPinReads}, in order. */
1399
1420
  async function readForkPins(tx, reads) {
1400
1421
  const listing = reads.at(-1);
1401
- for (const lock of reads.slice(0, -1)) await tx.get(lock.sql, ...lock.params);
1422
+ const locks = reads.slice(0, -1);
1423
+ const locked = /* @__PURE__ */ new Set();
1424
+ for (const lock of locks) for (const row of await tx.all(lock.sql, ...lock.params)) locked.add(String(row.id));
1402
1425
  const rows = await tx.all(listing.sql, ...listing.params);
1403
1426
  const of = (kind) => [...new Set(rows.filter((row) => row.kind === kind).map((row) => String(row.id)))].sort();
1404
1427
  return {
1405
1428
  sources: of("s"),
1406
1429
  readers: of("r"),
1407
- lineage: rows.some((row) => row.kind === "l")
1430
+ lineage: rows.some((row) => row.kind === "l"),
1431
+ ...locks.length === 0 ? {} : { locked }
1408
1432
  };
1409
1433
  }
1410
1434
  /**
@@ -1430,21 +1454,32 @@ async function deleteForkedSessionWithin(host, tx, sessionId, deletedAt, pins) {
1430
1454
  * In `replace`'s transaction, before the session's rows go, given what {@link readForkPins} read: each fork reading
1431
1455
  * them gets its own copy, and the session drops its own segments, as a replaced session holds every row of its view
1432
1456
  * itself. Resolves with the sources those segments named, to sweep once the transaction commits. A session no fork
1433
- * history names costs no statement.
1457
+ * history names costs no statement. Throws {@link ForkReadersMoved}, unless `lockLate`, when it lists a fork its first
1458
+ * read did not lock: locked now, after the session's row, a fork of that fork could wait for the replace while it
1459
+ * waits for the fork. `lockLate` locks it all the same, as a replace that ran again too often does.
1434
1460
  */
1435
- async function replaceForkedSessionWithin(host, tx, sessionId, pins) {
1461
+ async function replaceForkedSessionWithin(host, tx, sessionId, pins, lockLate = false) {
1462
+ const { locked } = pins;
1463
+ if (!lockLate && locked !== void 0 && pins.readers.some((reader) => !locked.has(reader))) throw new ForkReadersMoved();
1436
1464
  if (pins.sources.length > 0) await host.writeForkSegments(tx, sessionId, []);
1437
1465
  for (const child of pins.readers) await detachForkWithin(host, tx, sessionId, child, false);
1438
1466
  return pins.sources;
1439
1467
  }
1440
1468
  /**
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.
1469
+ * In the transaction that writes a new session, by `create` or by a fork, before the session is written: when a
1470
+ * deleted session with this ID left a tombstone, the forks still reading its rows get their own copy, and the rows go.
1471
+ * Resolves with whether there was a tombstone.
1472
+ *
1473
+ * The tombstone is locked before the forks that read the rows, as every writer orders them: a fork locks the
1474
+ * tombstones among its sources before any session's row, so a fork that waits for this tombstone holds no row this
1475
+ * transaction locks next. Under the tombstone's lock no fork starts reading the rows, so the forks listed then are all
1476
+ * of them.
1443
1477
  */
1444
1478
  async function createOverTombstoneWithin(host, tx, sessionId) {
1445
- if (!await isTombstoned(host, tx, sessionId)) return;
1479
+ if (!await isTombstoned(host, tx, sessionId)) return false;
1446
1480
  for (const child of await lockedReferrers(host, tx, sessionId)) await detachForkWithin(host, tx, sessionId, child, false);
1447
1481
  await removeStoredRows(host, tx, sessionId);
1482
+ return true;
1448
1483
  }
1449
1484
  /** Never load the clone writer in an ordinary open. Fence a lapsed transfer before deleting so a paused donor
1450
1485
  * cannot publish a partially swept transfer. When more rows remain, the new token stays expired. */
@@ -1545,6 +1580,23 @@ function withForkViews(views, sql) {
1545
1580
  function forkViewParams(views) {
1546
1581
  return views.flatMap((view) => view.params);
1547
1582
  }
1583
+ // dist/core/storage/session/session-transactions.js
1584
+ /**
1585
+ * A write to the rows of the session `sessionId` of the sessions table `sessions`: on Postgres it is the only writer of
1586
+ * that session, while writers of other sessions run beside it; SQLite runs every write alone anyway. Every writer of a
1587
+ * session's rows names this one domain, whatever table it writes (the session store, its chat records, its search
1588
+ * index), so the checks each makes against the session's row hold until it commits. A transient failure runs it again
1589
+ * (#4383).
1590
+ */
1591
+ function sessionWriteTransaction(sessions, sessionId) {
1592
+ return {
1593
+ retryTransientFailures: true,
1594
+ concurrency: {
1595
+ kind: "serial",
1596
+ domain: `${sessions}:${sessionId}`
1597
+ }
1598
+ };
1599
+ }
1548
1600
  // dist/core/storage/session/sql-chat-records.js
1549
1601
  /** Rows one read fetches at most. */
1550
1602
  const READ_PAGE_ROWS = 64;
@@ -1640,9 +1692,9 @@ function sqlChatRecords(database, sessions, table, index, ledger) {
1640
1692
  row_number() OVER (ORDER BY position) AS page_row,
1641
1693
  sum(${bytes("anchor")}+${bytes("data")}) OVER (ORDER BY position) AS page_bytes
1642
1694
  FROM (SELECT position,anchor,data FROM ${table}
1643
- WHERE session_id=? AND epoch=? AND position>? AND anchor IN (${anchors.map(() => "?").join(",")})
1695
+ WHERE session_id=? AND epoch=? AND position>? AND ${inJsonList(dialect, "anchor")}
1644
1696
  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);
1697
+ ) AS page WHERE page_row=1 OR page_bytes<=? ORDER BY position`, owner.id, owner.epoch, after, JSON.stringify(anchors.map(lineKey)), CHAT_READ_PAGE_BYTES);
1646
1698
  for (const { anchor, data } of rows) {
1647
1699
  const record = decodeChatRecord(data);
1648
1700
  if (record) result.push({
@@ -1659,7 +1711,7 @@ function sqlChatRecords(database, sessions, table, index, ledger) {
1659
1711
  const orders = [];
1660
1712
  for (let i = 0; i < promptIds.length; i += ORDER_BATCH) {
1661
1713
  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);
1714
+ const rows = await database.all(`SELECT data FROM ${table} WHERE session_id=? AND epoch=? AND ${inJsonList(dialect, "anchor")} ORDER BY position`, owner.id, owner.epoch, JSON.stringify(keys));
1663
1715
  for (const { data } of rows) {
1664
1716
  const order = decodeChatOrder(data);
1665
1717
  if (order) orders.push(order);
@@ -1671,6 +1723,12 @@ function sqlChatRecords(database, sessions, table, index, ledger) {
1671
1723
  }
1672
1724
  // dist/core/storage/session/sql-session-store.js
1673
1725
  /**
1726
+ * `sessionEntryLinks` of `blob-store.ts`, which the copy a process of an earlier release loaded lacks. Such a process
1727
+ * keeps that copy after an in-place update, and can load this module from the update: a named import would fail to link
1728
+ * there. Without it, a materialization leaves the links the index's triggers wrote until the index is rebuilt (#6560).
1729
+ */
1730
+ const entryLinkers = blobStore;
1731
+ /**
1674
1732
  * The newest sessions schema this build reads and writes. Version 2 stores long entries in chunks (#4954), which a build
1675
1733
  * that knows only version 1 would read as stubs. A database stays at version 1, which older builds still open, until
1676
1734
  * this build writes its first chunked entry: that transaction moves the sessions meta to 2, and older builds refuse it
@@ -1763,6 +1821,25 @@ var ForkSourcesMoved = class extends Error {
1763
1821
  super("The fork's source moved its history while the fork read it");
1764
1822
  }
1765
1823
  };
1824
+ /**
1825
+ * A fork into the ID of a deleted session forks still read, whose reads did not lock that session's tombstone and the
1826
+ * forks reading it before the donor's row: the fork runs again with reads that do (#6560).
1827
+ */
1828
+ var ForkChildTombstoned = class extends Error {
1829
+ constructor() {
1830
+ super("The fork's child has the ID of a deleted session forks still read");
1831
+ }
1832
+ };
1833
+ /** The leading statements of a fork's transaction: its reads of {@link SharedForkReads}, in the order it makes them. */
1834
+ function sharedForkLeading(reads) {
1835
+ return [
1836
+ reads.exists,
1837
+ ...reads.childTombstone === void 0 ? [] : [reads.childTombstone],
1838
+ reads.tombstones,
1839
+ reads.lock,
1840
+ reads.segments
1841
+ ];
1842
+ }
1766
1843
  function windowIndex(state, seq) {
1767
1844
  return isSessionResumeIndex(state.windowResume, seq) ? state.windowResume : isSessionResumeIndex(state.resume, seq) ? state.resume : void 0;
1768
1845
  }
@@ -2119,12 +2196,16 @@ var SqlSessionStore = class SqlSessionStore {
2119
2196
  chatStore;
2120
2197
  /** The database's reader handle, once a read opened it: see `readerDatabase`. */
2121
2198
  reader;
2199
+ /** Each session's writes this store started and has not finished, each settled as its write is: see `writing`. */
2200
+ unfinishedWrites = /* @__PURE__ */ new Map();
2122
2201
  /** The sessions schema version each transaction read first, by its handle: see `sharedHistoryForks`. */
2123
2202
  schemaVersions = /* @__PURE__ */ new WeakMap();
2124
2203
  /** The fork tables under this store's prefix, which exist once its sessions schema is version 3 (#6560). */
2125
2204
  forkTables;
2126
2205
  /** See {@link forkLinks}. */
2127
2206
  forkLinkStatements;
2207
+ /** See {@link entryLinks}. */
2208
+ entryLinkStatements;
2128
2209
  /**
2129
2210
  * Whether a read of this store found its sessions schema at {@link SESSION_SCHEMA_VERSION_SHARED_HISTORY}: one way,
2130
2211
  * as the switch is. A read outside a transaction reads sessions through their views once it is set, and before that
@@ -2137,14 +2218,7 @@ var SqlSessionStore = class SqlSessionStore {
2137
2218
  forkedSessions = /* @__PURE__ */ new Map();
2138
2219
  /** The sessions each recently forked session's segments named when this store last read them (#6560). */
2139
2220
  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
2221
  get chatRecords() {
2146
- const { adapter, location } = this.database.descriptor;
2147
- if (adapter === "libsql" && /^file:/i.test(location)) return void 0;
2148
2222
  if (!this.chatStore) {
2149
2223
  const names = renderStorageIdentifiers("sessions", {
2150
2224
  rows: "chat_v1",
@@ -2200,7 +2274,7 @@ var SqlSessionStore = class SqlSessionStore {
2200
2274
  registerHistorySnapshot(this, (sessionId, project) => {
2201
2275
  this.assertOpen();
2202
2276
  validateSessionText("sessionId", sessionId);
2203
- return this.readTransaction(async (tx) => {
2277
+ return this.readTransaction(sessionId, async (tx) => {
2204
2278
  const head = await this.historyHead(tx, sessionId, true);
2205
2279
  return project(head.epoch, head.lastSeq, (from, through, backward) => this.historyPacket(tx, sessionId, head.epoch, from, through, backward));
2206
2280
  });
@@ -2329,7 +2403,7 @@ var SqlSessionStore = class SqlSessionStore {
2329
2403
  }],
2330
2404
  options: {
2331
2405
  table: storageMigrationTable(options.prefix),
2332
- recordedThrough: 3
2406
+ acceptNewer: true
2333
2407
  }
2334
2408
  }, {
2335
2409
  domain: SESSION_PRESENCE_DOMAIN,
@@ -2352,6 +2426,7 @@ var SqlSessionStore = class SqlSessionStore {
2352
2426
  acceptNewer: true
2353
2427
  }
2354
2428
  }]);
2429
+ if ((sessionsSchema?.version ?? 0) > 3) throw new StorageSchemaVersionError(SESSION_DOMAIN, sessionsSchema.version, 3);
2355
2430
  if (createdShared) {
2356
2431
  sharedHistory = true;
2357
2432
  noteStorageSchemaTables(database, Object.values(forkTables));
@@ -2381,6 +2456,7 @@ var SqlSessionStore = class SqlSessionStore {
2381
2456
  SqlSessionSearchIndex.open(database, tables, options.prefix),
2382
2457
  entryByteLengthOf(database)
2383
2458
  ]);
2459
+ if (shared) await ensureForkInheritedBlobGuard(database, snapshotIndexTables$1(options.prefix), forkTables.forkSegments, storageMigrationTable(options.prefix));
2384
2460
  const appendFunction = renderStorageIdentifiers("sessions", { append: SESSION_APPEND_FUNCTION }, options.prefix).append;
2385
2461
  const appendsThroughFunction = catalog?.hasFunction?.(appendFunction) === true && database.autocommit !== void 0 && typeof blobs.storedBlobsQuery === "function";
2386
2462
  const store = new SqlSessionStore(database, tables, options.prefix, options.cwdMatcher, blobs, legacyBlobData, searchIndex, entryByteLength, appendsThroughFunction ? appendFunction : void 0);
@@ -2474,10 +2550,15 @@ var SqlSessionStore = class SqlSessionStore {
2474
2550
  };
2475
2551
  }
2476
2552
  /**
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.
2553
+ * `transaction` for a body that only reads session `sessionId`, in one read-only snapshot, on the database's reader
2554
+ * handle when it offers one: its reads then wait for neither the writes queued on this store's connection nor their
2555
+ * locks. It first waits for the writes of that session this store started and has not finished (`writing`), so a
2556
+ * caller that starts a write and then reads, without awaiting the write, reads it as the store's own connection would
2557
+ * have; with none unfinished it waits for nothing.
2479
2558
  */
2480
- async readTransaction(body, leading = []) {
2559
+ async readTransaction(sessionId, body, leading = []) {
2560
+ const unfinished = this.unfinishedWrites.get(sessionId);
2561
+ if (unfinished !== void 0) await Promise.all(unfinished);
2481
2562
  return (await this.readerDatabase()).transaction(async (tx) => {
2482
2563
  await this.assertReadableSchema(tx);
2483
2564
  return body(tx);
@@ -2487,6 +2568,22 @@ var SqlSessionStore = class SqlSessionStore {
2487
2568
  }));
2488
2569
  }
2489
2570
  /**
2571
+ * `write`, a write of session `sessionId` this store has just started, kept in `unfinishedWrites` until it settles,
2572
+ * for the reads of the session that start meanwhile to wait for (`readTransaction`). No write waits for a read, and
2573
+ * no write of this store reads through `readTransaction`, so the wait never comes back to the write.
2574
+ */
2575
+ writing(sessionId, write) {
2576
+ const writes = this.unfinishedWrites.get(sessionId) ?? /* @__PURE__ */ new Set();
2577
+ this.unfinishedWrites.set(sessionId, writes);
2578
+ const settled = write.then(() => {}, () => {});
2579
+ writes.add(settled);
2580
+ settled.then(() => {
2581
+ writes.delete(settled);
2582
+ if (writes.size === 0 && this.unfinishedWrites.get(sessionId) === writes) this.unfinishedWrites.delete(sessionId);
2583
+ });
2584
+ return write;
2585
+ }
2586
+ /**
2490
2587
  * The database's reader handle, opened at the first read and closed with the store; the database without one. A
2491
2588
  * reader that cannot open, such as when its file can no longer be opened anew, leaves the read on the store's own
2492
2589
  * connection, as every read ran before readers, and the next read tries to open one again.
@@ -2682,6 +2779,7 @@ var SqlSessionStore = class SqlSessionStore {
2682
2779
  holders
2683
2780
  };
2684
2781
  await createSharedHistoryTables(tx, dialect, sessionForkTables(prefix));
2782
+ await installForkInheritedBlobGuard(tx, dialect, snapshotIndexTables$1(prefix), sessionForkTables(prefix).forkSegments);
2685
2783
  await statementBatch(tx, [
2686
2784
  dialect.dropTrigger(legacyForkLinksTriggerName(tables.entries), tables.entries, true),
2687
2785
  dialect.versionedMigrations && {
@@ -2744,27 +2842,19 @@ var SqlSessionStore = class SqlSessionStore {
2744
2842
  };
2745
2843
  }
2746
2844
  async create(header, entries) {
2845
+ return this.writing(header.id, this.writeCreate(header, entries));
2846
+ }
2847
+ async writeCreate(header, entries) {
2747
2848
  this.assertOpen();
2748
2849
  validateSessionHeader(header);
2749
2850
  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
- };
2851
+ const existing = this.newSessionRead(header.id);
2758
2852
  let written = [];
2759
2853
  let writtenRow;
2760
2854
  const created = await this.transactionCheckedAlongside(async (tx, checked) => {
2761
2855
  writtenRow = void 0;
2762
2856
  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
- });
2857
+ await this.startNewSession(tx, header.id, found, "create");
2768
2858
  const summary = this.summaryWrite(header.id, {
2769
2859
  header,
2770
2860
  entries,
@@ -2783,7 +2873,55 @@ var SqlSessionStore = class SqlSessionStore {
2783
2873
  this.rememberWritten(header.id, writtenRow);
2784
2874
  return created;
2785
2875
  }
2876
+ /**
2877
+ * The read that begins a transaction writing a new session `id`, by `create` or by a fork: whether it exists and, where
2878
+ * this store has seen shared history, whether a deleted session with this ID left rows forks still read, in the same
2879
+ * statement.
2880
+ */
2881
+ newSessionRead(id) {
2882
+ return this.sharedHistorySeen ? {
2883
+ sql: `SELECT (SELECT id FROM ${this.tables.sessions} WHERE id = ?) AS id, (SELECT session_id FROM ${this.forkTables.forkTombstones} WHERE session_id = ?) AS tombstone`,
2884
+ params: [id, id]
2885
+ } : {
2886
+ sql: `SELECT id FROM ${this.tables.sessions} WHERE id = ?`,
2887
+ params: [id]
2888
+ };
2889
+ }
2890
+ /**
2891
+ * In the transaction that writes a new session `id`, before its writes, given what {@link newSessionRead} found:
2892
+ * refuses a session that exists. Where a deleted session with this ID left rows forks still read, those forks get
2893
+ * their own copies first and the rows go, so the new session starts empty and their sweep never takes its rows. A
2894
+ * fork whose copy a missing source chunk refuses keeps the old rows, and the new session is refused with it.
2895
+ */
2896
+ async startNewSession(tx, id, found, operation) {
2897
+ if (found?.id != null) throw new SessionExistsError$1(id);
2898
+ if (!await this.sharedHistoryForks(tx)) return false;
2899
+ if (!(found?.tombstone === void 0 ? await this.hasForkTombstone(tx, id) : found.tombstone !== null)) return false;
2900
+ return createOverTombstoneWithin(this.forkHost(), tx, id).catch((error) => {
2901
+ noteForkCopyRefusal(error, operation);
2902
+ throw error;
2903
+ });
2904
+ }
2905
+ /**
2906
+ * {@link startNewSession} for a fork with shared history, once it has read its donor: resolves with the donor. A donor
2907
+ * that read the rows a deleted session with the child's ID left holds its own copy of them now, in segments of its
2908
+ * own, and is read again (#6560).
2909
+ */
2910
+ async startSharedFork(tx, child, donor, source, withState) {
2911
+ const found = donor.child;
2912
+ const tombstoned = found?.tombstone === void 0 ? await this.hasForkTombstone(tx, child) : found.tombstone !== null;
2913
+ if (tombstoned && !donor.ordered && this.dialect.lockClause("update") !== "") throw new ForkChildTombstoned();
2914
+ if (!await this.startNewSession(tx, child, {
2915
+ id: null,
2916
+ tombstone: tombstoned ? child : null
2917
+ }, "fork")) return donor;
2918
+ if (!donor.segments.some((segment) => segment.sourceId === child)) return donor;
2919
+ return this.sharedForkDonor(tx, child, source, this.sharedForkReads(child, source.sessionId, withState));
2920
+ }
2786
2921
  async createFork(header, entries, source) {
2922
+ return this.writing(header.id, this.writeCreateFork(header, entries, source));
2923
+ }
2924
+ async writeCreateFork(header, entries, source) {
2787
2925
  if (this.create !== SqlSessionStore.prototype.create) return void 0;
2788
2926
  if (!this.sharesTablesWith(source.store)) {
2789
2927
  if ("read" in entries) return entries.kind === "complete-session" ? this.createStagedFork(header, entries, source) : void 0;
@@ -2800,17 +2938,13 @@ var SqlSessionStore = class SqlSessionStore {
2800
2938
  validateSessionHeader(header);
2801
2939
  validateSessionEntries(entries);
2802
2940
  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;
2941
+ for (let attempt = 0, ordered = false;; attempt++) {
2942
+ const reads = this.sharedHistorySeen ? this.sharedForkReads(header.id, source.sessionId, false, ordered) : void 0;
2805
2943
  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
- ]));
2944
+ return await this.transactionCheckedAlongside((tx, checked) => this.writeEntriesFork(tx, checked, header, entries, source, reads), this.sessionWrite(header.id, ...reads === void 0 ? [] : sharedForkLeading(reads)));
2812
2945
  } catch (error) {
2813
- if (!(error instanceof ForkSourcesMoved) || attempt >= 3) throw error;
2946
+ if (error instanceof ForkChildTombstoned && !ordered) ordered = true;
2947
+ else if (!(error instanceof ForkSourcesMoved) || attempt >= 3) throw error;
2814
2948
  }
2815
2949
  }
2816
2950
  }
@@ -2850,6 +2984,7 @@ var SqlSessionStore = class SqlSessionStore {
2850
2984
  lastSeq: entries.length
2851
2985
  });
2852
2986
  await checked;
2987
+ if (shared !== void 0) shared = await this.startSharedFork(tx, header.id, shared, unchecked, false);
2853
2988
  const tables = await this.viewTables(tx);
2854
2989
  const writes = new SentWrites(tx);
2855
2990
  if (!sharing) {
@@ -3010,7 +3145,7 @@ var SqlSessionStore = class SqlSessionStore {
3010
3145
  */
3011
3146
  forkBlobCopy(source, child, hashes) {
3012
3147
  if (this.getBlob !== SqlSessionStore.prototype.getBlob || this.putBlob !== SqlSessionStore.prototype.putBlob) return void 0;
3013
- return forkBlobCopy(this.tables, {
3148
+ return forkBlobCopy(this.dialect, this.tables, {
3014
3149
  legacyBlobData: this.legacyBlobData,
3015
3150
  chunkBytes: SESSION_BLOB_CHUNK_BYTES
3016
3151
  }, source, child, [...new Set(hashes)]);
@@ -3042,6 +3177,9 @@ var SqlSessionStore = class SqlSessionStore {
3042
3177
  * `remainingBlobs` names the blobs left to copy with `copySessionBlobs`: those the source no longer holds.
3043
3178
  */
3044
3179
  async createStagedFork(header, stream, source) {
3180
+ return this.writing(header.id, this.writeCreateStagedFork(header, stream, source));
3181
+ }
3182
+ async writeCreateStagedFork(header, stream, source) {
3045
3183
  this.assertOpen();
3046
3184
  validateSessionHeader(header);
3047
3185
  const { createStagedFork } = await import("../core/storage/session/fork-staging.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
@@ -3080,7 +3218,7 @@ var SqlSessionStore = class SqlSessionStore {
3080
3218
  legacyBlobData: this.legacyBlobData,
3081
3219
  chunkBytes: SESSION_BLOB_CHUNK_BYTES
3082
3220
  },
3083
- materializedLinks: this.forkLinks().materialized,
3221
+ entryLinks: this.entryLinks(),
3084
3222
  transaction: (body) => this.transaction(body, SESSION_TRANSACTION)
3085
3223
  });
3086
3224
  }
@@ -3095,6 +3233,13 @@ var SqlSessionStore = class SqlSessionStore {
3095
3233
  }, this.dialect);
3096
3234
  return this.forkLinkStatements;
3097
3235
  }
3236
+ /** How the snapshot index links a materialization's copies and a fork moved onto another copy (#6560). */
3237
+ entryLinks() {
3238
+ this.entryLinkStatements ??= entryLinkers.sessionEntryLinks?.(this.prefix, this.dialect, this.forkTables.forkSegments) ?? { async settle(tx, _sessionId, _fromSeq, before) {
3239
+ for (const { sql, params } of before) await tx.run(sql, ...params);
3240
+ } };
3241
+ return this.entryLinkStatements;
3242
+ }
3098
3243
  /**
3099
3244
  * @internal Gives every fork that shares history with `sessionId` its own copy of what it reads, so the session's
3100
3245
  * rows no longer stay for them; see fork-detach.ts. Detaches a crash stopped are finished first. Nothing to do where
@@ -3152,6 +3297,10 @@ var SqlSessionStore = class SqlSessionStore {
3152
3297
  lastSeq
3153
3298
  }, summary, index),
3154
3299
  create: (header, entries) => this.create(header, entries),
3300
+ newSessionRead: (id) => this.newSessionRead(id),
3301
+ startNewSession: async (tx, id, found) => {
3302
+ await this.startNewSession(tx, id, found, "fork");
3303
+ },
3155
3304
  sourceStoredEntryChunks: (source) => {
3156
3305
  const store = nativeForkReader(source, "entry");
3157
3306
  return store instanceof SqlSessionStore && store.readEntryChunk === SqlSessionStore.prototype.readEntryChunk ? (reference, index) => store.readStoredEntryChunk(reference, index) : void 0;
@@ -3181,7 +3330,7 @@ var SqlSessionStore = class SqlSessionStore {
3181
3330
  */
3182
3331
  async readStoredEntryChunk(reference, index) {
3183
3332
  this.assertOpen();
3184
- return this.readTransaction(async (tx) => {
3333
+ return this.readTransaction(reference.sessionId, async (tx) => {
3185
3334
  const { sessionId, epoch, seq } = reference;
3186
3335
  const head = await this.historyHead(tx, sessionId, true);
3187
3336
  if (head.epoch !== epoch) throw new SessionConflictError$1(sessionId, seq, head.lastSeq);
@@ -3197,7 +3346,7 @@ var SqlSessionStore = class SqlSessionStore {
3197
3346
  /** How many chunks the entry `reference` names is stored in, 0 when it is stored whole, in its generation. */
3198
3347
  async readStoredChunks(reference) {
3199
3348
  this.assertOpen();
3200
- return this.readTransaction(async (tx) => {
3349
+ return this.readTransaction(reference.sessionId, async (tx) => {
3201
3350
  const { sessionId, epoch, seq } = reference;
3202
3351
  const head = await this.historyHead(tx, sessionId, true);
3203
3352
  if (head.epoch !== epoch) throw new SessionConflictError$1(sessionId, seq, head.lastSeq);
@@ -3219,10 +3368,10 @@ var SqlSessionStore = class SqlSessionStore {
3219
3368
  const rows = await this.outsideTransaction((tables) => this.database.all(`SELECT b.hash, b.bytes, b.chunks, CASE WHEN b.chunks >= 0 AND b.bytes <= ? THEN c.data END AS data,
3220
3369
  CASE WHEN w.place = 0 THEN 1 ELSE 0 END AS own
3221
3370
  FROM ${this.blobPlaces(tables)} w JOIN ${this.tables.blobs} b
3222
- ON b.session_id = w.owner AND b.hash IN (${hashes.map(() => "?").join(", ")})
3371
+ ON b.session_id = w.owner AND ${inJsonList(this.dialect, "b.hash")}
3223
3372
  LEFT JOIN ${this.tables.blobChunks} c ON c.session_id = b.session_id AND c.hash = b.hash AND c.idx = 0
3224
3373
  ${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);
3374
+ ORDER BY own DESC, b.session_id`, maxBytes, ...this.blobPlaceParams(tables, sessionId), JSON.stringify(hashes)), (found) => found.length > 0);
3226
3375
  for (const row of rows) if (!parts.has(String(row.hash))) parts.set(String(row.hash), {
3227
3376
  bytes: Number(row.bytes),
3228
3377
  chunks: Number(row.chunks),
@@ -3260,25 +3409,24 @@ var SqlSessionStore = class SqlSessionStore {
3260
3409
  async createStreamedFork(header, stream, source) {
3261
3410
  this.assertOpen();
3262
3411
  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;
3412
+ for (let attempt = 0, ordered = false;; attempt++) {
3413
+ const reads = this.sharedHistorySeen ? this.sharedForkReads(header.id, source.sessionId, stream.prefix !== void 0, ordered) : void 0;
3265
3414
  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
- ]));
3415
+ return await this.transactionCheckedAlongside((tx, checked) => this.writeStreamedFork(tx, checked, header, stream, source, reads), this.sessionWrite(header.id, ...reads === void 0 ? [] : sharedForkLeading(reads)));
3272
3416
  } catch (error) {
3273
- if (!(error instanceof ForkSourcesMoved) || attempt >= 3) throw error;
3417
+ if (error instanceof ForkChildTombstoned && !ordered) ordered = true;
3418
+ else if (!(error instanceof ForkSourcesMoved) || attempt >= 3) throw error;
3274
3419
  }
3275
3420
  }
3276
3421
  }
3277
3422
  async writeStreamedFork(tx, checked, header, stream, source, reads) {
3278
3423
  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);
3424
+ const withState = stream.prefix !== void 0;
3425
+ let shared = await this.sharedHistoryForks(tx) ? await (sharedRead ?? this.sharedForkDonor(tx, header.id, source, this.sharedForkReads(header.id, source.sessionId, withState))) : void 0;
3426
+ const read = shared ?? await this.forkDonor(tx, header.id, source);
3281
3427
  await checked;
3428
+ if (shared !== void 0) shared = await this.startSharedFork(tx, header.id, shared, source, withState);
3429
+ const head = shared ?? read;
3282
3430
  const { encodedForkRow } = await import("../core/storage/session/fork-row-bytes.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
3283
3431
  const { foldForkRow } = await import("../core/storage/session/fork-row-index.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
3284
3432
  const prefix = stream.prefix;
@@ -3466,37 +3614,40 @@ var SqlSessionStore = class SqlSessionStore {
3466
3614
  }
3467
3615
  /**
3468
3616
  * 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.
3617
+ * exists; the tombstones of the deleted sessions among the donor's sources, locked `key-share`; the rows of the donor
3618
+ * and of the sessions its segments name, as the statement starts or as this store last saw them, each locked
3619
+ * `key-share` in id order, unless the child exists, with the donor's watermark and generation, and with `withState`
3620
+ * its summary state; then the donor's segments, read once those locks are held.
3472
3621
  */
3473
- sharedForkReads(child, donor, withState) {
3622
+ sharedForkReads(child, donor, withState, ordered = false) {
3474
3623
  const ids = [.../* @__PURE__ */ new Set([donor, ...this.forkSources.get(donor) ?? []])].sort();
3475
3624
  const epoch = `COALESCE(${this.dialect.jsonText("summary_state", "epoch")}, ${this.dialect.jsonText("summary_state", "resume", "epoch")}, revision)`;
3625
+ const readers = ordered ? ` OR id IN (SELECT session_id FROM ${this.forkTables.forkSegments} WHERE source_id = ?)` : "";
3476
3626
  return {
3477
- ids,
3478
- exists: {
3479
- sql: `SELECT id FROM ${this.tables.sessions} WHERE id = ?`,
3627
+ exists: this.newSessionRead(child),
3628
+ ...ordered ? { childTombstone: {
3629
+ sql: `SELECT session_id FROM ${this.forkTables.forkTombstones} WHERE session_id = ?${this.dialect.lockClause("update")}`,
3480
3630
  params: [child]
3481
- },
3631
+ } } : {},
3482
3632
  lock: {
3483
3633
  sql: `SELECT id, last_seq, CASE WHEN id = ? THEN ${epoch} END AS epoch${withState ? ", CASE WHEN id = ? THEN summary_state END AS summary_state" : ""}
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")}`,
3634
+ FROM ${this.tables.sessions} WHERE (${inJsonList(this.dialect, "id")}
3635
+ OR id IN (SELECT source_id FROM ${this.forkTables.forkSegments} WHERE session_id = ?)${readers})
3636
+ AND NOT EXISTS (SELECT 1 FROM ${this.tables.sessions} c WHERE c.id = ?) ORDER BY id${this.dialect.lockClause(ordered ? "update" : "key-share")}`,
3487
3637
  params: [
3488
3638
  donor,
3489
3639
  ...withState ? [donor] : [],
3490
- ...ids,
3640
+ JSON.stringify(ids),
3491
3641
  donor,
3642
+ ...ordered ? [child] : [],
3492
3643
  child
3493
3644
  ]
3494
3645
  },
3495
3646
  tombstones: {
3496
- sql: `SELECT session_id FROM ${this.forkTables.forkTombstones} WHERE session_id IN (${ids.map(() => "?").join(", ")})
3647
+ sql: `SELECT session_id FROM ${this.forkTables.forkTombstones} WHERE ${inJsonList(this.dialect, "session_id")}
3497
3648
  OR session_id IN (SELECT source_id FROM ${this.forkTables.forkSegments} WHERE session_id = ?)
3498
3649
  ORDER BY session_id${this.dialect.lockClause("key-share")}`,
3499
- params: [...ids, donor]
3650
+ params: [JSON.stringify(ids), donor]
3500
3651
  },
3501
3652
  segments: {
3502
3653
  sql: `SELECT source_id, from_seq, to_seq, base_seq FROM ${this.forkTables.forkSegments} WHERE session_id = ? ORDER BY idx`,
@@ -3512,20 +3663,23 @@ var SqlSessionStore = class SqlSessionStore {
3512
3663
  async sharedForkDonor(tx, child, source, reads) {
3513
3664
  const settle = (read) => read.then((value) => ({ value }), (error) => ({ error }));
3514
3665
  const existing = settle(tx.get(reads.exists.sql, ...reads.exists.params));
3515
- const locked = settle(tx.all(reads.lock.sql, ...reads.lock.params));
3666
+ const childTombstone = reads.childTombstone === void 0 ? void 0 : settle(tx.all(reads.childTombstone.sql, ...reads.childTombstone.params));
3516
3667
  const tombstones = settle(tx.all(reads.tombstones.sql, ...reads.tombstones.params));
3668
+ const locked = settle(tx.all(reads.lock.sql, ...reads.lock.params));
3517
3669
  const segmentRows = settle(tx.all(reads.segments.sql, ...reads.segments.params));
3518
3670
  for (const read of [
3519
3671
  existing,
3520
- locked,
3672
+ ...childTombstone === void 0 ? [] : [childTombstone],
3521
3673
  tombstones,
3674
+ locked,
3522
3675
  segmentRows
3523
3676
  ]) {
3524
3677
  const answer = await read;
3525
3678
  if ("error" in answer) throw answer.error;
3526
3679
  }
3527
3680
  const answer = (read) => read.value;
3528
- if (answer(await existing)) throw new SessionExistsError$1(child);
3681
+ const found = answer(await existing);
3682
+ if (found?.id != null) throw new SessionExistsError$1(child);
3529
3683
  const row = answer(await locked).find((candidate) => String(candidate.id) === source.sessionId);
3530
3684
  if (row === void 0) throw new SessionNotFoundError$1(source.sessionId);
3531
3685
  const segments = answer(await segmentRows).map((segment) => ({
@@ -3536,11 +3690,7 @@ var SqlSessionStore = class SqlSessionStore {
3536
3690
  }));
3537
3691
  const sources = [...new Set(segments.map((segment) => segment.sourceId))].sort();
3538
3692
  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
- ]);
3693
+ const lockedIds = /* @__PURE__ */ new Set([...answer(await locked).map((candidate) => String(candidate.id)), ...answer(await tombstones).map((candidate) => String(candidate.session_id))]);
3544
3694
  if (sources.some((id) => !lockedIds.has(id))) throw new ForkSourcesMoved();
3545
3695
  const lastSeq = Number(row.last_seq);
3546
3696
  const epoch = String(row.epoch);
@@ -3549,6 +3699,8 @@ var SqlSessionStore = class SqlSessionStore {
3549
3699
  lastSeq,
3550
3700
  epoch,
3551
3701
  segments,
3702
+ child: found,
3703
+ ordered: reads.childTombstone !== void 0,
3552
3704
  ...typeof row.summary_state === "string" ? { state: JSON.parse(row.summary_state) } : {}
3553
3705
  };
3554
3706
  }
@@ -3632,6 +3784,9 @@ var SqlSessionStore = class SqlSessionStore {
3632
3784
  } : original], seq, texts, false);
3633
3785
  }
3634
3786
  async append(sessionId, entries, options) {
3787
+ return this.writing(sessionId, this.writeAppend(sessionId, entries, options));
3788
+ }
3789
+ async writeAppend(sessionId, entries, options) {
3635
3790
  this.assertOpen();
3636
3791
  validateSessionText("sessionId", sessionId);
3637
3792
  const fast = await this.appendThroughFunction(sessionId, entries, options);
@@ -3873,21 +4028,29 @@ $grant$`);
3873
4028
  });
3874
4029
  }
3875
4030
  async replace(sessionId, header, entries, options) {
4031
+ return this.writing(sessionId, this.writeReplace(sessionId, header, entries, options));
4032
+ }
4033
+ async writeReplace(sessionId, header, entries, options) {
3876
4034
  this.assertOpen();
3877
4035
  validateSessionText("sessionId", sessionId);
3878
4036
  this.writtenRows.delete(sessionId);
3879
4037
  let released = [];
3880
4038
  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) => {
4039
+ const pinReads = this.sharedHistorySeen ? forkPinReads(this.forkHost(), this.tables.sessions, sessionId, true) : void 0;
4040
+ const searchLock = this.searchIndex?.writeLock(sessionId);
4041
+ const run = (lockLate) => this.transactionCheckedAlongside(async (tx, checked) => {
3883
4042
  released = [];
3884
4043
  entriesWritten = [];
3885
- const [, pins] = await Promise.all([this.forWrite(tx, sessionId, options), this.readForkPinsWithin(tx, sessionId, pinReads)]);
4044
+ const [, , pins] = await Promise.all([
4045
+ searchLock === void 0 ? void 0 : tx.get(searchLock.sql, ...searchLock.params),
4046
+ this.forWrite(tx, sessionId, options),
4047
+ this.readForkPinsWithin(tx, sessionId, pinReads, true)
4048
+ ]);
3886
4049
  await checked;
3887
4050
  validateSessionHeader(header);
3888
4051
  validateSessionEntries(entries);
3889
4052
  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) => {
4053
+ if (pins !== void 0) released = await replaceForkedSessionWithin(this.forkHost(), tx, sessionId, pins, lockLate).catch((error) => {
3891
4054
  noteForkCopyRefusal(error, "replace");
3892
4055
  throw error;
3893
4056
  });
@@ -3905,12 +4068,22 @@ $grant$`);
3905
4068
  lastSeq: entries.length,
3906
4069
  epoch
3907
4070
  };
3908
- }, this.sessionWrite(sessionId, ...pinReads === void 0 ? [] : [this.headRead(sessionId, options, false), ...pinReads]));
4071
+ }, this.sessionWrite(sessionId, ...searchLock === void 0 ? [] : [searchLock], ...pinReads === void 0 ? [] : [this.headRead(sessionId, options, false), ...pinReads]));
4072
+ let written;
4073
+ for (let attempt = 0;; attempt++) try {
4074
+ written = await run(attempt >= 3);
4075
+ break;
4076
+ } catch (error) {
4077
+ if (!(error instanceof ForkReadersMoved)) throw error;
4078
+ }
3909
4079
  this.noteWritten(sessionId, written.epoch, entriesWritten);
3910
4080
  await this.sweepReleasedForkRows(released);
3911
4081
  return written;
3912
4082
  }
3913
4083
  async updateHeader(header, options) {
4084
+ return this.writing(header.id, this.writeUpdateHeader(header, options));
4085
+ }
4086
+ async writeUpdateHeader(header, options) {
3914
4087
  this.assertOpen();
3915
4088
  validateSessionHeader(header);
3916
4089
  this.writtenRows.delete(header.id);
@@ -3943,7 +4116,7 @@ $grant$`);
3943
4116
  const row = await this.database.get(`SELECT last_seq FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
3944
4117
  if (row) announceHistoryLoad(row.last_seq);
3945
4118
  }
3946
- return this.readTransaction((tx) => this.read(tx, sessionId));
4119
+ return this.readTransaction(sessionId, (tx) => this.read(tx, sessionId));
3947
4120
  }
3948
4121
  async readEntryRange(sessionId, query) {
3949
4122
  this.assertOpen();
@@ -4053,6 +4226,9 @@ $grant$`);
4053
4226
  return row ? JSON.parse(row.header_json) : void 0;
4054
4227
  }
4055
4228
  async delete(sessionId) {
4229
+ return this.writing(sessionId, this.writeDelete(sessionId));
4230
+ }
4231
+ async writeDelete(sessionId) {
4056
4232
  this.assertOpen();
4057
4233
  validateSessionText("sessionId", sessionId);
4058
4234
  this.writtenRows.delete(sessionId);
@@ -4087,10 +4263,10 @@ $grant$`);
4087
4263
  * The fork history of `sessionId` where the transaction `tx` runs on shared history: through `reads`, the transaction's
4088
4264
  * leading reads, or, for a store that had not seen shared history when the transaction began, read now.
4089
4265
  */
4090
- async readForkPinsWithin(tx, sessionId, reads) {
4266
+ async readForkPinsWithin(tx, sessionId, reads, readers = false) {
4091
4267
  if (reads !== void 0) return readForkPins(tx, reads);
4092
4268
  if (!await this.sharedHistoryForks(tx)) return void 0;
4093
- return readForkPins(tx, forkPinReads(this.forkHost(), this.tables.sessions, sessionId));
4269
+ return readForkPins(tx, forkPinReads(this.forkHost(), this.tables.sessions, sessionId, readers));
4094
4270
  }
4095
4271
  /**
4096
4272
  * Removes the rows of deleted sessions no fork reads any more, among `released` and any an earlier sweep left, in
@@ -4395,10 +4571,10 @@ $grant$`);
4395
4571
  }
4396
4572
  const idPrefix = query.idPrefix?.toLowerCase();
4397
4573
  return {
4398
- where: `(? = 1 OR internal = 0)${projectCwds ? ` AND cwd IN (${projectCwds.map(() => "?").join(", ")})` : ""}${idPrefix === void 0 ? "" : " AND substr(lower(id), 1, ?) = ?"}`,
4574
+ where: `(? = 1 OR internal = 0)${projectCwds ? ` AND ${inJsonList(this.dialect, "cwd")}` : ""}${idPrefix === void 0 ? "" : " AND substr(lower(id), 1, ?) = ?"}`,
4399
4575
  params: [
4400
4576
  query.includeInternal ? 1 : 0,
4401
- ...projectCwds ?? [],
4577
+ ...projectCwds ? [JSON.stringify(projectCwds)] : [],
4402
4578
  ...idPrefix === void 0 ? [] : [idPrefix.length, idPrefix]
4403
4579
  ],
4404
4580
  inScope: (row) => !matchesCwd || matchesCwd(row.cwd)
@@ -4419,7 +4595,7 @@ $grant$`);
4419
4595
  if (stale.length <= rows.length / 4) {
4420
4596
  for (let start = 0; start < stale.length; start += 500) {
4421
4597
  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));
4598
+ const fetched = new Set((await this.readSummaries(inJsonList(this.dialect, "id"), [JSON.stringify(ids)])).map((row) => row.id));
4423
4599
  for (const id of ids) if (!fetched.has(id)) this.summaries.delete(id);
4424
4600
  this.assertListing(query);
4425
4601
  }
@@ -4587,7 +4763,7 @@ $grant$`);
4587
4763
  async readRows(tx, sessionId, range = {}, seqs, epoch, viewTables) {
4588
4764
  const tables = viewTables ?? await this.viewTables(tx, sessionId);
4589
4765
  const through = range.through ?? FORK_VIEW_END;
4590
- const filter = seqs === void 0 ? "" : ` AND seq IN (${seqs.map(() => "?").join(", ")})`;
4766
+ const filter = seqs === void 0 ? "" : ` AND ${inJsonList(this.dialect, "seq", true)}`;
4591
4767
  const entries = [];
4592
4768
  for (let after = Math.max(0, (range.from ?? 1) - 1), limit = SESSION_READ_FETCH.first;;) {
4593
4769
  const view = this.entriesView(tables, sessionId, after, tables.segments === void 0 || seqs !== void 0 ? through : Math.min(through, after + limit + 1));
@@ -4610,7 +4786,7 @@ $grant$`);
4610
4786
  ) AS windowed WHERE (page_chars <= ? OR page_row = 1) AND page_row <= ?
4611
4787
  ) SELECT seq, COALESCE(inline_json, (
4612
4788
  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);
4789
+ )) AS entry_json, chunks, fetched, batch_chars, page_chars FROM page ORDER BY seq`), ...forkViewParams([view]), SESSION_READ_INLINE_BYTES, after, ...seqs === void 0 ? [] : [JSON.stringify(seqs)], limit + 1, limit, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, limit);
4614
4790
  const generation = await epoch;
4615
4791
  const note = generation === void 0 || !this.sharedHistorySeen ? void 0 : storedEntryNotes(this, sessionId, generation);
4616
4792
  for (const entry of rows) {
@@ -5051,7 +5227,7 @@ $grant$`);
5051
5227
  this.assertOpen();
5052
5228
  validateSessionText("sessionId", sessionId);
5053
5229
  const start = Math.max(1, fromSeq);
5054
- const { tail } = await this.withResumeIndex(sessionId, () => this.readTransaction(async (tx) => {
5230
+ const { tail } = await this.withResumeIndex(sessionId, () => this.readTransaction(sessionId, async (tx) => {
5055
5231
  const source = await this.resumeSource(tx, sessionId);
5056
5232
  const stateSeqs = stateSeqsBefore(source.index, start);
5057
5233
  if (hasHistoryLoadObserver()) announceHistoryLoad(stateSeqs.length + Math.max(0, source.index.seq - start + 1));
@@ -5068,7 +5244,7 @@ $grant$`);
5068
5244
  this.assertOpen();
5069
5245
  validateSessionText("sessionId", sessionId);
5070
5246
  const start = Math.max(1, startSeq);
5071
- return this.readTransaction(async (tx) => {
5247
+ return this.readTransaction(sessionId, async (tx) => {
5072
5248
  const head = await this.historyHead(tx, sessionId, true);
5073
5249
  if (expectedEpoch !== void 0 && expectedEpoch !== head.epoch) throw new SessionConflictError$1(sessionId, endSeq, head.lastSeq);
5074
5250
  const entries = endSeq < start ? [] : await this.readRows(tx, sessionId, {
@@ -5140,7 +5316,7 @@ $grant$`);
5140
5316
  const { childDisplayCut } = await import("../core/storage/session/card-view.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
5141
5317
  const { index } = await this.prepareResume(sessionId);
5142
5318
  if (typeof launch.launchLeafId !== "string") return childDisplayCut(index, launch);
5143
- return this.readTransaction(async (tx) => {
5319
+ return this.readTransaction(sessionId, async (tx) => {
5144
5320
  const head = await this.historyHead(tx, sessionId, true);
5145
5321
  if (head.epoch !== index.epoch || head.lastSeq < index.seq) throw new SessionConflictError$1(sessionId, index.seq, head.lastSeq);
5146
5322
  const view = forkView(await this.viewTables(tx, sessionId), {
@@ -5195,7 +5371,7 @@ $grant$`);
5195
5371
  * timestamp; its caller streams those fields instead of joining or decoding the stored body. */
5196
5372
  async readTreeOutline(sessionId, fromSeq, toSeq, epoch) {
5197
5373
  this.assertOpen();
5198
- return this.readTransaction(async (tx) => {
5374
+ return this.readTransaction(sessionId, async (tx) => {
5199
5375
  const head = await this.historyHead(tx, sessionId, true);
5200
5376
  if (epoch !== void 0 && head.epoch !== epoch || head.lastSeq < toSeq) throw new SessionConflictError$1(sessionId, toSeq, head.lastSeq);
5201
5377
  const sqlite = this.dialect.name === "sqlite";
@@ -5240,12 +5416,12 @@ $grant$`);
5240
5416
  const limit = entrySizeLimit(options.limit);
5241
5417
  const wanted = options.backward ? seqs.slice(-limit) : seqs.slice(0, limit);
5242
5418
  if (!wanted.length) return { items: [] };
5243
- return this.readTransaction(async (tx) => {
5419
+ return this.readTransaction(sessionId, async (tx) => {
5244
5420
  const head = await this.historyHead(tx, sessionId, true);
5245
5421
  if (head.epoch !== epoch || head.lastSeq < wanted.at(-1)) throw new SessionConflictError$1(sessionId, wanted.at(-1), head.lastSeq);
5246
5422
  const tail = `(SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id=e.src_id AND c.seq=e.src_seq AND c.idx=e.chunks-1)`;
5247
5423
  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);
5424
+ const rows = await tx.all(withForkViews([view], `SELECT seq,CASE WHEN chunks=0 THEN ${this.entryByteLength("entry_json")} ELSE (chunks-1)*?+${tail} END bytes FROM ${view.name} e WHERE session_id=? AND ${inJsonList(this.dialect, "seq", true)} ORDER BY seq`), ...view.params, SESSION_ENTRY_CHUNK_BYTES, sessionId, JSON.stringify(wanted));
5249
5425
  const sizes = new Map(rows.map((row) => [Number(row.seq), row.bytes == null ? void 0 : Number(row.bytes)]));
5250
5426
  const plan = selectedPagePlan(sessionId, wanted, head.lastSeq, (seq) => {
5251
5427
  const bytes = sizes.get(seq);
@@ -5279,7 +5455,7 @@ $grant$`);
5279
5455
  async readEntrySizes(sessionId, startSeq, endSeq, limit) {
5280
5456
  this.assertOpen();
5281
5457
  validateSessionText("sessionId", sessionId);
5282
- return this.readTransaction(async (tx) => {
5458
+ return this.readTransaction(sessionId, async (tx) => {
5283
5459
  const head = await this.historyHead(tx, sessionId, true);
5284
5460
  const lastChunk = `(SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.src_id AND c.seq = e.src_seq AND c.idx = e.chunks - 1)`;
5285
5461
  const tables = await this.viewTables(tx, sessionId);
@@ -5444,7 +5620,7 @@ $grant$`);
5444
5620
  }
5445
5621
  /**
5446
5622
  * 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
5623
+ * on SQLite, a message whose stored type and role say it is a tool result, or an assistant message with a
5448
5624
  * tool call named other than `exceptCalls`, and any row that is not valid JSON; on Postgres, which would parse each
5449
5625
  * row's JSON to read those, any row whose JSON holds a tool call block's `"toolCall"` or a result's `"toolResult"`,
5450
5626
  * which `JSON.stringify`, the only writer of a row, always writes as such (it never escapes a letter).
@@ -5513,7 +5689,7 @@ $grant$`);
5513
5689
  this.assertOpen();
5514
5690
  validateSessionText("sessionId", sessionId);
5515
5691
  const { candidates, afterSeq, limit } = taskReferenceDuplicateQuery(query);
5516
- return this.readTransaction(async (tx) => {
5692
+ return this.readTransaction(sessionId, async (tx) => {
5517
5693
  const tables = await this.viewTables(tx, sessionId);
5518
5694
  const head = await this.historyHead(tx, sessionId, true);
5519
5695
  if (head.epoch !== query.epoch || head.lastSeq < query.throughSeq) throw new SessionConflictError$1(sessionId, query.throughSeq, head.lastSeq);
@@ -5585,7 +5761,7 @@ $grant$`);
5585
5761
  this.assertOpen();
5586
5762
  validateSessionText("sessionId", sessionId);
5587
5763
  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) => {
5764
+ return this.readTransaction(sessionId, async (tx) => {
5589
5765
  const snapshots = snapshotIndexTables$1(this.prefix);
5590
5766
  const shared = await this.viewTables(tx);
5591
5767
  const headRead = (leafTables) => {
@@ -5626,7 +5802,7 @@ $grant$`);
5626
5802
  const raw = this.dialect.name === "sqlite" ? "CAST(entry_json AS BLOB)" : "convert_to(entry_json,'UTF8')";
5627
5803
  const size = this.dialect.textByteLength("entry_json");
5628
5804
  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);
5805
+ const rows = await tx.all(withForkViews([view], `SELECT seq,chunks,${size} AS bytes,CASE WHEN chunks=0 AND ${size}<=512 THEN entry_json END AS body FROM ${view.name} WHERE session_id=? AND ${inJsonList(this.dialect, "seq", true)} ORDER BY seq`), ...view.params, sessionId, JSON.stringify(seqs));
5630
5806
  for (const row of rows) {
5631
5807
  const seq = Number(row.seq);
5632
5808
  if (row.body !== null) result.push(forkMetadata(seq, JSON.parse(row.body)));
@@ -5643,6 +5819,7 @@ $grant$`);
5643
5819
  return result;
5644
5820
  };
5645
5821
  const j = (field) => this.dialect.jsonText("entry_json", field);
5822
+ const dialect = this.dialect;
5646
5823
  const scanWindow = (from, through) => {
5647
5824
  const end = tables.segments === void 0 ? through : Math.min(through, from - 1 + SCAN_SELECT_WINDOW);
5648
5825
  return {
@@ -5692,7 +5869,7 @@ $grant$`);
5692
5869
  for (let i = 0; i < chunkedMessages.length; i += SEQ_BATCH) {
5693
5870
  const batch = chunkedMessages.slice(i, i + SEQ_BATCH);
5694
5871
  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);
5872
+ const prefixes = await tx.all(withForkViews([view], `SELECT v.seq,substr(c.data,1,${FORK_ROLE_PREFIX_BYTES}) AS prefix FROM ${view.name} v JOIN ${this.tables.entryChunks} c ON c.session_id=v.src_id AND c.seq=v.src_seq AND c.idx=0 WHERE ${inJsonList(this.dialect, "v.seq", true)}`), ...view.params, JSON.stringify(batch));
5696
5873
  for (const row of prefixes) roles.set(Number(row.seq), messageRoleIn(row.prefix));
5697
5874
  }
5698
5875
  }
@@ -5725,13 +5902,13 @@ $grant$`);
5725
5902
  through: hi
5726
5903
  }, void 0, generation), (seqs) => this.readSeqs(tx, sessionId, seqs, generation), metadata, async function* (ranges, kinds, types = []) {
5727
5904
  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(",")})))`);
5905
+ if (types.length) filters.push(inJsonList(dialect, j("type")));
5906
+ if (kinds.length) filters.push(`(${j("type")}='custom' AND (chunks>0 OR ${inJsonList(dialect, j("customType"))}))`);
5730
5907
  for (const [lo, hi] of ranges) for (let seq = lo; seq <= hi;) {
5731
5908
  const labels = types.length === 1 && types[0] === "label";
5732
5909
  const limit = labels ? SESSION_READ_FETCH.first : SESSION_READ_FETCH.max;
5733
5910
  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);
5911
+ const rows = await tx.all(withForkViews([view], `SELECT seq,${j("type")} AS kind${labels ? `,${labelBody} AS body` : ""} FROM ${view.name} WHERE session_id=? AND seq BETWEEN ? AND ? AND (${filters.join(" OR ")}) ORDER BY seq LIMIT ${limit}`), ...view.params, sessionId, seq, end, ...types.length ? [JSON.stringify(types)] : [], ...kinds.length ? [JSON.stringify(kinds)] : []);
5735
5912
  const deferred = rows.filter((r) => r.kind === "custom" || r.kind === "label" && !r.body).map((r) => Number(r.seq));
5736
5913
  const projected = /* @__PURE__ */ new Map();
5737
5914
  for (let i = 0; i < deferred.length; i += SEQ_BATCH) for (const m of await metadata(deferred.slice(i, i + SEQ_BATCH))) projected.set(m.seq, m);
@@ -5773,7 +5950,7 @@ $grant$`);
5773
5950
  validateSessionText("sessionId", sessionId);
5774
5951
  if (leafId !== void 0) validateSessionText("entry.id", leafId);
5775
5952
  if (leafId === void 0 && throughSeq === void 0) try {
5776
- return await this.readTransaction(async (tx) => {
5953
+ return await this.readTransaction(sessionId, async (tx) => {
5777
5954
  const { header, index } = await this.resumeSource(tx, sessionId);
5778
5955
  return this.resumeIn(tx, sessionId, header, index, options);
5779
5956
  }, [this.resumeRow(sessionId)]);
@@ -5782,7 +5959,7 @@ $grant$`);
5782
5959
  }
5783
5960
  for (let attempt = 0; attempt < 3; attempt++) {
5784
5961
  const { index, revision } = await this.prepareResume(sessionId, leafId, throughSeq);
5785
- const resume = await this.readTransaction(async (tx) => {
5962
+ const resume = await this.readTransaction(sessionId, async (tx) => {
5786
5963
  const { segments } = await this.viewTables(tx);
5787
5964
  const head = await tx.get(`SELECT header_json,revision${this.forkedColumn(segments)} FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
5788
5965
  if (!head) throw new SessionNotFoundError$1(sessionId);
@@ -5816,7 +5993,7 @@ $grant$`);
5816
5993
  this.assertOpen();
5817
5994
  validateSessionText("sessionId", sessionId);
5818
5995
  if (leafId !== void 0) validateSessionText("entry.id", leafId);
5819
- const { point } = await this.withResumeIndex(sessionId, () => this.readTransaction(async (tx) => {
5996
+ const { point } = await this.withResumeIndex(sessionId, () => this.readTransaction(sessionId, async (tx) => {
5820
5997
  const source = await this.resumeSource(tx, sessionId);
5821
5998
  const { index } = source;
5822
5999
  const leafSeq = leafId === void 0 ? index.leafSeq : await this.seqOfEntry(tx, await this.viewTables(tx, sessionId), sessionId, leafId) ?? -1;
@@ -12769,16 +12946,16 @@ var ThemeSelectorComponent = class extends FramedSelector {
12769
12946
  * update without an ESM missing-export error.
12770
12947
  */
12771
12948
  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 };
12949
+ export { CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL, COMPACTOR_COMPRESSION_RATIO, ClassifierDecisionError, GITHUB_COPILOT_ERROR_DIAGNOSTIC, GitHubCopilotAuthenticationError, GitHubCopilotContentFilterError, GitHubCopilotEmptyResponseError, GitHubCopilotError, GitHubCopilotInvalidRequestError, GitHubCopilotModelUnavailableError, GitHubCopilotPromptTooLargeError, GitHubCopilotQuotaExhaustedError, GitHubCopilotRateLimitError, GitHubCopilotServiceUnavailableError, GitHubCopilotStreamEndedEarlyError, GitHubCopilotUnrecognizedResponseError, IntercomBrokerError, IntercomBrokerProtocolError, IntercomBrokerStopTimeoutError, IntercomBrokerSuccessorTimeoutError, IntercomBrokerUpgradeError, IntercomRoutingChangedError, IntercomRoutingError, IntercomRoutingMismatchError, IntercomRoutingTimeoutError, IntercomRoutingUnavailableError, LISTING_FETCH_BATCH, MAX_SESSION_START_TIMEOUT_MS, McpOAuthAuthorizationRequiredError, McpOAuthCredentialStore, McpSignInCancelledError, MemorySnapshotBlobStore, ModelRegistry, OAuthRefreshRejectedError, OAuthTemporarilyUnavailableError, OutputRepairExhaustedError, ProjectGroupError, ProviderRequestFailure, RUNTIME_INTERCOM_GROUP_ENV, SESSION_APPEND_FUNCTION_DOMAIN, SESSION_BLOB_CHUNK_BYTES, SESSION_DOMAIN, SESSION_ENTRY_CHUNK_BYTES, SESSION_FILLFACTOR_DOMAIN, SESSION_PRESENCE_DOMAIN, SESSION_PRESENCE_TABLES, SESSION_READ_FETCH, SESSION_READ_PAGE_CHARS, SESSION_RESUME_REBUILD, SESSION_SCHEMA_VERSION, SESSION_SCHEMA_VERSION_CHUNKED, SESSION_SCHEMA_VERSION_SHARED_HISTORY, SESSION_TABLES, SNAPSHOT_COLLECTION_BATCH, SessionConflictError, SessionExistsError, SessionFormatVersionError, SessionIdMismatchError, SessionInvalidTextError, SessionInvalidTimestampError, SessionNotFoundError, SessionStartConfigError, SessionStartError, SessionStartTimeoutError, ShowImagesSelectorComponent, SqlSessionStore, SqlSnapshotBlobStore, TEAM_JOIN_COMMAND, TerminalDecisionError, ThemeSelectorComponent, addMcpServerConfigAsync, announceBlueprintBuildWaits, clampThinkingLevel, classifyGitHubCopilotFailure, configuredSecretRedactor, createGatewayBindingFetch, createMcpAuthProvider, createMcpExtension, createTranscript, decide, decisionFailure, describeGitHubCopilotModel, deserializeGitHubCopilotError, findGitHubCopilotError, findSessionStartError, generateStructuredOutput, getGitHubCopilotError, getMcpToolExposure, getSupportedThinkingLevels, githubChecks, githubReviews, interval, isGitHubCopilotAuthenticationError, isGitHubCopilotContentFilterError, isGitHubCopilotEmptyResponseError, isGitHubCopilotError, isGitHubCopilotInvalidRequestError, isGitHubCopilotModelUnavailableError, isGitHubCopilotPromptTooLargeError, isGitHubCopilotQuotaExhaustedError, isGitHubCopilotRateLimitError, isGitHubCopilotServiceUnavailableError, isGitHubCopilotStreamEndedEarlyError, isGitHubCopilotUnrecognizedResponseError, isIntercomBrokerError, isIntercomBrokerProtocolError, isIntercomBrokerStopTimeoutError, isIntercomBrokerSuccessorTimeoutError, isIntercomBrokerUpgradeError, isIntercomRoutingChangedError, isIntercomRoutingError, isIntercomRoutingMismatchError, isIntercomRoutingTimeoutError, isIntercomRoutingUnavailableError, isOAuthRefreshRejectedError, isProjectGroupError, isRetryableGitHubCopilotError, isRetryableIntercomBrokerError, isRetryableIntercomRoutingError, isRetryableSessionStartError, isSessionStartConfigError, isSessionStartError, isSessionStartTimeoutError, loadMcpConfigAsync, logTail, mcpNamespace, mcpRequestTimeoutMs, parseFlattenedKeyPath, parseSessionStartTimeoutMs, publishExtensionContextEffect, publishPullRequest, readRuntimeIntercomGroup, reconstructFlattenedKeys, registerExtensionContextRetirementEffect, rehydrateIntercomBrokerError, rehydrateSessionStartError, removeMcpServerConfigAsync, resolveAutoModel, resolveDecisionModel, resolveMcpServerUrl, restoreRunWorktree, runDecision, runPrintMode, runRestorePreconditionError, runtimeIntercomGroupEnvKey, serializeGitHubCopilotError, serializeIntercomBrokerError, serializeSessionStartError, sessionScopedExtensionState, sessionStartStepText, setUpRestoredRunWorktrees, setUpResumedRunWorktrees, signInMcpServer, snapshotBlobHashes, snapshotIndexTables, unflattenArgumentsWithSchema, updateMcpServerConfig, updateMcpServerConfigAsync, validateMcpServerConfig, webhook, workspaceChangeSet, writeBlueprintBuildEvent };
12773
12950
 
12774
- //# sourceMappingURL=sdk-IQMULKFU.js.map
12951
+ //# sourceMappingURL=sdk-B5LEWGGI.js.map
12775
12952
  // __atomicOnDemandFailed: written by the build (scripts/in-place-update-gate.mjs). An import of this release's code on
12776
12953
  // demand that fails in a process an in-place update left running says to restart.
12777
12954
  function __atomicOnDemandFailed(error, feature) {
12778
12955
  return (async () => {
12779
12956
  const root = new URL("../", import.meta.url);
12780
12957
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
12781
- const key = `${root.href}#0.10.11-alpha.2`;
12958
+ const key = `${root.href}#0.10.11-alpha.3`;
12782
12959
  let release = releases.get(key);
12783
12960
  if (release === undefined) {
12784
12961
  const current = (async () => {
@@ -12806,7 +12983,7 @@ function __atomicOnDemandFailed(error, feature) {
12806
12983
  } catch {
12807
12984
  // No installation to read, as in a bundle of the package: the release the process runs decides.
12808
12985
  }
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;
12986
+ const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.3" ? installed : running !== undefined && running.version !== "0.10.11-alpha.3" ? "0.10.11-alpha.3" : undefined;
12810
12987
  if (updatedTo === undefined) throw error;
12811
12988
  const application = typeof running?.name === "string" ? running.name : "atomic";
12812
12989
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {