@bastani/atomic 0.10.10 → 0.10.11-alpha.2

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 (402) hide show
  1. package/CHANGELOG.md +139 -0
  2. package/README.md +1 -1
  3. package/dist/_shared/dist-KOELCESV.js +2 -2
  4. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  5. package/dist/_shared/lib-4PES5P4V.js +2 -2
  6. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +11 -13
  7. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js.map +1 -1
  8. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +9 -9
  9. package/dist/_shared/mode-shared-2QJSCUM6.js +55 -18
  10. package/dist/_shared/mode-shared-2QJSCUM6.js.map +1 -1
  11. package/dist/_shared/p1a-prewarm-XIU57JHF.js +3 -3
  12. package/dist/_shared/runtime-O4KCSG4C.js +5 -5
  13. package/dist/_shared/{sdk-RRLVN7ER.js → sdk-IQMULKFU.js} +2962 -470
  14. package/dist/_shared/sdk-IQMULKFU.js.map +1 -0
  15. package/dist/_shared/session-data-AHTU7IS6.js +4 -4
  16. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  17. package/dist/_shared/settings-startup-8-DNZ2RIHM.js +1 -1
  18. package/dist/_shared/{settings-startup-4QCVCI53.js → settings-startup-HXQLSUWM.js} +8 -2
  19. package/dist/_shared/settings-startup-HXQLSUWM.js.map +1 -0
  20. package/dist/_shared/{startup-0-0-4VG2G44V.js → startup-0-0-3IXNMFM2.js} +482 -53
  21. package/dist/_shared/startup-0-0-3IXNMFM2.js.map +1 -0
  22. package/dist/_shared/{startup-0-1-XTIL65D4.js → startup-0-1-7T2IAE7J.js} +121 -251
  23. package/dist/_shared/startup-0-1-7T2IAE7J.js.map +1 -0
  24. package/dist/_shared/{startup-0-2-27OWFHV6.js → startup-0-2-5QHPCEON.js} +293 -10
  25. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -0
  26. package/dist/_shared/{startup-0-3-T4DVFYWX.js → startup-0-3-4ZYBYQNM.js} +273 -14
  27. package/dist/_shared/startup-0-3-4ZYBYQNM.js.map +1 -0
  28. package/dist/_shared/startup-0-4-ZMJV547D.js +6 -6
  29. package/dist/_shared/{startup-0-5-FD2P735I.js → startup-0-5-YDW47QX6.js} +29 -71
  30. package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -0
  31. package/dist/_shared/startup-10-0-TDQNBDDL.js +9 -9
  32. package/dist/_shared/startup-12-0-55AAXBJZ.js +4 -4
  33. package/dist/_shared/startup-14-0-MLX36RBG.js +6 -6
  34. package/dist/_shared/startup-15-0-YUKGAC63.js +34 -10
  35. package/dist/_shared/startup-15-0-YUKGAC63.js.map +1 -1
  36. package/dist/_shared/startup-15-1-4S7FLMNG.js +10 -9
  37. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  38. package/dist/_shared/startup-8-0-34CBHPZH.js +421 -84
  39. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  40. package/dist/_shared/{startup-8-1-4KANEHRA.js → startup-8-1-X32CYSXB.js} +1291 -722
  41. package/dist/_shared/startup-8-1-X32CYSXB.js.map +1 -0
  42. package/dist/_shared/storage-command-7MGXLJGZ.js +17 -9
  43. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  44. package/dist/_shared/task-reference-stream-JWMUZSJX.js +1 -1
  45. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  46. package/dist/_shared/tree-outline-MUEPK5B7.js +3 -3
  47. package/dist/builtin/intercom/CHANGELOG.md +29 -0
  48. package/dist/builtin/intercom/broker/broker.bundle.mjs +1138 -384
  49. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +103 -24
  50. package/dist/builtin/intercom/broker/multinode-router.ts +42 -21
  51. package/dist/builtin/intercom/broker/multinode-state-store.ts +22 -1
  52. package/dist/builtin/intercom/broker/open-broker-state.ts +82 -31
  53. package/dist/builtin/intercom/broker/paths.ts +8 -4
  54. package/dist/builtin/intercom/broker/released-asker-remote-replies.ts +18 -6
  55. package/dist/builtin/intercom/broker/sql-add-column.ts +4 -1
  56. package/dist/builtin/intercom/broker/sql-ended-child-queue-store.ts +65 -44
  57. package/dist/builtin/intercom/broker/sql-held-send-store.ts +11 -3
  58. package/dist/builtin/intercom/broker/sql-known-session-store.ts +24 -12
  59. package/dist/builtin/intercom/broker/sql-lease-store.ts +386 -65
  60. package/dist/builtin/intercom/broker/sql-outbox-store.ts +462 -130
  61. package/dist/builtin/intercom/broker/sql-pending-ask-store.ts +20 -9
  62. package/dist/builtin/intercom/broker/sql-released-ask-store.ts +14 -6
  63. package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +27 -11
  64. package/dist/builtin/intercom/broker/sql-schema.ts +198 -5
  65. package/dist/builtin/intercom/broker/sql-sent-message-authority.ts +97 -34
  66. package/dist/builtin/intercom/index.bundle.mjs +11 -8
  67. package/dist/builtin/intercom/package.json +1 -1
  68. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  69. package/dist/builtin/mcp/package.json +1 -1
  70. package/dist/builtin/subagents/CHANGELOG.md +18 -0
  71. package/dist/builtin/subagents/package.json +1 -1
  72. package/dist/builtin/subagents/skills/skill-creator/SKILL.md +1 -1
  73. package/dist/builtin/subagents/src/extension/index.bundle.mjs +62 -23
  74. package/dist/builtin/web-access/index.bundle.mjs +1 -1
  75. package/dist/builtin/web-access/package.json +1 -1
  76. package/dist/cli/args.js +2 -2
  77. package/dist/cli/auth-cli.code.js +6 -6
  78. package/dist/cli/auth-cli.impl.js +3 -3
  79. package/dist/cli/auth-cli.js +3 -3
  80. package/dist/cli/blueprint-command.code.js +4 -4
  81. package/dist/cli/blueprint-command.impl.js +3 -3
  82. package/dist/cli/blueprint-command.js +3 -3
  83. package/dist/cli/intercom-command.code.js +3 -3
  84. package/dist/cli/intercom-command.impl.js +3 -3
  85. package/dist/cli/intercom-command.js +3 -3
  86. package/dist/cli/list-models.code.js +2 -2
  87. package/dist/cli/list-models.impl.js +3 -3
  88. package/dist/cli/list-models.js +3 -3
  89. package/dist/cli/session-picker.code.js +2 -2
  90. package/dist/cli/session-picker.impl.js +3 -3
  91. package/dist/cli/session-picker.js +3 -3
  92. package/dist/cli/startup-ui.code.js +2 -2
  93. package/dist/cli/startup-ui.impl.js +3 -3
  94. package/dist/cli/startup-ui.js +3 -3
  95. package/dist/cli/storage-command.impl.js +3 -3
  96. package/dist/cli/storage-command.js +3 -3
  97. package/dist/cli/storage-search-session.code.js +3 -3
  98. package/dist/cli/storage-search-session.impl.js +3 -3
  99. package/dist/cli/storage-search-session.js +3 -3
  100. package/dist/cli/team-command.code.js +3 -3
  101. package/dist/cli/team-command.impl.js +3 -3
  102. package/dist/cli/team-command.js +3 -3
  103. package/dist/cli.js +2 -2
  104. package/dist/core/agent-session-methods.d.ts +3 -0
  105. package/dist/core/agent-session-methods.js.map +1 -1
  106. package/dist/core/agent-session.d.ts +1 -0
  107. package/dist/core/compaction/compactor.d.ts +2 -0
  108. package/dist/core/debug.impl.js +3 -3
  109. package/dist/core/debug.js +3 -3
  110. package/dist/core/export-html/card-projection.code.js +1 -1
  111. package/dist/core/export-html/card-projection.impl.js +3 -3
  112. package/dist/core/export-html/card-projection.js +3 -3
  113. package/dist/core/export-html/index.code.js +2 -2
  114. package/dist/core/export-html/index.impl.js +3 -3
  115. package/dist/core/export-html/index.js +3 -3
  116. package/dist/core/export-html/json-spans.impl.js +3 -3
  117. package/dist/core/export-html/json-spans.js +3 -3
  118. package/dist/core/export-html/oversized-render-inputs.code.js +2 -2
  119. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  120. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  121. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  122. package/dist/core/export-html/tool-renderer.js +3 -3
  123. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  124. package/dist/core/extensions/jiti-loader.js +3 -3
  125. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  126. package/dist/core/extensions/jiti-static-loader.js +3 -3
  127. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  128. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  129. package/dist/core/extensions/loader-host-modules.js +3 -3
  130. package/dist/core/extensions/loader-virtual-modules.js +2 -2
  131. package/dist/core/extensions/runner-context.js +4 -4
  132. package/dist/core/extensions/runner-context.js.map +1 -1
  133. package/dist/core/intercom-broker-control-host.code.js +1 -1
  134. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  135. package/dist/core/intercom-broker-control-host.js +3 -3
  136. package/dist/core/intercom-broker-control.code.js +3 -3
  137. package/dist/core/intercom-broker-control.impl.js +3 -3
  138. package/dist/core/intercom-broker-control.js +3 -3
  139. package/dist/core/model-registry.js +1 -1
  140. package/dist/core/model-resolver-defaults.d.ts +3 -2
  141. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  142. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  143. package/dist/core/package-manager-storage-adapters.js +3 -3
  144. package/dist/core/sdk.code.js +4 -5
  145. package/dist/core/sdk.impl.js +3 -3
  146. package/dist/core/sdk.js +3 -3
  147. package/dist/core/session-manager-core.d.ts +5 -2
  148. package/dist/core/session-manager-core.js +39 -23
  149. package/dist/core/session-manager-core.js.map +1 -1
  150. package/dist/core/session-manager-list.impl.js +3 -3
  151. package/dist/core/session-manager-list.js +3 -3
  152. package/dist/core/session-manager.code.js +3 -3
  153. package/dist/core/session-manager.impl.js +3 -3
  154. package/dist/core/session-manager.js +3 -3
  155. package/dist/core/session-open-markers.js +3 -0
  156. package/dist/core/session-open-markers.js.map +1 -0
  157. package/dist/core/session-storage.code.js +1 -1
  158. package/dist/core/session-storage.impl.js +3 -3
  159. package/dist/core/session-storage.js +3 -3
  160. package/dist/core/storage/added-exports.d.ts +6 -0
  161. package/dist/core/storage/added-exports.js +19 -0
  162. package/dist/core/storage/added-exports.js.map +1 -0
  163. package/dist/core/storage/database.d.ts +53 -0
  164. package/dist/core/storage/database.js.map +1 -1
  165. package/dist/core/storage/fenced-paths.d.ts +47 -0
  166. package/dist/core/storage/fenced-paths.js +53 -0
  167. package/dist/core/storage/fenced-paths.js.map +1 -1
  168. package/dist/core/storage/file-identity.js +31 -2
  169. package/dist/core/storage/file-identity.js.map +1 -1
  170. package/dist/core/storage/index.d.ts +4 -1
  171. package/dist/core/storage/index.js +5 -2
  172. package/dist/core/storage/index.js.map +1 -1
  173. package/dist/core/storage/migrations.d.ts +33 -2
  174. package/dist/core/storage/migrations.js +73 -5
  175. package/dist/core/storage/migrations.js.map +1 -1
  176. package/dist/core/storage/node-sqlite-thread.js +48 -6
  177. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  178. package/dist/core/storage/node-sqlite.js +137 -4
  179. package/dist/core/storage/node-sqlite.js.map +1 -1
  180. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  181. package/dist/core/storage/offline-snapshot-file.js +3 -3
  182. package/dist/core/storage/prefix.d.ts +3 -2
  183. package/dist/core/storage/prefix.js +23 -2
  184. package/dist/core/storage/prefix.js.map +1 -1
  185. package/dist/core/storage/provider.js +2 -2
  186. package/dist/core/storage/schema-catalog.d.ts +120 -0
  187. package/dist/core/storage/schema-catalog.js +351 -0
  188. package/dist/core/storage/schema-catalog.js.map +1 -0
  189. package/dist/core/storage/selection.js +2 -2
  190. package/dist/core/storage/session/branch-fork-source.code.js +47 -25
  191. package/dist/core/storage/session/branch-fork-source.code.js.map +1 -1
  192. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  193. package/dist/core/storage/session/branch-fork-source.js +3 -3
  194. package/dist/core/storage/session/card-view.impl.js +3 -3
  195. package/dist/core/storage/session/card-view.js +3 -3
  196. package/dist/core/storage/session/child-reader.code.js +4 -4
  197. package/dist/core/storage/session/child-reader.impl.js +3 -3
  198. package/dist/core/storage/session/child-reader.js +3 -3
  199. package/dist/core/storage/session/chunked-resume-projection.code.js +1 -1
  200. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  201. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  202. package/dist/core/storage/session/errors.js +1 -1
  203. package/dist/core/storage/session/expanded-child-details.code.js +4 -4
  204. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  205. package/dist/core/storage/session/expanded-child-details.js +3 -3
  206. package/dist/core/storage/session/fork-detach.d.ts +118 -0
  207. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  208. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  209. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  210. package/dist/core/storage/session/fork-row-index.js +3 -3
  211. package/dist/core/storage/session/fork-schema.js +53 -0
  212. package/dist/core/storage/session/fork-schema.js.map +1 -0
  213. package/dist/core/storage/session/fork-segments.d.ts +58 -0
  214. package/dist/core/storage/session/fork-staging.code.js +176 -36
  215. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  216. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  217. package/dist/core/storage/session/fork-staging.js +3 -3
  218. package/dist/core/storage/session/fork-sweep.js +61 -0
  219. package/dist/core/storage/session/fork-sweep.js.map +1 -0
  220. package/dist/core/storage/session/fork-window.code.js +4 -4
  221. package/dist/core/storage/session/fork-window.impl.js +3 -3
  222. package/dist/core/storage/session/fork-window.js +3 -3
  223. package/dist/core/storage/session/history-pages.impl.js +3 -3
  224. package/dist/core/storage/session/history-pages.js +3 -3
  225. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  226. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  227. package/dist/core/storage/session/jsonl-session-store.d.ts +37 -1
  228. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  229. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  230. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  231. package/dist/core/storage/session/memory-session-store.js +3 -3
  232. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  233. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  234. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  235. package/dist/core/storage/session/released-history-files.code.js +3 -3
  236. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  237. package/dist/core/storage/session/released-history-files.js +3 -3
  238. package/dist/core/storage/session/resident-fork-rows.code.js +1 -1
  239. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  240. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  241. package/dist/core/storage/session/session-resume.impl.js +3 -3
  242. package/dist/core/storage/session/session-resume.js +3 -3
  243. package/dist/core/storage/session/session-search-index.d.ts +5 -0
  244. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  245. package/dist/core/storage/session/snapshot-cut.js +3 -3
  246. package/dist/core/storage/session/snapshot-history.code.js +4 -4
  247. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  248. package/dist/core/storage/session/snapshot-history.js +3 -3
  249. package/dist/core/storage/session/sql-chat-records.d.ts +15 -0
  250. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  251. package/dist/core/storage/session/sql-session-store.d.ts +445 -11
  252. package/dist/core/storage/session/sql-session-store.impl.js +4 -4
  253. package/dist/core/storage/session/sql-session-store.js +4 -4
  254. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  255. package/dist/core/storage/session/tree-outline.js +3 -3
  256. package/dist/core/storage/session/tree-presentation.code.js +1 -1
  257. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  258. package/dist/core/storage/session/tree-presentation.js +3 -3
  259. package/dist/core/storage/session/types.d.ts +36 -0
  260. package/dist/core/storage/sqlite-facade.d.ts +54 -6
  261. package/dist/core/storage/sqlite-facade.js +384 -18
  262. package/dist/core/storage/sqlite-facade.js.map +1 -1
  263. package/dist/core/storage/statement-sequence.d.ts +83 -0
  264. package/dist/core/storage/statement-sequence.js +21 -0
  265. package/dist/core/storage/statement-sequence.js.map +1 -1
  266. package/dist/core/storage/storage-status.code.js +1 -1
  267. package/dist/core/storage/storage-status.impl.js +3 -3
  268. package/dist/core/storage/storage-status.js +3 -3
  269. package/dist/core/storage/team.code.js +1 -1
  270. package/dist/core/storage/team.impl.js +3 -3
  271. package/dist/core/storage/team.js +3 -3
  272. package/dist/core/structured-output/index.code.js +1 -1
  273. package/dist/core/structured-output/index.impl.js +3 -3
  274. package/dist/core/structured-output/index.js +3 -3
  275. package/dist/core/tasks/task-completion-entry.code.js +1 -1
  276. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  277. package/dist/core/tasks/task-completion-entry.js +3 -3
  278. package/dist/core/tasks/task-file-history.code.js +4 -4
  279. package/dist/core/tasks/task-file-history.impl.js +3 -3
  280. package/dist/core/tasks/task-file-history.js +3 -3
  281. package/dist/core/tasks/task-reference-archive.code.js +5 -5
  282. package/dist/core/tasks/task-reference-archive.js +3 -3
  283. package/dist/core/tasks/task-reference-identity.js +3 -3
  284. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  285. package/dist/core/tasks/task-reference-stream.js +3 -3
  286. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  287. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  288. package/dist/core/tasks/task-view-source.code.js +1 -1
  289. package/dist/core/tasks/task-view-source.impl.js +3 -3
  290. package/dist/core/tasks/task-view-source.js +3 -3
  291. package/dist/core/tools/bash.d.ts +8 -4
  292. package/dist/core/tools/history-session.d.ts +7 -0
  293. package/dist/core/tools/history-tasks.d.ts +123 -0
  294. package/dist/core/tools/kill.d.ts +5 -2
  295. package/dist/core/tools/powershell.d.ts +2 -2
  296. package/dist/core/tools/read-url.code.js +3 -3
  297. package/dist/core/tools/read-url.impl.js +3 -3
  298. package/dist/core/tools/read-url.js +3 -3
  299. package/dist/core/tools/read.d.ts +12 -2
  300. package/dist/core/tools/resource-selectors.d.ts +2 -0
  301. package/dist/core/tools/search.d.ts +12 -2
  302. package/dist/core/worktree-snapshot/blob-store.d.ts +45 -2
  303. package/dist/core/worktree-snapshot/blob-store.js +228 -60
  304. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  305. package/dist/core/worktree-snapshot/errors.code.js +3 -3
  306. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  307. package/dist/core/worktree-snapshot/errors.js +3 -3
  308. package/dist/core/worktree-snapshot/fork-snapshot-index.js +121 -0
  309. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -0
  310. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  311. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  312. package/dist/extensions/codemode/execute.code.js +3 -3
  313. package/dist/extensions/codemode/execute.impl.js +3 -3
  314. package/dist/extensions/codemode/execute.js +3 -3
  315. package/dist/extensions/codemode/renderer.code.js +2 -2
  316. package/dist/extensions/codemode/renderer.impl.js +3 -3
  317. package/dist/extensions/codemode/renderer.js +3 -3
  318. package/dist/extensions/mcp/cli.code.js +3 -3
  319. package/dist/extensions/mcp/cli.impl.js +3 -3
  320. package/dist/extensions/mcp/cli.js +3 -3
  321. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  322. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  323. package/dist/extensions/mcp/cli.lazy.js +3 -3
  324. package/dist/extensions/mcp/runtime.code.js +1 -1
  325. package/dist/extensions/mcp/runtime.impl.js +3 -3
  326. package/dist/extensions/mcp/runtime.js +3 -3
  327. package/dist/index.js +8 -8
  328. package/dist/main-first-time-setup.code.js +2 -2
  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/agent-panel.d.ts +1 -0
  333. package/dist/modes/interactive/components/stored-tree-view.code.js +3 -3
  334. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  335. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  336. package/dist/modes/interactive/components/task-inspector.d.ts +2 -0
  337. package/dist/modes/interactive/components/user-message-selector-archive.code.js +1 -1
  338. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  339. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  340. package/dist/modes/interactive/interactive-mode-helpers.d.ts +2 -2
  341. package/dist/modes/print-mode.js +1 -1
  342. package/dist/modes/rpc/agent-panel-bridge.d.ts +5 -0
  343. package/dist/package-manager-cli.code.js +7 -7
  344. package/dist/package-manager-cli.impl.js +3 -3
  345. package/dist/package-manager-cli.js +3 -3
  346. package/dist/rpc-entry.js +1 -1
  347. package/dist/startup-files.json +1 -1
  348. package/dist/startup-stages/0.js +1 -1
  349. package/dist/startup-stages/1.js +1 -1
  350. package/dist/startup-stages/10.js +1 -1
  351. package/dist/startup-stages/12.js +1 -1
  352. package/dist/startup-stages/2.js +9 -1
  353. package/dist/startup-stages/3.js +1 -6
  354. package/dist/startup-stages/5.js +1 -1
  355. package/dist/startup-stages/7.js +1 -1
  356. package/dist/startup-stages/8.js +2 -2
  357. package/dist/utils/startup-database-spare.code.js +3 -3
  358. package/dist/utils/startup-database-spare.impl.js +3 -3
  359. package/dist/utils/startup-database-spare.js +3 -3
  360. package/dist/utils/tools-manager.code.js +1 -1
  361. package/dist/utils/tools-manager.impl.js +3 -3
  362. package/dist/utils/tools-manager.js +3 -3
  363. package/docs/background-tasks.md +123 -23
  364. package/docs/compaction.md +18 -0
  365. package/docs/docs.json +2 -0
  366. package/docs/environment-variables.md +1 -1
  367. package/docs/getting-started/installation.md +9 -2
  368. package/docs/guides/postgres-pgbouncer.md +346 -0
  369. package/docs/guides/postgres-tuning.md +311 -0
  370. package/docs/guides/resume-on-any-machine.md +2 -2
  371. package/docs/guides.md +2 -0
  372. package/docs/index.md +1 -1
  373. package/docs/libraries/agent-core.md +1 -1
  374. package/docs/libraries/ai.md +2 -2
  375. package/docs/libraries/codemode.md +1 -1
  376. package/docs/libraries/storage-libsql.md +6 -1
  377. package/docs/libraries/storage-postgres.md +11 -6
  378. package/docs/libraries/tui.md +1 -1
  379. package/docs/libraries.md +2 -2
  380. package/docs/programmatic.md +1 -1
  381. package/docs/quickstart.md +1 -1
  382. package/docs/sdk/storage.md +1 -1
  383. package/docs/sdk/web-server.md +1 -3
  384. package/docs/sdk.md +1 -7
  385. package/docs/sessions.md +67 -2
  386. package/docs/settings.md +20 -1
  387. package/docs/skills/authoring.md +1 -1
  388. package/docs/skills.md +79 -6
  389. package/docs/storage.md +305 -14
  390. package/docs/subagents/reference.md +2 -2
  391. package/docs/subagents.md +4 -3
  392. package/docs/tools.md +44 -10
  393. package/docs/windows.md +1 -1
  394. package/package.json +9 -9
  395. package/dist/_shared/sdk-RRLVN7ER.js.map +0 -1
  396. package/dist/_shared/settings-startup-4QCVCI53.js.map +0 -1
  397. package/dist/_shared/startup-0-0-4VG2G44V.js.map +0 -1
  398. package/dist/_shared/startup-0-1-XTIL65D4.js.map +0 -1
  399. package/dist/_shared/startup-0-2-27OWFHV6.js.map +0 -1
  400. package/dist/_shared/startup-0-3-T4DVFYWX.js.map +0 -1
  401. package/dist/_shared/startup-0-5-FD2P735I.js.map +0 -1
  402. package/dist/_shared/startup-8-1-4KANEHRA.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"node-sqlite-thread.js","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite-thread.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAEpE,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAG7C;;;;;;GAMG;AACH,MAAM,iBAAiB,GAAG;EACxB,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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K,CAAC,qBAAqB,CACjC,IAAuB,EACvB,QAAyE,EACzE,eAA8B;QAE9B,MAAM,EAAE,8BAA8B,EAAE,GAAG,MAAM,MAAM,CAAC,uCAAuC,CAAC,CAAC;QACjG,IAAI,eAAe,EAAE,IAAI,8BAA8B,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,EAAE,CAAC;YAChF,gBAAgB,CAAC,UAAU,EAAE,CAAC;QAC/B,CAAC;IACF,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport { startupNodeOptions } from \"@bastani/atomic-codemode/node-options\";\nimport { EVAL_WORKER_BUILTIN } from \"../../utils/worker-threads.js\";\nimport type { SqliteRow, SqliteValue } from \"./database.js\";\nimport { sqliteDialect } from \"./dialect.js\";\nimport type { SequencedStatement, SqliteSequence } from \"./statement-sequence.js\";\n\n/**\n * A node:sqlite connection that runs on a worker thread of its own (#5376). The thread owns the `DatabaseSync`; the\n * calling thread sends it one request at a time and receives each answer as a message, so no statement, lock wait or\n * synced commit runs on the caller's event loop. SQLite's busy handler waits on the connection's own thread, so a\n * statement waiting for a lock that another connection of the same process holds never stops that connection from\n * finishing.\n */\nconst CONNECTION_SOURCE = `\n${EVAL_WORKER_BUILTIN}\nconst { parentPort, workerData } = builtin(\"node:worker_threads\");\nprocess.emitWarning = () => {};\nconst { DatabaseSync } = builtin(\"node:sqlite\");\nlet database;\n\nconst STANDARD_ERRORS = [Error, TypeError, RangeError, SyntaxError, ReferenceError, EvalError, URIError];\n// Bun stamps every error with where it was thrown; the caller's copy gets its own.\nconst LOCATION_FIELDS = new Set([\"stack\", \"message\", \"line\", \"column\", \"originalLine\", \"originalColumn\", \"sourceURL\"]);\n\n// An object's own fields that hold plain values, with their enumerability.\nfunction fieldsOf(object, skip) {\n\tconst fields = [];\n\tfor (const key of Object.getOwnPropertyNames(object)) {\n\t\tif (skip.has(key)) continue;\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(object, key);\n\t\tconst value = descriptor?.value;\n\t\tif (value === null || (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\" && typeof value !== \"bigint\")) continue;\n\t\tfields.push([key, value, descriptor.enumerable === true]);\n\t}\n\treturn fields;\n}\n\n// A thrown error as it crosses to the caller: the standard constructor it descends from, its message, and its own\n// fields with their enumerability. A runtime's error class of its own between the error and that constructor (Bun's\n// node:sqlite errors have one holding name, code and toString) is described by its fields and whether it has a\n// toString of its own, and how it shows.\nfunction failure(error) {\n\tif (!(error instanceof Error)) return { constructor: \"Error\", message: String(error), fields: [] };\n\tlet standard = Object.getPrototypeOf(error);\n\tlet between;\n\twhile (standard !== null && !STANDARD_ERRORS.some((each) => each.prototype === standard)) {\n\t\tif (between === undefined) {\n\t\t\tconst toString = Object.getOwnPropertyDescriptor(standard, \"toString\");\n\t\t\tbetween = {\n\t\t\t\tfields: fieldsOf(standard, new Set([\"constructor\", \"message\"])),\n\t\t\t\t...(typeof toString?.value === \"function\" ? { toString: { enumerable: toString.enumerable === true } } : {}),\n\t\t\t};\n\t\t}\n\t\tstandard = Object.getPrototypeOf(standard);\n\t}\n\treturn {\n\t\tconstructor: standard === null ? \"Error\" : standard.constructor.name,\n\t\tmessage: String(error.message),\n\t\tfields: fieldsOf(error, LOCATION_FIELDS),\n\t\t...(between === undefined ? {} : { between }),\n\t};\n}\n\nfunction statement(sql) {\n\tconst prepared = database.prepare(sql);\n\tprepared.setReadBigInts(true);\n\treturn prepared;\n}\n\n// Node 22 binds an empty Uint8Array that arrived in a message as NULL; a new empty one binds as a zero-length blob.\nfunction bind(params) {\n\treturn params.map((value) => (value instanceof Uint8Array && value.byteLength === 0 ? new Uint8Array(0) : value));\n}\n\nfunction value(each) {\n\tif (typeof each === \"bigint\") return each >= -BigInt(Number.MAX_SAFE_INTEGER) && each <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(each) : each;\n\t// A copy of its own: a view of a larger buffer would send the whole buffer.\n\treturn each instanceof Uint8Array ? new Uint8Array(each) : each;\n}\n\n// Rows cross as their column names and one array of values each, in the order the driver gives a row's fields.\nfunction table(rows) {\n\tif (rows.length === 0) return { columns: [], values: [] };\n\tconst columns = Object.keys(rows[0]);\n\treturn { columns, values: rows.map((row) => columns.map((column) => value(row[column]))) };\n}\n\nconst handlers = {\n\topen: (request) => {\n\t\tdatabase = new DatabaseSync(request.path, { readOnly: request.readOnly });\n\t\treturn database.location();\n\t},\n\texec: (request) => {\n\t\tdatabase.exec(request.sql);\n\t},\n\trun: (request) => ({ changes: Number(statement(request.sql).run(...bind(request.params)).changes) }),\n\tget: (request) => {\n\t\tconst row = statement(request.sql).get(...bind(request.params));\n\t\treturn row === undefined ? undefined : table([row]);\n\t},\n\tall: (request) => table(statement(request.sql).all(...bind(request.params))),\n\t// One non-blocking BEGIN IMMEDIATE, the connection's busy timeout restored before answering.\n\tbegin: (request) => {\n\t\t// The file's lock word (see FREE in node-sqlite-file-gate.ts): taken before BEGIN, after waiting here for a\n\t\t// statement the calling thread runs meanwhile; settleLock gives it back once the transaction ended.\n\t\tif (request.lockState !== undefined) {\n\t\t\tconst state = new Int32Array(request.lockState);\n\t\t\tfor (;;) {\n\t\t\t\tconst found = Atomics.compareExchange(state, 0, 0, request.lockTag * 4 + 2);\n\t\t\t\tif (found === 0) break;\n\t\t\t\t// Anything but a statement of the calling thread (1) is another holder: a lock taken, as BEGIN would find.\n\t\t\t\tif (found !== 1)\n\t\t\t\t\tthrow Object.assign(new Error(\"database is locked\"), { code: \"ERR_SQLITE_ERROR\", errcode: 5, errstr: \"database is locked\" });\n\t\t\t\tAtomics.wait(state, 0, 1, 50);\n\t\t\t}\n\t\t\tAtomics.notify(state, 0);\n\t\t\tlockState = { state, held: request.lockTag * 4 + 3 };\n\t\t}\n\t\tconst configured = Number(database.prepare(\"PRAGMA busy_timeout\").get()?.timeout ?? 0);\n\t\tdatabase.exec(\"PRAGMA busy_timeout=0\");\n\t\tlet began = false;\n\t\ttry {\n\t\t\tdatabase.exec(\"BEGIN IMMEDIATE\");\n\t\t\tbegan = true;\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tdatabase.exec(\"PRAGMA busy_timeout=\" + configured);\n\t\t\t} catch (restoreFailure) {\n\t\t\t\tif (began) database.exec(\"ROLLBACK\");\n\t\t\t\tthrow restoreFailure;\n\t\t\t}\n\t\t}\n\t},\n\t// \\`repeat\\`, then each statement, in one request: the statements the caller would send one at a time, in the same\n\t// order, each prepared when it is reached. The caller's abort flag is read where the caller would check its signal.\n\tsequence: (request) => {\n\t\tconst abort = request.abort === undefined ? undefined : new Int32Array(request.abort);\n\t\tconst aborted = () => abort !== undefined && Atomics.load(abort, 0) !== 0;\n\t\tlet repeated = 0;\n\t\tif (request.repeat !== undefined) {\n\t\t\tconst { statement: repeat, times, minChanges } = request.repeat;\n\t\t\twhile (repeated < times) {\n\t\t\t\tif (aborted()) return { aborted: true };\n\t\t\t\tconst before = Number(statement(\"SELECT total_changes() AS changes\").get().changes);\n\t\t\t\tstatement(repeat.sql).run(...bind(repeat.params));\n\t\t\t\tconst after = Number(statement(\"SELECT total_changes() AS changes\").get().changes);\n\t\t\t\tif (after - before < minChanges) break;\n\t\t\t\trepeated++;\n\t\t\t}\n\t\t}\n\t\tfor (const { sql, params, script } of request.statements) {\n\t\t\tif (aborted()) return { aborted: true };\n\t\t\tif (script === true) database.exec(sql);\n\t\t\telse statement(sql).run(...bind(params));\n\t\t}\n\t\treturn { repeated };\n\t},\n\tdataVersion: () => Number(database.prepare(\"PRAGMA data_version\").get()?.data_version ?? 0),\n\tnow: () => Number(database.prepare(workerData.nowSql).get().now),\n\tjsonbExtract: () => {\n\t\ttry {\n\t\t\tstatement(\"SELECT jsonb_extract('[]', '$')\");\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"no such function: jsonb_extract\") return false;\n\t\t\tthrow error;\n\t\t}\n\t},\n\tclose: () => {\n\t\tdatabase?.close();\n\t\tglobalThis.Bun?.gc?.(true);\n\t},\n};\n\n// The file's lock word while this connection takes or holds the lock: held while a transaction is open on it, given\n// back (and the waiting threads woken) once none is, before the request that ended it is answered.\nlet lockState;\n\nfunction settleLock() {\n\tif (lockState === undefined) return;\n\tconst { state, held } = lockState;\n\tlet open = false;\n\ttry {\n\t\topen = database?.isTransaction === true;\n\t} catch {}\n\tif (open) {\n\t\tif (Atomics.compareExchange(state, 0, held - 1, held) === held - 1) Atomics.notify(state, 0);\n\t\treturn;\n\t}\n\tlockState = undefined;\n\tif (Atomics.compareExchange(state, 0, held, 0) === held || Atomics.compareExchange(state, 0, held - 1, 0) === held - 1)\n\t\tAtomics.notify(state, 0);\n}\n\nfunction handle(request) {\n\ttry {\n\t\treturn handlers[request.kind](request);\n\t} finally {\n\t\tsettleLock();\n\t}\n}\n\nparentPort.on(\"message\", (request) => {\n\ttry {\n\t\tparentPort.postMessage({ id: request.id, value: handle(request) });\n\t} catch (error) {\n\t\tparentPort.postMessage({ id: request.id, failure: failure(error) });\n\t}\n});\n`;\n\n/**\n * Statements sent as one request (see `SqliteSequence`). `abort` holds one `Int32` the caller sets to non-zero when its\n * signal aborts: the thread reads it before each run of `repeat` and before each statement.\n */\nexport interface SequenceRequest {\n\treadonly kind: \"sequence\";\n\treadonly repeat?: SqliteSequence[\"repeat\"];\n\treadonly statements: readonly SequencedStatement[];\n\treadonly abort?: SharedArrayBuffer;\n}\n\n/**\n * What a sequence request is answered with: how many runs of `repeat` changed `minChanges` rows or more, or that it\n * stopped because the caller's signal aborted.\n */\nexport type SequenceAnswer = { readonly repeated: number } | { readonly aborted: true };\n\n/** What a connection's thread is asked to do; each request is answered once, in the order it was sent. */\nexport type ConnectionRequest =\n\t| { readonly kind: \"open\"; readonly path: string; readonly readOnly: boolean }\n\t| { readonly kind: \"exec\"; readonly sql: string }\n\t| { readonly kind: \"run\" | \"get\" | \"all\"; readonly sql: string; readonly params: readonly SqliteValue[] }\n\t| { readonly kind: \"begin\"; readonly lockState?: SharedArrayBuffer; readonly lockTag?: number }\n\t| { readonly kind: \"dataVersion\" | \"now\" | \"jsonbExtract\" | \"close\" }\n\t| SequenceRequest;\n\n/** Rows as they cross from a connection's thread: the column names, then each row's values in their order. */\ninterface RowTable {\n\treadonly columns: readonly string[];\n\treadonly values: readonly (readonly SqliteValue[])[];\n}\n\n/** What a request's answer carries as it crosses, before rows are rebuilt. */\ntype ConnectionValue =\n\t| RowTable\n\t| { readonly changes: number }\n\t| SequenceAnswer\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| undefined;\n\n/**\n * What a request is answered with: `get` a row or undefined, `all` rows, `run` the changes, `sequence` a\n * `SequenceAnswer`, `open` the location, `dataVersion` and `now` a number, `jsonbExtract` a boolean, the others\n * undefined.\n */\nexport type ConnectionAnswer =\n\t| SqliteRow\n\t| SqliteRow[]\n\t| { readonly changes: number }\n\t| SequenceAnswer\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| undefined;\n\n/** An own field that holds a plain value: its key, value and enumerability. */\ntype ConnectionField = readonly [string, string | number | boolean | bigint, boolean];\n\n/** A failure as it crosses from a connection's thread; see `failure` in the thread's source. */\ninterface ConnectionFailure {\n\treadonly constructor: string;\n\treadonly message: string;\n\treadonly fields: readonly ConnectionField[];\n\treadonly between?: {\n\t\treadonly fields: readonly ConnectionField[];\n\t\treadonly toString?: { readonly enumerable: boolean };\n\t};\n}\n\ninterface ConnectionReply {\n\treadonly id: number;\n\treadonly value?: ConnectionValue;\n\treadonly failure?: ConnectionFailure;\n}\n\nconst STANDARD_ERRORS: Readonly<Record<string, ErrorConstructor>> = {\n\tError,\n\tTypeError,\n\tRangeError,\n\tSyntaxError,\n\tReferenceError,\n\tEvalError,\n\tURIError,\n};\n\n/** One prototype per runtime error class seen, by what it holds: see `connectionError`. */\nconst betweenPrototypes = new Map<string, object>();\n\n/** How a runtime's error class of its own shows an error, as Bun's do: `TypeError [ERR_INVALID_ARG_VALUE]: …`. */\nfunction showWithCode(this: Error & { readonly code?: unknown }): string {\n\treturn `${this.name} [${String(this.code)}]: ${this.message}`;\n}\n\nfunction betweenPrototype(base: ErrorConstructor, between: NonNullable<ConnectionFailure[\"between\"]>): object {\n\tconst key = JSON.stringify([\n\t\tbase.name,\n\t\tbetween.fields.map(([field, value, enumerable]) => [field, String(value), enumerable]),\n\t\tbetween.toString,\n\t]);\n\tlet prototype = betweenPrototypes.get(key);\n\tif (prototype === undefined) {\n\t\tconst created: object = Object.create(base.prototype);\n\t\tfor (const [field, value, enumerable] of between.fields)\n\t\t\tObject.defineProperty(created, field, { value, enumerable, writable: true, configurable: true });\n\t\tif (between.toString !== undefined)\n\t\t\tObject.defineProperty(created, \"toString\", {\n\t\t\t\tvalue: showWithCode,\n\t\t\t\tenumerable: between.toString.enumerable,\n\t\t\t\twritable: true,\n\t\t\t\tconfigurable: true,\n\t\t\t});\n\t\tbetweenPrototypes.set(key, created);\n\t\tprototype = created;\n\t}\n\treturn prototype;\n}\n\n/**\n * The driver's error, rebuilt on the calling thread as the driver threw it: an instance of the same standard error\n * class with the same message, and the same own fields (`code`, `errcode`, `errstr` for SQLite's errors) with the same\n * enumerability. A runtime's own error class between them is stood in for by a prototype that holds the same fields and\n * shows the error the same way.\n */\nfunction connectionError(failure: ConnectionFailure): Error {\n\tconst base = STANDARD_ERRORS[failure.constructor] ?? Error;\n\tconst error = new base(failure.message);\n\tif (failure.between !== undefined) Object.setPrototypeOf(error, betweenPrototype(base, failure.between));\n\tfor (const [key, value, enumerable] of failure.fields)\n\t\tObject.defineProperty(error, key, { value, enumerable, writable: true, configurable: true });\n\treturn error;\n}\n\n/** The rows of `table`, each a plain object built the way the calling-thread connection builds them. */\nfunction rowsOf(table: RowTable): SqliteRow[] {\n\tconst { columns, values } = table;\n\treturn values.map((row) => Object.fromEntries(columns.map((column, index) => [column, row[index] as SqliteValue])));\n}\n\ninterface Waiter {\n\treadonly resolve: (value: ConnectionValue) => void;\n\treadonly reject: (error: unknown) => void;\n}\n\n/** Thrown for a request to a connection whose thread is gone: closed, or lost to an error or an exit. */\nexport class ConnectionThreadEndedError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"ConnectionThreadEndedError\";\n\t}\n}\n\n/** Options that make every worker thread run code of the user's: a preload or a module loader. */\nconst WORKER_CODE_OPTIONS = new Set([\"--require\", \"-r\", \"--import\", \"--loader\", \"--experimental-loader\"]);\n\n/** The thread `startSpare` started for the next open, until an open takes it or `releaseSpare` ends it. */\nlet spare: ThreadConnection | undefined;\n\n/** A node:sqlite connection running on its own worker thread. */\nexport class ThreadConnection {\n\tprivate readonly worker: Worker;\n\tprivate readonly waiting = new Map<number, Waiter>();\n\tprivate nextId = 1;\n\tprivate ended?: Error;\n\tprivate closing?: Promise<undefined>;\n\n\tprivate constructor() {\n\t\t// None of the process's own flags: the caller's preloads would run again for every connection, and its\n\t\t// `--input-type=module` would make this source a module. Whether node:sqlite is available was settled by the\n\t\t// open before it started the thread.\n\t\tthis.worker = new Worker(CONNECTION_SOURCE, {\n\t\t\teval: true,\n\t\t\texecArgv: [],\n\t\t\tworkerData: { nowSql: `SELECT ${sqliteDialect.nowMs} AS now` },\n\t\t});\n\t\tthis.worker.on(\"message\", (reply: ConnectionReply) => this.receive(reply));\n\t\tthis.worker.on(\"error\", (error: Error) => this.end(error));\n\t\tthis.worker.on(\"exit\", (code: number) =>\n\t\t\tthis.end(new ConnectionThreadEndedError(`SQLite connection thread exited with code ${code}`)),\n\t\t);\n\t}\n\n\t/**\n\t * Opens `openAs` (or `path`) on a thread of its own and resolves with the location SQLite reports for it. A failure\n\t * to start the thread or to open the database rejects with its cause; the thread is gone then.\n\t */\n\tstatic async open(\n\t\tpath: string,\n\t\toptions: { readonly readOnly: boolean; readonly openAs?: string },\n\t): Promise<{ readonly connection: ThreadConnection; readonly location: string | null }> {\n\t\tconst started = spare;\n\t\tspare = undefined;\n\t\tif (started !== undefined && started.ended === undefined) {\n\t\t\ttry {\n\t\t\t\treturn await ThreadConnection.openOn(started, path, options);\n\t\t\t} catch (error) {\n\t\t\t\t// The spare thread was lost before it answered: open on a thread of its own, as without one.\n\t\t\t\tif (error !== started.ended) throw error;\n\t\t\t}\n\t\t}\n\t\treturn ThreadConnection.openOn(new ThreadConnection(), path, options);\n\t}\n\n\t/**\n\t * Starts one connection thread now, for the next open to take, so that the thread's startup overlaps whatever the\n\t * process does until then (an interactive session loads its modules meanwhile). Idle, the thread keeps nothing\n\t * alive. Nothing starts when the process runs a preload or a module loader, which every worker thread runs again,\n\t * or runs under the permission model; a thread that cannot start leaves every open as it is without one.\n\t */\n\tstatic startSpare(): void {\n\t\tif (spare !== undefined || process.permission !== undefined) return;\n\t\tif (startupNodeOptions().some((option) => WORKER_CODE_OPTIONS.has(option.name))) return;\n\t\ttry {\n\t\t\tconst started = new ThreadConnection();\n\t\t\tstarted.worker.unref();\n\t\t\tspare = started;\n\t\t} catch {\n\t\t\t// Opens start their own threads.\n\t\t}\n\t}\n\n\t/** Ends the spare thread if no open has taken it. */\n\tstatic releaseSpare(): void {\n\t\tconst started = spare;\n\t\tspare = undefined;\n\t\tif (started !== undefined) void started.stop();\n\t}\n\n\tprivate static async openOn(\n\t\tconnection: ThreadConnection,\n\t\tpath: string,\n\t\toptions: { readonly readOnly: boolean; readonly openAs?: string },\n\t): Promise<{ readonly connection: ThreadConnection; readonly location: string | null }> {\n\t\ttry {\n\t\t\tconst location = await connection.request({\n\t\t\t\tkind: \"open\",\n\t\t\t\tpath: options.openAs ?? path,\n\t\t\t\treadOnly: options.readOnly,\n\t\t\t});\n\t\t\treturn { connection, location: typeof location === \"string\" ? location : null };\n\t\t} catch (error) {\n\t\t\tawait connection.stop();\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Sends one request; resolves with the thread's answer or rejects with the driver's error, rebuilt. While a request\n\t * waits for its answer the thread keeps the process alive; an idle connection does not, as a connection on the\n\t * calling thread would not.\n\t */\n\trequest(request: ConnectionRequest): Promise<ConnectionAnswer> {\n\t\tif (request.kind === \"close\") return this.close();\n\t\tconst answer = this.send(request);\n\t\tif (request.kind === \"get\")\n\t\t\treturn answer.then((value) => (value === undefined ? undefined : rowsOf(value as RowTable)[0]));\n\t\tif (request.kind === \"all\") return answer.then((value) => rowsOf(value as RowTable));\n\t\treturn answer as Promise<ConnectionAnswer>;\n\t}\n\n\tprivate send(request: ConnectionRequest): Promise<ConnectionValue> {\n\t\treturn new Promise<ConnectionValue>((resolve, reject) => {\n\t\t\tif (this.ended !== undefined) {\n\t\t\t\treject(this.ended);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst id = this.nextId++;\n\t\t\ttry {\n\t\t\t\tthis.worker.postMessage({ id, ...request });\n\t\t\t} catch (error) {\n\t\t\t\t// A value the thread cannot receive.\n\t\t\t\treject(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.waiting.set(id, { resolve, reject });\n\t\t\tif (this.waiting.size === 1) this.worker.ref();\n\t\t});\n\t}\n\n\t/**\n\t * Closes the database on its thread, then ends the thread: a `close` request. Requests sent after it are rejected. A\n\t * thread already lost has nothing to close.\n\t */\n\tprivate close(): Promise<undefined> {\n\t\tthis.closing ??= (async () => {\n\t\t\ttry {\n\t\t\t\tif (this.ended === undefined) await this.send({ kind: \"close\" });\n\t\t\t} finally {\n\t\t\t\tawait this.stop();\n\t\t\t}\n\t\t\treturn undefined;\n\t\t})();\n\t\treturn this.closing;\n\t}\n\n\tprivate receive(reply: ConnectionReply): void {\n\t\tconst waiter = this.waiting.get(reply.id);\n\t\tif (waiter === undefined) return;\n\t\tthis.waiting.delete(reply.id);\n\t\tif (this.waiting.size === 0) this.worker.unref();\n\t\tif (reply.failure === undefined) waiter.resolve(reply.value);\n\t\telse waiter.reject(connectionError(reply.failure));\n\t}\n\n\t/** Rejects every request still waiting, oldest first, and every later one. Ending again does nothing. */\n\tprivate end(cause: Error): void {\n\t\tif (this.ended !== undefined) return;\n\t\t// Kept for as long as the connection is: an error's stack, until formatted, keeps the functions of the frames it\n\t\t// names, and so whatever they hold, such as a session that closed its store.\n\t\tvoid cause.stack;\n\t\tthis.ended = cause;\n\t\tconst waiting = [...this.waiting.values()];\n\t\tthis.waiting.clear();\n\t\tthis.worker.unref();\n\t\tfor (const waiter of waiting) waiter.reject(cause);\n\t}\n\n\tprivate async stop(): Promise<void> {\n\t\tthis.end(new ConnectionThreadEndedError(\"SQLite connection closed\"));\n\t\tawait this.worker.terminate();\n\t}\n\n\t/** Calls `listener` once the connection's thread has exited, whether closed or lost. */\n\tonExit(listener: () => void): void {\n\t\tthis.worker.once(\"exit\", listener);\n\t}\n\n\t/**\n\t * Starts a spare worker for a non-interactive or storage-overridden CLI\n\t * invocation only when the real CLI/storage resolvers select a SQLite store.\n\t */\n\tstatic async startSpareIfSqlNeeded(\n\t\targs: readonly string[],\n\t\tterminal: { readonly stdinIsTTY: boolean; readonly stdoutIsTTY: boolean },\n\t\tstillBeforeMain: () => boolean,\n\t): Promise<void> {\n\t\tconst { shouldStartSpareDatabaseThread } = await import(\"../../utils/startup-database-spare.ts\");\n\t\tif (stillBeforeMain() && shouldStartSpareDatabaseThread(args, false, terminal)) {\n\t\t\tThreadConnection.startSpare();\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"node-sqlite-thread.js","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite-thread.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAEpE,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAG7C;;;;;;GAMG;AACH,MAAM,iBAAiB,GAAG;EACxB,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAC,IAAI,0BAA0B,CAAC,0BAA0B,CAAC,CAAC,CAAC;QACrE,MAAM,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC;IAC/B,CAAC;IAED,wFAAwF;IACxF,MAAM,CAAC,QAAoB;QAC1B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IACpC,CAAC;IAED;;;OAGG;IACH,MAAM,CAAC,KAAK,CAAC,qBAAqB,CACjC,IAAuB,EACvB,QAAyE,EACzE,eAA8B;QAE9B,MAAM,EAAE,8BAA8B,EAAE,GAAG,MAAM,MAAM,CAAC,uCAAuC,CAAC,CAAC;QACjG,IAAI,eAAe,EAAE,IAAI,8BAA8B,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,EAAE,CAAC;YAChF,gBAAgB,CAAC,UAAU,EAAE,CAAC;QAC/B,CAAC;IACF,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport { startupNodeOptions } from \"@bastani/atomic-codemode/node-options\";\nimport { EVAL_WORKER_BUILTIN } from \"../../utils/worker-threads.js\";\nimport type { SqliteRow, SqliteStatement, SqliteValue } from \"./database.js\";\nimport { sqliteDialect } from \"./dialect.js\";\nimport type { SequencedStatement, SqliteSequence } from \"./statement-sequence.js\";\n\n/**\n * A node:sqlite connection that runs on a worker thread of its own (#5376). The thread owns the `DatabaseSync`; the\n * calling thread sends it one request at a time and receives each answer as a message, so no statement, lock wait or\n * synced commit runs on the caller's event loop. SQLite's busy handler waits on the connection's own thread, so a\n * statement waiting for a lock that another connection of the same process holds never stops that connection from\n * finishing.\n */\nconst CONNECTION_SOURCE = `\n${EVAL_WORKER_BUILTIN}\nconst { parentPort, workerData } = builtin(\"node:worker_threads\");\nprocess.emitWarning = () => {};\nconst { DatabaseSync } = builtin(\"node:sqlite\");\nlet database;\n\nconst STANDARD_ERRORS = [Error, TypeError, RangeError, SyntaxError, ReferenceError, EvalError, URIError];\n// Bun stamps every error with where it was thrown; the caller's copy gets its own.\nconst LOCATION_FIELDS = new Set([\"stack\", \"message\", \"line\", \"column\", \"originalLine\", \"originalColumn\", \"sourceURL\"]);\n\n// An object's own fields that hold plain values, with their enumerability.\nfunction fieldsOf(object, skip) {\n\tconst fields = [];\n\tfor (const key of Object.getOwnPropertyNames(object)) {\n\t\tif (skip.has(key)) continue;\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(object, key);\n\t\tconst value = descriptor?.value;\n\t\tif (value === null || (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\" && typeof value !== \"bigint\")) continue;\n\t\tfields.push([key, value, descriptor.enumerable === true]);\n\t}\n\treturn fields;\n}\n\n// A thrown error as it crosses to the caller: the standard constructor it descends from, its message, and its own\n// fields with their enumerability. A runtime's error class of its own between the error and that constructor (Bun's\n// node:sqlite errors have one holding name, code and toString) is described by its fields and whether it has a\n// toString of its own, and how it shows.\nfunction failure(error) {\n\tif (!(error instanceof Error)) return { constructor: \"Error\", message: String(error), fields: [] };\n\tlet standard = Object.getPrototypeOf(error);\n\tlet between;\n\twhile (standard !== null && !STANDARD_ERRORS.some((each) => each.prototype === standard)) {\n\t\tif (between === undefined) {\n\t\t\tconst toString = Object.getOwnPropertyDescriptor(standard, \"toString\");\n\t\t\tbetween = {\n\t\t\t\tfields: fieldsOf(standard, new Set([\"constructor\", \"message\"])),\n\t\t\t\t...(typeof toString?.value === \"function\" ? { toString: { enumerable: toString.enumerable === true } } : {}),\n\t\t\t};\n\t\t}\n\t\tstandard = Object.getPrototypeOf(standard);\n\t}\n\treturn {\n\t\tconstructor: standard === null ? \"Error\" : standard.constructor.name,\n\t\tmessage: String(error.message),\n\t\tfields: fieldsOf(error, LOCATION_FIELDS),\n\t\t...(between === undefined ? {} : { between }),\n\t};\n}\n\nconst prepared = new Map();\n\nfunction statement(sql) {\n\tconst cached = prepared.get(sql);\n\tif (cached !== undefined) {\n\t\tprepared.delete(sql);\n\t\tprepared.set(sql, cached);\n\t\treturn cached;\n\t}\n\tconst made = database.prepare(sql);\n\tmade.setReadBigInts(true);\n\tprepared.set(sql, made);\n\tif (prepared.size > workerData.statementCacheSize) prepared.delete(prepared.keys().next().value);\n\treturn made;\n}\n\n// Node 22 binds an empty Uint8Array that arrived in a message as NULL; a new empty one binds as a zero-length blob.\nfunction bind(params) {\n\treturn params.map((value) => (value instanceof Uint8Array && value.byteLength === 0 ? new Uint8Array(0) : value));\n}\n\nfunction value(each) {\n\tif (typeof each === \"bigint\") return each >= -BigInt(Number.MAX_SAFE_INTEGER) && each <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(each) : each;\n\t// A copy of its own: a view of a larger buffer would send the whole buffer.\n\treturn each instanceof Uint8Array ? new Uint8Array(each) : each;\n}\n\n// Rows cross as their column names and one array of values each, in the order the driver gives a row's fields.\nfunction table(rows) {\n\tif (rows.length === 0) return { columns: [], values: [] };\n\tconst columns = Object.keys(rows[0]);\n\treturn { columns, values: rows.map((row) => columns.map((column) => value(row[column]))) };\n}\n\nconst handlers = {\n\topen: (request) => {\n\t\tdatabase = new DatabaseSync(request.path, { readOnly: request.readOnly });\n\t\treturn database.location();\n\t},\n\texec: (request) => {\n\t\tdatabase.exec(request.sql);\n\t},\n\trun: (request) => ({ changes: Number(statement(request.sql).run(...bind(request.params)).changes) }),\n\tget: (request) => {\n\t\tconst row = statement(request.sql).get(...bind(request.params));\n\t\treturn row === undefined ? undefined : table([row]);\n\t},\n\tall: (request) => table(statement(request.sql).all(...bind(request.params))),\n\t// A read transaction's start: BEGIN, then its leading reads, in one request. A BEGIN that fails fails the request and\n\t// leaves no transaction. The reads answer up to the first that fails, which, with the ones after it, the caller then\n\t// sends on its own in the same transaction, so it fails or answers there as it always would.\n\tread: (request) => {\n\t\tdatabase.exec(\"BEGIN\");\n\t\tconst answers = [];\n\t\tfor (const { sql, params } of request.statements) {\n\t\t\ttry {\n\t\t\t\tanswers.push(table(statement(sql).all(...bind(params))));\n\t\t\t} catch {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn answers;\n\t},\n\t// A read transaction's end, which its caller does not wait for: COMMIT, or ROLLBACK where COMMIT fails, so the\n\t// connection is never left inside it.\n\tendRead: () => {\n\t\ttry {\n\t\t\tdatabase.exec(\"COMMIT\");\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tdatabase.exec(\"ROLLBACK\");\n\t\t\t} catch {}\n\t\t\tthrow error;\n\t\t}\n\t},\n\t// One non-blocking BEGIN IMMEDIATE, the connection's busy timeout restored before answering.\n\tbegin: (request) => {\n\t\t// The file's lock word (see FREE in node-sqlite-file-gate.ts): taken before BEGIN, after waiting here for a\n\t\t// statement the calling thread runs meanwhile; settleLock gives it back once the transaction ended.\n\t\tif (request.lockState !== undefined) {\n\t\t\tconst state = new Int32Array(request.lockState);\n\t\t\tfor (;;) {\n\t\t\t\tconst found = Atomics.compareExchange(state, 0, 0, request.lockTag * 4 + 2);\n\t\t\t\tif (found === 0) break;\n\t\t\t\t// Anything but a statement of the calling thread (1) is another holder: a lock taken, as BEGIN would find.\n\t\t\t\tif (found !== 1)\n\t\t\t\t\tthrow Object.assign(new Error(\"database is locked\"), { code: \"ERR_SQLITE_ERROR\", errcode: 5, errstr: \"database is locked\" });\n\t\t\t\tAtomics.wait(state, 0, 1, 50);\n\t\t\t}\n\t\t\tAtomics.notify(state, 0);\n\t\t\tlockState = { state, held: request.lockTag * 4 + 3 };\n\t\t}\n\t\tconst configured = Number(database.prepare(\"PRAGMA busy_timeout\").get()?.timeout ?? 0);\n\t\tdatabase.exec(\"PRAGMA busy_timeout=0\");\n\t\tlet began = false;\n\t\ttry {\n\t\t\tdatabase.exec(\"BEGIN IMMEDIATE\");\n\t\t\tbegan = true;\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tdatabase.exec(\"PRAGMA busy_timeout=\" + configured);\n\t\t\t} catch (restoreFailure) {\n\t\t\t\tif (began) database.exec(\"ROLLBACK\");\n\t\t\t\tthrow restoreFailure;\n\t\t\t}\n\t\t}\n\t},\n\t// \\`repeat\\`, then each statement, in one request: the statements the caller would send one at a time, in the same\n\t// order, each prepared when it is reached. The caller's abort flag is read where the caller would check its signal.\n\tsequence: (request) => {\n\t\tconst abort = request.abort === undefined ? undefined : new Int32Array(request.abort);\n\t\tconst aborted = () => abort !== undefined && Atomics.load(abort, 0) !== 0;\n\t\tlet repeated = 0;\n\t\tif (request.repeat !== undefined) {\n\t\t\tconst { statement: repeat, times, minChanges } = request.repeat;\n\t\t\twhile (repeated < times) {\n\t\t\t\tif (aborted()) return { aborted: true };\n\t\t\t\tconst before = Number(statement(\"SELECT total_changes() AS changes\").get().changes);\n\t\t\t\tstatement(repeat.sql).run(...bind(repeat.params));\n\t\t\t\tconst after = Number(statement(\"SELECT total_changes() AS changes\").get().changes);\n\t\t\t\tif (after - before < minChanges) break;\n\t\t\t\trepeated++;\n\t\t\t}\n\t\t}\n\t\tfor (const { sql, params, script } of request.statements) {\n\t\t\tif (aborted()) return { aborted: true };\n\t\t\tif (script === true) database.exec(sql);\n\t\t\telse statement(sql).run(...bind(params));\n\t\t}\n\t\treturn { repeated };\n\t},\n\tdataVersion: () => Number(database.prepare(\"PRAGMA data_version\").get()?.data_version ?? 0),\n\tnow: () => Number(database.prepare(workerData.nowSql).get().now),\n\tjsonbExtract: () => {\n\t\ttry {\n\t\t\tstatement(\"SELECT jsonb_extract('[]', '$')\");\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"no such function: jsonb_extract\") return false;\n\t\t\tthrow error;\n\t\t}\n\t},\n\tclose: () => {\n\t\tprepared.clear();\n\t\tdatabase?.close();\n\t\tglobalThis.Bun?.gc?.(true);\n\t},\n};\n\n// The file's lock word while this connection takes or holds the lock: held while a transaction is open on it, given\n// back (and the waiting threads woken) once none is, before the request that ended it is answered.\nlet lockState;\n\nfunction settleLock() {\n\tif (lockState === undefined) return;\n\tconst { state, held } = lockState;\n\tlet open = false;\n\ttry {\n\t\topen = database?.isTransaction === true;\n\t} catch {}\n\tif (open) {\n\t\tif (Atomics.compareExchange(state, 0, held - 1, held) === held - 1) Atomics.notify(state, 0);\n\t\treturn;\n\t}\n\tlockState = undefined;\n\tif (Atomics.compareExchange(state, 0, held, 0) === held || Atomics.compareExchange(state, 0, held - 1, 0) === held - 1)\n\t\tAtomics.notify(state, 0);\n}\n\nfunction handle(request) {\n\ttry {\n\t\treturn handlers[request.kind](request);\n\t} finally {\n\t\tsettleLock();\n\t}\n}\n\nparentPort.on(\"message\", (request) => {\n\ttry {\n\t\tparentPort.postMessage({ id: request.id, value: handle(request) });\n\t} catch (error) {\n\t\tparentPort.postMessage({ id: request.id, failure: failure(error) });\n\t}\n});\n`;\n\n/**\n * Statements sent as one request (see `SqliteSequence`). `abort` holds one `Int32` the caller sets to non-zero when its\n * signal aborts: the thread reads it before each run of `repeat` and before each statement.\n */\nexport interface SequenceRequest {\n\treadonly kind: \"sequence\";\n\treadonly repeat?: SqliteSequence[\"repeat\"];\n\treadonly statements: readonly SequencedStatement[];\n\treadonly abort?: SharedArrayBuffer;\n}\n\n/**\n * What a sequence request is answered with: how many runs of `repeat` changed `minChanges` rows or more, or that it\n * stopped because the caller's signal aborted.\n */\nexport type SequenceAnswer = { readonly repeated: number } | { readonly aborted: true };\n\n/** What a connection's thread is asked to do; each request is answered once, in the order it was sent. */\nexport type ConnectionRequest =\n\t| { readonly kind: \"open\"; readonly path: string; readonly readOnly: boolean }\n\t| { readonly kind: \"exec\"; readonly sql: string }\n\t| { readonly kind: \"run\" | \"get\" | \"all\"; readonly sql: string; readonly params: readonly SqliteValue[] }\n\t| { readonly kind: \"begin\"; readonly lockState?: SharedArrayBuffer; readonly lockTag?: number }\n\t| { readonly kind: \"dataVersion\" | \"now\" | \"jsonbExtract\" | \"close\" }\n\t| ReadTransactionRequest\n\t| SequenceRequest;\n\n/**\n * A read-only transaction's start with its leading reads, and its end, which only a connection on a thread of its own\n * is sent: see the thread's `read` and `endRead`.\n */\nexport type ReadTransactionRequest =\n\t| { readonly kind: \"read\"; readonly statements: readonly SqliteStatement[] }\n\t| { readonly kind: \"endRead\" };\n\n/** Rows as they cross from a connection's thread: the column names, then each row's values in their order. */\ninterface RowTable {\n\treadonly columns: readonly string[];\n\treadonly values: readonly (readonly SqliteValue[])[];\n}\n\n/** What a request's answer carries as it crosses, before rows are rebuilt. */\ntype ConnectionValue =\n\t| RowTable\n\t| readonly RowTable[]\n\t| { readonly changes: number }\n\t| SequenceAnswer\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| undefined;\n\n/**\n * What a request is answered with: `get` a row or undefined, `all` rows, `read` the rows of each leading read up to\n * the first that failed, `run` the changes, `sequence` a `SequenceAnswer`, `open` the location, `dataVersion` and `now`\n * a number, `jsonbExtract` a boolean, the others undefined.\n */\nexport type ConnectionAnswer =\n\t| SqliteRow\n\t| SqliteRow[]\n\t| SqliteRow[][]\n\t| { readonly changes: number }\n\t| SequenceAnswer\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| undefined;\n\n/** An own field that holds a plain value: its key, value and enumerability. */\ntype ConnectionField = readonly [string, string | number | boolean | bigint, boolean];\n\n/** A failure as it crosses from a connection's thread; see `failure` in the thread's source. */\ninterface ConnectionFailure {\n\treadonly constructor: string;\n\treadonly message: string;\n\treadonly fields: readonly ConnectionField[];\n\treadonly between?: {\n\t\treadonly fields: readonly ConnectionField[];\n\t\treadonly toString?: { readonly enumerable: boolean };\n\t};\n}\n\ninterface ConnectionReply {\n\treadonly id: number;\n\treadonly value?: ConnectionValue;\n\treadonly failure?: ConnectionFailure;\n}\n\nconst STANDARD_ERRORS: Readonly<Record<string, ErrorConstructor>> = {\n\tError,\n\tTypeError,\n\tRangeError,\n\tSyntaxError,\n\tReferenceError,\n\tEvalError,\n\tURIError,\n};\n\n/** One prototype per runtime error class seen, by what it holds: see `connectionError`. */\nconst betweenPrototypes = new Map<string, object>();\n\n/** How a runtime's error class of its own shows an error, as Bun's do: `TypeError [ERR_INVALID_ARG_VALUE]: …`. */\nfunction showWithCode(this: Error & { readonly code?: unknown }): string {\n\treturn `${this.name} [${String(this.code)}]: ${this.message}`;\n}\n\nfunction betweenPrototype(base: ErrorConstructor, between: NonNullable<ConnectionFailure[\"between\"]>): object {\n\tconst key = JSON.stringify([\n\t\tbase.name,\n\t\tbetween.fields.map(([field, value, enumerable]) => [field, String(value), enumerable]),\n\t\tbetween.toString,\n\t]);\n\tlet prototype = betweenPrototypes.get(key);\n\tif (prototype === undefined) {\n\t\tconst created: object = Object.create(base.prototype);\n\t\tfor (const [field, value, enumerable] of between.fields)\n\t\t\tObject.defineProperty(created, field, { value, enumerable, writable: true, configurable: true });\n\t\tif (between.toString !== undefined)\n\t\t\tObject.defineProperty(created, \"toString\", {\n\t\t\t\tvalue: showWithCode,\n\t\t\t\tenumerable: between.toString.enumerable,\n\t\t\t\twritable: true,\n\t\t\t\tconfigurable: true,\n\t\t\t});\n\t\tbetweenPrototypes.set(key, created);\n\t\tprototype = created;\n\t}\n\treturn prototype;\n}\n\n/**\n * The driver's error, rebuilt on the calling thread as the driver threw it: an instance of the same standard error\n * class with the same message, and the same own fields (`code`, `errcode`, `errstr` for SQLite's errors) with the same\n * enumerability. A runtime's own error class between them is stood in for by a prototype that holds the same fields and\n * shows the error the same way.\n */\nfunction connectionError(failure: ConnectionFailure): Error {\n\tconst base = STANDARD_ERRORS[failure.constructor] ?? Error;\n\tconst error = new base(failure.message);\n\tif (failure.between !== undefined) Object.setPrototypeOf(error, betweenPrototype(base, failure.between));\n\tfor (const [key, value, enumerable] of failure.fields)\n\t\tObject.defineProperty(error, key, { value, enumerable, writable: true, configurable: true });\n\treturn error;\n}\n\n/** The rows of `table`, each a plain object built the way the calling-thread connection builds them. */\nfunction rowsOf(table: RowTable): SqliteRow[] {\n\tconst { columns, values } = table;\n\treturn values.map((row) => Object.fromEntries(columns.map((column, index) => [column, row[index] as SqliteValue])));\n}\n\ninterface Waiter {\n\treadonly resolve: (value: ConnectionValue) => void;\n\treadonly reject: (error: unknown) => void;\n}\n\n/** Thrown for a request to a connection whose thread is gone: closed, or lost to an error or an exit. */\nexport class ConnectionThreadEndedError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"ConnectionThreadEndedError\";\n\t}\n}\n\n/** Options that make every worker thread run code of the user's: a preload or a module loader. */\nconst WORKER_CODE_OPTIONS = new Set([\"--require\", \"-r\", \"--import\", \"--loader\", \"--experimental-loader\"]);\n\n/** The thread `startSpare` started for the next open, until an open takes it or `releaseSpare` ends it. */\nlet spare: ThreadConnection | undefined;\n\n/** How many prepared statements a connection keeps for reuse, least recently used first out. */\nexport const STATEMENT_CACHE_SIZE = 256;\n\n/** A node:sqlite connection running on its own worker thread. */\nexport class ThreadConnection {\n\tprivate readonly worker: Worker;\n\tprivate readonly waiting = new Map<number, Waiter>();\n\tprivate nextId = 1;\n\tprivate ended?: Error;\n\tprivate closing?: Promise<undefined>;\n\n\tprivate constructor() {\n\t\t// None of the process's own flags: the caller's preloads would run again for every connection, and its\n\t\t// `--input-type=module` would make this source a module. Whether node:sqlite is available was settled by the\n\t\t// open before it started the thread.\n\t\tthis.worker = new Worker(CONNECTION_SOURCE, {\n\t\t\teval: true,\n\t\t\texecArgv: [],\n\t\t\tworkerData: { nowSql: `SELECT ${sqliteDialect.nowMs} AS now`, statementCacheSize: STATEMENT_CACHE_SIZE },\n\t\t});\n\t\tthis.worker.on(\"message\", (reply: ConnectionReply) => this.receive(reply));\n\t\tthis.worker.on(\"error\", (error: Error) => this.end(error));\n\t\tthis.worker.on(\"exit\", (code: number) =>\n\t\t\tthis.end(new ConnectionThreadEndedError(`SQLite connection thread exited with code ${code}`)),\n\t\t);\n\t}\n\n\t/**\n\t * Opens `openAs` (or `path`) on a thread of its own and resolves with the location SQLite reports for it. A failure\n\t * to start the thread or to open the database rejects with its cause; the thread is gone then.\n\t */\n\tstatic async open(\n\t\tpath: string,\n\t\toptions: { readonly readOnly: boolean; readonly openAs?: string },\n\t): Promise<{ readonly connection: ThreadConnection; readonly location: string | null }> {\n\t\tconst started = spare;\n\t\tspare = undefined;\n\t\tif (started !== undefined && started.ended === undefined) {\n\t\t\ttry {\n\t\t\t\treturn await ThreadConnection.openOn(started, path, options);\n\t\t\t} catch (error) {\n\t\t\t\t// The spare thread was lost before it answered: open on a thread of its own, as without one.\n\t\t\t\tif (error !== started.ended) throw error;\n\t\t\t}\n\t\t}\n\t\treturn ThreadConnection.openOn(new ThreadConnection(), path, options);\n\t}\n\n\t/**\n\t * Starts one connection thread now, for the next open to take, so that the thread's startup overlaps whatever the\n\t * process does until then (an interactive session loads its modules meanwhile). Idle, the thread keeps nothing\n\t * alive. Nothing starts when the process runs a preload or a module loader, which every worker thread runs again,\n\t * or runs under the permission model; a thread that cannot start leaves every open as it is without one.\n\t */\n\tstatic startSpare(): void {\n\t\tif (spare !== undefined || process.permission !== undefined) return;\n\t\tif (startupNodeOptions().some((option) => WORKER_CODE_OPTIONS.has(option.name))) return;\n\t\ttry {\n\t\t\tconst started = new ThreadConnection();\n\t\t\tstarted.worker.unref();\n\t\t\tspare = started;\n\t\t} catch {\n\t\t\t// Opens start their own threads.\n\t\t}\n\t}\n\n\t/** Ends the spare thread if no open has taken it. */\n\tstatic releaseSpare(): void {\n\t\tconst started = spare;\n\t\tspare = undefined;\n\t\tif (started !== undefined) void started.stop();\n\t}\n\n\tprivate static async openOn(\n\t\tconnection: ThreadConnection,\n\t\tpath: string,\n\t\toptions: { readonly readOnly: boolean; readonly openAs?: string },\n\t): Promise<{ readonly connection: ThreadConnection; readonly location: string | null }> {\n\t\ttry {\n\t\t\tconst location = await connection.request({\n\t\t\t\tkind: \"open\",\n\t\t\t\tpath: options.openAs ?? path,\n\t\t\t\treadOnly: options.readOnly,\n\t\t\t});\n\t\t\treturn { connection, location: typeof location === \"string\" ? location : null };\n\t\t} catch (error) {\n\t\t\tawait connection.stop();\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Sends one request; resolves with the thread's answer or rejects with the driver's error, rebuilt. While a request\n\t * waits for its answer the thread keeps the process alive; an idle connection does not, as a connection on the\n\t * calling thread would not.\n\t */\n\trequest(request: ConnectionRequest): Promise<ConnectionAnswer> {\n\t\tif (request.kind === \"close\") return this.close();\n\t\tconst answer = this.send(request);\n\t\tif (request.kind === \"get\")\n\t\t\treturn answer.then((value) => (value === undefined ? undefined : rowsOf(value as RowTable)[0]));\n\t\tif (request.kind === \"all\") return answer.then((value) => rowsOf(value as RowTable));\n\t\tif (request.kind === \"read\") return answer.then((value) => (value as readonly RowTable[]).map(rowsOf));\n\t\treturn answer as Promise<ConnectionAnswer>;\n\t}\n\n\tprivate send(request: ConnectionRequest): Promise<ConnectionValue> {\n\t\treturn new Promise<ConnectionValue>((resolve, reject) => {\n\t\t\tif (this.ended !== undefined) {\n\t\t\t\treject(this.ended);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst id = this.nextId++;\n\t\t\ttry {\n\t\t\t\tthis.worker.postMessage({ id, ...request });\n\t\t\t} catch (error) {\n\t\t\t\t// A value the thread cannot receive.\n\t\t\t\treject(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.waiting.set(id, { resolve, reject });\n\t\t\tif (this.waiting.size === 1) this.worker.ref();\n\t\t});\n\t}\n\n\t/**\n\t * Closes the database on its thread, then ends the thread: a `close` request. Requests sent after it are rejected. A\n\t * thread already lost has nothing to close.\n\t */\n\tprivate close(): Promise<undefined> {\n\t\tthis.closing ??= (async () => {\n\t\t\ttry {\n\t\t\t\tif (this.ended === undefined) await this.send({ kind: \"close\" });\n\t\t\t} finally {\n\t\t\t\tawait this.stop();\n\t\t\t}\n\t\t\treturn undefined;\n\t\t})();\n\t\treturn this.closing;\n\t}\n\n\tprivate receive(reply: ConnectionReply): void {\n\t\tconst waiter = this.waiting.get(reply.id);\n\t\tif (waiter === undefined) return;\n\t\tthis.waiting.delete(reply.id);\n\t\tif (this.waiting.size === 0) this.worker.unref();\n\t\tif (reply.failure === undefined) waiter.resolve(reply.value);\n\t\telse waiter.reject(connectionError(reply.failure));\n\t}\n\n\t/** Rejects every request still waiting, oldest first, and every later one. Ending again does nothing. */\n\tprivate end(cause: Error): void {\n\t\tif (this.ended !== undefined) return;\n\t\t// Kept for as long as the connection is: an error's stack, until formatted, keeps the functions of the frames it\n\t\t// names, and so whatever they hold, such as a session that closed its store.\n\t\tvoid cause.stack;\n\t\tthis.ended = cause;\n\t\tconst waiting = [...this.waiting.values()];\n\t\tthis.waiting.clear();\n\t\tthis.worker.unref();\n\t\tfor (const waiter of waiting) waiter.reject(cause);\n\t}\n\n\tprivate async stop(): Promise<void> {\n\t\tthis.end(new ConnectionThreadEndedError(\"SQLite connection closed\"));\n\t\tawait this.worker.terminate();\n\t}\n\n\t/** Calls `listener` once the connection's thread has exited, whether closed or lost. */\n\tonExit(listener: () => void): void {\n\t\tthis.worker.once(\"exit\", listener);\n\t}\n\n\t/**\n\t * Starts a spare worker for a non-interactive or storage-overridden CLI\n\t * invocation only when the real CLI/storage resolvers select a SQLite store.\n\t */\n\tstatic async startSpareIfSqlNeeded(\n\t\targs: readonly string[],\n\t\tterminal: { readonly stdinIsTTY: boolean; readonly stdoutIsTTY: boolean },\n\t\tstillBeforeMain: () => boolean,\n\t): Promise<void> {\n\t\tconst { shouldStartSpareDatabaseThread } = await import(\"../../utils/startup-database-spare.ts\");\n\t\tif (stillBeforeMain() && shouldStartSpareDatabaseThread(args, false, terminal)) {\n\t\t\tThreadConnection.startSpare();\n\t\t}\n\t}\n}\n"]}
