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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (457) hide show
  1. package/CHANGELOG.md +155 -0
  2. package/README.md +5 -8
  3. package/dist/_shared/dist-KOELCESV.js +2 -2
  4. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  5. package/dist/_shared/lib-4PES5P4V.js +2 -2
  6. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +9 -9
  7. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +8 -8
  8. package/dist/_shared/mode-shared-2QJSCUM6.js +9 -9
  9. package/dist/_shared/p0-cli-BB45ZQY6.js +46 -67
  10. package/dist/_shared/p0-cli-BB45ZQY6.js.map +1 -1
  11. package/dist/_shared/p1a-prewarm-XIU57JHF.js +7 -8
  12. package/dist/_shared/p1a-prewarm-XIU57JHF.js.map +1 -1
  13. package/dist/_shared/{p1b-elig-ENCUPKKJ.js → p1b-elig-TVB5CBLL.js} +14 -2
  14. package/dist/_shared/{p1b-elig-ENCUPKKJ.js.map → p1b-elig-TVB5CBLL.js.map} +1 -1
  15. package/dist/_shared/runtime-O4KCSG4C.js +5 -5
  16. package/dist/_shared/{sdk-AVFII7NK.js → sdk-B5LEWGGI.js} +2633 -488
  17. package/dist/_shared/sdk-B5LEWGGI.js.map +1 -0
  18. package/dist/_shared/session-data-AHTU7IS6.js +3 -3
  19. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  20. package/dist/_shared/settings-startup-8-DNZ2RIHM.js +1 -1
  21. package/dist/_shared/{settings-startup-4QCVCI53.js → settings-startup-HXQLSUWM.js} +8 -2
  22. package/dist/_shared/settings-startup-HXQLSUWM.js.map +1 -0
  23. package/dist/_shared/{startup-0-0-57KF6LZH.js → startup-0-0-EZUKEP4Q.js} +436 -51
  24. package/dist/_shared/startup-0-0-EZUKEP4Q.js.map +1 -0
  25. package/dist/_shared/{startup-0-1-GIY75K46.js → startup-0-1-RTOHJFDJ.js} +240 -279
  26. package/dist/_shared/startup-0-1-RTOHJFDJ.js.map +1 -0
  27. package/dist/_shared/{startup-0-2-27OWFHV6.js → startup-0-2-5QHPCEON.js} +254 -46
  28. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -0
  29. package/dist/_shared/{startup-0-3-T4DVFYWX.js → startup-0-3-4ZYBYQNM.js} +273 -14
  30. package/dist/_shared/startup-0-3-4ZYBYQNM.js.map +1 -0
  31. package/dist/_shared/startup-0-4-ZMJV547D.js +14 -9
  32. package/dist/_shared/startup-0-4-ZMJV547D.js.map +1 -1
  33. package/dist/_shared/startup-0-5-YDW47QX6.js +10 -10
  34. package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -1
  35. package/dist/_shared/startup-10-0-TDQNBDDL.js +9 -9
  36. package/dist/_shared/startup-12-0-55AAXBJZ.js +3 -3
  37. package/dist/_shared/startup-14-0-MLX36RBG.js +6 -7
  38. package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
  39. package/dist/_shared/startup-15-0-YUKGAC63.js +7 -7
  40. package/dist/_shared/startup-15-1-4S7FLMNG.js +22 -30
  41. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  42. package/dist/_shared/startup-8-0-34CBHPZH.js +455 -102
  43. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  44. package/dist/_shared/{startup-8-1-X32CYSXB.js → startup-8-1-LZFXSD3Z.js} +162 -1184
  45. package/dist/_shared/startup-8-1-LZFXSD3Z.js.map +1 -0
  46. package/dist/_shared/storage-command-7MGXLJGZ.js +189 -36
  47. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  48. package/dist/_shared/storage-status-K7PX2RXA.js +557 -0
  49. package/dist/_shared/storage-status-K7PX2RXA.js.map +1 -0
  50. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  51. package/dist/_shared/team-DOQKICG2.js +376 -0
  52. package/dist/_shared/team-DOQKICG2.js.map +1 -0
  53. package/dist/_shared/tree-outline-MUEPK5B7.js +3 -3
  54. package/dist/builtin/intercom/CHANGELOG.md +34 -0
  55. package/dist/builtin/intercom/README.md +2 -2
  56. package/dist/builtin/intercom/broker/broker.bundle.mjs +1091 -344
  57. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +243 -64
  58. package/dist/builtin/intercom/broker/multinode-router.ts +154 -22
  59. package/dist/builtin/intercom/broker/multinode-state-store.ts +30 -3
  60. package/dist/builtin/intercom/broker/open-broker-state.ts +14 -0
  61. package/dist/builtin/intercom/broker/sql-add-column.ts +29 -5
  62. package/dist/builtin/intercom/broker/sql-ended-child-queue-store.ts +3 -2
  63. package/dist/builtin/intercom/broker/sql-held-send-store.ts +2 -2
  64. package/dist/builtin/intercom/broker/sql-known-session-store.ts +43 -19
  65. package/dist/builtin/intercom/broker/sql-lease-store.ts +208 -101
  66. package/dist/builtin/intercom/broker/sql-outbox-store.ts +516 -102
  67. package/dist/builtin/intercom/broker/sql-pending-ask-store.ts +8 -5
  68. package/dist/builtin/intercom/broker/sql-released-ask-store.ts +12 -5
  69. package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +24 -7
  70. package/dist/builtin/intercom/broker/sql-retention.ts +141 -0
  71. package/dist/builtin/intercom/broker/sql-schema.ts +199 -27
  72. package/dist/builtin/intercom/broker/sql-sent-message-authority.ts +74 -19
  73. package/dist/builtin/intercom/broker/wake-up-bus.ts +6 -0
  74. package/dist/builtin/intercom/index.bundle.mjs +2 -3
  75. package/dist/builtin/intercom/package.json +1 -1
  76. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  77. package/dist/builtin/mcp/package.json +1 -1
  78. package/dist/builtin/subagents/CHANGELOG.md +6 -0
  79. package/dist/builtin/subagents/package.json +1 -1
  80. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  81. package/dist/builtin/web-access/index.bundle.mjs +2 -10
  82. package/dist/builtin/web-access/package.json +1 -1
  83. package/dist/bun/bundled-sqlite.js +41 -0
  84. package/dist/bun/bundled-sqlite.js.map +1 -0
  85. package/dist/cli/args.js +2 -2
  86. package/dist/cli/auth-cli.code.js +6 -6
  87. package/dist/cli/auth-cli.impl.js +3 -3
  88. package/dist/cli/auth-cli.js +3 -3
  89. package/dist/cli/blueprint-command.code.js +4 -4
  90. package/dist/cli/blueprint-command.impl.js +3 -3
  91. package/dist/cli/blueprint-command.js +3 -3
  92. package/dist/cli/intercom-command.code.js +4 -4
  93. package/dist/cli/intercom-command.code.js.map +1 -1
  94. package/dist/cli/intercom-command.impl.js +3 -3
  95. package/dist/cli/intercom-command.js +3 -3
  96. package/dist/cli/list-models.code.js +2 -2
  97. package/dist/cli/list-models.impl.js +3 -3
  98. package/dist/cli/list-models.js +3 -3
  99. package/dist/cli/session-picker.code.js +2 -2
  100. package/dist/cli/session-picker.impl.js +3 -3
  101. package/dist/cli/session-picker.js +3 -3
  102. package/dist/cli/startup-ui.code.js +2 -2
  103. package/dist/cli/startup-ui.impl.js +3 -3
  104. package/dist/cli/startup-ui.js +3 -3
  105. package/dist/cli/storage-command.impl.js +3 -3
  106. package/dist/cli/storage-command.js +3 -3
  107. package/dist/cli/storage-search-session.code.js +3 -3
  108. package/dist/cli/storage-search-session.impl.js +3 -3
  109. package/dist/cli/storage-search-session.js +3 -3
  110. package/dist/cli/team-command.code.js +20 -114
  111. package/dist/cli/team-command.code.js.map +1 -1
  112. package/dist/cli/team-command.impl.js +3 -3
  113. package/dist/cli/team-command.js +3 -3
  114. package/dist/cli.js +5 -18
  115. package/dist/cli.js.map +1 -1
  116. package/dist/core/agent-rehydrate-errors.d.ts +4 -9
  117. package/dist/core/compaction/compactor.d.ts +3 -3
  118. package/dist/core/debug.code.js +1 -1
  119. package/dist/core/debug.impl.js +3 -3
  120. package/dist/core/debug.js +3 -3
  121. package/dist/core/export-html/card-projection.impl.js +3 -3
  122. package/dist/core/export-html/card-projection.js +3 -3
  123. package/dist/core/export-html/index.code.js +2 -2
  124. package/dist/core/export-html/index.impl.js +3 -3
  125. package/dist/core/export-html/index.js +3 -3
  126. package/dist/core/export-html/json-spans.impl.js +3 -3
  127. package/dist/core/export-html/json-spans.js +3 -3
  128. package/dist/core/export-html/oversized-render-inputs.code.js +1 -1
  129. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  130. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  131. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  132. package/dist/core/export-html/tool-renderer.js +3 -3
  133. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  134. package/dist/core/extensions/jiti-loader.js +3 -3
  135. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  136. package/dist/core/extensions/jiti-static-loader.js +3 -3
  137. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  138. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  139. package/dist/core/extensions/loader-host-modules.js +3 -3
  140. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  141. package/dist/core/extensions/runner-context.js +3 -3
  142. package/dist/core/intercom-broker-control-host.code.js +2 -2
  143. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  144. package/dist/core/intercom-broker-control-host.js +3 -3
  145. package/dist/core/intercom-broker-control.code.js +3 -3
  146. package/dist/core/intercom-broker-control.impl.js +3 -3
  147. package/dist/core/intercom-broker-control.js +3 -3
  148. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  149. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  150. package/dist/core/package-manager-storage-adapters.js +3 -3
  151. package/dist/core/process-start-token.d.ts +8 -0
  152. package/dist/core/process-tree-containment.d.ts +16 -0
  153. package/dist/core/sdk-types.d.ts +1 -2
  154. package/dist/core/sdk-types.js.map +1 -1
  155. package/dist/core/sdk.code.js +4 -4
  156. package/dist/core/sdk.impl.js +3 -3
  157. package/dist/core/sdk.js +3 -3
  158. package/dist/core/session-manager-core.js +27 -15
  159. package/dist/core/session-manager-core.js.map +1 -1
  160. package/dist/core/session-manager-list.impl.js +3 -3
  161. package/dist/core/session-manager-list.js +3 -3
  162. package/dist/core/session-manager.code.js +3 -3
  163. package/dist/core/session-manager.impl.js +3 -3
  164. package/dist/core/session-manager.js +3 -3
  165. package/dist/core/session-open-markers.js +3 -0
  166. package/dist/core/session-open-markers.js.map +1 -0
  167. package/dist/core/session-storage.code.js +1 -1
  168. package/dist/core/session-storage.impl.js +3 -3
  169. package/dist/core/session-storage.js +3 -3
  170. package/dist/core/settings-schema.d.ts +0 -3
  171. package/dist/core/storage/added-exports-0-10-11.js +19 -0
  172. package/dist/core/storage/added-exports-0-10-11.js.map +1 -0
  173. package/dist/core/storage/added-exports.js +3 -0
  174. package/dist/core/storage/added-exports.js.map +1 -1
  175. package/dist/core/storage/creation-time.js +105 -0
  176. package/dist/core/storage/creation-time.js.map +1 -0
  177. package/dist/core/storage/database.d.ts +56 -5
  178. package/dist/core/storage/database.js.map +1 -1
  179. package/dist/core/storage/dialect.d.ts +1 -1
  180. package/dist/core/storage/dialect.js +1 -1
  181. package/dist/core/storage/dialect.js.map +1 -1
  182. package/dist/core/storage/errors.d.ts +13 -13
  183. package/dist/core/storage/errors.js +10 -16
  184. package/dist/core/storage/errors.js.map +1 -1
  185. package/dist/core/storage/fenced-paths.d.ts +11 -0
  186. package/dist/core/storage/fenced-paths.js +11 -0
  187. package/dist/core/storage/fenced-paths.js.map +1 -1
  188. package/dist/core/storage/file-identity.d.ts +2 -0
  189. package/dist/core/storage/file-identity.js +24 -8
  190. package/dist/core/storage/file-identity.js.map +1 -1
  191. package/dist/core/storage/index.d.ts +4 -3
  192. package/dist/core/storage/index.js +5 -3
  193. package/dist/core/storage/index.js.map +1 -1
  194. package/dist/core/storage/libsql-removed.d.ts +71 -0
  195. package/dist/core/storage/libsql-removed.js +123 -0
  196. package/dist/core/storage/libsql-removed.js.map +1 -0
  197. package/dist/core/storage/migrations.d.ts +81 -8
  198. package/dist/core/storage/migrations.js +386 -47
  199. package/dist/core/storage/migrations.js.map +1 -1
  200. package/dist/core/storage/node-sqlite-file-gate.js +0 -15
  201. package/dist/core/storage/node-sqlite-file-gate.js.map +1 -1
  202. package/dist/core/storage/node-sqlite-thread.js +36 -12
  203. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  204. package/dist/core/storage/node-sqlite.js +135 -3
  205. package/dist/core/storage/node-sqlite.js.map +1 -1
  206. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  207. package/dist/core/storage/offline-snapshot-file.js +3 -3
  208. package/dist/core/storage/prefix.d.ts +1 -1
  209. package/dist/core/storage/prefix.js +14 -2
  210. package/dist/core/storage/prefix.js.map +1 -1
  211. package/dist/core/storage/process-selection.d.ts +5 -5
  212. package/dist/core/storage/provider.js +2 -2
  213. package/dist/core/storage/schema-catalog.d.ts +82 -5
  214. package/dist/core/storage/schema-catalog.js +244 -34
  215. package/dist/core/storage/schema-catalog.js.map +1 -1
  216. package/dist/core/storage/selection.d.ts +7 -82
  217. package/dist/core/storage/selection.js +20 -235
  218. package/dist/core/storage/selection.js.map +1 -1
  219. package/dist/core/storage/session/branch-fork-source.code.js +9 -8
  220. package/dist/core/storage/session/branch-fork-source.code.js.map +1 -1
  221. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  222. package/dist/core/storage/session/branch-fork-source.js +3 -3
  223. package/dist/core/storage/session/card-view.impl.js +3 -3
  224. package/dist/core/storage/session/card-view.js +3 -3
  225. package/dist/core/storage/session/child-reader.code.js +4 -4
  226. package/dist/core/storage/session/child-reader.impl.js +3 -3
  227. package/dist/core/storage/session/child-reader.js +3 -3
  228. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  229. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  230. package/dist/core/storage/session/errors.js +1 -1
  231. package/dist/core/storage/session/expanded-child-details.code.js +3 -3
  232. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  233. package/dist/core/storage/session/expanded-child-details.js +3 -3
  234. package/dist/core/storage/session/fork-detach.d.ts +118 -0
  235. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  236. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  237. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  238. package/dist/core/storage/session/fork-row-index.js +3 -3
  239. package/dist/core/storage/session/fork-schema.js +53 -0
  240. package/dist/core/storage/session/fork-schema.js.map +1 -0
  241. package/dist/core/storage/session/fork-segments.d.ts +58 -0
  242. package/dist/core/storage/session/fork-staging.code.js +5 -8
  243. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  244. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  245. package/dist/core/storage/session/fork-staging.js +3 -3
  246. package/dist/core/storage/session/fork-sweep.js +61 -0
  247. package/dist/core/storage/session/fork-sweep.js.map +1 -0
  248. package/dist/core/storage/session/fork-window.code.js +4 -4
  249. package/dist/core/storage/session/fork-window.impl.js +3 -3
  250. package/dist/core/storage/session/fork-window.js +3 -3
  251. package/dist/core/storage/session/history-pages.impl.js +3 -3
  252. package/dist/core/storage/session/history-pages.js +3 -3
  253. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  254. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  255. package/dist/core/storage/session/jsonl-session-store.d.ts +42 -2
  256. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  257. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  258. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  259. package/dist/core/storage/session/memory-session-store.js +3 -3
  260. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  261. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  262. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  263. package/dist/core/storage/session/released-history-files.code.js +4 -4
  264. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  265. package/dist/core/storage/session/released-history-files.js +3 -3
  266. package/dist/core/storage/session/resident-fork-rows.code.js +1 -1
  267. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  268. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  269. package/dist/core/storage/session/session-resume.impl.js +3 -3
  270. package/dist/core/storage/session/session-resume.js +3 -3
  271. package/dist/core/storage/session/session-search-index.d.ts +43 -4
  272. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  273. package/dist/core/storage/session/snapshot-cut.js +3 -3
  274. package/dist/core/storage/session/snapshot-history.code.js +4 -4
  275. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  276. package/dist/core/storage/session/snapshot-history.js +3 -3
  277. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  278. package/dist/core/storage/session/sql-session-store.d.ts +394 -20
  279. package/dist/core/storage/session/sql-session-store.impl.js +4 -4
  280. package/dist/core/storage/session/sql-session-store.js +4 -4
  281. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  282. package/dist/core/storage/session/tree-outline.js +3 -3
  283. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  284. package/dist/core/storage/session/tree-presentation.js +3 -3
  285. package/dist/core/storage/session/types.d.ts +22 -0
  286. package/dist/core/storage/sqlite-facade.d.ts +23 -2
  287. package/dist/core/storage/sqlite-facade.js +34 -0
  288. package/dist/core/storage/sqlite-facade.js.map +1 -1
  289. package/dist/core/storage/storage-status.code.js +1 -1
  290. package/dist/core/storage/storage-status.impl.js +3 -3
  291. package/dist/core/storage/storage-status.js +3 -3
  292. package/dist/core/storage/team.code.js +1 -1
  293. package/dist/core/storage/team.d.ts +26 -115
  294. package/dist/core/storage/team.impl.js +3 -3
  295. package/dist/core/storage/team.js +3 -3
  296. package/dist/core/structured-output/index.code.js +1 -1
  297. package/dist/core/structured-output/index.impl.js +3 -3
  298. package/dist/core/structured-output/index.js +3 -3
  299. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  300. package/dist/core/tasks/task-completion-entry.js +3 -3
  301. package/dist/core/tasks/task-file-history.code.js +4 -4
  302. package/dist/core/tasks/task-file-history.impl.js +3 -3
  303. package/dist/core/tasks/task-file-history.js +3 -3
  304. package/dist/core/tasks/task-reference-archive.code.js +5 -5
  305. package/dist/core/tasks/task-reference-archive.js +3 -3
  306. package/dist/core/tasks/task-reference-identity.js +3 -3
  307. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  308. package/dist/core/tasks/task-reference-stream.js +3 -3
  309. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  310. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  311. package/dist/core/tasks/task-view-source.code.js +1 -1
  312. package/dist/core/tasks/task-view-source.impl.js +3 -3
  313. package/dist/core/tasks/task-view-source.js +3 -3
  314. package/dist/core/tools/history-session.d.ts +2 -0
  315. package/dist/core/tools/history-tasks.d.ts +3 -2
  316. package/dist/core/tools/read-url.code.js +4 -4
  317. package/dist/core/tools/read-url.impl.js +3 -3
  318. package/dist/core/tools/read-url.js +3 -3
  319. package/dist/core/worktree-snapshot/blob-store.d.ts +71 -3
  320. package/dist/core/worktree-snapshot/blob-store.js +575 -67
  321. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  322. package/dist/core/worktree-snapshot/errors.code.js +3 -3
  323. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  324. package/dist/core/worktree-snapshot/errors.js +3 -3
  325. package/dist/core/worktree-snapshot/fork-blob-guard.js +81 -0
  326. package/dist/core/worktree-snapshot/fork-blob-guard.js.map +1 -0
  327. package/dist/core/worktree-snapshot/fork-snapshot-index.js +162 -0
  328. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -0
  329. package/dist/core/worktree-snapshot/session-index-reset.code.js +4 -0
  330. package/dist/core/worktree-snapshot/session-index-reset.code.js.map +1 -1
  331. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  332. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  333. package/dist/extensions/codemode/execute.code.js +2 -2
  334. package/dist/extensions/codemode/execute.impl.js +3 -3
  335. package/dist/extensions/codemode/execute.js +3 -3
  336. package/dist/extensions/codemode/renderer.code.js +2 -2
  337. package/dist/extensions/codemode/renderer.impl.js +3 -3
  338. package/dist/extensions/codemode/renderer.js +3 -3
  339. package/dist/extensions/mcp/cli.code.js +3 -3
  340. package/dist/extensions/mcp/cli.impl.js +3 -3
  341. package/dist/extensions/mcp/cli.js +3 -3
  342. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  343. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  344. package/dist/extensions/mcp/cli.lazy.js +3 -3
  345. package/dist/extensions/mcp/runtime.code.js +1 -1
  346. package/dist/extensions/mcp/runtime.impl.js +3 -3
  347. package/dist/extensions/mcp/runtime.js +3 -3
  348. package/dist/index.d.ts +3 -1
  349. package/dist/index.js +8 -8
  350. package/dist/main-first-time-setup.code.js +2 -2
  351. package/dist/main-first-time-setup.impl.js +3 -3
  352. package/dist/main-first-time-setup.js +3 -3
  353. package/dist/main.js +1 -1
  354. package/dist/modes/interactive/components/stored-tree-view.code.js +3 -3
  355. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  356. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  357. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  358. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  359. package/dist/modes/interactive/startup-shell-eligibility.js +1 -1
  360. package/dist/modes/interactive-engine/engine-prewarm.d.ts +1 -1
  361. package/dist/modes/print-mode.js +1 -1
  362. package/dist/package-manager-cli.code.js +7 -7
  363. package/dist/package-manager-cli.impl.js +3 -3
  364. package/dist/package-manager-cli.js +3 -3
  365. package/dist/rpc-entry.js +1 -1
  366. package/dist/startup-files.json +1 -1
  367. package/dist/startup-stages/10.js +1 -1
  368. package/dist/startup-stages/11.js +1 -1
  369. package/dist/startup-stages/12.js +1 -1
  370. package/dist/startup-stages/2.js +2 -3
  371. package/dist/startup-stages/3.js +1 -3
  372. package/dist/startup-stages/4.js +1 -2
  373. package/dist/startup-stages/5.js +1 -1
  374. package/dist/startup-stages/6.js +5 -7
  375. package/dist/startup-stages/7.js +3 -6
  376. package/dist/startup-stages/8.js +7 -2
  377. package/dist/startup-stages/9.js +1 -7
  378. package/dist/startup-stages/stages.json +1 -1
  379. package/dist/utils/compile-cache-deferral.js +8 -13
  380. package/dist/utils/compile-cache-deferral.js.map +1 -1
  381. package/dist/utils/compile-cache-warmup-host.js +3 -4
  382. package/dist/utils/compile-cache-warmup-host.js.map +1 -1
  383. package/dist/utils/compile-cache.js +12 -100
  384. package/dist/utils/compile-cache.js.map +1 -1
  385. package/dist/utils/startup-database-spare.code.js +3 -3
  386. package/dist/utils/startup-database-spare.impl.js +3 -3
  387. package/dist/utils/startup-database-spare.js +3 -3
  388. package/dist/utils/tools-manager.code.js +1 -1
  389. package/dist/utils/tools-manager.impl.js +3 -3
  390. package/dist/utils/tools-manager.js +3 -3
  391. package/dist/utils/worker-threads.js +2 -15
  392. package/dist/utils/worker-threads.js.map +1 -1
  393. package/docs/build.md +3 -3
  394. package/docs/changelog.mdx +1421 -69
  395. package/docs/compaction/reference.md +5 -5
  396. package/docs/compaction.md +7 -9
  397. package/docs/containerization.md +2 -2
  398. package/docs/custom-provider/api-reference.md +1 -1
  399. package/docs/docs.json +37 -10
  400. package/docs/environment-variables.md +0 -2
  401. package/docs/extensions/api-reference.md +4 -4
  402. package/docs/getting-started/installation.md +3 -0
  403. package/docs/guides/configuration.md +1 -1
  404. package/docs/guides/non-interactive.md +1 -1
  405. package/docs/guides/resume-on-any-machine.md +14 -22
  406. package/docs/guides/team-setup.md +56 -83
  407. package/docs/guides.md +2 -4
  408. package/docs/herdr.md +1 -1
  409. package/docs/index.md +1 -1
  410. package/docs/intercom/operations.md +26 -21
  411. package/docs/intercom/reference.md +2 -2
  412. package/docs/intercom.md +1 -1
  413. package/docs/libraries/storage-postgres.md +9 -9
  414. package/docs/libraries.md +2 -3
  415. package/docs/models-configuration.md +2 -2
  416. package/docs/models.md +2 -3
  417. package/docs/packages/authoring.md +7 -7
  418. package/docs/packages.md +1 -1
  419. package/docs/programmatic.md +2 -2
  420. package/docs/quickstart.md +1 -1
  421. package/docs/reference/cli.md +6 -11
  422. package/docs/reference.md +2 -2
  423. package/docs/rpc/extension-ui.md +2 -2
  424. package/docs/sdk/reference.md +5 -4
  425. package/docs/sdk/storage.md +8 -92
  426. package/docs/sdk/structured-decisions.md +1 -1
  427. package/docs/sdk/web-server.md +3 -3
  428. package/docs/sdk.md +14 -4
  429. package/docs/security.md +1 -1
  430. package/docs/session-format.md +5 -5
  431. package/docs/sessions.md +31 -42
  432. package/docs/settings.md +7 -8
  433. package/docs/storage/custom-adapters.md +255 -0
  434. package/docs/storage/jsonl.md +117 -0
  435. package/docs/{guides/postgres-pgbouncer.md → storage/postgres/pgbouncer.md} +73 -68
  436. package/docs/storage/postgres/tuning.md +337 -0
  437. package/docs/storage/postgres.md +556 -0
  438. package/docs/storage/sqlite.md +99 -0
  439. package/docs/storage.md +333 -956
  440. package/docs/subagents/authoring.md +1 -1
  441. package/docs/subagents.md +2 -2
  442. package/docs/tools.md +1 -1
  443. package/docs/worktree-snapshots.md +2 -2
  444. package/package.json +9 -9
  445. package/schemas/models.schema.json +2 -2
  446. package/schemas/settings.schema.json +0 -14
  447. package/dist/_shared/sdk-AVFII7NK.js.map +0 -1
  448. package/dist/_shared/settings-startup-4QCVCI53.js.map +0 -1
  449. package/dist/_shared/startup-0-0-57KF6LZH.js.map +0 -1
  450. package/dist/_shared/startup-0-1-GIY75K46.js.map +0 -1
  451. package/dist/_shared/startup-0-2-27OWFHV6.js.map +0 -1
  452. package/dist/_shared/startup-0-3-T4DVFYWX.js.map +0 -1
  453. package/dist/_shared/startup-8-1-X32CYSXB.js.map +0 -1
  454. package/dist/core/intercom-broker-control.d.ts +0 -129
  455. package/dist/startup-stages/13.js +0 -1
  456. package/docs/guides/postgres-tuning.md +0 -311
  457. package/docs/libraries/storage-libsql.md +0 -97
@@ -1,24 +1,25 @@
1
1
  import { __name } from "./rolldown-runtime-BGM3D5V3.js";
2
2
  import { createSessionCwdMatcher, normalizePath, resolvePath } from "./p0-cli-BB45ZQY6.js";
3
- import { CURRENT_SESSION_VERSION, EntryTypeReader, JsonTextChecker, applySessionSummaryEntries, bindChatEpoch, boundedChatRecord, decodeChatRecord, firstChatOrders, getErrnoCode, historySnapshotFor, inheritForkScope, isClassifiedWorkflowSession, materializeSessionSummaryMetadata, noteSnapshotGeneration, observeReferenceCut, readLines, referenceMetadataRead, registerArchiveLoad, registerForkScope, require_sha256, sha256Hex, summarizeSession, yieldTurn } from "./startup-0-0-57KF6LZH.js";
4
- import { AgentRehydrateError, AgentReleaseConfigError, SessionKeyDigests, appendFileChatRecord, deleteFileChatRecords, hasFileChatRecords, latestLegacyMessageTime, legacyCompletionTarget, readFileChatOrders, readFileChatRecords, rememberEarlierCompletion, summarizeLegacySession } from "./startup-0-1-GIY75K46.js";
5
- import { agentWakeDispatcher } from "./startup-0-2-27OWFHV6.js";
6
- import { SESSION_HISTORY_CHUNK_BYTES, SESSION_HISTORY_PAGE_BYTES, SESSION_HISTORY_SCAN_ENTRIES, SessionIdError, entrySizeLimit, matchesSessionIdPrefix, yieldSessionTurn } from "./settings-startup-4QCVCI53.js";
7
- import { access, appendFile, copyFile, link, mkdir, open, readFile, readdir, rename, stat, truncate, unlink, writeFile } from "node:fs/promises";
3
+ import { CURRENT_SESSION_VERSION, EntryTypeReader, JsonTextChecker, applySessionSummaryEntries, bindChatEpoch, boundedChatRecord, decodeChatRecord, epochHasCreationTime, fileEpochOf, firstChatOrders, getErrnoCode, historySnapshotFor, inheritForkScope, isClassifiedWorkflowSession, legacyFileEpochOf, materializeSessionSummaryMetadata, noteSnapshotGeneration, observeReferenceCut, readLines, referenceMetadataRead, registerArchiveLoad, registerForkScope, require_sha256, sha256Hex, summarizeSession, yieldTurn } from "./startup-0-0-EZUKEP4Q.js";
4
+ import { AgentRehydrateError, AgentReleaseConfigError, SessionKeyDigests, appendFileChatRecord, deleteFileChatRecords, hasFileChatRecords, latestLegacyMessageTime, legacyCompletionTarget, readFileChatOrders, readFileChatRecords, rememberEarlierCompletion, summarizeLegacySession } from "./startup-0-1-RTOHJFDJ.js";
5
+ import { agentWakeDispatcher } from "./startup-0-2-5QHPCEON.js";
6
+ import { SESSION_HISTORY_CHUNK_BYTES, SESSION_HISTORY_PAGE_BYTES, SESSION_HISTORY_SCAN_ENTRIES, SessionIdError, entrySizeLimit, matchesSessionIdPrefix, onlySeqs, yieldSessionTurn } from "./settings-startup-HXQLSUWM.js";
7
+ import { access, copyFile, link, mkdir, open, readFile, readdir, rename, stat, truncate, unlink, writeFile } from "node:fs/promises";
8
8
  import { closeSync, existsSync, openSync, readSync, readdirSync, statSync } from "fs";
9
9
  import { join } from "path";
10
10
  import { basename as basename$1, dirname as dirname$1, join as join$1, resolve as resolve$1 } from "node:path";
11
11
  import { createSessionCwdMatcherAsync } from "../utils/canonical-path.js";
12
- import { createReadStream, rmdir as rmdir$1, stat as stat$1 } from "node:fs";
12
+ import { constants as constants$1, createReadStream, rmdir as rmdir$1, stat as stat$1 } from "node:fs";
13
13
  import { uuidv7 } from "@bastani/atomic-ai";
14
14
  import { SessionSpillError, StoragePayloadTooLargeError, describeStorageError, isStorageTransientError, isStorageWriteLockTimeoutError, isStorageWriterQueueUnusableError } from "../core/storage/errors.js";
15
15
  import { open as open$1 } from "fs/promises";
16
16
  import { createHash, randomUUID } from "node:crypto";
17
17
  import lockfile from "proper-lockfile";
18
- import { setTimeout } from "node:timers/promises";
18
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
19
19
  import { randomUUID as randomUUID$1 } from "crypto";
20
20
  import { SessionConflictError, SessionExistsError, SessionFormatVersionError, SessionFormatVersionError as SessionFormatVersionError$1, SessionIdMismatchError, SessionInvalidTextError, SessionInvalidTimestampError, SessionNotFoundError, StorageUnavailableError as StorageUnavailableError$1, StoreClosedError as StoreClosedError$1 } from "../core/storage/session/errors.js";
21
21
  import { isProxy } from "node:util/types";
22
+ import { learnCreationTime } from "../core/storage/creation-time.js";
22
23
  import { openNodeSqliteDatabase } from "../core/storage/node-sqlite.js";
23
24
  import { StringDecoder } from "string_decoder";
24
25
  // dist/core/storage/session/validation.js
@@ -3057,6 +3058,31 @@ function renameHookMessage(entry) {
3057
3058
  };
3058
3059
  }
3059
3060
  // dist/core/storage/session/jsonl-session-store.js
3061
+ /**
3062
+ * The state each session file was last recorded in by a store of this process, by path, least recently recorded first.
3063
+ * A store opening the directory again takes a file's state from here while the file's stat stamp is unchanged, rather
3064
+ * than read the file again (#6560). The stamp names the inode, the size and the change times, so a state taken from
3065
+ * here is one the file is in.
3066
+ */
3067
+ const recordedFileStates = /* @__PURE__ */ new Map();
3068
+ /** The most files {@link recordedFileStates} keeps; the least recently recorded goes first. */
3069
+ const RECORDED_FILE_STATES = 2048;
3070
+ /** How many files an open stats at once to check them against {@link recordedFileStates}. */
3071
+ const SCAN_STATS_IN_FLIGHT = 32;
3072
+ function recordFileState(path, state) {
3073
+ recordedFileStates.delete(path);
3074
+ recordedFileStates.set(path, state);
3075
+ if (recordedFileStates.size > RECORDED_FILE_STATES) recordedFileStates.delete(recordedFileStates.keys().next().value);
3076
+ }
3077
+ /**
3078
+ * Windows refuses to remove a directory that holds an open file and may refuse to replace one, so there a handle is
3079
+ * closed once its appends are written.
3080
+ */
3081
+ const KEEP_APPEND_FILES = process.platform !== "win32";
3082
+ /** How long a kept handle stays open after its last use. */
3083
+ const KEPT_FILE_IDLE_MS = 3e4;
3084
+ /** The most handles one store keeps open; the least recently used is closed first. */
3085
+ const KEPT_FILES = 16;
3060
3086
  function isForkCatalogType(type) {
3061
3087
  return type === "session_info" || type === "session_summary" || type === "branch_summary";
3062
3088
  }
@@ -3089,7 +3115,13 @@ function appendedForkIndex(cached, entries) {
3089
3115
  catalog: catalog ?? previous.catalog
3090
3116
  } : previous;
3091
3117
  }
3092
- const JSONL_INDEX_VERSION = 2;
3118
+ /** The sidecar version an older build reads, whose epochs all hold the file's creation time. */
3119
+ const BIRTHTIME_INDEX_VERSION = 2;
3120
+ /**
3121
+ * The newest sidecar version. A sidecar whose epoch leaves out the creation time is written as version 3, so an older
3122
+ * build, which compares it with an epoch that has one, indexes the file again rather than read it. Both are read.
3123
+ */
3124
+ const JSONL_INDEX_VERSION = 3;
3093
3125
  const SIDECAR_SUFFIX = ".idx";
3094
3126
  const SIDECAR_REFRESH_BYTES = 1048576;
3095
3127
  const INDEX_BATCH_ENTRIES = 512;
@@ -3099,6 +3131,10 @@ const SCAN_WINDOW_BYTES$1 = 1048576;
3099
3131
  function witnessOf(bytes) {
3100
3132
  return Buffer.from(bytes.subarray(-64));
3101
3133
  }
3134
+ /** The witness of `witness` followed by `bytes`, copying no more of `bytes` than the witness keeps. */
3135
+ function witnessAfter(witness, bytes) {
3136
+ return bytes.length >= 64 ? witnessOf(bytes) : witnessOf(Buffer.concat([witness, bytes]));
3137
+ }
3102
3138
  /**
3103
3139
  * The entry on a last line that has no newline after it, or `undefined` when that line is torn: its writer stopped
3104
3140
  * before finishing it, so it was never acknowledged. Every entry line is a JSON object, and no part of an object's
@@ -3409,6 +3445,37 @@ async function scanSessionLines(file, size, atEnd, from, index, signal, visitor)
3409
3445
  header: false
3410
3446
  };
3411
3447
  }
3448
+ /**
3449
+ * Where the `count`th entry line before byte `end` starts, `end` being the end of an entry line: read backwards from
3450
+ * `end` a chunk at a time, each twice the last up to one scan window, as `tail -n` reads. A line of only whitespace is
3451
+ * not an entry, as {@link scanSessionLines} skips it. Undefined when the header comes first, or when a line holds no
3452
+ * visible ASCII but bytes of multi-byte characters, which only decoding it would call blank or not.
3453
+ */
3454
+ async function lineStartFromEnd(file, end, count, signal) {
3455
+ let found = 0;
3456
+ let visible = false;
3457
+ let wide = false;
3458
+ let chunkBytes = RANGE_CHUNK_BYTES;
3459
+ for (let position = end; position > 0;) {
3460
+ signal?.throwIfAborted();
3461
+ const length = Math.min(chunkBytes, position);
3462
+ const bytes = await readFrom(file, position - length, length);
3463
+ position -= length;
3464
+ for (let at = length - 1; at >= 0; at--) {
3465
+ const byte = bytes[at];
3466
+ if (byte === 10) {
3467
+ if (position + at === end - 1) continue;
3468
+ if (visible) {
3469
+ if (++found === count) return position + at + 1;
3470
+ } else if (wide) return void 0;
3471
+ visible = false;
3472
+ wide = false;
3473
+ } else if (byte > 32 && byte < 128) visible = true;
3474
+ else if (byte >= 128) wide = true;
3475
+ }
3476
+ chunkBytes = Math.min(2 * chunkBytes, SCAN_WINDOW_BYTES$1);
3477
+ }
3478
+ }
3412
3479
  /** Session files whose torn last line this process has already reported. */
3413
3480
  const reportedTornFiles = /* @__PURE__ */ new Set();
3414
3481
  function reportTornLine(path) {
@@ -3616,6 +3683,10 @@ var JsonlSessionStore = class JsonlSessionStore {
3616
3683
  };
3617
3684
  }
3618
3685
  queue = Promise.resolve();
3686
+ /** Operations queued so far, counted so an append joins only a group that is still the last thing queued. */
3687
+ queued = 0;
3688
+ appendGroup;
3689
+ keptFiles = /* @__PURE__ */ new Map();
3619
3690
  closed = false;
3620
3691
  poisoned;
3621
3692
  directory;
@@ -3629,7 +3700,7 @@ var JsonlSessionStore = class JsonlSessionStore {
3629
3700
  record = boundedChatRecord(record);
3630
3701
  return this.run(async () => {
3631
3702
  const held = await this.locate(owner.id);
3632
- if (held && held.stats.birthtimeNs > 0n && held.path === owner.file && epochOf(held.stats, JSON.stringify(held.header)) === owner.epoch) await appendFileChatRecord(owner, anchor, record);
3703
+ if (held && held.stats.birthtimeNs > 0n && held.path === owner.file && fileEpochOf(held.stats, JSON.stringify(held.header)) === owner.epoch) await appendFileChatRecord(owner, anchor, record);
3633
3704
  });
3634
3705
  }
3635
3706
  };
@@ -3662,12 +3733,55 @@ var JsonlSessionStore = class JsonlSessionStore {
3662
3733
  */
3663
3734
  static async open(directory, options) {
3664
3735
  const store = new JsonlSessionStore(directory, options?.exactDirectory === true, options?.lockFs);
3665
- if (options?.createDirectory !== false) await store.run(() => mkdir(store.directory, { recursive: true }).then(() => {}), false);
3666
- if (options?.scanExisting !== false) await store.run(async () => {
3667
- for (const path of await store.paths()) try {
3668
- await store.readSnapshot(path);
3669
- } catch {
3736
+ const create = options?.createDirectory !== false;
3737
+ if (options?.scanExisting === false) {
3738
+ if (create) await store.run(() => mkdir(store.directory, { recursive: true }).then(() => {}), false);
3739
+ await learnCreationTime(store.directory);
3740
+ return store;
3741
+ }
3742
+ const paths = await store.run(async () => {
3743
+ try {
3744
+ return await store.paths();
3745
+ } catch (cause) {
3746
+ if (cause.code !== "ENOENT" || !create) return void 0;
3747
+ await mkdir(store.directory, { recursive: true });
3748
+ return [];
3749
+ }
3750
+ }, false);
3751
+ await learnCreationTime(store.directory);
3752
+ const unread = await store.run(async () => {
3753
+ const changed = /* @__PURE__ */ new Set();
3754
+ const all = paths ?? [];
3755
+ for (let at = 0; at < all.length; at += SCAN_STATS_IN_FLIGHT) {
3756
+ const batch = all.slice(at, at + SCAN_STATS_IN_FLIGHT);
3757
+ const stamps = await Promise.all(batch.map(async (path) => {
3758
+ const recorded = recordedFileStates.get(path);
3759
+ if (recorded?.summaryState === void 0) return void 0;
3760
+ const stats = await stat(path, { bigint: true }).catch(() => void 0);
3761
+ return stats !== void 0 && store.stamp(stats) === recorded.stamp ? recorded : void 0;
3762
+ }));
3763
+ for (const [index, path] of batch.entries()) {
3764
+ const recorded = stamps[index];
3765
+ if (recorded !== void 0) store.fileStates.set(path, recorded);
3766
+ else changed.add(path);
3767
+ }
3768
+ }
3769
+ return changed;
3770
+ }, false);
3771
+ if (paths === void 0 || unread.size > 0) await store.run(async () => {
3772
+ for (const path of paths ?? await store.paths()) {
3773
+ if (paths !== void 0 && !unread.has(path)) continue;
3774
+ try {
3775
+ await store.readSnapshot(path);
3776
+ } catch {
3777
+ store.fileStates.delete(path);
3778
+ }
3779
+ }
3780
+ for (const path of paths ?? []) {
3781
+ const state = store.fileStates.get(path);
3782
+ if (state === void 0) continue;
3670
3783
  store.fileStates.delete(path);
3784
+ store.fileStates.set(path, state);
3671
3785
  }
3672
3786
  });
3673
3787
  return store;
@@ -3688,7 +3802,7 @@ var JsonlSessionStore = class JsonlSessionStore {
3688
3802
  validateSessionHeader(header);
3689
3803
  validateSessionEntries(entries);
3690
3804
  if (await this.claimed(header.id)) throw new SessionExistsError(header.id);
3691
- const payload = this.encode(header, entries);
3805
+ const payload = Buffer.from(this.encode(header, entries));
3692
3806
  const path = location === void 0 ? this.locationFor(header) : resolve$1(location);
3693
3807
  await mkdir(resolve$1(path, ".."), { recursive: true });
3694
3808
  const temporary = `${path}.${randomUUID()}.tmp`;
@@ -3713,7 +3827,7 @@ var JsonlSessionStore = class JsonlSessionStore {
3713
3827
  };
3714
3828
  return {
3715
3829
  lastSeq: entries.length,
3716
- epoch: epochOf(stats, state.headerStamp)
3830
+ epoch: fileEpochOf(stats, state.headerStamp)
3717
3831
  };
3718
3832
  }, true);
3719
3833
  }
@@ -3804,7 +3918,7 @@ var JsonlSessionStore = class JsonlSessionStore {
3804
3918
  witness,
3805
3919
  summaryState: summary
3806
3920
  });
3807
- const epoch = epochOf(stats, headerStamp);
3921
+ const epoch = fileEpochOf(stats, headerStamp);
3808
3922
  await this.keepIndex(path, {
3809
3923
  identity: `${stats.dev}:${stats.ino}`,
3810
3924
  birthtimeNs: String(stats.birthtimeNs),
@@ -3834,19 +3948,113 @@ var JsonlSessionStore = class JsonlSessionStore {
3834
3948
  });
3835
3949
  }
3836
3950
  }
3951
+ /**
3952
+ * Appends made while an earlier one waits its turn join it and commit together, as a LevelDB log writer's queue does:
3953
+ * under one lock, each is checked against the session as the appends before it leave it, and each file gets one write
3954
+ * of all their lines. Every append is answered once its lines are written and the lock is released, as it was alone,
3955
+ * and one that conflicts or fails validation rejects alone. Nothing is synced, as before.
3956
+ */
3837
3957
  append(sessionId, entries, options) {
3838
- return this.run(async () => {
3839
- const { path, state } = await this.forWrite(sessionId, options);
3840
- validateSessionEntries(entries);
3841
- if (entries.length === 0) return { lastSeq: state.lastSeq };
3842
- if (state.torn) await truncate(path, state.size);
3843
- const lines = entries.map((entry) => JSON.stringify(entry));
3844
- let payload = `${lines.join("\n")}\n`;
3845
- if (!state.terminated) payload = `\n${payload}`;
3846
- const offset = state.size;
3847
- if (entries.some((entry) => entry.type === "compaction")) await copyFile(path, `${path}.${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.${randomUUID()}.compact.bak`);
3958
+ if (this.closed) return Promise.reject(new StoreClosedError$1(this.descriptor));
3959
+ return new Promise((resolve, reject) => {
3960
+ const request = {
3961
+ sessionId,
3962
+ entries,
3963
+ options,
3964
+ resolve,
3965
+ reject
3966
+ };
3967
+ const waiting = this.appendGroup;
3968
+ if (waiting !== void 0 && !waiting.started && waiting.queued === this.queued) {
3969
+ waiting.requests.push(request);
3970
+ return;
3971
+ }
3972
+ const group = {
3973
+ requests: [request],
3974
+ queued: 0,
3975
+ started: false
3976
+ };
3977
+ this.appendGroup = group;
3978
+ this.run(() => this.commitAppends(group)).then(() => {
3979
+ for (const { answer, resolve, reject } of group.requests) if (answer !== void 0 && "lastSeq" in answer) resolve(answer);
3980
+ else reject(answer?.error);
3981
+ }, (cause) => {
3982
+ for (const pending of group.requests) pending.reject(cause);
3983
+ });
3984
+ group.queued = this.queued;
3985
+ });
3986
+ }
3987
+ async commitAppends(group) {
3988
+ group.started = true;
3989
+ if (this.appendGroup === group) this.appendGroup = void 0;
3990
+ const staged = /* @__PURE__ */ new Map();
3991
+ for (const request of group.requests) try {
3992
+ await this.stageAppend(staged, request);
3993
+ } catch (cause) {
3994
+ if (this.poisoned) throw this.poisoned;
3995
+ request.answer = { error: this.failure(cause) };
3996
+ }
3997
+ for (const file of staged.values()) await this.writeStaged(file);
3998
+ }
3999
+ /** Checks one append against its session as the appends staged before it leave it, and stages its lines. */
4000
+ async stageAppend(staged, request) {
4001
+ const { sessionId, entries, options } = request;
4002
+ let file = staged.get(sessionId);
4003
+ if (file === void 0) {
4004
+ const { path, state, stats, header } = await this.forWrite(sessionId, options);
4005
+ file = {
4006
+ sessionId,
4007
+ path,
4008
+ identity: state.identity,
4009
+ epoch: fileEpochOf(stats, JSON.stringify(header)),
4010
+ before: state,
4011
+ entries: [],
4012
+ lines: [],
4013
+ requests: []
4014
+ };
4015
+ staged.set(sessionId, file);
4016
+ } else {
4017
+ const lastSeq = file.before.lastSeq + file.entries.length;
4018
+ if (options.expectSeq !== lastSeq || options.epoch !== void 0 && options.epoch !== file.epoch) throw new SessionConflictError(sessionId, options.expectSeq, lastSeq);
4019
+ }
4020
+ validateSessionEntries(entries);
4021
+ const lines = entries.map((entry) => JSON.stringify(entry));
4022
+ if (entries.some((entry) => entry.type === "compaction")) {
4023
+ if (!await this.writeStaged(file)) {
4024
+ staged.delete(sessionId);
4025
+ throw new SessionConflictError(sessionId, options.expectSeq, file.before.lastSeq);
4026
+ }
4027
+ await copyFile(file.path, `${file.path}.${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.${randomUUID()}.compact.bak`);
4028
+ }
4029
+ for (const [index, entry] of entries.entries()) {
4030
+ file.entries.push(entry);
4031
+ file.lines.push(lines[index]);
4032
+ }
4033
+ file.requests.push({
4034
+ request,
4035
+ lastSeq: file.before.lastSeq + file.entries.length
4036
+ });
4037
+ }
4038
+ /**
4039
+ * Writes the lines staged for `file` through its kept handle, then decides the appends they came from: false when the
4040
+ * write failed and they fail. A failed write is cut off again; when that fails too the store is poisoned.
4041
+ */
4042
+ async writeStaged(file) {
4043
+ const { path, before, entries, lines, requests } = file;
4044
+ file.entries = [];
4045
+ file.lines = [];
4046
+ file.requests = [];
4047
+ if (entries.length === 0) {
4048
+ for (const { request, lastSeq } of requests) request.answer = { lastSeq };
4049
+ return true;
4050
+ }
4051
+ const offset = before.size;
4052
+ const payload = Buffer.from(`${before.terminated ? "" : "\n"}${lines.join("\n")}\n`);
4053
+ try {
4054
+ const kept = await this.keptFile(path, file.identity);
4055
+ if (before.torn) await truncate(path, before.size);
3848
4056
  try {
3849
- await appendFile(path, payload);
4057
+ await writeAll(kept.handle, payload);
3850
4058
  } catch (cause) {
3851
4059
  try {
3852
4060
  await truncate(path, offset);
@@ -3856,24 +4064,34 @@ var JsonlSessionStore = class JsonlSessionStore {
3856
4064
  }
3857
4065
  throw cause;
3858
4066
  }
3859
- const lastSeq = state.lastSeq + entries.length;
3860
- const appended = await this.remember(path, {
3861
- ...state,
3862
- lastSeq,
4067
+ const stats = await kept.handle.stat({ bigint: true });
4068
+ await this.remember(path, {
4069
+ ...before,
4070
+ lastSeq: before.lastSeq + entries.length,
3863
4071
  lastEntryId: entries.at(-1)?.id,
3864
4072
  terminated: true,
3865
4073
  torn: false,
3866
- witness: witnessOf(Buffer.concat([state.witness, Buffer.from(payload)])),
3867
- ...state.summaryState === void 0 ? {} : { summaryState: applySessionSummaryEntries(state.summaryState, entries).state }
3868
- });
4074
+ witness: witnessAfter(before.witness, payload),
4075
+ ...before.summaryState === void 0 ? {} : { summaryState: applySessionSummaryEntries(before.summaryState, entries).state }
4076
+ }, void 0, stats);
4077
+ file.before = this.fileStates.get(path);
3869
4078
  const rangeIndex = this.rangeIndexes.get(path);
3870
- if (rangeIndex?.seenStamp === state.stamp) {
3871
- rangeIndex.seenStamp = this.stamp(appended);
3872
- rangeIndex.seenSize = Number(appended.size);
4079
+ if (rangeIndex?.seenStamp === before.stamp) {
4080
+ rangeIndex.seenStamp = this.stamp(stats);
4081
+ rangeIndex.seenSize = Number(stats.size);
3873
4082
  }
3874
- await this.indexAppended(path, state, entries, lines, offset + (state.terminated ? 0 : 1));
3875
- return { lastSeq };
3876
- });
4083
+ await this.indexAppended(path, before, entries, lines, offset + (before.terminated ? 0 : 1), stats);
4084
+ if (KEEP_APPEND_FILES) this.armIdle(path, kept);
4085
+ else await this.closeKept(path);
4086
+ } catch (cause) {
4087
+ await this.closeKept(path);
4088
+ const failure = cause === this.poisoned ? cause : this.failure(cause);
4089
+ for (const { request } of requests) request.answer = { error: failure };
4090
+ if (cause === this.poisoned) throw cause;
4091
+ return false;
4092
+ }
4093
+ for (const { request, lastSeq } of requests) request.answer = { lastSeq };
4094
+ return true;
3877
4095
  }
3878
4096
  replace(sessionId, header, entries, options) {
3879
4097
  return this.run(async () => {
@@ -3913,6 +4131,7 @@ var JsonlSessionStore = class JsonlSessionStore {
3913
4131
  await output.close();
3914
4132
  }
3915
4133
  await this.forgetIndex(path);
4134
+ await this.closeKept(path);
3916
4135
  await rename(temporary, path);
3917
4136
  const headerStamp = JSON.stringify(header);
3918
4137
  const stats = await this.remember(path, {
@@ -3924,7 +4143,7 @@ var JsonlSessionStore = class JsonlSessionStore {
3924
4143
  });
3925
4144
  return {
3926
4145
  lastSeq: state.lastSeq,
3927
- epoch: epochOf(stats, headerStamp)
4146
+ epoch: fileEpochOf(stats, headerStamp)
3928
4147
  };
3929
4148
  } finally {
3930
4149
  await unlink(temporary).catch((cause) => {
@@ -3935,7 +4154,8 @@ var JsonlSessionStore = class JsonlSessionStore {
3935
4154
  }
3936
4155
  async commit(path, header, entries) {
3937
4156
  await this.forgetIndex(path);
3938
- const payload = this.encode(header, entries);
4157
+ await this.closeKept(path);
4158
+ const payload = Buffer.from(this.encode(header, entries));
3939
4159
  const temporary = `${path}.${randomUUID()}.tmp`;
3940
4160
  try {
3941
4161
  await writeFile(temporary, payload, { flag: "wx" });
@@ -3946,7 +4166,7 @@ var JsonlSessionStore = class JsonlSessionStore {
3946
4166
  });
3947
4167
  }
3948
4168
  const state = this.contentState(header, entries, payload);
3949
- return epochOf(await this.remember(path, state), state.headerStamp);
4169
+ return fileEpochOf(await this.remember(path, state), state.headerStamp);
3950
4170
  }
3951
4171
  load(sessionId) {
3952
4172
  return this.run(async () => {
@@ -3960,7 +4180,11 @@ var JsonlSessionStore = class JsonlSessionStore {
3960
4180
  query.signal?.throwIfAborted();
3961
4181
  const located = await this.locate(sessionId);
3962
4182
  if (!located) throw new SessionNotFoundError(sessionId);
3963
- return this.readRangeOf(located.path, query, sessionId, located.state);
4183
+ const page = await this.readRangeOf(located.path, query, sessionId, located.state);
4184
+ return {
4185
+ ...page,
4186
+ entries: onlySeqs(page.entries, query.seqs)
4187
+ };
3964
4188
  }, false, query.signal);
3965
4189
  }
3966
4190
  readFileEntryRange(path, query) {
@@ -4065,6 +4289,15 @@ var JsonlSessionStore = class JsonlSessionStore {
4065
4289
  seq: mark.seq - 1,
4066
4290
  header: false
4067
4291
  };
4292
+ const back = index.completeCount - fromSeq + 1;
4293
+ if (index.completeEnd > 0 && back < fromSeq - 1 - cursor.seq) {
4294
+ const start = await lineStartFromEnd(file, index.completeEnd, back, query.signal);
4295
+ if (start !== void 0) cursor = {
4296
+ offset: start,
4297
+ seq: fromSeq - 1,
4298
+ header: false
4299
+ };
4300
+ }
4068
4301
  }
4069
4302
  const skipTypes = query.skipTypes ?? [];
4070
4303
  let chars = 0;
@@ -4221,7 +4454,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4221
4454
  const { path, jsonl } = await this.indexed(reference.sessionId);
4222
4455
  if (jsonl.index.epoch !== reference.epoch) throw new SessionConflictError(reference.sessionId, reference.seq, jsonl.index.seq);
4223
4456
  const start = spanStart(jsonl, reference.seq) + offset;
4224
- return readBytes(path, start, Math.min(SESSION_HISTORY_CHUNK_BYTES, spanEnd(jsonl, reference.seq) - start));
4457
+ return readBytes(path, start, Math.min(SESSION_HISTORY_CHUNK_BYTES, spanEnd(jsonl, reference.seq) - start), this.keptFor(path, jsonl.identity));
4225
4458
  });
4226
4459
  }
4227
4460
  readRange(sessionId, startSeq, endSeq, expectedEpoch) {
@@ -4284,7 +4517,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4284
4517
  legacy: isCurrentSessionHeader(stored) ? void 0 : stored
4285
4518
  };
4286
4519
  const headerStamp = JSON.stringify(header);
4287
- const topology = await this.foldFile(path, epochOf(stats, headerStamp), () => true, input);
4520
+ const topology = await this.foldFile(path, fileEpochOf(stats, headerStamp), () => true, input);
4288
4521
  const jsonl = await this.buildIndex(path, headerStamp, stats, input, {
4289
4522
  topology,
4290
4523
  branch: false
@@ -4472,8 +4705,9 @@ var JsonlSessionStore = class JsonlSessionStore {
4472
4705
  if (!located) throw new SessionNotFoundError(sessionId);
4473
4706
  if (!isCurrentSessionHeader(located.stored)) throw new SessionFormatVersionError$1(located.path, located.stored.version);
4474
4707
  }
4475
- const { path, header } = located;
4476
- const jsonl = await this.indexFor(path, header);
4708
+ const { path, header, stats } = located;
4709
+ const jsonl = await this.indexFor(path, header, stats);
4710
+ const prior = this.fileStates.get(path);
4477
4711
  await this.remember(path, {
4478
4712
  headerStamp: jsonl.headerStamp,
4479
4713
  headerId: header.id,
@@ -4481,27 +4715,38 @@ var JsonlSessionStore = class JsonlSessionStore {
4481
4715
  lastEntryId: jsonl.index.lastId ?? void 0,
4482
4716
  witness: jsonl.witness,
4483
4717
  terminated: jsonl.terminated,
4484
- torn: jsonl.torn
4485
- }, jsonl.torn ? jsonl.size : void 0);
4718
+ torn: jsonl.torn,
4719
+ ...prior?.summaryState !== void 0 && prior.stamp === this.stamp(stats) ? { summaryState: prior.summaryState } : {}
4720
+ }, jsonl.torn ? jsonl.size : void 0, stats);
4486
4721
  return {
4487
4722
  path,
4488
4723
  header,
4489
4724
  jsonl
4490
4725
  };
4491
4726
  }
4492
- async indexFor(path, header) {
4493
- const stats = await stat(path, { bigint: true });
4727
+ async indexFor(path, header, stats) {
4494
4728
  const identity = `${stats.dev}:${stats.ino}`;
4495
4729
  const headerStamp = JSON.stringify(header);
4496
- const cached = this.indexes.get(path) ?? await readSidecar(path);
4497
- if (cached !== void 0 && cached.identity === identity && cached.birthtimeNs === String(stats.birthtimeNs) && cached.headerStamp === headerStamp) {
4730
+ const epoch = fileEpochOf(stats, headerStamp);
4731
+ let cached = this.indexes.get(path) ?? await readSidecar(path);
4732
+ const older = cached !== void 0 && cached.index.epoch !== epoch && cached.index.epoch === legacyFileEpochOf(stats, headerStamp);
4733
+ if (cached !== void 0 && older) cached = {
4734
+ ...cached,
4735
+ index: {
4736
+ ...cached.index,
4737
+ epoch
4738
+ }
4739
+ };
4740
+ if (cached !== void 0 && cached.identity === identity && cached.birthtimeNs === String(stats.birthtimeNs) && cached.headerStamp === headerStamp && cached.index.epoch === epoch) {
4498
4741
  const fileSize = Number(stats.size);
4499
- if (cached.fileSize === fileSize && cached.mtimeNs === String(stats.mtimeNs) && await witnessHolds(path, cached)) {
4742
+ const kept = this.keptFor(path, identity);
4743
+ if (cached.fileSize === fileSize && cached.mtimeNs === String(stats.mtimeNs) && await witnessHolds(path, cached, kept)) {
4744
+ if (older) return this.keepIndex(path, cached);
4500
4745
  this.indexes.set(path, cached);
4501
4746
  return cached;
4502
4747
  }
4503
- if (fileSize > cached.size && await witnessHolds(path, cached)) {
4504
- const grown = await this.catchUp(path, cached, stats);
4748
+ if (fileSize > cached.size && await witnessHolds(path, cached, kept)) {
4749
+ const grown = await this.catchUp(path, cached, stats, kept);
4505
4750
  if (grown !== void 0) return this.keepIndex(path, grown);
4506
4751
  }
4507
4752
  }
@@ -4525,8 +4770,18 @@ var JsonlSessionStore = class JsonlSessionStore {
4525
4770
  * again, for a reader of positions that never selects a window. */
4526
4771
  async buildIndex(path, headerStamp, stats, input, folded) {
4527
4772
  const identity = `${stats.dev}:${stats.ino}`;
4773
+ if (input === void 0) {
4774
+ const kept = this.keptFor(path, identity);
4775
+ if (kept !== void 0) return this.buildIndex(path, headerStamp, stats, { handle: kept }, folded);
4776
+ const handle = await open(path, "r");
4777
+ try {
4778
+ return await this.buildIndex(path, headerStamp, stats, { handle }, folded);
4779
+ } finally {
4780
+ await handle.close();
4781
+ }
4782
+ }
4528
4783
  const birthtimeNs = String(stats.birthtimeNs);
4529
- const epoch = epochOf(stats, headerStamp);
4784
+ const epoch = fileEpochOf(stats, headerStamp);
4530
4785
  const topology = folded?.topology ?? await this.foldFile(path, epoch, () => true, input);
4531
4786
  const ranges = folded?.branch === false || topology.index.jumps.length === 0 ? void 0 : branchRanges(topology.index, topology.index.leafSeq);
4532
4787
  const active = ranges === void 0 ? topology : await this.foldFile(path, epoch, (seq) => ranges.some(([low, high]) => seq >= low && seq <= high), input);
@@ -4537,7 +4792,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4537
4792
  fileSize: Number(stats.size),
4538
4793
  mtimeNs: String(stats.mtimeNs),
4539
4794
  size: active.size,
4540
- witness: input ? await readFrom(input.handle, Math.max(0, active.size - WITNESS_BYTES), Math.min(active.size, WITNESS_BYTES)) : await readWitness(path, active.size),
4795
+ witness: await readFrom(input.handle, Math.max(0, active.size - WITNESS_BYTES), Math.min(active.size, WITNESS_BYTES)),
4541
4796
  terminated: active.terminated,
4542
4797
  torn: active.torn,
4543
4798
  spans: active.spans,
@@ -4606,10 +4861,10 @@ var JsonlSessionStore = class JsonlSessionStore {
4606
4861
  if (!pinned) await file.close();
4607
4862
  }
4608
4863
  }
4609
- async catchUp(path, cached, stats) {
4864
+ async catchUp(path, cached, stats, kept) {
4610
4865
  const from = cached.size - cached.witness.length;
4611
4866
  if (Number(stats.size) - from > SCAN_WINDOW_BYTES$1) return this.streamCatchUp(path, cached, stats);
4612
- const bytes = await readBytes(path, from, Number(stats.size) - from);
4867
+ const bytes = await readBytes(path, from, Number(stats.size) - from, kept);
4613
4868
  let offset = cached.size;
4614
4869
  let appended = bytes.subarray(cached.witness.length);
4615
4870
  if (appended.length > 0 && !cached.terminated) {
@@ -4653,7 +4908,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4653
4908
  fileSize: Number(stats.size),
4654
4909
  mtimeNs: String(stats.mtimeNs),
4655
4910
  size,
4656
- witness: witnessOf(Buffer.concat([cached.witness, appended.subarray(0, size - offset)])),
4911
+ witness: witnessAfter(cached.witness, appended.subarray(0, size - offset)),
4657
4912
  terminated: appended.length === 0 ? cached.terminated : terminated,
4658
4913
  torn,
4659
4914
  spans,
@@ -4739,7 +4994,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4739
4994
  }
4740
4995
  return foldSessionResume(cached.index, entries, (id) => seqs.get(id));
4741
4996
  }
4742
- async indexAppended(path, before, entries, lines, firstLine) {
4997
+ async indexAppended(path, before, entries, lines, firstLine, stats) {
4743
4998
  const cached = this.indexes.get(path);
4744
4999
  if (cached === void 0 || cached.identity !== before.identity || cached.size !== before.size || cached.index.seq !== before.lastSeq || resumeIndexNeedsRefold(cached.index, entries)) {
4745
5000
  this.indexes.delete(path);
@@ -4753,7 +5008,6 @@ var JsonlSessionStore = class JsonlSessionStore {
4753
5008
  position += length + 1;
4754
5009
  }
4755
5010
  const state = this.fileStates.get(path);
4756
- const stats = await stat(path, { bigint: true });
4757
5011
  const next = {
4758
5012
  ...cached,
4759
5013
  fileSize: Number(stats.size),
@@ -4774,7 +5028,8 @@ var JsonlSessionStore = class JsonlSessionStore {
4774
5028
  const wanted = [...new Set(seqs.filter((seq) => seq >= 1 && seq <= jsonl.index.seq))].sort((a, b) => a - b);
4775
5029
  const entries = [];
4776
5030
  if (wanted.length === 0) return entries;
4777
- const file = input?.handle ?? await open(path, "r");
5031
+ const kept = input === void 0 ? this.keptFor(path, jsonl.identity) : void 0;
5032
+ const file = input?.handle ?? kept ?? await open(path, "r");
4778
5033
  try {
4779
5034
  if (exactRevision && !matchesIndexRevision(await file.stat({ bigint: true }), jsonl)) return [];
4780
5035
  let index = 0;
@@ -4805,7 +5060,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4805
5060
  }
4806
5061
  if (exactRevision && !matchesIndexRevision(await file.stat({ bigint: true }), jsonl)) return [];
4807
5062
  } finally {
4808
- if (!input) await file.close();
5063
+ if (!input && !kept) await file.close();
4809
5064
  }
4810
5065
  return entries;
4811
5066
  }
@@ -4817,7 +5072,8 @@ var JsonlSessionStore = class JsonlSessionStore {
4817
5072
  for (let seq = 1; seq <= total; seq++) if (jsonl.ids[seq - 1] === hash) candidates.push(seq);
4818
5073
  const oversized = (seq) => spanEnd(jsonl, seq) - spanStart(jsonl, seq) > SCAN_WINDOW_BYTES$1;
4819
5074
  if (!candidates.some(oversized)) return (await this.entriesAt(path, jsonl, candidates, pinned ? { handle: pinned } : void 0)).findLast((held) => held.entry.id === entryId)?.seq;
4820
- const file = pinned ?? await open(path, "r");
5075
+ const kept = pinned ? void 0 : this.keptFor(path, jsonl.identity);
5076
+ const file = pinned ?? kept ?? await open(path, "r");
4821
5077
  try {
4822
5078
  for (let at = candidates.length - 1; at >= 0; at--) {
4823
5079
  const seq = candidates[at];
@@ -4826,7 +5082,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4826
5082
  if ((oversized(seq) ? (await jsonlEntryProjection(readChunks(file, start, end)))?.entry : JSON.parse((await readFrom(file, start, end - start)).toString("utf8")))?.id === entryId) return seq;
4827
5083
  }
4828
5084
  } finally {
4829
- if (!pinned) await file.close();
5085
+ if (!pinned && !kept) await file.close();
4830
5086
  }
4831
5087
  }
4832
5088
  async readPersisted(path, stored) {
@@ -4854,8 +5110,9 @@ var JsonlSessionStore = class JsonlSessionStore {
4854
5110
  const owner = {
4855
5111
  file: located.path,
4856
5112
  id: sessionId,
4857
- epoch: epochOf(located.stats, JSON.stringify(located.header))
5113
+ epoch: fileEpochOf(located.stats, JSON.stringify(located.header))
4858
5114
  };
5115
+ await this.closeKept(located.path);
4859
5116
  await unlink(located.path);
4860
5117
  this.fileStates.delete(located.path);
4861
5118
  await this.forgetIndex(located.path);
@@ -4944,23 +5201,84 @@ var JsonlSessionStore = class JsonlSessionStore {
4944
5201
  close() {
4945
5202
  if (this.closed) return Promise.reject(new StoreClosedError$1(this.descriptor));
4946
5203
  this.closed = true;
4947
- return this.queue;
5204
+ return this.queue.then(async () => {
5205
+ for (const path of [...this.keptFiles.keys()]) await this.closeKept(path);
5206
+ });
5207
+ }
5208
+ /** Closes the handles kept for the session's files: nothing live writes it any more. */
5209
+ releaseSession(sessionId) {
5210
+ if (this.closed) return Promise.resolve();
5211
+ return this.run(async () => {
5212
+ for (const [path, state] of this.fileStates) if (state.headerId === sessionId) await this.closeKept(path);
5213
+ }, false);
5214
+ }
5215
+ /**
5216
+ * The handle kept open to append to the file at `path`, opened when there is none for the file `identity` names. It
5217
+ * is used only while the caller holds the directory lock and has found that the path still names that file.
5218
+ */
5219
+ async keptFile(path, identity) {
5220
+ const kept = this.keptFiles.get(path);
5221
+ if (kept?.identity === identity) {
5222
+ this.keptFiles.delete(path);
5223
+ this.keptFiles.set(path, kept);
5224
+ return kept;
5225
+ }
5226
+ await this.closeKept(path);
5227
+ const opened = {
5228
+ handle: await open(path, constants$1.O_RDWR | constants$1.O_APPEND),
5229
+ identity,
5230
+ idle: void 0,
5231
+ armed: 0
5232
+ };
5233
+ this.keptFiles.set(path, opened);
5234
+ while (this.keptFiles.size > KEPT_FILES) await this.closeKept(this.keptFiles.keys().next().value);
5235
+ return opened;
5236
+ }
5237
+ /** The kept handle of the file at `path`, while it is the file `identity` names, to read through. */
5238
+ keptFor(path, identity) {
5239
+ const kept = this.keptFiles.get(path);
5240
+ if (kept?.identity !== identity) return void 0;
5241
+ this.armIdle(path, kept);
5242
+ return kept.handle;
5243
+ }
5244
+ async closeKept(path) {
5245
+ const kept = this.keptFiles.get(path);
5246
+ if (kept === void 0) return;
5247
+ this.keptFiles.delete(path);
5248
+ clearTimeout(kept.idle);
5249
+ await kept.handle.close().catch(() => void 0);
5250
+ }
5251
+ /** Closes the handle once it goes unused for {@link KEPT_FILE_IDLE_MS}, between two of this store's operations. */
5252
+ armIdle(path, kept) {
5253
+ clearTimeout(kept.idle);
5254
+ const armed = ++kept.armed;
5255
+ kept.idle = setTimeout(() => {
5256
+ this.queue = this.queue.then(async () => {
5257
+ if (this.keptFiles.get(path) === kept && kept.armed === armed) await this.closeKept(path);
5258
+ });
5259
+ }, KEPT_FILE_IDLE_MS);
5260
+ kept.idle.unref();
4948
5261
  }
4949
5262
  run(operation, locked = true, signal) {
4950
5263
  if (this.closed) return Promise.reject(new StoreClosedError$1(this.descriptor));
5264
+ this.queued++;
4951
5265
  const result = this.queue.then(async () => {
4952
5266
  if (this.poisoned) throw this.poisoned;
4953
5267
  try {
4954
5268
  return await (locked ? this.exclusive(operation, signal) : operation());
4955
5269
  } catch (cause) {
4956
5270
  if (signal?.aborted && cause === signal.reason) throw cause;
4957
- if (cause instanceof SessionConflictError || cause instanceof SessionExistsError || cause instanceof SessionNotFoundError || cause instanceof SessionIdMismatchError || cause instanceof SessionInvalidTextError || cause instanceof SessionInvalidTimestampError || cause instanceof SessionFormatVersionError$1 || cause instanceof JsonlStoragePoisonedError || cause instanceof DOMException) throw cause;
4958
- throw new StorageUnavailableError$1(this.descriptor, cause);
5271
+ throw this.failure(cause);
4959
5272
  }
4960
5273
  });
4961
5274
  this.queue = result.then(() => {}, () => {});
4962
5275
  return result;
4963
5276
  }
5277
+ /** What an operation rejects with for `cause`: the session errors as they are, any other as the store unavailable. */
5278
+ failure(cause) {
5279
+ if (cause instanceof SessionConflictError || cause instanceof SessionExistsError || cause instanceof SessionNotFoundError || cause instanceof SessionIdMismatchError || cause instanceof SessionInvalidTextError || cause instanceof SessionInvalidTimestampError || cause instanceof SessionFormatVersionError$1 || cause instanceof JsonlStoragePoisonedError || cause instanceof DOMException) return cause;
5280
+ return new StorageUnavailableError$1(this.descriptor, cause);
5281
+ }
4964
5282
  async exclusive(operation, signal, directory = this.directory) {
4965
5283
  const lockfilePath = join$1(directory, ".session.lock");
4966
5284
  let release;
@@ -4970,6 +5288,7 @@ var JsonlSessionStore = class JsonlSessionStore {
4970
5288
  try {
4971
5289
  release = await lockfile.lock(directory, {
4972
5290
  lockfilePath,
5291
+ realpath: false,
4973
5292
  ...this.lockFs ? { fs: this.lockFs } : {},
4974
5293
  onCompromised: (cause) => {
4975
5294
  this.poisoned = new StorageUnavailableError$1(this.descriptor, cause);
@@ -4979,12 +5298,12 @@ var JsonlSessionStore = class JsonlSessionStore {
4979
5298
  } catch (cause) {
4980
5299
  const code = cause.code;
4981
5300
  if (code === "EPERM" && process.platform === "win32" && refusals < LOCK_BACKOFF_MS.length) {
4982
- await setTimeout(LOCK_BACKOFF_MS[refusals++]);
5301
+ await setTimeout$1(LOCK_BACKOFF_MS[refusals++]);
4983
5302
  continue;
4984
5303
  }
4985
5304
  if (code !== "ELOCKED") throw cause;
4986
5305
  if (await this.clearUnreleased(lockfilePath)) continue;
4987
- await setTimeout(5);
5306
+ await setTimeout$1(5);
4988
5307
  }
4989
5308
  }
4990
5309
  let result;
@@ -5017,7 +5336,7 @@ var JsonlSessionStore = class JsonlSessionStore {
5017
5336
  if (!TRANSIENT_RELEASE_CODES.has(cause.code ?? "")) throw cause;
5018
5337
  }
5019
5338
  for (const wait of LOCK_BACKOFF_MS) {
5020
- await setTimeout(wait);
5339
+ await setTimeout$1(wait);
5021
5340
  try {
5022
5341
  await removeDirectory(fs, lockfilePath);
5023
5342
  return;
@@ -5133,6 +5452,24 @@ var JsonlSessionStore = class JsonlSessionStore {
5133
5452
  if (cached.headerId !== sessionId) continue;
5134
5453
  const parent = dirname$1(path);
5135
5454
  if (parent !== this.directory && (this.exactDirectory || dirname$1(parent) !== this.directory)) return void 0;
5455
+ const kept = this.keptFiles.get(path);
5456
+ const current = kept && await stat(path, { bigint: true }).catch(() => void 0);
5457
+ if (current !== void 0 && `${current.dev}:${current.ino}` === kept?.identity) {
5458
+ const stored = await readFirstLineFrom(kept.handle, headerLineBytes(cached.headerStamp), 0).catch(() => void 0);
5459
+ if (stored === void 0) return void 0;
5460
+ if (stored.id !== sessionId) {
5461
+ this.fileStates.delete(path);
5462
+ return;
5463
+ }
5464
+ this.armIdle(path, kept);
5465
+ return {
5466
+ path,
5467
+ header: await this.readHeaderAt(path, stored),
5468
+ stored,
5469
+ stats: current,
5470
+ state: cached
5471
+ };
5472
+ }
5136
5473
  let stored;
5137
5474
  try {
5138
5475
  stored = await this.readFirstLine(path, headerLineBytes(cached.headerStamp));
@@ -5202,7 +5539,7 @@ var JsonlSessionStore = class JsonlSessionStore {
5202
5539
  torn,
5203
5540
  summaryState: applySessionSummaryEntries(void 0, entries).state
5204
5541
  }, torn ? size : void 0);
5205
- bindChatEpoch(header, epochOf(stats, JSON.stringify(header)));
5542
+ bindChatEpoch(header, fileEpochOf(stats, JSON.stringify(header)));
5206
5543
  return {
5207
5544
  header,
5208
5545
  entries,
@@ -5225,9 +5562,9 @@ var JsonlSessionStore = class JsonlSessionStore {
5225
5562
  const newline = bytes.lastIndexOf(10);
5226
5563
  if (newline !== -1) {
5227
5564
  complete = size + newline + 1;
5228
- completeWitness = witnessOf(Buffer.concat([witness, bytes.subarray(0, newline + 1)]));
5565
+ completeWitness = witnessAfter(witness, bytes.subarray(0, newline + 1));
5229
5566
  }
5230
- witness = witnessOf(Buffer.concat([witness, bytes]));
5567
+ witness = witnessAfter(witness, bytes);
5231
5568
  size += bytes.length;
5232
5569
  });
5233
5570
  const entries = [];
@@ -5276,16 +5613,19 @@ var JsonlSessionStore = class JsonlSessionStore {
5276
5613
  lastSeq: entries.length,
5277
5614
  headerId: header.id,
5278
5615
  lastEntryId: entries.at(-1)?.id,
5279
- terminated: content.endsWith("\n"),
5616
+ terminated: content.at(-1) === 10,
5280
5617
  torn: false,
5281
- witness: witnessOf(Buffer.from(content)),
5618
+ witness: witnessOf(content),
5282
5619
  summaryState: applySessionSummaryEntries(void 0, entries).state
5283
5620
  };
5284
5621
  }
5285
- /** Records the file as it is now; `size` ends it before a torn last line. */
5286
- async remember(path, state, size) {
5287
- const stats = await stat(path, { bigint: true });
5288
- this.fileStates.set(path, {
5622
+ /**
5623
+ * Records the file as it is now; `size` ends it before a torn last line. `stats` are the file's, taken since its last
5624
+ * change, when the caller has them.
5625
+ */
5626
+ async remember(path, state, size, stats) {
5627
+ stats ??= await stat(path, { bigint: true });
5628
+ this.keepFileState(path, {
5289
5629
  ...state,
5290
5630
  stamp: this.stamp(stats),
5291
5631
  identity: `${stats.dev}:${stats.ino}`,
@@ -5293,6 +5633,10 @@ var JsonlSessionStore = class JsonlSessionStore {
5293
5633
  });
5294
5634
  return stats;
5295
5635
  }
5636
+ keepFileState(path, state) {
5637
+ this.fileStates.set(path, state);
5638
+ recordFileState(path, state);
5639
+ }
5296
5640
  /**
5297
5641
  * Foreign appends read only the header, at most 64 known boundary bytes, and new bytes.
5298
5642
  * The witness detects a changed append boundary, not arbitrary edits in old history.
@@ -5351,13 +5695,15 @@ var JsonlSessionStore = class JsonlSessionStore {
5351
5695
  witness: witnessOf(bytes.subarray(0, end)),
5352
5696
  ...state.summaryState === void 0 ? {} : { summaryState: applySessionSummaryEntries(state.summaryState, entries).state }
5353
5697
  };
5354
- this.fileStates.set(path, state);
5698
+ this.keepFileState(path, state);
5355
5699
  }
5356
5700
  }
5357
- if (state.lastSeq !== options.expectSeq || options.epoch !== void 0 && epochOf(stats, JSON.stringify(header)) !== options.epoch) throw new SessionConflictError(sessionId, options.expectSeq, state.lastSeq);
5701
+ if (state.lastSeq !== options.expectSeq || options.epoch !== void 0 && fileEpochOf(stats, JSON.stringify(header)) !== options.epoch) throw new SessionConflictError(sessionId, options.expectSeq, state.lastSeq);
5358
5702
  return {
5359
5703
  path,
5360
- state
5704
+ state,
5705
+ stats,
5706
+ header
5361
5707
  };
5362
5708
  }
5363
5709
  encode(header, entries) {
@@ -5410,9 +5756,6 @@ function decodeIdHashes(text) {
5410
5756
  for (let offset = 0; offset < bytes.length; offset += 4) hashes.push(bytes.readUInt32LE(offset));
5411
5757
  return hashes;
5412
5758
  }
5413
- function epochOf(stats, headerStamp) {
5414
- return `${stats.dev}:${stats.ino}:${stats.birthtimeNs}:${createHash("sha256").update(headerStamp).digest("hex").slice(0, 16)}`;
5415
- }
5416
5759
  async function readFrom(file, position, length) {
5417
5760
  const bytes = Buffer.alloc(Math.max(0, length));
5418
5761
  for (let read = 0; read < bytes.length;) {
@@ -5422,6 +5765,15 @@ async function readFrom(file, position, length) {
5422
5765
  }
5423
5766
  return bytes;
5424
5767
  }
5768
+ /** Node's own write size for a file: a larger payload is written a slice at a time, as `appendFile` writes it. */
5769
+ const WRITE_SLICE_BYTES = 524288;
5770
+ /** Writes all of `bytes` at the end of the file `file` was opened to append to. */
5771
+ async function writeAll(file, bytes) {
5772
+ for (let at = 0; at < bytes.length;) {
5773
+ const { bytesWritten } = await file.write(bytes, at, Math.min(WRITE_SLICE_BYTES, bytes.length - at));
5774
+ at += bytesWritten;
5775
+ }
5776
+ }
5425
5777
  async function readFirstLineFrom(file, firstReadBytes, start = null) {
5426
5778
  const chunks = [];
5427
5779
  let position = start;
@@ -5437,7 +5789,8 @@ async function readFirstLineFrom(file, firstReadBytes, start = null) {
5437
5789
  const value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
5438
5790
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
5439
5791
  }
5440
- async function readBytes(path, position, length) {
5792
+ async function readBytes(path, position, length, kept) {
5793
+ if (kept !== void 0) return readFrom(kept, position, length);
5441
5794
  const file = await open(path, "r");
5442
5795
  try {
5443
5796
  return await readFrom(file, position, length);
@@ -5445,13 +5798,13 @@ async function readBytes(path, position, length) {
5445
5798
  await file.close();
5446
5799
  }
5447
5800
  }
5448
- async function readWitness(path, size) {
5801
+ async function readWitness(path, size, kept) {
5449
5802
  const from = Math.max(0, size - 64);
5450
- return readBytes(path, from, size - from);
5803
+ return readBytes(path, from, size - from, kept);
5451
5804
  }
5452
- async function witnessHolds(path, jsonl) {
5805
+ async function witnessHolds(path, jsonl, kept) {
5453
5806
  try {
5454
- return (await readWitness(path, jsonl.size)).equals(jsonl.witness);
5807
+ return (await readWitness(path, jsonl.size, kept)).equals(jsonl.witness);
5455
5808
  } catch {
5456
5809
  return false;
5457
5810
  }
@@ -5474,7 +5827,7 @@ function decodeDeltas(text) {
5474
5827
  }
5475
5828
  async function writeSidecar(path, jsonl) {
5476
5829
  const body = JSON.stringify({
5477
- version: 2,
5830
+ version: epochHasCreationTime(jsonl.index.epoch) ? BIRTHTIME_INDEX_VERSION : 3,
5478
5831
  identity: jsonl.identity,
5479
5832
  birthtimeNs: jsonl.birthtimeNs,
5480
5833
  headerStamp: jsonl.headerStamp,
@@ -5523,7 +5876,7 @@ async function readSidecar(path) {
5523
5876
  } catch {
5524
5877
  return;
5525
5878
  }
5526
- if (stored.version !== 2 || typeof stored.identity !== "string" || typeof stored.birthtimeNs !== "string" || typeof stored.headerStamp !== "string" || typeof stored.fileSize !== "number" || typeof stored.mtimeNs !== "string" || typeof stored.size !== "number" || typeof stored.witness !== "string" || typeof stored.terminated !== "boolean" || typeof stored.torn !== "boolean" || typeof stored.spans !== "string" || typeof stored.ids !== "string") return void 0;
5879
+ if (stored.version !== 3 && stored.version !== BIRTHTIME_INDEX_VERSION || typeof stored.identity !== "string" || typeof stored.birthtimeNs !== "string" || typeof stored.headerStamp !== "string" || typeof stored.fileSize !== "number" || typeof stored.mtimeNs !== "string" || typeof stored.size !== "number" || typeof stored.witness !== "string" || typeof stored.terminated !== "boolean" || typeof stored.torn !== "boolean" || typeof stored.spans !== "string" || typeof stored.ids !== "string") return void 0;
5527
5880
  const spans = decodeDeltas(stored.spans);
5528
5881
  const ids = decodeIdHashes(stored.ids);
5529
5882
  if (spans.length % 2 !== 0 || ids?.length !== spans.length / 2 || !isSessionResumeIndex(stored.index, spans.length / 2)) return void 0;
@@ -6495,7 +6848,7 @@ var MemorySessionStore = class MemorySessionStore {
6495
6848
  if (entries === void 0) continue;
6496
6849
  return {
6497
6850
  lastSeq,
6498
- entries,
6851
+ entries: onlySeqs(entries, query.seqs),
6499
6852
  throughSeq
6500
6853
  };
6501
6854
  }
@@ -6594,7 +6947,7 @@ var MemorySessionStore = class MemorySessionStore {
6594
6947
  directory: record.directory,
6595
6948
  file: record.file,
6596
6949
  spilledBytes: record.spilledBytes,
6597
- blocks: [...record.blocks],
6950
+ blocks: record.blocks,
6598
6951
  chunks: [...record.entries],
6599
6952
  lastSeq: record.lastSeq,
6600
6953
  totalBytes: record.totalBytes
@@ -8023,7 +8376,7 @@ function __atomicOnDemandFailed(error, feature) {
8023
8376
  return (async () => {
8024
8377
  const root = new URL("../", import.meta.url);
8025
8378
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
8026
- const key = `${root.href}#0.10.11-alpha.1`;
8379
+ const key = `${root.href}#0.10.11-alpha.3`;
8027
8380
  let release = releases.get(key);
8028
8381
  if (release === undefined) {
8029
8382
  const current = (async () => {
@@ -8051,7 +8404,7 @@ function __atomicOnDemandFailed(error, feature) {
8051
8404
  } catch {
8052
8405
  // No installation to read, as in a bundle of the package: the release the process runs decides.
8053
8406
  }
8054
- const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.1" ? installed : running !== undefined && running.version !== "0.10.11-alpha.1" ? "0.10.11-alpha.1" : undefined;
8407
+ 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;
8055
8408
  if (updatedTo === undefined) throw error;
8056
8409
  const application = typeof running?.name === "string" ? running.name : "atomic";
8057
8410
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {