@bastani/atomic 0.10.2 → 0.10.3-alpha.1

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 (499) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +11 -0
  3. package/dist/builtin/intercom/broker/broker-instance.ts +2 -13
  4. package/dist/builtin/intercom/broker/broker.ts +158 -73
  5. package/dist/builtin/intercom/broker/durable-ended-queue.ts +14 -2
  6. package/dist/builtin/intercom/broker/host-command-environment.ts +13 -0
  7. package/dist/builtin/intercom/broker/hosted-session-errors.ts +1 -0
  8. package/dist/builtin/intercom/broker/multinode-router.ts +111 -16
  9. package/dist/builtin/intercom/broker/multinode-state-store.ts +50 -4
  10. package/dist/builtin/intercom/broker/open-broker-state.ts +5 -4
  11. package/dist/builtin/intercom/broker/spawn.ts +144 -25
  12. package/dist/builtin/intercom/broker/sql-add-column.ts +33 -0
  13. package/dist/builtin/intercom/broker/sql-known-session-store.ts +120 -36
  14. package/dist/builtin/intercom/broker/sql-outbox-store.ts +75 -13
  15. package/dist/builtin/intercom/broker/start-announcement.ts +55 -10
  16. package/dist/builtin/intercom/broker/watchdog.ts +10 -7
  17. package/dist/builtin/intercom/index.bundle.mjs +111 -27
  18. package/dist/builtin/intercom/package.json +1 -1
  19. package/dist/builtin/mcp/package.json +1 -1
  20. package/dist/builtin/subagents/CHANGELOG.md +13 -0
  21. package/dist/builtin/subagents/package.json +1 -1
  22. package/dist/builtin/subagents/skills/skill-creator/SKILL.md +30 -52
  23. package/dist/builtin/subagents/skills/skill-creator/eval-viewer/generate_review.py +34 -40
  24. package/dist/builtin/subagents/skills/skill-creator/eval-viewer/viewer.html +2 -2
  25. package/dist/builtin/subagents/skills/skill-creator/scripts/atomic_cli.py +668 -0
  26. package/dist/builtin/subagents/skills/skill-creator/scripts/generate_report.py +3 -3
  27. package/dist/builtin/subagents/skills/skill-creator/scripts/improve_description.py +42 -38
  28. package/dist/builtin/subagents/skills/skill-creator/scripts/run_eval.py +268 -176
  29. package/dist/builtin/subagents/skills/skill-creator/scripts/run_loop.py +20 -11
  30. package/dist/builtin/subagents/skills/skill-creator/scripts/utils.py +1 -1
  31. package/dist/builtin/subagents/src/extension/index.bundle.mjs +163 -97
  32. package/dist/builtin/web-access/CHANGELOG.md +7 -0
  33. package/dist/builtin/web-access/index.bundle.mjs +5 -4
  34. package/dist/builtin/web-access/package.json +1 -1
  35. package/dist/core/agent-session-auto-compaction.d.ts +10 -1
  36. package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
  37. package/dist/core/agent-session-auto-compaction.js +54 -2
  38. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  39. package/dist/core/agent-session-compaction.d.ts +4 -0
  40. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  41. package/dist/core/agent-session-compaction.js +17 -2
  42. package/dist/core/agent-session-compaction.js.map +1 -1
  43. package/dist/core/agent-session-custom-message-commit.d.ts.map +1 -1
  44. package/dist/core/agent-session-custom-message-commit.js +3 -1
  45. package/dist/core/agent-session-custom-message-commit.js.map +1 -1
  46. package/dist/core/agent-session-events.d.ts +2 -0
  47. package/dist/core/agent-session-events.d.ts.map +1 -1
  48. package/dist/core/agent-session-events.js +34 -13
  49. package/dist/core/agent-session-events.js.map +1 -1
  50. package/dist/core/agent-session-export.d.ts.map +1 -1
  51. package/dist/core/agent-session-export.js +3 -0
  52. package/dist/core/agent-session-export.js.map +1 -1
  53. package/dist/core/agent-session-message-queue.d.ts +27 -0
  54. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  55. package/dist/core/agent-session-message-queue.js +213 -30
  56. package/dist/core/agent-session-message-queue.js.map +1 -1
  57. package/dist/core/agent-session-methods.d.ts +6 -1
  58. package/dist/core/agent-session-methods.d.ts.map +1 -1
  59. package/dist/core/agent-session-methods.js.map +1 -1
  60. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  61. package/dist/core/agent-session-prompt.js +35 -3
  62. package/dist/core/agent-session-prompt.js.map +1 -1
  63. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  64. package/dist/core/agent-session-runtime.js +2 -2
  65. package/dist/core/agent-session-runtime.js.map +1 -1
  66. package/dist/core/agent-session-state.d.ts.map +1 -1
  67. package/dist/core/agent-session-state.js +6 -1
  68. package/dist/core/agent-session-state.js.map +1 -1
  69. package/dist/core/agent-session-tool-hooks.d.ts.map +1 -1
  70. package/dist/core/agent-session-tool-hooks.js +15 -2
  71. package/dist/core/agent-session-tool-hooks.js.map +1 -1
  72. package/dist/core/agent-session-typed-queue.d.ts +14 -1
  73. package/dist/core/agent-session-typed-queue.d.ts.map +1 -1
  74. package/dist/core/agent-session-typed-queue.js +26 -1
  75. package/dist/core/agent-session-typed-queue.js.map +1 -1
  76. package/dist/core/agent-session-types.d.ts +5 -0
  77. package/dist/core/agent-session-types.d.ts.map +1 -1
  78. package/dist/core/agent-session-types.js.map +1 -1
  79. package/dist/core/agent-session.d.ts.map +1 -1
  80. package/dist/core/agent-session.js +2 -1
  81. package/dist/core/agent-session.js.map +1 -1
  82. package/dist/core/async-scope.d.ts +9 -4
  83. package/dist/core/async-scope.d.ts.map +1 -1
  84. package/dist/core/async-scope.js +13 -5
  85. package/dist/core/async-scope.js.map +1 -1
  86. package/dist/core/builtin-diagnostics.js +2 -2
  87. package/dist/core/builtin-diagnostics.js.map +1 -1
  88. package/dist/core/chat-admission-order.d.ts.map +1 -1
  89. package/dist/core/chat-admission-order.js +2 -1
  90. package/dist/core/chat-admission-order.js.map +1 -1
  91. package/dist/core/chat-record-saves.d.ts +4 -0
  92. package/dist/core/chat-record-saves.d.ts.map +1 -0
  93. package/dist/core/chat-record-saves.js +25 -0
  94. package/dist/core/chat-record-saves.js.map +1 -0
  95. package/dist/core/command-deliveries.d.ts +62 -0
  96. package/dist/core/command-deliveries.d.ts.map +1 -0
  97. package/dist/core/command-deliveries.js +139 -0
  98. package/dist/core/command-deliveries.js.map +1 -0
  99. package/dist/core/diagnostic-writer.d.ts.map +1 -1
  100. package/dist/core/diagnostic-writer.js +5 -4
  101. package/dist/core/diagnostic-writer.js.map +1 -1
  102. package/dist/core/extension-startup-close.d.ts +1 -2
  103. package/dist/core/extension-startup-close.d.ts.map +1 -1
  104. package/dist/core/extension-startup-close.js +2 -2
  105. package/dist/core/extension-startup-close.js.map +1 -1
  106. package/dist/core/extensions/jiti-aliases.d.ts +11 -0
  107. package/dist/core/extensions/jiti-aliases.d.ts.map +1 -0
  108. package/dist/core/extensions/jiti-aliases.js +28 -0
  109. package/dist/core/extensions/jiti-aliases.js.map +1 -0
  110. package/dist/core/extensions/loader-api.js +3 -3
  111. package/dist/core/extensions/loader-api.js.map +1 -1
  112. package/dist/core/extensions/loader-bindings.js +2 -2
  113. package/dist/core/extensions/loader-bindings.js.map +1 -1
  114. package/dist/core/extensions/loader-rollback.d.ts +1 -2
  115. package/dist/core/extensions/loader-rollback.d.ts.map +1 -1
  116. package/dist/core/extensions/loader-rollback.js +2 -2
  117. package/dist/core/extensions/loader-rollback.js.map +1 -1
  118. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  119. package/dist/core/extensions/loader-virtual-modules.js +53 -9
  120. package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
  121. package/dist/core/extensions/native-builtin-entries.d.ts +5 -0
  122. package/dist/core/extensions/native-builtin-entries.d.ts.map +1 -1
  123. package/dist/core/extensions/native-builtin-entries.js +8 -1
  124. package/dist/core/extensions/native-builtin-entries.js.map +1 -1
  125. package/dist/core/extensions/reloadable-scripts.d.ts +21 -2
  126. package/dist/core/extensions/reloadable-scripts.d.ts.map +1 -1
  127. package/dist/core/extensions/reloadable-scripts.js +11 -3
  128. package/dist/core/extensions/reloadable-scripts.js.map +1 -1
  129. package/dist/core/extensions/source-builtin-imports.d.ts +40 -0
  130. package/dist/core/extensions/source-builtin-imports.d.ts.map +1 -0
  131. package/dist/core/extensions/source-builtin-imports.js +142 -0
  132. package/dist/core/extensions/source-builtin-imports.js.map +1 -0
  133. package/dist/core/extensions/transform-graph.d.ts +15 -0
  134. package/dist/core/extensions/transform-graph.d.ts.map +1 -0
  135. package/dist/core/extensions/transform-graph.js +85 -0
  136. package/dist/core/extensions/transform-graph.js.map +1 -0
  137. package/dist/core/extensions/ts-source-specifiers.d.ts +2 -0
  138. package/dist/core/extensions/ts-source-specifiers.d.ts.map +1 -1
  139. package/dist/core/extensions/ts-source-specifiers.js +7 -0
  140. package/dist/core/extensions/ts-source-specifiers.js.map +1 -1
  141. package/dist/core/extensions/ts-transform-worker.d.ts +2 -0
  142. package/dist/core/extensions/ts-transform-worker.d.ts.map +1 -0
  143. package/dist/core/extensions/ts-transform-worker.js +43 -0
  144. package/dist/core/extensions/ts-transform-worker.js.map +1 -0
  145. package/dist/core/message-admission.d.ts.map +1 -1
  146. package/dist/core/message-admission.js +4 -4
  147. package/dist/core/message-admission.js.map +1 -1
  148. package/dist/core/messages.d.ts +5 -0
  149. package/dist/core/messages.d.ts.map +1 -1
  150. package/dist/core/messages.js +35 -0
  151. package/dist/core/messages.js.map +1 -1
  152. package/dist/core/model-fallback-failures.d.ts +1 -1
  153. package/dist/core/model-fallback-failures.d.ts.map +1 -1
  154. package/dist/core/model-fallback-failures.js +18 -1
  155. package/dist/core/model-fallback-failures.js.map +1 -1
  156. package/dist/core/process-start-token.d.ts +7 -0
  157. package/dist/core/process-start-token.d.ts.map +1 -1
  158. package/dist/core/process-start-token.js +14 -0
  159. package/dist/core/process-start-token.js.map +1 -1
  160. package/dist/core/project-trust-electorate.d.ts +24 -0
  161. package/dist/core/project-trust-electorate.d.ts.map +1 -0
  162. package/dist/core/project-trust-electorate.js +52 -0
  163. package/dist/core/project-trust-electorate.js.map +1 -0
  164. package/dist/core/project-trust-state.d.ts +15 -0
  165. package/dist/core/project-trust-state.d.ts.map +1 -1
  166. package/dist/core/project-trust-state.js +15 -0
  167. package/dist/core/project-trust-state.js.map +1 -1
  168. package/dist/core/provider-request-admission.d.ts.map +1 -1
  169. package/dist/core/provider-request-admission.js +2 -2
  170. package/dist/core/provider-request-admission.js.map +1 -1
  171. package/dist/core/queued-input-admission.js +2 -2
  172. package/dist/core/queued-input-admission.js.map +1 -1
  173. package/dist/core/queued-message-delivery.d.ts +2 -2
  174. package/dist/core/queued-message-delivery.d.ts.map +1 -1
  175. package/dist/core/queued-message-delivery.js +6 -3
  176. package/dist/core/queued-message-delivery.js.map +1 -1
  177. package/dist/core/resource-admission-scope.js +2 -2
  178. package/dist/core/resource-admission-scope.js.map +1 -1
  179. package/dist/core/resume/blueprint/process.d.ts +3 -4
  180. package/dist/core/resume/blueprint/process.d.ts.map +1 -1
  181. package/dist/core/resume/blueprint/process.js +33 -17
  182. package/dist/core/resume/blueprint/process.js.map +1 -1
  183. package/dist/core/resume/path-mapping.js +4 -4
  184. package/dist/core/resume/path-mapping.js.map +1 -1
  185. package/dist/core/resume/session-resume.d.ts +9 -0
  186. package/dist/core/resume/session-resume.d.ts.map +1 -1
  187. package/dist/core/resume/session-resume.js +27 -2
  188. package/dist/core/resume/session-resume.js.map +1 -1
  189. package/dist/core/resume-cache-checkpoint.d.ts +27 -1
  190. package/dist/core/resume-cache-checkpoint.d.ts.map +1 -1
  191. package/dist/core/resume-cache-checkpoint.js +45 -0
  192. package/dist/core/resume-cache-checkpoint.js.map +1 -1
  193. package/dist/core/sdk.d.ts.map +1 -1
  194. package/dist/core/sdk.js +7 -31
  195. package/dist/core/sdk.js.map +1 -1
  196. package/dist/core/session-lifecycle-scope.d.ts +1 -2
  197. package/dist/core/session-lifecycle-scope.d.ts.map +1 -1
  198. package/dist/core/session-lifecycle-scope.js +2 -2
  199. package/dist/core/session-lifecycle-scope.js.map +1 -1
  200. package/dist/core/session-lifecycle-work.js +2 -2
  201. package/dist/core/session-lifecycle-work.js.map +1 -1
  202. package/dist/core/session-manager-core.d.ts.map +1 -1
  203. package/dist/core/session-manager-core.js +3 -0
  204. package/dist/core/session-manager-core.js.map +1 -1
  205. package/dist/core/session-storage.d.ts +12 -0
  206. package/dist/core/session-storage.d.ts.map +1 -1
  207. package/dist/core/session-storage.js +68 -1
  208. package/dist/core/session-storage.js.map +1 -1
  209. package/dist/core/settings-lock-directory.d.ts.map +1 -1
  210. package/dist/core/settings-lock-directory.js +4 -3
  211. package/dist/core/settings-lock-directory.js.map +1 -1
  212. package/dist/core/settings-write-ownership.d.ts +1 -2
  213. package/dist/core/settings-write-ownership.d.ts.map +1 -1
  214. package/dist/core/settings-write-ownership.js +2 -2
  215. package/dist/core/settings-write-ownership.js.map +1 -1
  216. package/dist/core/storage/node-sqlite-thread.d.ts.map +1 -1
  217. package/dist/core/storage/node-sqlite-thread.js +6 -4
  218. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  219. package/dist/core/storage/node-sqlite.d.ts.map +1 -1
  220. package/dist/core/storage/node-sqlite.js +22 -8
  221. package/dist/core/storage/node-sqlite.js.map +1 -1
  222. package/dist/core/system-prompt.d.ts +16 -2
  223. package/dist/core/system-prompt.d.ts.map +1 -1
  224. package/dist/core/system-prompt.js +33 -6
  225. package/dist/core/system-prompt.js.map +1 -1
  226. package/dist/core/tasks/agent-adapter.d.ts.map +1 -1
  227. package/dist/core/tasks/agent-adapter.js +2 -1
  228. package/dist/core/tasks/agent-adapter.js.map +1 -1
  229. package/dist/core/tasks/completion.d.ts +3 -2
  230. package/dist/core/tasks/completion.d.ts.map +1 -1
  231. package/dist/core/tasks/completion.js.map +1 -1
  232. package/dist/core/tasks/execution-scope.js +2 -2
  233. package/dist/core/tasks/execution-scope.js.map +1 -1
  234. package/dist/core/tools/bash.d.ts.map +1 -1
  235. package/dist/core/tools/bash.js +2 -1
  236. package/dist/core/tools/bash.js.map +1 -1
  237. package/dist/core/tools/history-regex-worker.d.ts.map +1 -1
  238. package/dist/core/tools/history-regex-worker.js +3 -2
  239. package/dist/core/tools/history-regex-worker.js.map +1 -1
  240. package/dist/core/tools/shell-task-render.d.ts +3 -2
  241. package/dist/core/tools/shell-task-render.d.ts.map +1 -1
  242. package/dist/core/tools/shell-task-render.js +7 -5
  243. package/dist/core/tools/shell-task-render.js.map +1 -1
  244. package/dist/core/tools/shell-task-status.d.ts +6 -2
  245. package/dist/core/tools/shell-task-status.d.ts.map +1 -1
  246. package/dist/core/tools/shell-task-status.js +13 -8
  247. package/dist/core/tools/shell-task-status.js.map +1 -1
  248. package/dist/core/tools/sqlite-selector-connection.d.ts.map +1 -1
  249. package/dist/core/tools/sqlite-selector-connection.js +4 -3
  250. package/dist/core/tools/sqlite-selector-connection.js.map +1 -1
  251. package/dist/core/tools/windows-directory-security.d.ts.map +1 -1
  252. package/dist/core/tools/windows-directory-security.js +2 -1
  253. package/dist/core/tools/windows-directory-security.js.map +1 -1
  254. package/dist/core/worktree-snapshot/git.js +2 -2
  255. package/dist/core/worktree-snapshot/git.js.map +1 -1
  256. package/dist/extensions/mcp/index.d.ts +6 -1
  257. package/dist/extensions/mcp/index.d.ts.map +1 -1
  258. package/dist/extensions/mcp/index.js +150 -18
  259. package/dist/extensions/mcp/index.js.map +1 -1
  260. package/dist/extensions/mcp/tool-records.d.ts +44 -9
  261. package/dist/extensions/mcp/tool-records.d.ts.map +1 -1
  262. package/dist/extensions/mcp/tool-records.js +58 -16
  263. package/dist/extensions/mcp/tool-records.js.map +1 -1
  264. package/dist/index.d.ts +2 -0
  265. package/dist/index.d.ts.map +1 -1
  266. package/dist/index.js +4 -0
  267. package/dist/index.js.map +1 -1
  268. package/dist/main-session.d.ts +3 -1
  269. package/dist/main-session.d.ts.map +1 -1
  270. package/dist/main-session.js +1 -0
  271. package/dist/main-session.js.map +1 -1
  272. package/dist/main.d.ts.map +1 -1
  273. package/dist/main.js +230 -96
  274. package/dist/main.js.map +1 -1
  275. package/dist/modes/interactive/agent-view/agent-view-bridge.d.ts +5 -0
  276. package/dist/modes/interactive/agent-view/agent-view-bridge.d.ts.map +1 -1
  277. package/dist/modes/interactive/agent-view/agent-view-bridge.js.map +1 -1
  278. package/dist/modes/interactive/agent-view/agent-view-switcher.d.ts +5 -2
  279. package/dist/modes/interactive/agent-view/agent-view-switcher.d.ts.map +1 -1
  280. package/dist/modes/interactive/agent-view/agent-view-switcher.js +3 -3
  281. package/dist/modes/interactive/agent-view/agent-view-switcher.js.map +1 -1
  282. package/dist/modes/interactive/agent-view/contracts.d.ts +6 -0
  283. package/dist/modes/interactive/agent-view/contracts.d.ts.map +1 -1
  284. package/dist/modes/interactive/agent-view/contracts.js.map +1 -1
  285. package/dist/modes/interactive/agent-view/install.d.ts.map +1 -1
  286. package/dist/modes/interactive/agent-view/install.js +2 -1
  287. package/dist/modes/interactive/agent-view/install.js.map +1 -1
  288. package/dist/modes/interactive/agent-view/open-port.d.ts +4 -2
  289. package/dist/modes/interactive/agent-view/open-port.d.ts.map +1 -1
  290. package/dist/modes/interactive/agent-view/open-port.js +4 -3
  291. package/dist/modes/interactive/agent-view/open-port.js.map +1 -1
  292. package/dist/modes/interactive/agent-view/prompt-retarget.d.ts.map +1 -1
  293. package/dist/modes/interactive/agent-view/prompt-retarget.js +18 -5
  294. package/dist/modes/interactive/agent-view/prompt-retarget.js.map +1 -1
  295. package/dist/modes/interactive/agent-view/remote-port.d.ts +10 -1
  296. package/dist/modes/interactive/agent-view/remote-port.d.ts.map +1 -1
  297. package/dist/modes/interactive/agent-view/remote-port.js +36 -4
  298. package/dist/modes/interactive/agent-view/remote-port.js.map +1 -1
  299. package/dist/modes/interactive/agent-view/viewed-keys.d.ts +56 -0
  300. package/dist/modes/interactive/agent-view/viewed-keys.d.ts.map +1 -0
  301. package/dist/modes/interactive/agent-view/viewed-keys.js +63 -0
  302. package/dist/modes/interactive/agent-view/viewed-keys.js.map +1 -0
  303. package/dist/modes/interactive/agent-view/viewed-submit.d.ts +14 -4
  304. package/dist/modes/interactive/agent-view/viewed-submit.d.ts.map +1 -1
  305. package/dist/modes/interactive/agent-view/viewed-submit.js +51 -17
  306. package/dist/modes/interactive/agent-view/viewed-submit.js.map +1 -1
  307. package/dist/modes/interactive/components/agent-panel.d.ts.map +1 -1
  308. package/dist/modes/interactive/components/agent-panel.js +8 -21
  309. package/dist/modes/interactive/components/agent-panel.js.map +1 -1
  310. package/dist/modes/interactive/components/chat-session-host-actions.d.ts.map +1 -1
  311. package/dist/modes/interactive/components/chat-session-host-actions.js +18 -5
  312. package/dist/modes/interactive/components/chat-session-host-actions.js.map +1 -1
  313. package/dist/modes/interactive/components/chat-session-host-rendering.d.ts.map +1 -1
  314. package/dist/modes/interactive/components/chat-session-host-rendering.js +6 -0
  315. package/dist/modes/interactive/components/chat-session-host-rendering.js.map +1 -1
  316. package/dist/modes/interactive/components/chat-session-host-state.d.ts +1 -0
  317. package/dist/modes/interactive/components/chat-session-host-state.d.ts.map +1 -1
  318. package/dist/modes/interactive/components/chat-session-host-state.js +2 -0
  319. package/dist/modes/interactive/components/chat-session-host-state.js.map +1 -1
  320. package/dist/modes/interactive/components/chat-session-host-types.d.ts +5 -0
  321. package/dist/modes/interactive/components/chat-session-host-types.d.ts.map +1 -1
  322. package/dist/modes/interactive/components/chat-session-host-types.js.map +1 -1
  323. package/dist/modes/interactive/components/custom-editor.d.ts +33 -2
  324. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  325. package/dist/modes/interactive/components/custom-editor.js +58 -2
  326. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  327. package/dist/modes/interactive/components/host-session-picker.js +2 -2
  328. package/dist/modes/interactive/components/host-session-picker.js.map +1 -1
  329. package/dist/modes/interactive/components/main-composer-keys.d.ts +16 -5
  330. package/dist/modes/interactive/components/main-composer-keys.d.ts.map +1 -1
  331. package/dist/modes/interactive/components/main-composer-keys.js +27 -8
  332. package/dist/modes/interactive/components/main-composer-keys.js.map +1 -1
  333. package/dist/modes/interactive/components/notice-line.d.ts +8 -25
  334. package/dist/modes/interactive/components/notice-line.d.ts.map +1 -1
  335. package/dist/modes/interactive/components/notice-line.js +18 -17
  336. package/dist/modes/interactive/components/notice-line.js.map +1 -1
  337. package/dist/modes/interactive/components/prompt-slot.d.ts +20 -3
  338. package/dist/modes/interactive/components/prompt-slot.d.ts.map +1 -1
  339. package/dist/modes/interactive/components/prompt-slot.js +82 -32
  340. package/dist/modes/interactive/components/prompt-slot.js.map +1 -1
  341. package/dist/modes/interactive/components/queued-messages-view.d.ts +5 -2
  342. package/dist/modes/interactive/components/queued-messages-view.d.ts.map +1 -1
  343. package/dist/modes/interactive/components/queued-messages-view.js +12 -5
  344. package/dist/modes/interactive/components/queued-messages-view.js.map +1 -1
  345. package/dist/modes/interactive/components/task-board.d.ts +5 -8
  346. package/dist/modes/interactive/components/task-board.d.ts.map +1 -1
  347. package/dist/modes/interactive/components/task-board.js +5 -49
  348. package/dist/modes/interactive/components/task-board.js.map +1 -1
  349. package/dist/modes/interactive/components/task-completion-message.d.ts.map +1 -1
  350. package/dist/modes/interactive/components/task-completion-message.js +9 -2
  351. package/dist/modes/interactive/components/task-completion-message.js.map +1 -1
  352. package/dist/modes/interactive/components/task-marks.d.ts +19 -0
  353. package/dist/modes/interactive/components/task-marks.d.ts.map +1 -0
  354. package/dist/modes/interactive/components/task-marks.js +25 -0
  355. package/dist/modes/interactive/components/task-marks.js.map +1 -0
  356. package/dist/modes/interactive/components/task-row.d.ts +10 -2
  357. package/dist/modes/interactive/components/task-row.d.ts.map +1 -1
  358. package/dist/modes/interactive/components/task-row.js +39 -32
  359. package/dist/modes/interactive/components/task-row.js.map +1 -1
  360. package/dist/modes/interactive/components/task-transcript-page.d.ts +7 -0
  361. package/dist/modes/interactive/components/task-transcript-page.d.ts.map +1 -1
  362. package/dist/modes/interactive/components/task-transcript-page.js +106 -10
  363. package/dist/modes/interactive/components/task-transcript-page.js.map +1 -1
  364. package/dist/modes/interactive/components/tool-block-families.d.ts.map +1 -1
  365. package/dist/modes/interactive/components/tool-block-families.js +8 -9
  366. package/dist/modes/interactive/components/tool-block-families.js.map +1 -1
  367. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  368. package/dist/modes/interactive/components/tool-execution.js +5 -1
  369. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  370. package/dist/modes/interactive/extension-command-hold.d.ts.map +1 -1
  371. package/dist/modes/interactive/extension-command-hold.js +5 -7
  372. package/dist/modes/interactive/extension-command-hold.js.map +1 -1
  373. package/dist/modes/interactive/interactive-extension-dialogs.js +6 -1
  374. package/dist/modes/interactive/interactive-extension-dialogs.js.map +1 -1
  375. package/dist/modes/interactive/interactive-extension-runtime.d.ts.map +1 -1
  376. package/dist/modes/interactive/interactive-extension-runtime.js +21 -7
  377. package/dist/modes/interactive/interactive-extension-runtime.js.map +1 -1
  378. package/dist/modes/interactive/interactive-initial-session-binding.d.ts +1 -2
  379. package/dist/modes/interactive/interactive-initial-session-binding.d.ts.map +1 -1
  380. package/dist/modes/interactive/interactive-initial-session-binding.js +2 -2
  381. package/dist/modes/interactive/interactive-initial-session-binding.js.map +1 -1
  382. package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
  383. package/dist/modes/interactive/interactive-input-handling.js +13 -4
  384. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  385. package/dist/modes/interactive/interactive-mode-base.d.ts +2 -1
  386. package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
  387. package/dist/modes/interactive/interactive-mode-base.js +6 -1
  388. package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
  389. package/dist/modes/interactive/interactive-mode-helpers.d.ts +4 -2
  390. package/dist/modes/interactive/interactive-mode-helpers.d.ts.map +1 -1
  391. package/dist/modes/interactive/interactive-mode-helpers.js +6 -0
  392. package/dist/modes/interactive/interactive-mode-helpers.js.map +1 -1
  393. package/dist/modes/interactive/interactive-mode-surface.d.ts +5 -0
  394. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  395. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  396. package/dist/modes/interactive/interactive-process-lifecycle.js +96 -17
  397. package/dist/modes/interactive/interactive-process-lifecycle.js.map +1 -1
  398. package/dist/modes/interactive/interactive-queueing.d.ts +5 -0
  399. package/dist/modes/interactive/interactive-queueing.d.ts.map +1 -1
  400. package/dist/modes/interactive/interactive-queueing.js +37 -5
  401. package/dist/modes/interactive/interactive-queueing.js.map +1 -1
  402. package/dist/modes/interactive/interactive-render-chat.d.ts.map +1 -1
  403. package/dist/modes/interactive/interactive-render-chat.js +45 -4
  404. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  405. package/dist/modes/interactive/interactive-resource-disclosure.d.ts +4 -1
  406. package/dist/modes/interactive/interactive-resource-disclosure.d.ts.map +1 -1
  407. package/dist/modes/interactive/interactive-resource-disclosure.js +20 -1
  408. package/dist/modes/interactive/interactive-resource-disclosure.js.map +1 -1
  409. package/dist/modes/interactive/interactive-resource-rendering.js +3 -0
  410. package/dist/modes/interactive/interactive-resource-rendering.js.map +1 -1
  411. package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
  412. package/dist/modes/interactive/interactive-startup.js +43 -5
  413. package/dist/modes/interactive/interactive-startup.js.map +1 -1
  414. package/dist/modes/interactive-engine/activity-watchdog.d.ts +6 -3
  415. package/dist/modes/interactive-engine/activity-watchdog.d.ts.map +1 -1
  416. package/dist/modes/interactive-engine/activity-watchdog.js +3 -2
  417. package/dist/modes/interactive-engine/activity-watchdog.js.map +1 -1
  418. package/dist/modes/interactive-engine/engine-health.d.ts +2 -0
  419. package/dist/modes/interactive-engine/engine-health.d.ts.map +1 -1
  420. package/dist/modes/interactive-engine/engine-health.js.map +1 -1
  421. package/dist/modes/interactive-engine/engine-quit-intent.d.ts +10 -0
  422. package/dist/modes/interactive-engine/engine-quit-intent.d.ts.map +1 -1
  423. package/dist/modes/interactive-engine/engine-quit-intent.js +33 -0
  424. package/dist/modes/interactive-engine/engine-quit-intent.js.map +1 -1
  425. package/dist/modes/interactive-engine/extension-ui-bridge.d.ts +7 -1
  426. package/dist/modes/interactive-engine/extension-ui-bridge.d.ts.map +1 -1
  427. package/dist/modes/interactive-engine/extension-ui-bridge.js +15 -2
  428. package/dist/modes/interactive-engine/extension-ui-bridge.js.map +1 -1
  429. package/dist/modes/interactive-engine/host-listener-failures.d.ts +24 -0
  430. package/dist/modes/interactive-engine/host-listener-failures.d.ts.map +1 -0
  431. package/dist/modes/interactive-engine/host-listener-failures.js +98 -0
  432. package/dist/modes/interactive-engine/host-listener-failures.js.map +1 -0
  433. package/dist/modes/interactive-engine/isolated-runtime.d.ts +16 -0
  434. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  435. package/dist/modes/interactive-engine/isolated-runtime.js +74 -7
  436. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  437. package/dist/modes/interactive-engine/protocol.d.ts +5 -0
  438. package/dist/modes/interactive-engine/protocol.d.ts.map +1 -1
  439. package/dist/modes/interactive-engine/protocol.js +8 -2
  440. package/dist/modes/interactive-engine/protocol.js.map +1 -1
  441. package/dist/modes/interactive-engine/remote-component.d.ts +13 -0
  442. package/dist/modes/interactive-engine/remote-component.d.ts.map +1 -1
  443. package/dist/modes/interactive-engine/remote-component.js +69 -4
  444. package/dist/modes/interactive-engine/remote-component.js.map +1 -1
  445. package/dist/modes/print-mode.d.ts.map +1 -1
  446. package/dist/modes/print-mode.js +34 -6
  447. package/dist/modes/print-mode.js.map +1 -1
  448. package/dist/modes/rpc/agent-panel-bridge.d.ts +7 -0
  449. package/dist/modes/rpc/agent-panel-bridge.d.ts.map +1 -1
  450. package/dist/modes/rpc/agent-panel-bridge.js +11 -1
  451. package/dist/modes/rpc/agent-panel-bridge.js.map +1 -1
  452. package/dist/modes/rpc/agent-view-rpc-panel.d.ts.map +1 -1
  453. package/dist/modes/rpc/agent-view-rpc-panel.js +11 -5
  454. package/dist/modes/rpc/agent-view-rpc-panel.js.map +1 -1
  455. package/dist/modes/rpc/rpc-client-process.d.ts +8 -1
  456. package/dist/modes/rpc/rpc-client-process.d.ts.map +1 -1
  457. package/dist/modes/rpc/rpc-client-process.js +89 -65
  458. package/dist/modes/rpc/rpc-client-process.js.map +1 -1
  459. package/dist/modes/rpc/rpc-client.d.ts +21 -0
  460. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  461. package/dist/modes/rpc/rpc-client.js +77 -33
  462. package/dist/modes/rpc/rpc-client.js.map +1 -1
  463. package/dist/modes/rpc/rpc-event-buffer.d.ts +5 -0
  464. package/dist/modes/rpc/rpc-event-buffer.d.ts.map +1 -1
  465. package/dist/modes/rpc/rpc-event-buffer.js +8 -2
  466. package/dist/modes/rpc/rpc-event-buffer.js.map +1 -1
  467. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  468. package/dist/modes/rpc/rpc-mode.js +9 -2
  469. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  470. package/dist/utils/shell.d.ts +5 -1
  471. package/dist/utils/shell.d.ts.map +1 -1
  472. package/dist/utils/shell.js +14 -7
  473. package/dist/utils/shell.js.map +1 -1
  474. package/dist/utils/worker-threads.d.ts +10 -4
  475. package/dist/utils/worker-threads.d.ts.map +1 -1
  476. package/dist/utils/worker-threads.js +10 -4
  477. package/dist/utils/worker-threads.js.map +1 -1
  478. package/docs/background-tasks.md +10 -10
  479. package/docs/compaction.md +1 -0
  480. package/docs/development.md +1 -1
  481. package/docs/environment-variables.md +4 -0
  482. package/docs/extensions/api-reference.md +2 -0
  483. package/docs/extensions/events.md +1 -1
  484. package/docs/getting-started/installation.md +1 -0
  485. package/docs/guides/non-interactive.md +2 -0
  486. package/docs/guides/resume-on-any-machine.md +3 -1
  487. package/docs/intercom/reference.md +1 -1
  488. package/docs/keybindings.md +6 -5
  489. package/docs/libraries/ai.md +2 -1
  490. package/docs/mcp-servers.md +1 -1
  491. package/docs/sdk/reference.md +1 -1
  492. package/docs/sdk.md +6 -0
  493. package/docs/security.md +4 -2
  494. package/docs/settings.md +2 -1
  495. package/docs/storage.md +2 -0
  496. package/docs/subagents.md +2 -2
  497. package/docs/tui/reference.md +3 -1
  498. package/npm-shrinkwrap.json +49 -49
  499. package/package.json +6 -6
@@ -16,6 +16,18 @@ type EngineSessionStorage = Extract<StorageSelection, {
16
16
  }>;
17
17
  export declare const ENGINE_SESSION_STORAGE_FLAG = "--internal-session-storage";
18
18
  export declare function getEngineSessionStorage(store: SessionStore): EngineSessionStorage | undefined;
19
+ /**
20
+ * Whether the project settings layers (highest precedence first) can put a folder's sessions in another store than
21
+ * `global` alone: their storage-selecting values are merged over the global ones as settings merge, and compared as
22
+ * written. Nothing is resolved, read or opened, so equal values are the only proof of the same store.
23
+ */
24
+ export declare function sessionStorageSettingsDiffer(global: Settings, projectLayers: readonly Settings[]): boolean;
25
+ /**
26
+ * Whether a project's own settings files can put its sessions in another store than the global settings, read as
27
+ * plain JSON without applying them (#5693). A file that cannot be read or parsed counts as different: only the
28
+ * folder's decision may tell what it would choose.
29
+ */
30
+ export declare function projectSettingsChooseSessionStorage(cwd: string, globalSettings: Settings): boolean;
19
31
  export declare function canIsolateSessionStore(store: SessionStore): boolean;
20
32
  export declare function takeEngineSessionStorageArg(args: readonly string[]): {
21
33
  args: string[];
@@ -1 +1 @@
1
- {"version":3,"file":"session-storage.d.ts","sourceRoot":"","sources":["../../src/core/session-storage.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAMN,KAAK,mBAAmB,EAIxB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAmB,KAAK,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAI/E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAE/D,MAAM,WAAW,qBAAqB;IACrC,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ,CAAC,EAAE,QAAQ,CAAC;IAC7B,QAAQ,CAAC,YAAY,CAAC,EAAE,YAAY,GAAG,gBAAgB,CAAC;IACxD,QAAQ,CAAC,SAAS,CAAC,EAAE,OAAO,CAAC;IAC7B,QAAQ,CAAC,UAAU,CAAC,EAAE,MA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  import { Value } from "typebox/value";
4
- import { getAgentDir } from "../config.js";
5
+ import { getAgentDir, getProjectConfigPaths } from "../config.js";
5
6
  import { resolvePath } from "../utils/paths.js";
7
+ import { stripBom } from "../utils/text.js";
6
8
  import { SettingsManager } from "./settings-manager.js";
9
+ import { deepMergeSettings } from "./settings-merge.js";
7
10
  import { SessionStorageSelectionSchema } from "./settings-schema.js";
8
11
  import { StorageConfigError } from "./storage/errors.js";
9
12
  import { defaultSessionDatabasePathAsync, defaultSessionDatabasePathSteps, defaultSharedStoragePathSteps, runStorageSteps, runStorageStepsSync, storagePathBaseDirSteps, storageSettingsSteps, } from "./storage/file-identity.js";
@@ -20,6 +23,70 @@ export const ENGINE_SESSION_STORAGE_FLAG = "--internal-session-storage";
20
23
  export function getEngineSessionStorage(store) {
21
24
  return engineSelections.get(store) ?? undefined;
22
25
  }
26
+ /** The settings keys that select a session store and the storage home its relative paths resolve from. */
27
+ const SESSION_STORAGE_SETTINGS = ["sessions", "storage", "workflows"];
28
+ /** The parts of `settings` that select the session store, as stable text. */
29
+ function sessionStorageProjection(settings) {
30
+ const stable = (value) => typeof value === "object" && value !== null && !Array.isArray(value)
31
+ ? Object.fromEntries(Object.keys(value)
32
+ .sort()
33
+ .map((key) => [key, stable(value[key])]))
34
+ : Array.isArray(value)
35
+ ? value.map(stable)
36
+ : value;
37
+ const workflows = settings.workflows;
38
+ return JSON.stringify(stable({
39
+ sessions: settings.sessions?.storage,
40
+ storage: settings.storage,
41
+ journal: typeof workflows === "object" && workflows !== null && !Array.isArray(workflows)
42
+ ? workflows.journal
43
+ : undefined,
44
+ }));
45
+ }
46
+ /**
47
+ * Whether the project settings layers (highest precedence first) can put a folder's sessions in another store than
48
+ * `global` alone: their storage-selecting values are merged over the global ones as settings merge, and compared as
49
+ * written. Nothing is resolved, read or opened, so equal values are the only proof of the same store.
50
+ */
51
+ export function sessionStorageSettingsDiffer(global, projectLayers) {
52
+ const project = projectLayers.reduceRight((merged, layer) => {
53
+ const selecting = {};
54
+ for (const key of SESSION_STORAGE_SETTINGS)
55
+ if (Object.hasOwn(layer, key))
56
+ selecting[key] = layer[key];
57
+ return deepMergeSettings(merged, selecting);
58
+ }, {});
59
+ return sessionStorageProjection(deepMergeSettings(global, project)) !== sessionStorageProjection(global);
60
+ }
61
+ /**
62
+ * Whether a project's own settings files can put its sessions in another store than the global settings, read as
63
+ * plain JSON without applying them (#5693). A file that cannot be read or parsed counts as different: only the
64
+ * folder's decision may tell what it would choose.
65
+ */
66
+ export function projectSettingsChooseSessionStorage(cwd, globalSettings) {
67
+ const layers = [];
68
+ for (const path of getProjectConfigPaths(cwd, "settings.json")) {
69
+ let text;
70
+ try {
71
+ text = readFileSync(path, "utf8");
72
+ }
73
+ catch (error) {
74
+ if (error.code === "ENOENT")
75
+ continue;
76
+ return true;
77
+ }
78
+ try {
79
+ const parsed = JSON.parse(stripBom(text));
80
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
81
+ return true;
82
+ layers.push(parsed);
83
+ }
84
+ catch {
85
+ return true;
86
+ }
87
+ }
88
+ return sessionStorageSettingsDiffer(globalSettings, layers);
89
+ }
23
90
  export function canIsolateSessionStore(store) {
24
91
  return (isolatedCliMemoryStores.has(store) ||
25
92
  getEngineSessionStorage(store) !== undefined ||
@@ -1 +1 @@
1
- {"version":3,"file":"session-storage.js","sourceRoot":"","sources":["../../src/core/session-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACtD,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,6BAA6B,EAAE,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,KAAK,EAAE,CAAC;QAChB,IAAI,KAAK,YAAY,kBAAkB,EAAE,CAAC;YACzC,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;YACtC,MAAM,IAAI,kBAAkB,CAAC,MAAM,EAAE,MAAM,IAAI,KAAK,EAAE,MAAM,EAAE,KAAK,IAAI,cAAc,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;QACtG,CAAC;QACD,MAAM,KAAK,CAAC;IACb,CAAC;AACF,CAAC","sourcesContent":["import { mkdir } from \"node:fs/promises\";\nimport { isAbsolute, join, resolve } from \"node:path\";\nimport { Value } from \"typebox/value\";\nimport { getAgentDir } from \"../config.js\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { SessionStorageSelectionSchema } from \"./settings-schema.ts\";\nimport type { Settings } from \"./settings-types.ts\";\nimport { StorageConfigError } from \"./storage/errors.js\";\nimport {\n\tdefaultSessionDatabasePathAsync,\n\tdefaultSessionDatabasePathSteps,\n\tdefaultSharedStoragePathSteps,\n\trunStorageSteps,\n\trunStorageStepsSync,\n\ttype StorageHomeSettings,\n\ttype StorageSteps,\n\tstoragePathBaseDirSteps,\n\tstorageSettingsSteps,\n} from \"./storage/file-identity.js\";\nimport { selectProcessStorageSteps } from \"./storage/process-selection.js\";\nimport { StorageProvider, type StorageSelection } from \"./storage/provider.js\";\nimport { selectStorageSteps } from \"./storage/selection.js\";\nimport { JsonlSessionStore } from \"./storage/session/jsonl-session-store.js\";\nimport { LegacySessionStore } from \"./storage/session/legacy-session-store.js\";\nimport type { SessionStore } from \"./storage/session/types.js\";\n\nexport interface SessionStorageOptions {\n\treadonly agentDir?: string;\n\treadonly settings?: Settings;\n\treadonly sessionStore?: SessionStore | StorageSelection;\n\treadonly noSession?: boolean;\n\treadonly sessionDir?: string;\n\treadonly sessionStorePath?: string;\n\treadonly sessionPrefix?: string;\n}\n\nconst provider = new StorageProvider();\nconst sources = new WeakMap<StorageSelection, { source: \"settings\" | \"cli\" | \"env\"; field: string }>();\ntype EngineSessionStorage = Extract<StorageSelection, { kind: \"sqlite\" }>;\nconst engineSelections = new WeakMap<SessionStore, EngineSessionStorage | null>();\nconst isolatedCliMemoryStores = new WeakSet<SessionStore>();\nexport const ENGINE_SESSION_STORAGE_FLAG = \"--internal-session-storage\";\n\nexport function getEngineSessionStorage(store: SessionStore): EngineSessionStorage | undefined {\n\treturn engineSelections.get(store) ?? undefined;\n}\n\nexport function canIsolateSessionStore(store: SessionStore): boolean {\n\treturn (\n\t\tisolatedCliMemoryStores.has(store) ||\n\t\tgetEngineSessionStorage(store) !== undefined ||\n\t\t(store instanceof JsonlSessionStore && !engineSelections.has(store))\n\t);\n}\n\nexport function takeEngineSessionStorageArg(args: readonly string[]): {\n\targs: string[];\n\tsessionStorage?: EngineSessionStorage;\n} {\n\tconst remaining: string[] = [];\n\tlet sessionStorage: EngineSessionStorage | undefined;\n\tfor (let index = 0; index < args.length; index++) {\n\t\tif (args[index] !== ENGINE_SESSION_STORAGE_FLAG) {\n\t\t\tremaining.push(args[index]!);\n\t\t\tcontinue;\n\t\t}\n\t\tlet parsed: EngineSessionStorage;\n\t\ttry {\n\t\t\tparsed = JSON.parse(args[++index]!) as EngineSessionStorage;\n\t\t} catch {\n\t\t\tthrow new StorageConfigError(\"cli\", ENGINE_SESSION_STORAGE_FLAG, \"invalid-selection\");\n\t\t}\n\t\tif (parsed?.kind !== \"sqlite\" || typeof parsed.path !== \"string\") {\n\t\t\tthrow new StorageConfigError(\"cli\", ENGINE_SESSION_STORAGE_FLAG, \"invalid-selection\");\n\t\t}\n\t\tsessionStorage = parsed;\n\t}\n\treturn { args: remaining, ...(sessionStorage === undefined ? {} : { sessionStorage }) };\n}\n\nfunction resolveStoragePath(path: string, base: string, source: \"cli\" | \"env\" | \"settings\", field: string): string {\n\ttry {\n\t\treturn resolvePath(path, base);\n\t} catch {\n\t\tthrow new StorageConfigError(source, field, \"invalid-path\");\n\t}\n}\n\nexport function selectSessionStorage(\n\tcwd: string,\n\toptions: SessionStorageOptions = {},\n): SessionStore | StorageSelection {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\treturn runStorageStepsSync(\n\t\tselectSessionStorageSteps(cwd, options, agentDir),\n\t\t() => options.settings ?? SettingsManager.create(cwd, agentDir).getSettings(),\n\t);\n}\n\nexport function selectSessionStorageWithSettings(\n\tcwd: string,\n\toptions: SessionStorageOptions & { readonly settings: Settings },\n): SessionStore | StorageSelection {\n\treturn runStorageStepsSync(\n\t\tselectSessionStorageSteps(cwd, options, options.agentDir ?? getAgentDir()),\n\t\t() => options.settings,\n\t);\n}\n\nexport function selectSessionStorageWithSettingsAsync(\n\tcwd: string,\n\toptions: SessionStorageOptions & { readonly settings: Settings },\n): Promise<SessionStore | StorageSelection> {\n\treturn runStorageSteps(\n\t\tselectSessionStorageSteps(cwd, options, options.agentDir ?? getAgentDir()),\n\t\tasync () => options.settings,\n\t);\n}\n\nfunction* selectSessionStorageSteps(\n\tcwd: string,\n\toptions: SessionStorageOptions,\n\tagentDir: string,\n): StorageSteps<SessionStore | StorageSelection> {\n\treturn (\n\t\t(yield* selectSessionStorageBeforeSettingsSteps(cwd, options, agentDir)) ??\n\t\t(yield* selectSessionStorageFromSettingsSteps(yield* storageSettingsSteps<Settings>(), agentDir))\n\t);\n}\n\nfunction* selectSessionStorageBeforeSettingsSteps(\n\tcwd: string,\n\toptions: SessionStorageOptions,\n\tagentDir: string,\n): StorageSteps<SessionStore | StorageSelection | undefined> {\n\tif (options.sessionStore !== undefined) {\n\t\tconst value = options.sessionStore;\n\t\tif (value !== null && typeof value === \"object\" && \"load\" in value) {\n\t\t\tif (\n\t\t\t\t[\n\t\t\t\t\tvalue.create,\n\t\t\t\t\tvalue.append,\n\t\t\t\t\tvalue.replace,\n\t\t\t\t\tvalue.load,\n\t\t\t\t\tvalue.readHeader,\n\t\t\t\t\tvalue.delete,\n\t\t\t\t\tvalue.list,\n\t\t\t\t\tvalue.findMostRecent,\n\t\t\t\t\tvalue.close,\n\t\t\t\t].some((hook) => typeof hook !== \"function\") ||\n\t\t\t\t!value.descriptor ||\n\t\t\t\ttypeof value.descriptor.adapter !== \"string\" ||\n\t\t\t\ttypeof value.descriptor.location !== \"string\"\n\t\t\t)\n\t\t\t\tthrow new StorageConfigError(\"sdk\", \"sessionStore\", \"invalid-session-store\");\n\t\t\treturn value;\n\t\t}\n\t\treturn value;\n\t}\n\tif (options.sessionStorePath !== undefined) {\n\t\tconst selection = {\n\t\t\tkind: \"sqlite\",\n\t\t\tpath: resolveStoragePath(options.sessionStorePath, cwd, \"cli\", \"--session-store\"),\n\t\t\t...(options.sessionPrefix === undefined ? {} : { prefix: options.sessionPrefix }),\n\t\t} as const;\n\t\tsources.set(selection, { source: \"cli\", field: \"--session-store\" });\n\t\treturn selection;\n\t}\n\tif (options.noSession) return { kind: \"memory\" };\n\tif (options.sessionDir !== undefined) {\n\t\tif (typeof options.sessionDir !== \"string\") throw new StorageConfigError(\"cli\", \"--session-dir\", \"invalid-dir\");\n\t\tconst selection = {\n\t\t\tkind: \"jsonl\",\n\t\t\tdir: resolveStoragePath(options.sessionDir, cwd, \"cli\", \"--session-dir\"),\n\t\t} as const;\n\t\tsources.set(selection, { source: \"cli\", field: \"--session-dir\" });\n\t\treturn selection;\n\t}\n\tconst processChoice = yield* selectProcessStorageSteps(\"sessions\", agentDir, cwd);\n\tif (processChoice !== undefined) {\n\t\tsources.set(processChoice.selection, { source: processChoice.source, field: processChoice.field });\n\t\treturn processChoice.selection;\n\t}\n\treturn undefined;\n}\n\nfunction* selectSessionStorageFromSettingsSteps(settings: Settings, agentDir: string): StorageSteps<StorageSelection> {\n\tif (\n\t\tsettings.sessions !== undefined &&\n\t\t(settings.sessions === null || typeof settings.sessions !== \"object\" || Array.isArray(settings.sessions))\n\t) {\n\t\tthrow new StorageConfigError(\"settings\", \"sessions\", \"selection-object-required\");\n\t}\n\tconst value = settings.sessions?.storage !== undefined ? settings.sessions.storage : settings.storage;\n\tif (value === undefined) return { kind: \"sqlite\", path: yield* defaultSessionDatabasePathSteps(agentDir, settings) };\n\tconst field = settings.sessions?.storage !== undefined ? \"sessions.storage\" : \"storage\";\n\tconst selection = yield* selectSessionSettingSteps(value, field, agentDir, settings);\n\tsources.set(selection, { source: \"settings\", field });\n\treturn selection;\n}\n\n/**\n * The selection a settings value for sessions names: a `{ dir }` JSONL directory or a storage selection, with relative\n * paths resolved against the Atomic home. `field` is the setting it came from, `sessions.storage` or `storage`; a value\n * that is not a valid selection for it throws {@link StorageConfigError}.\n */\nexport function selectSessionSetting(\n\tvalue: NonNullable<NonNullable<Settings[\"sessions\"]>[\"storage\"]>,\n\tfield: \"sessions.storage\" | \"storage\",\n\tagentDir: string,\n\tsettings?: StorageHomeSettings,\n): StorageSelection {\n\treturn runStorageStepsSync(selectSessionSettingSteps(value, field, agentDir, settings));\n}\n\nfunction* selectSessionSettingSteps(\n\tvalue: NonNullable<NonNullable<Settings[\"sessions\"]>[\"storage\"]>,\n\tfield: \"sessions.storage\" | \"storage\",\n\tagentDir: string,\n\tsettings?: StorageHomeSettings,\n): StorageSteps<StorageSelection> {\n\tif (!Value.Check(SessionStorageSelectionSchema, value) || (field === \"storage\" && \"dir\" in value)) {\n\t\tthrow new StorageConfigError(\"settings\", field, \"invalid-selection\");\n\t}\n\tconst effectiveSettings: StorageHomeSettings =\n\t\tsettings ?? (field === \"storage\" ? { storage: value } : { sessions: { storage: value } });\n\tif (\"dir\" in value)\n\t\treturn {\n\t\t\tkind: \"jsonl\",\n\t\t\tdir: resolveStoragePath(\n\t\t\t\tvalue.dir,\n\t\t\t\tyield* storagePathBaseDirSteps(value.dir, agentDir, effectiveSettings),\n\t\t\t\t\"settings\",\n\t\t\t\tfield,\n\t\t\t),\n\t\t};\n\tconst selection = yield* selectStorageSteps(value, \"settings\", field, () =>\n\t\tfield === \"storage\"\n\t\t\t? defaultSharedStoragePathSteps(agentDir, effectiveSettings)\n\t\t\t: defaultSessionDatabasePathSteps(agentDir, effectiveSettings),\n\t);\n\tif (selection.kind === \"sqlite\" && !isAbsolute(selection.path)) {\n\t\treturn {\n\t\t\t...selection,\n\t\t\tpath: resolveStoragePath(\n\t\t\t\tselection.path,\n\t\t\t\tyield* storagePathBaseDirSteps(selection.path, agentDir, effectiveSettings),\n\t\t\t\t\"settings\",\n\t\t\t\tfield,\n\t\t\t),\n\t\t};\n\t}\n\treturn selection;\n}\n\n/**\n * The shared default database, selected directly or handed to the engine child. Sessions saved\n * before it became the default stay readable from the agent directory's JSONL files.\n */\nasync function isDefaultDatabase(selection: StorageSelection, agentDir: string): Promise<boolean> {\n\treturn (\n\t\tselection.kind === \"sqlite\" &&\n\t\t!selection.prefix &&\n\t\tselection.path !== \"\" &&\n\t\tselection.path !== \":memory:\" &&\n\t\tresolve(selection.path) === resolve(await defaultSessionDatabasePathAsync(agentDir))\n\t);\n}\n\nexport async function resolveSessionStore(cwd: string, options: SessionStorageOptions = {}): Promise<SessionStore> {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst settings = options.settings ?? (await SettingsManager.createAsync(cwd, agentDir)).getSettings();\n\tconst select = () => selectSessionStorageWithSettingsAsync(cwd, { ...options, settings });\n\tlet selection = await select();\n\tif (selection !== null && typeof selection === \"object\" && \"load\" in selection) return selection;\n\tif (\n\t\t(selection.kind === \"sqlite\" || selection.kind === \"jsonl\") &&\n\t\toptions.sessionStore === undefined &&\n\t\toptions.sessionStorePath === undefined &&\n\t\toptions.sessionDir === undefined\n\t) {\n\t\tawait mkdir(agentDir, { recursive: true });\n\t\tselection = (await select()) as StorageSelection;\n\t}\n\t// Released sessions' history that a killed process left in this agent directory goes, once per process (#4502).\n\tvoid import(\"./storage/session/released-history-files.js\").then(\n\t\t({ sweepReleasedHistoryOnce }) => sweepReleasedHistoryOnce(agentDir),\n\t\t() => undefined,\n\t);\n\ttry {\n\t\tconst opened = await provider.openSessionStore(selection, { agentDir, domain: \"sessions\" });\n\t\tconst store =\n\t\t\tselection.kind === \"sqlite\" && (await isDefaultDatabase(selection, agentDir))\n\t\t\t\t? new LegacySessionStore(opened, {\n\t\t\t\t\t\tlegacyDirectory: join(agentDir, \"sessions\"),\n\t\t\t\t\t\tdatabasePath: resolve(selection.path),\n\t\t\t\t\t})\n\t\t\t\t: opened;\n\t\tif (selection.kind === \"sqlite\" && selection.path !== \"\" && selection.path !== \":memory:\") {\n\t\t\tengineSelections.set(store, {\n\t\t\t\tkind: \"sqlite\",\n\t\t\t\tpath: resolve(selection.path),\n\t\t\t\t...(selection.prefix === undefined ? {} : { prefix: selection.prefix }),\n\t\t\t});\n\t\t} else if (selection.kind !== \"jsonl\") engineSelections.set(store, null);\n\t\tif (selection.kind === \"memory\" && options.noSession && options.sessionStore === undefined) {\n\t\t\tisolatedCliMemoryStores.add(store);\n\t\t}\n\t\treturn store;\n\t} catch (error) {\n\t\tif (error instanceof StorageConfigError) {\n\t\t\tconst origin = sources.get(selection);\n\t\t\tthrow new StorageConfigError(origin?.source ?? \"sdk\", origin?.field ?? \"sessionStore\", error.reason);\n\t\t}\n\t\tthrow error;\n\t}\n}\n"]}
1
+ {"version":3,"file":"session-storage.js","sourceRoot":"","sources":["../../src/core/session-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACtD,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAClE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,iBAAiB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QACpC,CAAC;QACD,OAAO,KAAK,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,IAAI,KAAK,YAAY,kBAAkB,EAAE,CAAC;YACzC,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;YACtC,MAAM,IAAI,kBAAkB,CAAC,MAAM,EAAE,MAAM,IAAI,KAAK,EAAE,MAAM,EAAE,KAAK,IAAI,cAAc,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;QACtG,CAAC;QACD,MAAM,KAAK,CAAC;IACb,CAAC;AACF,CAAC","sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { mkdir } from \"node:fs/promises\";\nimport { isAbsolute, join, resolve } from \"node:path\";\nimport { Value } from \"typebox/value\";\nimport { getAgentDir, getProjectConfigPaths } from \"../config.js\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { stripBom } from \"../utils/text.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { deepMergeSettings } from \"./settings-merge.js\";\nimport { SessionStorageSelectionSchema } from \"./settings-schema.ts\";\nimport type { Settings } from \"./settings-types.ts\";\nimport { StorageConfigError } from \"./storage/errors.js\";\nimport {\n\tdefaultSessionDatabasePathAsync,\n\tdefaultSessionDatabasePathSteps,\n\tdefaultSharedStoragePathSteps,\n\trunStorageSteps,\n\trunStorageStepsSync,\n\ttype StorageHomeSettings,\n\ttype StorageSteps,\n\tstoragePathBaseDirSteps,\n\tstorageSettingsSteps,\n} from \"./storage/file-identity.js\";\nimport { selectProcessStorageSteps } from \"./storage/process-selection.js\";\nimport { StorageProvider, type StorageSelection } from \"./storage/provider.js\";\nimport { selectStorageSteps } from \"./storage/selection.js\";\nimport { JsonlSessionStore } from \"./storage/session/jsonl-session-store.js\";\nimport { LegacySessionStore } from \"./storage/session/legacy-session-store.js\";\nimport type { SessionStore } from \"./storage/session/types.js\";\n\nexport interface SessionStorageOptions {\n\treadonly agentDir?: string;\n\treadonly settings?: Settings;\n\treadonly sessionStore?: SessionStore | StorageSelection;\n\treadonly noSession?: boolean;\n\treadonly sessionDir?: string;\n\treadonly sessionStorePath?: string;\n\treadonly sessionPrefix?: string;\n}\n\nconst provider = new StorageProvider();\nconst sources = new WeakMap<StorageSelection, { source: \"settings\" | \"cli\" | \"env\"; field: string }>();\ntype EngineSessionStorage = Extract<StorageSelection, { kind: \"sqlite\" }>;\nconst engineSelections = new WeakMap<SessionStore, EngineSessionStorage | null>();\nconst isolatedCliMemoryStores = new WeakSet<SessionStore>();\nexport const ENGINE_SESSION_STORAGE_FLAG = \"--internal-session-storage\";\n\nexport function getEngineSessionStorage(store: SessionStore): EngineSessionStorage | undefined {\n\treturn engineSelections.get(store) ?? undefined;\n}\n\n/** The settings keys that select a session store and the storage home its relative paths resolve from. */\nconst SESSION_STORAGE_SETTINGS = [\"sessions\", \"storage\", \"workflows\"] as const;\n\n/** The parts of `settings` that select the session store, as stable text. */\nfunction sessionStorageProjection(settings: Settings): string {\n\tconst stable = (value: unknown): unknown =>\n\t\ttypeof value === \"object\" && value !== null && !Array.isArray(value)\n\t\t\t? Object.fromEntries(\n\t\t\t\t\tObject.keys(value)\n\t\t\t\t\t\t.sort()\n\t\t\t\t\t\t.map((key) => [key, stable((value as Record<string, unknown>)[key])]),\n\t\t\t\t)\n\t\t\t: Array.isArray(value)\n\t\t\t\t? value.map(stable)\n\t\t\t\t: value;\n\tconst workflows = (settings as StorageHomeSettings).workflows;\n\treturn JSON.stringify(\n\t\tstable({\n\t\t\tsessions: settings.sessions?.storage,\n\t\t\tstorage: settings.storage,\n\t\t\tjournal:\n\t\t\t\ttypeof workflows === \"object\" && workflows !== null && !Array.isArray(workflows)\n\t\t\t\t\t? workflows.journal\n\t\t\t\t\t: undefined,\n\t\t}),\n\t);\n}\n\n/**\n * Whether the project settings layers (highest precedence first) can put a folder's sessions in another store than\n * `global` alone: their storage-selecting values are merged over the global ones as settings merge, and compared as\n * written. Nothing is resolved, read or opened, so equal values are the only proof of the same store.\n */\nexport function sessionStorageSettingsDiffer(global: Settings, projectLayers: readonly Settings[]): boolean {\n\tconst project = projectLayers.reduceRight<Settings>((merged, layer) => {\n\t\tconst selecting: Record<string, unknown> = {};\n\t\tfor (const key of SESSION_STORAGE_SETTINGS)\n\t\t\tif (Object.hasOwn(layer, key)) selecting[key] = (layer as Record<string, unknown>)[key];\n\t\treturn deepMergeSettings(merged, selecting as Settings);\n\t}, {});\n\treturn sessionStorageProjection(deepMergeSettings(global, project)) !== sessionStorageProjection(global);\n}\n\n/**\n * Whether a project's own settings files can put its sessions in another store than the global settings, read as\n * plain JSON without applying them (#5693). A file that cannot be read or parsed counts as different: only the\n * folder's decision may tell what it would choose.\n */\nexport function projectSettingsChooseSessionStorage(cwd: string, globalSettings: Settings): boolean {\n\tconst layers: Settings[] = [];\n\tfor (const path of getProjectConfigPaths(cwd, \"settings.json\")) {\n\t\tlet text: string;\n\t\ttry {\n\t\t\ttext = readFileSync(path, \"utf8\");\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n\t\t\treturn true;\n\t\t}\n\t\ttry {\n\t\t\tconst parsed: unknown = JSON.parse(stripBom(text));\n\t\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return true;\n\t\t\tlayers.push(parsed as Settings);\n\t\t} catch {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn sessionStorageSettingsDiffer(globalSettings, layers);\n}\n\nexport function canIsolateSessionStore(store: SessionStore): boolean {\n\treturn (\n\t\tisolatedCliMemoryStores.has(store) ||\n\t\tgetEngineSessionStorage(store) !== undefined ||\n\t\t(store instanceof JsonlSessionStore && !engineSelections.has(store))\n\t);\n}\n\nexport function takeEngineSessionStorageArg(args: readonly string[]): {\n\targs: string[];\n\tsessionStorage?: EngineSessionStorage;\n} {\n\tconst remaining: string[] = [];\n\tlet sessionStorage: EngineSessionStorage | undefined;\n\tfor (let index = 0; index < args.length; index++) {\n\t\tif (args[index] !== ENGINE_SESSION_STORAGE_FLAG) {\n\t\t\tremaining.push(args[index]!);\n\t\t\tcontinue;\n\t\t}\n\t\tlet parsed: EngineSessionStorage;\n\t\ttry {\n\t\t\tparsed = JSON.parse(args[++index]!) as EngineSessionStorage;\n\t\t} catch {\n\t\t\tthrow new StorageConfigError(\"cli\", ENGINE_SESSION_STORAGE_FLAG, \"invalid-selection\");\n\t\t}\n\t\tif (parsed?.kind !== \"sqlite\" || typeof parsed.path !== \"string\") {\n\t\t\tthrow new StorageConfigError(\"cli\", ENGINE_SESSION_STORAGE_FLAG, \"invalid-selection\");\n\t\t}\n\t\tsessionStorage = parsed;\n\t}\n\treturn { args: remaining, ...(sessionStorage === undefined ? {} : { sessionStorage }) };\n}\n\nfunction resolveStoragePath(path: string, base: string, source: \"cli\" | \"env\" | \"settings\", field: string): string {\n\ttry {\n\t\treturn resolvePath(path, base);\n\t} catch {\n\t\tthrow new StorageConfigError(source, field, \"invalid-path\");\n\t}\n}\n\nexport function selectSessionStorage(\n\tcwd: string,\n\toptions: SessionStorageOptions = {},\n): SessionStore | StorageSelection {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\treturn runStorageStepsSync(\n\t\tselectSessionStorageSteps(cwd, options, agentDir),\n\t\t() => options.settings ?? SettingsManager.create(cwd, agentDir).getSettings(),\n\t);\n}\n\nexport function selectSessionStorageWithSettings(\n\tcwd: string,\n\toptions: SessionStorageOptions & { readonly settings: Settings },\n): SessionStore | StorageSelection {\n\treturn runStorageStepsSync(\n\t\tselectSessionStorageSteps(cwd, options, options.agentDir ?? getAgentDir()),\n\t\t() => options.settings,\n\t);\n}\n\nexport function selectSessionStorageWithSettingsAsync(\n\tcwd: string,\n\toptions: SessionStorageOptions & { readonly settings: Settings },\n): Promise<SessionStore | StorageSelection> {\n\treturn runStorageSteps(\n\t\tselectSessionStorageSteps(cwd, options, options.agentDir ?? getAgentDir()),\n\t\tasync () => options.settings,\n\t);\n}\n\nfunction* selectSessionStorageSteps(\n\tcwd: string,\n\toptions: SessionStorageOptions,\n\tagentDir: string,\n): StorageSteps<SessionStore | StorageSelection> {\n\treturn (\n\t\t(yield* selectSessionStorageBeforeSettingsSteps(cwd, options, agentDir)) ??\n\t\t(yield* selectSessionStorageFromSettingsSteps(yield* storageSettingsSteps<Settings>(), agentDir))\n\t);\n}\n\nfunction* selectSessionStorageBeforeSettingsSteps(\n\tcwd: string,\n\toptions: SessionStorageOptions,\n\tagentDir: string,\n): StorageSteps<SessionStore | StorageSelection | undefined> {\n\tif (options.sessionStore !== undefined) {\n\t\tconst value = options.sessionStore;\n\t\tif (value !== null && typeof value === \"object\" && \"load\" in value) {\n\t\t\tif (\n\t\t\t\t[\n\t\t\t\t\tvalue.create,\n\t\t\t\t\tvalue.append,\n\t\t\t\t\tvalue.replace,\n\t\t\t\t\tvalue.load,\n\t\t\t\t\tvalue.readHeader,\n\t\t\t\t\tvalue.delete,\n\t\t\t\t\tvalue.list,\n\t\t\t\t\tvalue.findMostRecent,\n\t\t\t\t\tvalue.close,\n\t\t\t\t].some((hook) => typeof hook !== \"function\") ||\n\t\t\t\t!value.descriptor ||\n\t\t\t\ttypeof value.descriptor.adapter !== \"string\" ||\n\t\t\t\ttypeof value.descriptor.location !== \"string\"\n\t\t\t)\n\t\t\t\tthrow new StorageConfigError(\"sdk\", \"sessionStore\", \"invalid-session-store\");\n\t\t\treturn value;\n\t\t}\n\t\treturn value;\n\t}\n\tif (options.sessionStorePath !== undefined) {\n\t\tconst selection = {\n\t\t\tkind: \"sqlite\",\n\t\t\tpath: resolveStoragePath(options.sessionStorePath, cwd, \"cli\", \"--session-store\"),\n\t\t\t...(options.sessionPrefix === undefined ? {} : { prefix: options.sessionPrefix }),\n\t\t} as const;\n\t\tsources.set(selection, { source: \"cli\", field: \"--session-store\" });\n\t\treturn selection;\n\t}\n\tif (options.noSession) return { kind: \"memory\" };\n\tif (options.sessionDir !== undefined) {\n\t\tif (typeof options.sessionDir !== \"string\") throw new StorageConfigError(\"cli\", \"--session-dir\", \"invalid-dir\");\n\t\tconst selection = {\n\t\t\tkind: \"jsonl\",\n\t\t\tdir: resolveStoragePath(options.sessionDir, cwd, \"cli\", \"--session-dir\"),\n\t\t} as const;\n\t\tsources.set(selection, { source: \"cli\", field: \"--session-dir\" });\n\t\treturn selection;\n\t}\n\tconst processChoice = yield* selectProcessStorageSteps(\"sessions\", agentDir, cwd);\n\tif (processChoice !== undefined) {\n\t\tsources.set(processChoice.selection, { source: processChoice.source, field: processChoice.field });\n\t\treturn processChoice.selection;\n\t}\n\treturn undefined;\n}\n\nfunction* selectSessionStorageFromSettingsSteps(settings: Settings, agentDir: string): StorageSteps<StorageSelection> {\n\tif (\n\t\tsettings.sessions !== undefined &&\n\t\t(settings.sessions === null || typeof settings.sessions !== \"object\" || Array.isArray(settings.sessions))\n\t) {\n\t\tthrow new StorageConfigError(\"settings\", \"sessions\", \"selection-object-required\");\n\t}\n\tconst value = settings.sessions?.storage !== undefined ? settings.sessions.storage : settings.storage;\n\tif (value === undefined) return { kind: \"sqlite\", path: yield* defaultSessionDatabasePathSteps(agentDir, settings) };\n\tconst field = settings.sessions?.storage !== undefined ? \"sessions.storage\" : \"storage\";\n\tconst selection = yield* selectSessionSettingSteps(value, field, agentDir, settings);\n\tsources.set(selection, { source: \"settings\", field });\n\treturn selection;\n}\n\n/**\n * The selection a settings value for sessions names: a `{ dir }` JSONL directory or a storage selection, with relative\n * paths resolved against the Atomic home. `field` is the setting it came from, `sessions.storage` or `storage`; a value\n * that is not a valid selection for it throws {@link StorageConfigError}.\n */\nexport function selectSessionSetting(\n\tvalue: NonNullable<NonNullable<Settings[\"sessions\"]>[\"storage\"]>,\n\tfield: \"sessions.storage\" | \"storage\",\n\tagentDir: string,\n\tsettings?: StorageHomeSettings,\n): StorageSelection {\n\treturn runStorageStepsSync(selectSessionSettingSteps(value, field, agentDir, settings));\n}\n\nfunction* selectSessionSettingSteps(\n\tvalue: NonNullable<NonNullable<Settings[\"sessions\"]>[\"storage\"]>,\n\tfield: \"sessions.storage\" | \"storage\",\n\tagentDir: string,\n\tsettings?: StorageHomeSettings,\n): StorageSteps<StorageSelection> {\n\tif (!Value.Check(SessionStorageSelectionSchema, value) || (field === \"storage\" && \"dir\" in value)) {\n\t\tthrow new StorageConfigError(\"settings\", field, \"invalid-selection\");\n\t}\n\tconst effectiveSettings: StorageHomeSettings =\n\t\tsettings ?? (field === \"storage\" ? { storage: value } : { sessions: { storage: value } });\n\tif (\"dir\" in value)\n\t\treturn {\n\t\t\tkind: \"jsonl\",\n\t\t\tdir: resolveStoragePath(\n\t\t\t\tvalue.dir,\n\t\t\t\tyield* storagePathBaseDirSteps(value.dir, agentDir, effectiveSettings),\n\t\t\t\t\"settings\",\n\t\t\t\tfield,\n\t\t\t),\n\t\t};\n\tconst selection = yield* selectStorageSteps(value, \"settings\", field, () =>\n\t\tfield === \"storage\"\n\t\t\t? defaultSharedStoragePathSteps(agentDir, effectiveSettings)\n\t\t\t: defaultSessionDatabasePathSteps(agentDir, effectiveSettings),\n\t);\n\tif (selection.kind === \"sqlite\" && !isAbsolute(selection.path)) {\n\t\treturn {\n\t\t\t...selection,\n\t\t\tpath: resolveStoragePath(\n\t\t\t\tselection.path,\n\t\t\t\tyield* storagePathBaseDirSteps(selection.path, agentDir, effectiveSettings),\n\t\t\t\t\"settings\",\n\t\t\t\tfield,\n\t\t\t),\n\t\t};\n\t}\n\treturn selection;\n}\n\n/**\n * The shared default database, selected directly or handed to the engine child. Sessions saved\n * before it became the default stay readable from the agent directory's JSONL files.\n */\nasync function isDefaultDatabase(selection: StorageSelection, agentDir: string): Promise<boolean> {\n\treturn (\n\t\tselection.kind === \"sqlite\" &&\n\t\t!selection.prefix &&\n\t\tselection.path !== \"\" &&\n\t\tselection.path !== \":memory:\" &&\n\t\tresolve(selection.path) === resolve(await defaultSessionDatabasePathAsync(agentDir))\n\t);\n}\n\nexport async function resolveSessionStore(cwd: string, options: SessionStorageOptions = {}): Promise<SessionStore> {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst settings = options.settings ?? (await SettingsManager.createAsync(cwd, agentDir)).getSettings();\n\tconst select = () => selectSessionStorageWithSettingsAsync(cwd, { ...options, settings });\n\tlet selection = await select();\n\tif (selection !== null && typeof selection === \"object\" && \"load\" in selection) return selection;\n\tif (\n\t\t(selection.kind === \"sqlite\" || selection.kind === \"jsonl\") &&\n\t\toptions.sessionStore === undefined &&\n\t\toptions.sessionStorePath === undefined &&\n\t\toptions.sessionDir === undefined\n\t) {\n\t\tawait mkdir(agentDir, { recursive: true });\n\t\tselection = (await select()) as StorageSelection;\n\t}\n\t// Released sessions' history that a killed process left in this agent directory goes, once per process (#4502).\n\tvoid import(\"./storage/session/released-history-files.js\").then(\n\t\t({ sweepReleasedHistoryOnce }) => sweepReleasedHistoryOnce(agentDir),\n\t\t() => undefined,\n\t);\n\ttry {\n\t\tconst opened = await provider.openSessionStore(selection, { agentDir, domain: \"sessions\" });\n\t\tconst store =\n\t\t\tselection.kind === \"sqlite\" && (await isDefaultDatabase(selection, agentDir))\n\t\t\t\t? new LegacySessionStore(opened, {\n\t\t\t\t\t\tlegacyDirectory: join(agentDir, \"sessions\"),\n\t\t\t\t\t\tdatabasePath: resolve(selection.path),\n\t\t\t\t\t})\n\t\t\t\t: opened;\n\t\tif (selection.kind === \"sqlite\" && selection.path !== \"\" && selection.path !== \":memory:\") {\n\t\t\tengineSelections.set(store, {\n\t\t\t\tkind: \"sqlite\",\n\t\t\t\tpath: resolve(selection.path),\n\t\t\t\t...(selection.prefix === undefined ? {} : { prefix: selection.prefix }),\n\t\t\t});\n\t\t} else if (selection.kind !== \"jsonl\") engineSelections.set(store, null);\n\t\tif (selection.kind === \"memory\" && options.noSession && options.sessionStore === undefined) {\n\t\t\tisolatedCliMemoryStores.add(store);\n\t\t}\n\t\treturn store;\n\t} catch (error) {\n\t\tif (error instanceof StorageConfigError) {\n\t\t\tconst origin = sources.get(selection);\n\t\t\tthrow new StorageConfigError(origin?.source ?? \"sdk\", origin?.field ?? \"sessionStore\", error.reason);\n\t\t}\n\t\tthrow error;\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"settings-lock-directory.d.ts","sourceRoot":"","sources":["../../src/core/settings-lock-directory.ts"],"names":[],"mappings":"AAiCA,wBAAgB,4BAA4B,CAAC,IAAI,EAAE,iBAAiB,GAAG,SAAS,GAAG,IAAI,CAEtF;AA8CD,MAAM,WAAW,qBAAqB;IACrC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IAChC,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC;CAC3B;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,qBAAqB,CAUvE;AAED,wBAAgB,8BAA8B,CAAC,QAAQ,EAAE,qBAAqB,GAAG,OAAO,CAKvF"}
1
+ {"version":3,"file":"settings-lock-directory.d.ts","sourceRoot":"","sources":["../../src/core/settings-lock-directory.ts"],"names":[],"mappings":"AAkCA,wBAAgB,4BAA4B,CAAC,IAAI,EAAE,iBAAiB,GAAG,SAAS,GAAG,IAAI,CAEtF;AA8CD,MAAM,WAAW,qBAAqB;IACrC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IAChC,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC;CAC3B;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,qBAAqB,CAUvE;AAED,wBAAgB,8BAA8B,CAAC,QAAQ,EAAE,qBAAqB,GAAG,OAAO,CAKvF"}
@@ -1,13 +1,14 @@
1
1
  import { Worker } from "node:worker_threads";
2
- import { evalWorkerExecArgv } from "../utils/worker-threads.js";
2
+ import { EVAL_WORKER_BUILTIN, evalWorkerExecArgv } from "../utils/worker-threads.js";
3
3
  const QUEUED = 0;
4
4
  const CREATING = 1;
5
5
  const CREATED = 2;
6
6
  const FAILED = 3;
7
7
  const CLAIMED = 4;
8
8
  const CREATOR_SOURCE = `
9
- const { parentPort } = require("node:worker_threads");
10
- const { mkdirSync } = require("node:fs");
9
+ ${EVAL_WORKER_BUILTIN}
10
+ const { parentPort } = builtin("node:worker_threads");
11
+ const { mkdirSync } = builtin("node:fs");
11
12
  parentPort.on("message", ({ id, path, state, gate }) => {
12
13
  const slot = new Int32Array(state);
13
14
  if (Atomics.compareExchange(slot, 0, ${QUEUED}, ${CREATING}) !== ${QUEUED}) {
@@ -1 +1 @@
1
- {"version":3,"file":"settings-lock-directory.js","sourceRoot":"","sources":["../../src/core/settings-lock-directory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAEhE,MAAM,MAAM,GAAG,CAAC,CAAC;AACjB,MAAM,QAAQ,GAAG,CAAC,CAAC;AACnB,MAAM,OAAO,GAAG,CAAC,CAAC;AAClB,MAAM,MAAM,GAAG,CAAC,CAAC;AACjB,MAAM,OAAO,GAAG,CAAC,CAAC;AAElB,MAAM,cAAc,GAAG;;;;;yCAKkB,MAAM,KAAK,QAAQ,SAAS,MAAM;;;;;;;;;;;qCAWtC,MAAM,MAAM,OAAO;;;;CAIvD,CAAC;AAEF,IAAI,eAA8C,CAAC;AAEnD,MAAM,UAAU,4BAA4B,CAAC,IAAmC;IAC/E,eAAe,GAAG,IAAI,CAAC;AACxB,CAAC;AAcD,IAAI,OAA2B,CAAC;AAChC,IAAI,MAAM,GAAG,CAAC,CAAC;AACf,MAAM,OAAO,GAAG,IAAI,GAAG,EAA2B,CAAC;AAEnD,SAAS,aAAa;IACrB,IAAI,OAAO;QAAE,OAAO,OAAO,CAAC;IAC5B,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,cAAc,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,kBAAkB,EAAE,EAAE,CAAC,CAAC;IAC1F,MAAM,CAAC,KAAK,EAAE,CAAC;IACf,MAAM,CA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CREATING = 1;\nconst CREATED = 2;\nconst FAILED = 3;\nconst CLAIMED = 4;\n\nconst CREATOR_SOURCE = `\nconst { parentPort } = require(\"node:worker_threads\");\nconst { mkdirSync } = require(\"node:fs\");\nparentPort.on(\"message\", ({ id, path, state, gate }) => {\n const slot = new Int32Array(state);\n if (Atomics.compareExchange(slot, 0, ${QUEUED}, ${CREATING}) !== ${QUEUED}) {\n parentPort.postMessage({ id, claimed: true });\n return;\n }\n let failure;\n try {\n mkdirSync(path);\n } catch (error) {\n failure = { code: error && error.code, message: String(error && error.message) };\n }\n if (gate) Atomics.wait(new Int32Array(gate), 0, 0);\n Atomics.store(slot, 0, failure ? ${FAILED} : ${CREATED});\n Atomics.notify(slot, 0);\n parentPort.postMessage(failure ? { id, ...failure } : { id });\n});\n`;\n\nlet publicationGate: SharedArrayBuffer | undefined;\n\nexport function gateLockDirectoryPublication(gate: SharedArrayBuffer | undefined): void {\n\tpublicationGate = gate;\n}\n\ninterface CreatorReply {\n\treadonly id: number;\n\treadonly claimed?: boolean;\n\treadonly code?: string;\n\treadonly message?: string;\n}\n\ninterface PendingCreation {\n\treadonly resolve: () => void;\n\treadonly reject: (error: Error) => void;\n}\n\nlet creator: Worker | undefined;\nlet nextId = 0;\nconst pending = new Map<number, PendingCreation>();\n\nfunction creatorWorker(): Worker {\n\tif (creator) return creator;\n\tconst worker = new Worker(CREATOR_SOURCE, { eval: true, execArgv: evalWorkerExecArgv() });\n\tworker.unref();\n\tworker.on(\"message\", (reply: CreatorReply) => {\n\t\tconst creation = pending.get(reply.id);\n\t\tif (!creation) return;\n\t\tpending.delete(reply.id);\n\t\tif (pending.size === 0) worker.unref();\n\t\tif (reply.claimed)\n\t\t\tcreation.reject(\n\t\t\t\tObject.assign(new Error(\"The process exited before the lock was taken\"), { code: \"ECANCELED\" }),\n\t\t\t);\n\t\telse if (reply.code !== undefined || reply.message !== undefined)\n\t\t\tcreation.reject(Object.assign(new Error(reply.message ?? \"mkdir failed\"), { code: reply.code }));\n\t\telse creation.resolve();\n\t});\n\tworker.on(\"error\", (error) => {\n\t\tif (creator === worker) creator = undefined;\n\t\tfor (const [id, creation] of pending) {\n\t\t\tpending.delete(id);\n\t\t\tcreation.reject(error);\n\t\t}\n\t});\n\tcreator = worker;\n\treturn worker;\n}\n\nexport interface LockDirectoryCreation {\n\treadonly created: Promise<void>;\n\treadonly state: Int32Array;\n}\n\nexport function createLockDirectory(path: string): LockDirectoryCreation {\n\tconst state = new SharedArrayBuffer(4);\n\tconst id = nextId++;\n\tconst created = new Promise<void>((resolve, reject) => {\n\t\tpending.set(id, { resolve, reject });\n\t});\n\tconst worker = creatorWorker();\n\tif (pending.size === 1) worker.ref();\n\tworker.postMessage({ id, path, state, gate: publicationGate });\n\treturn { created, state: new Int32Array(state) };\n}\n\nexport function lockDirectoryCreatedBeforeExit(creation: LockDirectoryCreation): boolean {\n\tconst previous = Atomics.compareExchange(creation.state, 0, QUEUED, CLAIMED);\n\tif (previous === QUEUED || previous === CLAIMED) return false;\n\twhile (Atomics.load(creation.state, 0) === CREATING) Atomics.wait(creation.state, 0, CREATING);\n\treturn Atomics.load(creation.state, 0) === CREATED;\n}\n"]}
1
+ {"version":3,"file":"settings-lock-directory.js","sourceRoot":"","sources":["../../src/core/settings-lock-directory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAErF,MAAM,MAAM,GAAG,CAAC,CAAC;AACjB,MAAM,QAAQ,GAAG,CAAC,CAAC;AACnB,MAAM,OAAO,GAAG,CAAC,CAAC;AAClB,MAAM,MAAM,GAAG,CAAC,CAAC;AACjB,MAAM,OAAO,GAAG,CAAC,CAAC;AAElB,MAAM,cAAc,GAAG;EACrB,mBAAmB;;;;;yCAKoB,MAAM,KAAK,QAAQ,SAAS,MAAM;;;;;;;;;;;qCAWtC,MAAM,MAAM,OAAO;;;;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E,OAAO,CAAC,CAAC;IAC7E,IAAI,QAAQ,KAAK,MAAM,IAAI,QAAQ,KAAK,OAAO;QAAE,OAAO,KAAK,CAAC;IAC9D,OAAO,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC,KAAK,QAAQ;QAAE,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,EAAE,QAAQ,CAAC,CAAC;IAC/F,OAAO,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC,KAAK,OAAO,CAAC;AACpD,CAAC","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport { EVAL_WORKER_BUILTIN, evalWorkerExecArgv } from \"../utils/worker-threads.js\";\n\nconst QUEUED = 0;\nconst CREATING = 1;\nconst CREATED = 2;\nconst FAILED = 3;\nconst CLAIMED = 4;\n\nconst CREATOR_SOURCE = `\n${EVAL_WORKER_BUILTIN}\nconst { parentPort } = builtin(\"node:worker_threads\");\nconst { mkdirSync } = builtin(\"node:fs\");\nparentPort.on(\"message\", ({ id, path, state, gate }) => {\n const slot = new Int32Array(state);\n if (Atomics.compareExchange(slot, 0, ${QUEUED}, ${CREATING}) !== ${QUEUED}) {\n parentPort.postMessage({ id, claimed: true });\n return;\n }\n let failure;\n try {\n mkdirSync(path);\n } catch (error) {\n failure = { code: error && error.code, message: String(error && error.message) };\n }\n if (gate) Atomics.wait(new Int32Array(gate), 0, 0);\n Atomics.store(slot, 0, failure ? ${FAILED} : ${CREATED});\n Atomics.notify(slot, 0);\n parentPort.postMessage(failure ? { id, ...failure } : { id });\n});\n`;\n\nlet publicationGate: SharedArrayBuffer | undefined;\n\nexport function gateLockDirectoryPublication(gate: SharedArrayBuffer | undefined): void {\n\tpublicationGate = gate;\n}\n\ninterface CreatorReply {\n\treadonly id: number;\n\treadonly claimed?: boolean;\n\treadonly code?: string;\n\treadonly message?: string;\n}\n\ninterface PendingCreation {\n\treadonly resolve: () => void;\n\treadonly reject: (error: Error) => void;\n}\n\nlet creator: Worker | undefined;\nlet nextId = 0;\nconst pending = new Map<number, PendingCreation>();\n\nfunction creatorWorker(): Worker {\n\tif (creator) return creator;\n\tconst worker = new Worker(CREATOR_SOURCE, { eval: true, execArgv: evalWorkerExecArgv() });\n\tworker.unref();\n\tworker.on(\"message\", (reply: CreatorReply) => {\n\t\tconst creation = pending.get(reply.id);\n\t\tif (!creation) return;\n\t\tpending.delete(reply.id);\n\t\tif (pending.size === 0) worker.unref();\n\t\tif (reply.claimed)\n\t\t\tcreation.reject(\n\t\t\t\tObject.assign(new Error(\"The process exited before the lock was taken\"), { code: \"ECANCELED\" }),\n\t\t\t);\n\t\telse if (reply.code !== undefined || reply.message !== undefined)\n\t\t\tcreation.reject(Object.assign(new Error(reply.message ?? \"mkdir failed\"), { code: reply.code }));\n\t\telse creation.resolve();\n\t});\n\tworker.on(\"error\", (error) => {\n\t\tif (creator === worker) creator = undefined;\n\t\tfor (const [id, creation] of pending) {\n\t\t\tpending.delete(id);\n\t\t\tcreation.reject(error);\n\t\t}\n\t});\n\tcreator = worker;\n\treturn worker;\n}\n\nexport interface LockDirectoryCreation {\n\treadonly created: Promise<void>;\n\treadonly state: Int32Array;\n}\n\nexport function createLockDirectory(path: string): LockDirectoryCreation {\n\tconst state = new SharedArrayBuffer(4);\n\tconst id = nextId++;\n\tconst created = new Promise<void>((resolve, reject) => {\n\t\tpending.set(id, { resolve, reject });\n\t});\n\tconst worker = creatorWorker();\n\tif (pending.size === 1) worker.ref();\n\tworker.postMessage({ id, path, state, gate: publicationGate });\n\treturn { created, state: new Int32Array(state) };\n}\n\nexport function lockDirectoryCreatedBeforeExit(creation: LockDirectoryCreation): boolean {\n\tconst previous = Atomics.compareExchange(creation.state, 0, QUEUED, CLAIMED);\n\tif (previous === QUEUED || previous === CLAIMED) return false;\n\twhile (Atomics.load(creation.state, 0) === CREATING) Atomics.wait(creation.state, 0, CREATING);\n\treturn Atomics.load(creation.state, 0) === CREATED;\n}\n"]}
@@ -1,6 +1,5 @@
1
- import { AsyncLocalStorage } from "node:async_hooks";
2
1
  import type { SettingsScope } from "./settings-types.ts";
3
- export declare const settingsWriteOwner: AsyncLocalStorage<object>;
2
+ export declare const settingsWriteOwner: import("./async-scope.ts").AsyncScope<object>;
4
3
  export declare const ownedSettingsManagers: WeakMap<object, object>;
5
4
  export declare function recordSettingsWrite(owner: object | undefined, scope: SettingsScope, error?: unknown): void;
6
5
  export declare function assertSettingsWrites(owner: object): void;
@@ -1 +1 @@
1
- {"version":3,"file":"settings-write-ownership.d.ts","sourceRoot":"","sources":["../../src/core/settings-write-ownership.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGzD,eAAO,MAAM,kBAAkB,2BAAkC,CAAC;AAClE,eAAO,MAAM,qBAAqB,yBAAgC,CAAC;AAEnE,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAAE,KAAK,EAAE,aAAa,EAAE,KAAK,CAAC,EAAE,OAAO,GAAG,IAAI,CAS1G;AACD,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAGxD"}
1
+ {"version":3,"file":"settings-write-ownership.d.ts","sourceRoot":"","sources":["../../src/core/settings-write-ownership.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGzD,eAAO,MAAM,kBAAkB,+CAAuB,CAAC;AACvD,eAAO,MAAM,qBAAqB,yBAAgC,CAAC;AAEnE,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAAE,KAAK,EAAE,aAAa,EAAE,KAAK,CAAC,EAAE,OAAO,GAAG,IAAI,CAS1G;AACD,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAGxD"}
@@ -1,6 +1,6 @@
1
- import { AsyncLocalStorage } from "node:async_hooks";
1
+ import { asyncScope } from "./async-scope.js";
2
2
  // Internal write receipts: do not drain the manager's caller-owned error channel.
3
- export const settingsWriteOwner = new AsyncLocalStorage();
3
+ export const settingsWriteOwner = asyncScope();
4
4
  export const ownedSettingsManagers = new WeakMap();
5
5
  const failures = new WeakMap();
6
6
  export function recordSettingsWrite(owner, scope, error) {
@@ -1 +1 @@
1
- {"version":3,"file":"settings-write-ownership.js","sourceRoot":"","sources":["../../src/core/settings-write-ownership.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAGrD,kFAAkF;AAClF,MAAM,CAAC,MAAM,kBAAkB,GAAG,IAAI,iBAAiB,EAAU,CAAC;AAClE,MAAM,CAAC,MAAM,qBAAqB,GAAG,IAAI,OAAO,EAAkB,CAAC;AACnE,MAAM,QAAQ,GAAG,IAAI,OAAO,EAAuC,CAAC;AACpE,MAAM,UAAU,mBAAmB,CAAC,KAAyB,EAAE,KAAoB,EAAE,KAAe;IACnG,IAAI,CAAC,KAAK;QAAE,OAAO;IACnB,IAAI,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAClC,IAAI,CAAC,OAAO,EAAE,CAAC;QACd,OAAO,GAAG,IAAI,GAAG,EAAE,CAAC;QACpB,QAAQ,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAC9B,CAAC;IACD,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;;QAC1C,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;AAChC,CAAC;AACD,MAAM,UAAU,oBAAoB,CAAC,KAAa;IACjD,MAAM,MAAM,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IAC1D,IAAI,MAAM,CAAC,MAAM;QAAE,MAAM,IAAI,cAAc,CAAC,MAAM,EAAE,6BAA6B,CAAC,CAAC;AACpF,CAAC","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { SettingsScope } from \"./settings-types.ts\";\n\n// Internal write receipts: do not drain the manager's caller-owned error channel.\nexport const settingsWriteOwner = new AsyncLocalStorage<object>();\nexport const ownedSettingsManagers = new WeakMap<object, object>();\nconst failures = new WeakMap<object, Map<SettingsScope, unknown>>();\nexport function recordSettingsWrite(owner: object | undefined, scope: SettingsScope, error?: unknown): void {\n\tif (!owner) return;\n\tlet receipt = failures.get(owner);\n\tif (!receipt) {\n\t\treceipt = new Map();\n\t\tfailures.set(owner, receipt);\n\t}\n\tif (error === undefined) receipt.delete(scope);\n\telse receipt.set(scope, error);\n}\nexport function assertSettingsWrites(owner: object): void {\n\tconst errors = [...(failures.get(owner)?.values() ?? [])];\n\tif (errors.length) throw new AggregateError(errors, \"Settings persistence failed\");\n}\n"]}
1
+ {"version":3,"file":"settings-write-ownership.js","sourceRoot":"","sources":["../../src/core/settings-write-ownership.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAG9C,kFAAkF;AAClF,MAAM,CAAC,MAAM,kBAAkB,GAAG,UAAU,EAAU,CAAC;AACvD,MAAM,CAAC,MAAM,qBAAqB,GAAG,IAAI,OAAO,EAAkB,CAAC;AACnE,MAAM,QAAQ,GAAG,IAAI,OAAO,EAAuC,CAAC;AACpE,MAAM,UAAU,mBAAmB,CAAC,KAAyB,EAAE,KAAoB,EAAE,KAAe;IACnG,IAAI,CAAC,KAAK;QAAE,OAAO;IACnB,IAAI,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAClC,IAAI,CAAC,OAAO,EAAE,CAAC;QACd,OAAO,GAAG,IAAI,GAAG,EAAE,CAAC;QACpB,QAAQ,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAC9B,CAAC;IACD,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;;QAC1C,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;AAChC,CAAC;AACD,MAAM,UAAU,oBAAoB,CAAC,KAAa;IACjD,MAAM,MAAM,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IAC1D,IAAI,MAAM,CAAC,MAAM;QAAE,MAAM,IAAI,cAAc,CAAC,MAAM,EAAE,6BAA6B,CAAC,CAAC;AACpF,CAAC","sourcesContent":["import { asyncScope } from \"./async-scope.ts\";\nimport type { SettingsScope } from \"./settings-types.ts\";\n\n// Internal write receipts: do not drain the manager's caller-owned error channel.\nexport const settingsWriteOwner = asyncScope<object>();\nexport const ownedSettingsManagers = new WeakMap<object, object>();\nconst failures = new WeakMap<object, Map<SettingsScope, unknown>>();\nexport function recordSettingsWrite(owner: object | undefined, scope: SettingsScope, error?: unknown): void {\n\tif (!owner) return;\n\tlet receipt = failures.get(owner);\n\tif (!receipt) {\n\t\treceipt = new Map();\n\t\tfailures.set(owner, receipt);\n\t}\n\tif (error === undefined) receipt.delete(scope);\n\telse receipt.set(scope, error);\n}\nexport function assertSettingsWrites(owner: object): void {\n\tconst errors = [...(failures.get(owner)?.values() ?? [])];\n\tif (errors.length) throw new AggregateError(errors, \"Settings persistence failed\");\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"node-sqlite-thread.d.ts","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite-thread.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE7E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;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_WORKER_BUILTIN } from "../../utils/worker-threads.js";
2
3
  import { sqliteDialect } from "./dialect.js";
3
4
  /**
4
5
  * A node:sqlite connection that runs on a worker thread of its own (#5376). The thread owns the `DatabaseSync`; the
@@ -8,9 +9,10 @@ import { sqliteDialect } from "./dialect.js";
8
9
  * finishing.
9
10
  */
10
11
  const CONNECTION_SOURCE = `
11
- const { parentPort, workerData } = require("node:worker_threads");
12
+ ${EVAL_WORKER_BUILTIN}
13
+ const { parentPort, workerData } = builtin("node:worker_threads");
12
14
  process.emitWarning = () => {};
13
- const { DatabaseSync } = require("node:sqlite");
15
+ const { DatabaseSync } = builtin("node:sqlite");
14
16
  let database;
15
17
 
16
18
  const STANDARD_ERRORS = [Error, TypeError, RangeError, SyntaxError, ReferenceError, EvalError, URIError];
@@ -275,8 +277,8 @@ export class ThreadConnection {
275
277
  ended;
276
278
  closing;
277
279
  constructor() {
278
- // None of the process's own flags: an `--input-type=module` would make this CommonJS source a module, and the
279
- // caller's preloads would run again for every connection. Whether node:sqlite is available was settled by the
280
+ // None of the process's own flags: the caller's preloads would run again for every connection, and its
281
+ // `--input-type=module` would make this source a module. Whether node:sqlite is available was settled by the
280
282
  // open before it started the thread.
281
283
  this.worker = new Worker(CONNECTION_SOURCE, {
282
284
  eval: true,
@@ -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;AAE7C,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAG7C;;;;;;GAMG;AACH,MAAM,iBAAiB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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C;YAAE,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;QACjD,IAAI,KAAK,CAAC,OAAO,KAAK,SAAS;YAAE,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;;YACxD,MAAM,CAAC,MAAM,CAAC,eAAe,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;IACpD,CAAC;IAED,yGAAyG;IACjG,GAAG,CAAC,KAAY;QACvB,IAAI,IAAI,CAAC,KAAK,KAAK,SAAS;YAAE,OAAO;QACrC,iHAAiH;QACjH,6EAA6E;QAC7E,KAAK,KAAK,CAAC,KAAK,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,MAAM,OAAO,GAAG,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;QAC3C,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACrB,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;QACpB,KAAK,MAAM,MAAM,IAAI,OAAO;YAAE,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACpD,CAAC;IAEO,KAAK,CAAC,IAAI;QACjB,IAAI,CAAC,GAAG,CAAC,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;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport type { SqliteRow, SqliteStatement, SqliteValue } from \"./database.js\";\nimport { sqliteDialect } from \"./dialect.js\";\nimport type { 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 = `\nconst { parentPort, workerData } = require(\"node:worker_threads\");\nprocess.emitWarning = () => {};\nconst { DatabaseSync } = require(\"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 } of request.statements) {\n\t\t\tif (aborted()) return { aborted: true };\n\t\t\tstatement(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 SqliteStatement[];\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/** 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: an `--input-type=module` would make this CommonJS source a module, and the\n\t\t// caller's preloads would run again for every connection. 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 connection = new ThreadConnection();\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"]}
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,mBAAmB,EAAE,MAAM,+BAA+B,CA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QAC1B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IACpC,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport { EVAL_WORKER_BUILTIN } from \"../../utils/worker-threads.js\";\nimport type { SqliteRow, SqliteStatement, SqliteValue } from \"./database.js\";\nimport { sqliteDialect } from \"./dialect.js\";\nimport type { 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 } of request.statements) {\n\t\t\tif (aborted()) return { aborted: true };\n\t\t\tstatement(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 SqliteStatement[];\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/** 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 connection = new ThreadConnection();\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"]}
@@ -1 +1 @@
1
- {"version":3,"file":"node-sqlite.d.ts","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite.ts"],"names":[],"mappings":"AA4BA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAKhD,OAAO,KAAK,EACX,cAAc,EAOd,MAAM,eAAe,CAAC;AAEvB,OAAO,EAaN,+BAA+B,EAI/B,MAAM,aAAa,CAAC;AAmoBrB,wBAAgB,kBAAkB,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAE/D;AAqYD;;;;GAIG;AACH,eAAO,MAAM,4BAA4B,MAAM,CAAC;AA4BhD,mHAAmH;AACnH,MAAM,WAAW,gBAAgB;IAChC,sHAAsH;IACtH,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,oHAAoH;IACpH,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,wGAAwG;IACxG,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,0FAA0F;IAC1F,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,6DAA6D;IAC7D,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;CAClC;AAwkCD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,GAAE,MAAM,CAAC,QAA2B,GAAG,MAAM,CAGjG;AAED,2GAA2G;AAC3G,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,MAAM,GAAG,IAAI,EAAE,QAAQ,EAAE,CAAC,GAAG,CAAC,CAK1E;AA6BD,wBAAsB,sBAAsB,CAC3C,IAAI,EAAE,MAAM,EACZ,EACC,aAAoB,EACpB,UAA6C,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IG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,GAAE,MAAM,CAAC,QAA2B,GAAG,MAAM,CAGjG;AAED,2GAA2G;AAC3G,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,MAAM,GAAG,IAAI,EAAE,QAAQ,EAAE,CAAC,GAAG,CAAC,CAK1E;AA6BD,wBAAsB,sBAAsB,CAC3C,IAAI,EAAE,MAAM,EACZ,EACC,aAAoB,EACpB,UAA6C,EAC7C,QAAgB,EAChB,iBAAiB,GACjB,GAAE;IACF,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;CACtB,GACJ,OAAO,CAAC,cAAc,CAAC,CAsEzB;AAKD,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,YAAY,GAAG,cAAc,CAwB/E;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,cAAc,GAAG,gBAAgB,CAI9E;AAED;;;;;;;;GAQG;AACH,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,cAAc,GAAG,SAAS,+BAA+B,EAAE,CAI9G"}
@@ -1187,6 +1187,24 @@ function sendableStatement({ sql, params }) {
1187
1187
  function invalidTextParam(params) {
1188
1188
  return params.findIndex((value) => typeof value === "string" && value.includes("\0"));
1189
1189
  }
1190
+ const signalWatches = new WeakMap();
1191
+ /** Starts watching `signal` for a sequence; `unwatchSignal` ends that sequence's watch. */
1192
+ function watchSignal(signal) {
1193
+ let watch = signalWatches.get(signal);
1194
+ if (watch === undefined) {
1195
+ const flag = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT);
1196
+ const raised = new Int32Array(flag);
1197
+ watch = { derived: AbortSignal.any([signal]), flag, raise: () => Atomics.store(raised, 0, 1), running: 0 };
1198
+ signalWatches.set(signal, watch);
1199
+ }
1200
+ if (watch.running++ === 0)
1201
+ watch.derived.addEventListener("abort", watch.raise);
1202
+ return watch;
1203
+ }
1204
+ function unwatchSignal(watch) {
1205
+ if (--watch.running === 0)
1206
+ watch.derived.removeEventListener("abort", watch.raise);
1207
+ }
1190
1208
  class NodeSqliteDatabase {
1191
1209
  descriptor;
1192
1210
  connection;
@@ -1574,12 +1592,7 @@ class NodeSqliteDatabase {
1574
1592
  signal?.throwIfAborted();
1575
1593
  throw new StorageInvalidTextError(repeatInvalid);
1576
1594
  }
1577
- const shared = signal === undefined ? undefined : new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT);
1578
- // Only an actual abort of `signal` reaches a signal made from it: no other listener can keep the event from this
1579
- // one, and an abort event dispatched on `signal` without aborting it does not reach it.
1580
- const watched = signal === undefined ? undefined : AbortSignal.any([signal]);
1581
- const raise = () => Atomics.store(new Int32Array(shared), 0, 1);
1582
- watched?.addEventListener("abort", raise);
1595
+ const watch = signal === undefined ? undefined : watchSignal(signal);
1583
1596
  try {
1584
1597
  const pending = statements[Symbol.iterator]();
1585
1598
  let invalid = -1;
@@ -1611,7 +1624,7 @@ class NodeSqliteDatabase {
1611
1624
  ? { repeat: { ...repeats, statement: sendableStatement(repeats.statement) } }
1612
1625
  : {}),
1613
1626
  statements: batch,
1614
- ...(shared === undefined ? {} : { abort: shared }),
1627
+ ...(watch === undefined ? {} : { abort: watch.flag }),
1615
1628
  };
1616
1629
  const answer = (await connection.request(request).catch((cause) => {
1617
1630
  throw unavailable(this.descriptor, cause);
@@ -1628,7 +1641,8 @@ class NodeSqliteDatabase {
1628
1641
  return repeated;
1629
1642
  }
1630
1643
  finally {
1631
- watched?.removeEventListener("abort", raise);
1644
+ if (watch !== undefined)
1645
+ unwatchSignal(watch);
1632
1646
  }
1633
1647
  }
1634
1648
  enqueue(operation) {