@@ -11,7 +11,7 @@ import { sqliteDialect } from "./dialect.js";
11
11
  import { payloadTooLargeKind, SQLITE_PAYLOAD_LIMITS, StorageAdapterLoadError, StorageConfigError, StorageInvalidTextError, StoragePayloadTooLargeError, StorageRollbackError, StorageTransactionClosedError, StorageUnavailableError, StorageUnsupportedOperationError, StorageWriteLockTimeoutError, StorageWriterQueueDegradedError, StorageWriterQueueUnusableError, StoreClosedError, } from "./errors.js";
12
12
  import { fileIdentity, fileIdentityAsync } from "./file-identity.js";
13
13
  import { connectionWaits, currentHoldScope, forgetPlans, heldElsewhere, holdFile, inBacklog, modeOf, releaseHold, runDeferred, runInHold, runTryingFirst, runWhenFree, sqliteBusyError, useFileLock, useWrappedFile, } from "./node-sqlite-file-gate.js";
14
- import { ThreadConnection, } from "./node-sqlite-thread.js";
14
+ import { STATEMENT_CACHE_SIZE, ThreadConnection, } from "./node-sqlite-thread.js";
15
15
  import { MAX_SEQUENCE_REQUEST_STATEMENTS, offerSequences, } from "./statement-sequence.js";
16
16
  import { configureConnection, isSqliteBusy, switchToWriteAheadLogSync } from "./write-ahead-log.js";
17
17
  /** Loaded at the first degradation only, so opening a database does not load debug output. */
@@ -1087,9 +1087,13 @@ function normalizeRow(row) {
1087
1087
  class CallerThreadConnection {
1088
1088
  connection;
1089
1089
  ownsConnection;
1090
+ /** Statements kept for reuse; only on a connection of its own, so a caller's connection holds none of them. */
1091
+ prepared;
1090
1092
  constructor(connection, ownsConnection) {
1091
1093
  this.connection = connection;
1092
1094
  this.ownsConnection = ownsConnection;
1095
+ if (ownsConnection)
1096
+ this.prepared = new Map();
1093
1097
  }
1094
1098
  request(request) {
1095
1099
  switch (request.kind) {
@@ -1126,6 +1130,7 @@ class CallerThreadConnection {
1126
1130
  throw error;
1127
1131
  }
1128
1132
  case "close":
1133
+ this.prepared?.clear();
1129
1134
  if (this.ownsConnection)
1130
1135
  this.connection.close();
1131
1136
  finalizeReleasedStatements();
@@ -1133,8 +1138,19 @@ class CallerThreadConnection {
1133
1138
  }
1134
1139
  }
1135
1140
  statement(sql) {
1141
+ const cached = this.prepared?.get(sql);
1142
+ if (cached !== undefined) {
1143
+ this.prepared.delete(sql);
1144
+ this.prepared.set(sql, cached);
1145
+ return cached;
1146
+ }
1136
1147
  const prepared = this.connection.prepare(sql);
1137
1148
  prepared.setReadBigInts(true);
1149
+ if (this.prepared !== undefined) {
1150
+ this.prepared.set(sql, prepared);
1151
+ if (this.prepared.size > STATEMENT_CACHE_SIZE)
1152
+ this.prepared.delete(this.prepared.keys().next().value);
1153
+ }
1138
1154
  return prepared;
1139
1155
  }
1140
1156
  /** One `BEGIN IMMEDIATE` that does not wait for a busy lock; see `NodeSqliteDatabase.tryBegin`. */
@@ -1200,6 +1216,17 @@ function sendable(value) {
1200
1216
  function sendableStatement({ sql, params, script }) {
1201
1217
  return { sql, params: params.map(sendable), ...(script === true ? { script } : {}) };
1202
1218
  }
1219
+ /** Whether two statements' parameters bind the same values, bytes compared by content. */
1220
+ function sameParams(left, right) {
1221
+ if (left.length !== right.length)
1222
+ return false;
1223
+ return left.every((value, index) => {
1224
+ const other = right[index];
1225
+ if (!isUint8Array(value) || !isUint8Array(other))
1226
+ return value === other;
1227
+ return value.byteLength === other.byteLength && value.every((byte, at) => byte === other[at]);
1228
+ });
1229
+ }
1203
1230
  /** The index of the first text parameter holding NUL, which no statement may bind, or -1. */
1204
1231
  function invalidTextParam(params) {
1205
1232
  return params.findIndex((value) => typeof value === "string" && value.includes("\0"));
@@ -1239,6 +1266,11 @@ class NodeSqliteDatabase {
1239
1266
  closing = false;
1240
1267
  closePromise;
1241
1268
  executor;
1269
+ openReader;
1270
+ /** Readers this database opened and that are not closed; closing closes them. */
1271
+ readers = new Set();
1272
+ /** Called once this database closed. */
1273
+ closed;
1242
1274
  transactionIdentity;
1243
1275
  lockWaitMs;
1244
1276
  groupCommitHoldMs;
@@ -1287,6 +1319,12 @@ class NodeSqliteDatabase {
1287
1319
  this.holderRecord = new SqliteHolderRecord(transactionIdentity, (cause) => this.degraded("holder-record-unavailable", cause));
1288
1320
  }
1289
1321
  }
1322
+ /** The database file's canonical path; undefined for a database in memory or a caller's wrapped connection. */
1323
+ databaseIdentity() {
1324
+ return typeof this.transactionIdentity === "string"
1325
+ ? JSON.stringify(["sqlite", this.transactionIdentity])
1326
+ : undefined;
1327
+ }
1290
1328
  supportsJsonbExtract() {
1291
1329
  // Bun on macOS loads the system SQLite. Its functions need not match the build-time version.
1292
1330
  this.jsonbExtract ??= this.enqueueStatement(() => this.executor.checkJsonbExtract(), true).catch(() => {
@@ -1831,6 +1869,9 @@ class NodeSqliteDatabase {
1831
1869
  */
1832
1870
  transaction(callback, options) {
1833
1871
  if (options?.readOnly === true) {
1872
+ const connection = this.connection;
1873
+ if (connection instanceof ThreadConnection)
1874
+ return this.enqueueStatement(() => this.readOnThread(connection, callback, options.leading ?? []));
1834
1875
  return this.enqueueStatement(async () => {
1835
1876
  await this.executor.exec("BEGIN");
1836
1877
  let active = true;
@@ -1870,6 +1911,76 @@ class NodeSqliteDatabase {
1870
1911
  this.startBatch([queued]);
1871
1912
  });
1872
1913
  }
1914
+ /**
1915
+ * A read-only transaction on a connection thread, which it waits for once less at each end (#6560): `BEGIN` goes in
1916
+ * one request with `leading`, the reads the callback makes first, whose answers the callback's calls get in order
1917
+ * until one differs; that call, and every later one, is sent as before, in the same snapshot. A leading read that
1918
+ * fails ends the answers there, so the call that makes it is sent and fails as it always would. The `COMMIT` is sent
1919
+ * without waiting for its answer: it changes nothing a read-only transaction read, the thread runs it before anything
1920
+ * sent after it, and rolls the transaction back where it fails. A callback that fails rolls it back and waits, as
1921
+ * before.
1922
+ */
1923
+ async readOnThread(connection, callback, leading) {
1924
+ const lead = [];
1925
+ for (const { sql, params } of leading) {
1926
+ if (invalidTextParam(params) !== -1)
1927
+ break;
1928
+ lead.push({ sql, params: snapshotParams(params) });
1929
+ }
1930
+ const request = { kind: "read", statements: lead.map((each) => sendableStatement(each)) };
1931
+ const answers = (await connection.request(request).catch((cause) => {
1932
+ throw unavailable(this.descriptor, cause);
1933
+ }));
1934
+ const answered = lead
1935
+ .slice(0, answers.length)
1936
+ .map((statement, index) => ({ ...statement, rows: answers[index] }));
1937
+ let active = true;
1938
+ const executor = this.createExecutor(() => active);
1939
+ /** The rows of the next leading read when `sql` and `params` make it; otherwise the lead ends. */
1940
+ const ledBy = (sql, params) => {
1941
+ const next = answered[0];
1942
+ if (active && next !== undefined && next.sql === sql && sameParams(next.params, params)) {
1943
+ answered.shift();
1944
+ return next.rows;
1945
+ }
1946
+ answered.length = 0;
1947
+ return undefined;
1948
+ };
1949
+ const transaction = {
1950
+ exec: (sql) => {
1951
+ answered.length = 0;
1952
+ return executor.exec(sql);
1953
+ },
1954
+ run: (sql, ...params) => {
1955
+ answered.length = 0;
1956
+ return executor.run(sql, ...params);
1957
+ },
1958
+ get: (sql, ...params) => {
1959
+ const rows = ledBy(sql, params);
1960
+ return rows === undefined ? executor.get(sql, ...params) : Promise.resolve(rows[0]);
1961
+ },
1962
+ all: (sql, ...params) => {
1963
+ const rows = ledBy(sql, params);
1964
+ return rows === undefined ? executor.all(sql, ...params) : Promise.resolve(rows);
1965
+ },
1966
+ };
1967
+ try {
1968
+ const value = await callback(transaction);
1969
+ active = false;
1970
+ connection.request({ kind: "endRead" }).catch(() => { });
1971
+ return value;
1972
+ }
1973
+ catch (cause) {
1974
+ active = false;
1975
+ try {
1976
+ await this.executor.exec("ROLLBACK");
1977
+ }
1978
+ catch (rollbackCause) {
1979
+ throw new StorageRollbackError(cause, rollbackCause);
1980
+ }
1981
+ throw cause;
1982
+ }
1983
+ }
1873
1984
  startBatch(members) {
1874
1985
  const batch = { members, position: 0, open: true };
1875
1986
  this.waitingBatches.push(batch);
@@ -2024,10 +2135,29 @@ class NodeSqliteDatabase {
2024
2135
  // SQLite already rolled the transaction back; there is nothing left to undo.
2025
2136
  }
2026
2137
  }
2138
+ /**
2139
+ * Offers `openReader`: each reader is a connection of its own to the database's file, which `open` opens, with a
2140
+ * call queue of its own; in WAL mode it reads the last commit without waiting for this connection's writes.
2141
+ */
2142
+ offerReaders(open) {
2143
+ this.openReader = async () => {
2144
+ if (this.closing)
2145
+ throw new StoreClosedError(this.descriptor);
2146
+ const reader = (await open());
2147
+ if (this.closing) {
2148
+ await reader.close();
2149
+ throw new StoreClosedError(this.descriptor);
2150
+ }
2151
+ this.readers.add(reader);
2152
+ reader.closed = () => this.readers.delete(reader);
2153
+ return reader;
2154
+ };
2155
+ }
2027
2156
  close() {
2028
2157
  if (!this.closePromise) {
2029
2158
  this.closing = true;
2030
- this.closePromise = this.tail.then(async () => {
2159
+ const readers = Promise.allSettled([...this.readers].map((reader) => reader.close()));
2160
+ this.closePromise = Promise.all([this.tail, readers]).then(async () => {
2031
2161
  try {
2032
2162
  if (this.fileGate?.role === "waits")
2033
2163
  forgetPlans(this.fileGate.file, this.connection);
@@ -2038,6 +2168,7 @@ class NodeSqliteDatabase {
2038
2168
  this.wrappedUse?.release();
2039
2169
  this.fileLock?.release();
2040
2170
  await releaseOpenLock(this.openLock);
2171
+ this.closed?.();
2041
2172
  }
2042
2173
  });
2043
2174
  }
@@ -2150,6 +2281,8 @@ export async function openNodeSqliteDatabase(path, { busyTimeoutMs = 5000, lockW
2150
2281
  : undefined;
2151
2282
  const database = new NodeSqliteDatabase(connection, descriptor, identity, lockWaitMs, holdMs, heldOpenLock, gateFile === undefined ? undefined : { file: gateFile, role: "holds" });
2152
2283
  Object.defineProperty(database, "readOnly", { value: readOnly });
2284
+ if (!isInMemoryDatabase(path))
2285
+ database.offerReaders(() => openNodeSqliteDatabase(path, { busyTimeoutMs, readOnly: true }));
2153
2286
  opening = database;
2154
2287
  const [configuredSettings] = await Promise.allSettled([
2155
2288
  settings,
@@ -2228,7 +2361,7 @@ function __atomicOnDemandFailed(error, feature) {
2228
2361
  return (async () => {
2229
2362
  const root = new URL("../../", import.meta.url);
2230
2363
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
2231
- const key = `${root.href}#0.10.10`;
2364
+ const key = `${root.href}#0.10.11-alpha.2`;
2232
2365
  let release = releases.get(key);
2233
2366
  if (release === undefined) {
2234
2367
  const current = (async () => {
@@ -2256,7 +2389,7 @@ function __atomicOnDemandFailed(error, feature) {
2256
2389
  } catch {
2257
2390
  // No installation to read, as in a bundle of the package: the release the process runs decides.
2258
2391
  }
2259
- const updatedTo = typeof installed === "string" && installed !== "0.10.10" ? installed : running !== undefined && running.version !== "0.10.10" ? "0.10.10" : undefined;
2392
+ 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;
2260
2393
  if (updatedTo === undefined) throw error;
2261
2394
  const application = typeof running?.name === "string" ? running.name : "atomic";
2262
2395
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {