@bastani/atomic 0.10.0-alpha.1 → 0.10.1-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 (234) hide show
  1. package/CHANGELOG.md +211 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +22 -0
  3. package/dist/builtin/intercom/package.json +1 -1
  4. package/dist/builtin/mcp/package.json +1 -1
  5. package/dist/builtin/subagents/CHANGELOG.md +35 -0
  6. package/dist/builtin/subagents/package.json +1 -1
  7. package/dist/builtin/subagents/skills/tmux/scripts/wait-for-text.sh +33 -3
  8. package/dist/builtin/web-access/package.json +1 -1
  9. package/dist/core/agent-session-events.d.ts.map +1 -1
  10. package/dist/core/agent-session-events.js +21 -6
  11. package/dist/core/agent-session-events.js.map +1 -1
  12. package/dist/core/lifecycle-timings.d.ts +6 -0
  13. package/dist/core/lifecycle-timings.d.ts.map +1 -1
  14. package/dist/core/lifecycle-timings.js +12 -0
  15. package/dist/core/lifecycle-timings.js.map +1 -1
  16. package/dist/core/queued-message-delivery.d.ts +41 -0
  17. package/dist/core/queued-message-delivery.d.ts.map +1 -0
  18. package/dist/core/queued-message-delivery.js +48 -0
  19. package/dist/core/queued-message-delivery.js.map +1 -0
  20. package/dist/core/storage/node-sqlite-thread.d.ts +64 -0
  21. package/dist/core/storage/node-sqlite-thread.d.ts.map +1 -0
  22. package/dist/core/storage/node-sqlite-thread.js +326 -0
  23. package/dist/core/storage/node-sqlite-thread.js.map +1 -0
  24. package/dist/core/storage/node-sqlite.d.ts.map +1 -1
  25. package/dist/core/storage/node-sqlite.js +230 -104
  26. package/dist/core/storage/node-sqlite.js.map +1 -1
  27. package/dist/core/tasks/agent-panel-source.d.ts +5 -0
  28. package/dist/core/tasks/agent-panel-source.d.ts.map +1 -1
  29. package/dist/core/tasks/agent-panel-source.js +1 -1
  30. package/dist/core/tasks/agent-panel-source.js.map +1 -1
  31. package/dist/modes/interactive/agent-view/agent-view-bridge.d.ts +8 -1
  32. package/dist/modes/interactive/agent-view/agent-view-bridge.d.ts.map +1 -1
  33. package/dist/modes/interactive/agent-view/agent-view-bridge.js.map +1 -1
  34. package/dist/modes/interactive/agent-view/agent-view-switcher.d.ts +11 -5
  35. package/dist/modes/interactive/agent-view/agent-view-switcher.d.ts.map +1 -1
  36. package/dist/modes/interactive/agent-view/agent-view-switcher.js +17 -5
  37. package/dist/modes/interactive/agent-view/agent-view-switcher.js.map +1 -1
  38. package/dist/modes/interactive/agent-view/contracts.d.ts +5 -0
  39. package/dist/modes/interactive/agent-view/contracts.d.ts.map +1 -1
  40. package/dist/modes/interactive/agent-view/contracts.js.map +1 -1
  41. package/dist/modes/interactive/agent-view/install.d.ts.map +1 -1
  42. package/dist/modes/interactive/agent-view/install.js +6 -3
  43. package/dist/modes/interactive/agent-view/install.js.map +1 -1
  44. package/dist/modes/interactive/agent-view/local-port.d.ts +5 -0
  45. package/dist/modes/interactive/agent-view/local-port.d.ts.map +1 -1
  46. package/dist/modes/interactive/agent-view/local-port.js +8 -0
  47. package/dist/modes/interactive/agent-view/local-port.js.map +1 -1
  48. package/dist/modes/interactive/agent-view/remote-port.d.ts +4 -1
  49. package/dist/modes/interactive/agent-view/remote-port.d.ts.map +1 -1
  50. package/dist/modes/interactive/agent-view/remote-port.js +22 -8
  51. package/dist/modes/interactive/agent-view/remote-port.js.map +1 -1
  52. package/dist/modes/interactive/agent-view/transcript-slot.d.ts +9 -0
  53. package/dist/modes/interactive/agent-view/transcript-slot.d.ts.map +1 -1
  54. package/dist/modes/interactive/agent-view/transcript-slot.js +141 -1
  55. package/dist/modes/interactive/agent-view/transcript-slot.js.map +1 -1
  56. package/dist/modes/interactive/components/agent-panel.d.ts +6 -0
  57. package/dist/modes/interactive/components/agent-panel.d.ts.map +1 -1
  58. package/dist/modes/interactive/components/agent-panel.js +40 -10
  59. package/dist/modes/interactive/components/agent-panel.js.map +1 -1
  60. package/dist/modes/interactive/components/atomic-working-status.d.ts +15 -0
  61. package/dist/modes/interactive/components/atomic-working-status.d.ts.map +1 -1
  62. package/dist/modes/interactive/components/atomic-working-status.js +51 -3
  63. package/dist/modes/interactive/components/atomic-working-status.js.map +1 -1
  64. package/dist/modes/interactive/components/bash-execution.d.ts +2 -0
  65. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  66. package/dist/modes/interactive/components/bash-execution.js +5 -1
  67. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  68. package/dist/modes/interactive/components/branch-summary-message.d.ts +2 -0
  69. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  70. package/dist/modes/interactive/components/branch-summary-message.js +5 -1
  71. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  72. package/dist/modes/interactive/components/chat-message-renderer.d.ts +2 -0
  73. package/dist/modes/interactive/components/chat-message-renderer.d.ts.map +1 -1
  74. package/dist/modes/interactive/components/chat-message-renderer.js +17 -6
  75. package/dist/modes/interactive/components/chat-message-renderer.js.map +1 -1
  76. package/dist/modes/interactive/components/chat-session-host-events.d.ts.map +1 -1
  77. package/dist/modes/interactive/components/chat-session-host-events.js +35 -4
  78. package/dist/modes/interactive/components/chat-session-host-events.js.map +1 -1
  79. package/dist/modes/interactive/components/chat-session-host-rendering.d.ts.map +1 -1
  80. package/dist/modes/interactive/components/chat-session-host-rendering.js +70 -13
  81. package/dist/modes/interactive/components/chat-session-host-rendering.js.map +1 -1
  82. package/dist/modes/interactive/components/chat-session-host-runtime.d.ts +7 -0
  83. package/dist/modes/interactive/components/chat-session-host-runtime.d.ts.map +1 -1
  84. package/dist/modes/interactive/components/chat-session-host-runtime.js +25 -4
  85. package/dist/modes/interactive/components/chat-session-host-runtime.js.map +1 -1
  86. package/dist/modes/interactive/components/chat-session-host-state.d.ts +41 -1
  87. package/dist/modes/interactive/components/chat-session-host-state.d.ts.map +1 -1
  88. package/dist/modes/interactive/components/chat-session-host-state.js +24 -3
  89. package/dist/modes/interactive/components/chat-session-host-state.js.map +1 -1
  90. package/dist/modes/interactive/components/chat-session-host-steering.d.ts.map +1 -1
  91. package/dist/modes/interactive/components/chat-session-host-steering.js +2 -1
  92. package/dist/modes/interactive/components/chat-session-host-steering.js.map +1 -1
  93. package/dist/modes/interactive/components/chat-session-host.d.ts +13 -1
  94. package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
  95. package/dist/modes/interactive/components/chat-session-host.js +20 -2
  96. package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
  97. package/dist/modes/interactive/components/chat-transcript.d.ts +15 -0
  98. package/dist/modes/interactive/components/chat-transcript.d.ts.map +1 -1
  99. package/dist/modes/interactive/components/chat-transcript.js +14 -1
  100. package/dist/modes/interactive/components/chat-transcript.js.map +1 -1
  101. package/dist/modes/interactive/components/compaction-boundary-message.d.ts +2 -0
  102. package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
  103. package/dist/modes/interactive/components/compaction-boundary-message.js +5 -1
  104. package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
  105. package/dist/modes/interactive/components/custom-entry.d.ts +2 -0
  106. package/dist/modes/interactive/components/custom-entry.d.ts.map +1 -1
  107. package/dist/modes/interactive/components/custom-entry.js +5 -1
  108. package/dist/modes/interactive/components/custom-entry.js.map +1 -1
  109. package/dist/modes/interactive/components/custom-message.d.ts +2 -0
  110. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  111. package/dist/modes/interactive/components/custom-message.js +5 -1
  112. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  113. package/dist/modes/interactive/components/model-column.d.ts +96 -0
  114. package/dist/modes/interactive/components/model-column.d.ts.map +1 -0
  115. package/dist/modes/interactive/components/model-column.js +207 -0
  116. package/dist/modes/interactive/components/model-column.js.map +1 -0
  117. package/dist/modes/interactive/components/prompt-slot.d.ts +73 -0
  118. package/dist/modes/interactive/components/prompt-slot.d.ts.map +1 -0
  119. package/dist/modes/interactive/components/prompt-slot.js +201 -0
  120. package/dist/modes/interactive/components/prompt-slot.js.map +1 -0
  121. package/dist/modes/interactive/components/queued-messages-view.d.ts +6 -3
  122. package/dist/modes/interactive/components/queued-messages-view.d.ts.map +1 -1
  123. package/dist/modes/interactive/components/queued-messages-view.js +7 -4
  124. package/dist/modes/interactive/components/queued-messages-view.js.map +1 -1
  125. package/dist/modes/interactive/components/session-selector.d.ts +2 -0
  126. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  127. package/dist/modes/interactive/components/session-selector.js +4 -0
  128. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  129. package/dist/modes/interactive/components/skill-invocation-message.d.ts +2 -0
  130. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  131. package/dist/modes/interactive/components/skill-invocation-message.js +5 -1
  132. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  133. package/dist/modes/interactive/components/task-board.d.ts +12 -3
  134. package/dist/modes/interactive/components/task-board.d.ts.map +1 -1
  135. package/dist/modes/interactive/components/task-board.js +33 -17
  136. package/dist/modes/interactive/components/task-board.js.map +1 -1
  137. package/dist/modes/interactive/components/task-inspector.d.ts +6 -1
  138. package/dist/modes/interactive/components/task-inspector.d.ts.map +1 -1
  139. package/dist/modes/interactive/components/task-inspector.js +27 -7
  140. package/dist/modes/interactive/components/task-inspector.js.map +1 -1
  141. package/dist/modes/interactive/components/task-row.d.ts +4 -0
  142. package/dist/modes/interactive/components/task-row.d.ts.map +1 -1
  143. package/dist/modes/interactive/components/task-row.js +7 -1
  144. package/dist/modes/interactive/components/task-row.js.map +1 -1
  145. package/dist/modes/interactive/components/task-transcript-page.d.ts +5 -0
  146. package/dist/modes/interactive/components/task-transcript-page.d.ts.map +1 -1
  147. package/dist/modes/interactive/components/task-transcript-page.js +25 -0
  148. package/dist/modes/interactive/components/task-transcript-page.js.map +1 -1
  149. package/dist/modes/interactive/components/tool-execution.d.ts +7 -0
  150. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  151. package/dist/modes/interactive/components/tool-execution.js +19 -2
  152. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  153. package/dist/modes/interactive/components/tool-group-tracker.d.ts +20 -3
  154. package/dist/modes/interactive/components/tool-group-tracker.d.ts.map +1 -1
  155. package/dist/modes/interactive/components/tool-group-tracker.js +34 -7
  156. package/dist/modes/interactive/components/tool-group-tracker.js.map +1 -1
  157. package/dist/modes/interactive/components/transcript-block-clicks.d.ts +14 -2
  158. package/dist/modes/interactive/components/transcript-block-clicks.d.ts.map +1 -1
  159. package/dist/modes/interactive/components/transcript-block-clicks.js +23 -2
  160. package/dist/modes/interactive/components/transcript-block-clicks.js.map +1 -1
  161. package/dist/modes/interactive/interactive-agent-events.js +10 -2
  162. package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
  163. package/dist/modes/interactive/interactive-extension-runtime.d.ts +12 -1
  164. package/dist/modes/interactive/interactive-extension-runtime.d.ts.map +1 -1
  165. package/dist/modes/interactive/interactive-extension-runtime.js +37 -5
  166. package/dist/modes/interactive/interactive-extension-runtime.js.map +1 -1
  167. package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
  168. package/dist/modes/interactive/interactive-input-handling.js +70 -46
  169. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  170. package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
  171. package/dist/modes/interactive/interactive-mode-base.js +7 -1
  172. package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
  173. package/dist/modes/interactive/interactive-prompt-turn.js +17 -9
  174. package/dist/modes/interactive/interactive-prompt-turn.js.map +1 -1
  175. package/dist/modes/interactive/interactive-queueing.d.ts.map +1 -1
  176. package/dist/modes/interactive/interactive-queueing.js +2 -1
  177. package/dist/modes/interactive/interactive-queueing.js.map +1 -1
  178. package/dist/modes/interactive/interactive-render-chat.d.ts +18 -1
  179. package/dist/modes/interactive/interactive-render-chat.d.ts.map +1 -1
  180. package/dist/modes/interactive/interactive-render-chat.js +90 -10
  181. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  182. package/dist/modes/interactive/interactive-session-routing.js +2 -0
  183. package/dist/modes/interactive/interactive-session-routing.js.map +1 -1
  184. package/dist/modes/interactive/interactive-task-projection.js +2 -2
  185. package/dist/modes/interactive/interactive-task-projection.js.map +1 -1
  186. package/dist/modes/interactive/screen-hold.d.ts +41 -0
  187. package/dist/modes/interactive/screen-hold.d.ts.map +1 -0
  188. package/dist/modes/interactive/screen-hold.js +80 -0
  189. package/dist/modes/interactive/screen-hold.js.map +1 -0
  190. package/dist/modes/interactive/started-run-echo.d.ts +66 -0
  191. package/dist/modes/interactive/started-run-echo.d.ts.map +1 -0
  192. package/dist/modes/interactive/started-run-echo.js +75 -0
  193. package/dist/modes/interactive/started-run-echo.js.map +1 -0
  194. package/dist/modes/interactive-engine/engine-custom-ui.d.ts +1 -0
  195. package/dist/modes/interactive-engine/engine-custom-ui.d.ts.map +1 -1
  196. package/dist/modes/interactive-engine/engine-custom-ui.js +25 -1
  197. package/dist/modes/interactive-engine/engine-custom-ui.js.map +1 -1
  198. package/dist/modes/interactive-engine/engine-quit-intent.d.ts.map +1 -1
  199. package/dist/modes/interactive-engine/engine-quit-intent.js +3 -0
  200. package/dist/modes/interactive-engine/engine-quit-intent.js.map +1 -1
  201. package/dist/modes/interactive-engine/protocol.d.ts +5 -0
  202. package/dist/modes/interactive-engine/protocol.d.ts.map +1 -1
  203. package/dist/modes/interactive-engine/protocol.js +7 -1
  204. package/dist/modes/interactive-engine/protocol.js.map +1 -1
  205. package/dist/modes/interactive-engine/remote-component.d.ts +10 -2
  206. package/dist/modes/interactive-engine/remote-component.d.ts.map +1 -1
  207. package/dist/modes/interactive-engine/remote-component.js +19 -2
  208. package/dist/modes/interactive-engine/remote-component.js.map +1 -1
  209. package/dist/modes/interactive-engine/remote-renderer.d.ts +10 -0
  210. package/dist/modes/interactive-engine/remote-renderer.d.ts.map +1 -1
  211. package/dist/modes/interactive-engine/remote-renderer.js +24 -4
  212. package/dist/modes/interactive-engine/remote-renderer.js.map +1 -1
  213. package/dist/modes/interactive-engine/transcript-frame-layout.d.ts +50 -0
  214. package/dist/modes/interactive-engine/transcript-frame-layout.d.ts.map +1 -0
  215. package/dist/modes/interactive-engine/transcript-frame-layout.js +95 -0
  216. package/dist/modes/interactive-engine/transcript-frame-layout.js.map +1 -0
  217. package/dist/modes/rpc/agent-panel-bridge.d.ts.map +1 -1
  218. package/dist/modes/rpc/agent-panel-bridge.js +16 -0
  219. package/dist/modes/rpc/agent-panel-bridge.js.map +1 -1
  220. package/dist/modes/rpc/agent-view-engine-registry.d.ts.map +1 -1
  221. package/dist/modes/rpc/agent-view-engine-registry.js +36 -1
  222. package/dist/modes/rpc/agent-view-engine-registry.js.map +1 -1
  223. package/dist/modes/rpc/agent-view-rpc-panel.d.ts.map +1 -1
  224. package/dist/modes/rpc/agent-view-rpc-panel.js +5 -1
  225. package/dist/modes/rpc/agent-view-rpc-panel.js.map +1 -1
  226. package/dist/modes/rpc/task-ui-bridge.js +1 -1
  227. package/dist/modes/rpc/task-ui-bridge.js.map +1 -1
  228. package/docs/background-tasks.md +1 -1
  229. package/docs/development.md +2 -0
  230. package/docs/extensions/authoring.md +1 -1
  231. package/docs/keybindings.md +2 -2
  232. package/docs/storage.md +1 -0
  233. package/npm-shrinkwrap.json +49 -49
  234. package/package.json +6 -6
@@ -5,8 +5,10 @@ import { platform } from "node:os";
5
5
  import { basename, dirname, join, resolve, win32 } from "node:path";
6
6
  import { fileURLToPath, pathToFileURL } from "node:url";
7
7
  import { promisify } from "node:util";
8
+ import { isSharedArrayBuffer, isUint8Array } from "node:util/types";
8
9
  import { sqliteDialect } from "./dialect.js";
9
10
  import { payloadTooLargeKind, SQLITE_PAYLOAD_LIMITS, StorageAdapterLoadError, StorageConfigError, StorageInvalidTextError, StoragePayloadTooLargeError, StorageRollbackError, StorageTransactionClosedError, StorageUnavailableError, StorageUnsupportedOperationError, StorageWriteLockTimeoutError, StorageWriterQueueDegradedError, StorageWriterQueueUnusableError, StoreClosedError, } from "./errors.js";
11
+ import { ThreadConnection } from "./node-sqlite-thread.js";
10
12
  import { isSqliteBusy, switchToWriteAheadLog, switchToWriteAheadLogSync } from "./write-ahead-log.js";
11
13
  /** Loaded at the first degradation only, so opening a database does not load debug output. */
12
14
  let debugOutput;
@@ -36,13 +38,17 @@ const TICKET_TIME = /^(\d{15})-/;
36
38
  const DATABASE_NOW = `SELECT ${sqliteDialect.nowMs} AS now`;
37
39
  /** An in-memory connection of the process's own, which the database clock is read through. */
38
40
  let clockConnection;
41
+ /** node:sqlite's connection class, once an open loaded it. */
42
+ let loadedDatabaseSync;
39
43
  /**
40
44
  * Now on the clock SQLite reads for `unixepoch()`: the system clock, which every process shares, whatever this
41
45
  * process's own says. SQLite reads it from the operating system, not from a database file, so a connection of the
42
- * process's own reads the same time as every handle's, and a handle can read it after it is closed.
46
+ * process's own reads the same time as every handle's, and a handle can read it after it is closed. A connection on a
47
+ * thread of its own reads it there; this reads it on the calling thread, for a connection there and for the
48
+ * synchronous `getWriterQueueStats`.
43
49
  */
44
- function databaseNow(Database) {
45
- clockConnection ??= new Database(":memory:");
50
+ function databaseNow() {
51
+ clockConnection ??= new loadedDatabaseSync(":memory:");
46
52
  return Number(clockConnection.prepare(DATABASE_NOW).get().now);
47
53
  }
48
54
  let ticketSequence = 0;
@@ -111,7 +117,7 @@ class SqliteWriteQueue {
111
117
  directory;
112
118
  noticeDirectory;
113
119
  degraded;
114
- /** Now on the database's clock, in milliseconds. */
120
+ /** Now on the database's clock, in milliseconds, read where the connection runs. */
115
121
  now;
116
122
  observedAt;
117
123
  /** Time this writer was seen to run while it looked at the queue; see `advance`. */
@@ -311,7 +317,7 @@ class SqliteWriteQueue {
311
317
  // An empty queue, as contention leaves it, is read without the clock.
312
318
  if (names.length === 0)
313
319
  return [];
314
- const now = this.now();
320
+ const now = databaseNow();
315
321
  const entries = [];
316
322
  for (const name of names.sort()) {
317
323
  if (name === except)
@@ -358,7 +364,7 @@ class SqliteWriteQueue {
358
364
  else if (!isVanishedTicket(entry.error))
359
365
  throw entry.error;
360
366
  }
361
- const { live, abandoned } = this.judge(entries, this.now());
367
+ const { live, abandoned } = this.judge(entries, await this.now());
362
368
  for (const name of abandoned)
363
369
  await this.removeEntryOffLoop(name);
364
370
  return live;
@@ -388,7 +394,7 @@ class SqliteWriteTicket {
388
394
  if (performance.now() - this.refreshed < TICKET_REFRESH_MS)
389
395
  return false;
390
396
  this.refreshed = performance.now();
391
- const now = new Date(this.queue.now());
397
+ const now = new Date(await this.queue.now());
392
398
  try {
393
399
  await utimes(this.path, now, now);
394
400
  return false;
@@ -634,6 +640,24 @@ function sqliteTargetFilePath(spec) {
634
640
  return undefined;
635
641
  }
636
642
  }
643
+ /**
644
+ * Whether SQLite opens `spec` as an in-memory database: `:memory:`, `file::memory:`, or a `file:` URI whose last `mode`
645
+ * parameter, the one SQLite applies, is `memory`. Anything else, a URI this cannot read included, may be a file.
646
+ */
647
+ function isInMemoryDatabase(spec) {
648
+ if (spec === ":memory:")
649
+ return true;
650
+ if (!spec.startsWith("file:"))
651
+ return false;
652
+ const hashIndex = spec.indexOf("#");
653
+ const withoutHash = hashIndex === -1 ? spec : spec.slice(0, hashIndex);
654
+ const queryIndex = withoutHash.indexOf("?");
655
+ const uriPart = queryIndex === -1 ? withoutHash : withoutHash.slice(0, queryIndex);
656
+ if (uriPart === "file::memory:")
657
+ return true;
658
+ const query = new URLSearchParams(queryIndex === -1 ? "" : withoutHash.slice(queryIndex + 1));
659
+ return query.getAll("mode").at(-1) === "memory";
660
+ }
637
661
  function isMissingOpenLockDir(error) {
638
662
  if (isMissingFile(error))
639
663
  return true;
@@ -673,7 +697,10 @@ async function acquireOpenLock(filePath, readOnly, busyTimeoutMs) {
673
697
  let lock = null;
674
698
  let refusal;
675
699
  try {
676
- lock = locks.trySharedAdvisoryLock(sqliteFilePath(lockPath), 0);
700
+ lock =
701
+ locks.trySharedAdvisoryLockAsync === undefined
702
+ ? legacySharedOpenLock(locks, sqliteFilePath(lockPath))
703
+ : await locks.trySharedAdvisoryLockAsync(sqliteFilePath(lockPath), 0);
677
704
  }
678
705
  catch (error) {
679
706
  if (readOnly)
@@ -704,6 +731,13 @@ async function acquireOpenLock(filePath, readOnly, busyTimeoutMs) {
704
731
  delay = Math.min(delay * 2, 50);
705
732
  }
706
733
  }
734
+ /**
735
+ * The shared open lock, tried once on the calling thread, for a native binding older than the one this package ships,
736
+ * which has no form of it that runs elsewhere: an open still respects another process's exclusive lock.
737
+ */
738
+ function legacySharedOpenLock(locks, lockPath) {
739
+ return locks.trySharedAdvisoryLock(lockPath, 0);
740
+ }
707
741
  /**
708
742
  * Windows refuses to create a file for a few milliseconds after another process removes one of the same name, with
709
743
  * `Access is denied` while nothing is at the path; an open waits that out like a held lock, within its busy timeout.
@@ -1023,6 +1057,109 @@ function normalizeRow(row) {
1023
1057
  : value,
1024
1058
  ]));
1025
1059
  }
1060
+ /**
1061
+ * A connection whose statements run on the calling thread: an in-memory database, which never waits for the disk or
1062
+ * for a lock another connection holds, and a connection its caller opened and passed to `wrapNodeSqliteDatabase` (a
1063
+ * `DatabaseSync` cannot move to another thread). It answers each request as a connection's own thread does.
1064
+ */
1065
+ class CallerThreadConnection {
1066
+ connection;
1067
+ ownsConnection;
1068
+ constructor(connection, ownsConnection) {
1069
+ this.connection = connection;
1070
+ this.ownsConnection = ownsConnection;
1071
+ }
1072
+ request(request) {
1073
+ switch (request.kind) {
1074
+ case "open":
1075
+ return this.connection.location();
1076
+ case "exec":
1077
+ this.connection.exec(request.sql);
1078
+ return undefined;
1079
+ case "run":
1080
+ return { changes: Number(this.statement(request.sql).run(...request.params).changes) };
1081
+ case "get": {
1082
+ const row = this.statement(request.sql).get(...request.params);
1083
+ return row === undefined ? undefined : normalizeRow(row);
1084
+ }
1085
+ case "all":
1086
+ return this.statement(request.sql)
1087
+ .all(...request.params)
1088
+ .map((row) => normalizeRow(row));
1089
+ case "begin":
1090
+ this.begin();
1091
+ return undefined;
1092
+ case "dataVersion":
1093
+ return Number(this.connection.prepare("PRAGMA data_version").get()?.data_version ?? 0);
1094
+ case "now":
1095
+ return databaseNow();
1096
+ case "jsonbExtract":
1097
+ try {
1098
+ this.statement("SELECT jsonb_extract('[]', '$')");
1099
+ return true;
1100
+ }
1101
+ catch (error) {
1102
+ if (error instanceof Error && error.message === "no such function: jsonb_extract")
1103
+ return false;
1104
+ throw error;
1105
+ }
1106
+ case "close":
1107
+ if (this.ownsConnection)
1108
+ this.connection.close();
1109
+ finalizeReleasedStatements();
1110
+ return undefined;
1111
+ }
1112
+ }
1113
+ statement(sql) {
1114
+ const prepared = this.connection.prepare(sql);
1115
+ prepared.setReadBigInts(true);
1116
+ return prepared;
1117
+ }
1118
+ /** One `BEGIN IMMEDIATE` that does not wait for a busy lock; see `NodeSqliteDatabase.tryBegin`. */
1119
+ begin() {
1120
+ const configured = Number(this.connection.prepare("PRAGMA busy_timeout").get()?.timeout ?? 0);
1121
+ this.connection.exec("PRAGMA busy_timeout=0");
1122
+ let began = false;
1123
+ try {
1124
+ this.connection.exec("BEGIN IMMEDIATE");
1125
+ began = true;
1126
+ }
1127
+ finally {
1128
+ try {
1129
+ this.connection.exec(`PRAGMA busy_timeout=${configured}`);
1130
+ }
1131
+ catch (restoreFailure) {
1132
+ // Never hand back a transaction on a connection whose lock wait is no longer the configured one.
1133
+ if (began)
1134
+ this.connection.exec("ROLLBACK");
1135
+ // biome-ignore lint/correctness/noUnsafeFinally: a failed restore must replace the attempt's outcome.
1136
+ throw restoreFailure;
1137
+ }
1138
+ }
1139
+ }
1140
+ }
1141
+ /**
1142
+ * Sends one request to `connection`: a promise of its answer from a connection on a thread of its own, and the answer
1143
+ * itself from one on the calling thread, which runs it before returning, as node:sqlite does.
1144
+ */
1145
+ function send(connection, request) {
1146
+ if (!(connection instanceof ThreadConnection) || !("params" in request))
1147
+ return connection.request(request);
1148
+ return connection.request({ ...request, params: request.params.map(sendable) });
1149
+ }
1150
+ /**
1151
+ * A binary value as a connection's thread is sent it: the bytes it holds now, as a statement on the calling thread
1152
+ * binds them when it runs. A message shares a `SharedArrayBuffer` with the thread, so a change the caller makes before
1153
+ * the thread runs the statement would reach it, and it copies the whole buffer behind a view, so a view of part of a
1154
+ * buffer, or of a shared one, is sent as a copy of its own bytes. Any other value is sent as it is.
1155
+ */
1156
+ function sendable(value) {
1157
+ if (!isUint8Array(value))
1158
+ return value;
1159
+ if (!isSharedArrayBuffer(value.buffer) && value.byteOffset === 0 && value.byteLength === value.buffer.byteLength)
1160
+ return value;
1161
+ return new Uint8Array(value);
1162
+ }
1026
1163
  class NodeSqliteDatabase {
1027
1164
  descriptor;
1028
1165
  connection;
@@ -1035,7 +1172,6 @@ class NodeSqliteDatabase {
1035
1172
  closing = false;
1036
1173
  closePromise;
1037
1174
  executor;
1038
- ownsConnection;
1039
1175
  transactionIdentity;
1040
1176
  lockWaitMs;
1041
1177
  groupCommitHoldMs;
@@ -1049,17 +1185,16 @@ class NodeSqliteDatabase {
1049
1185
  leaving;
1050
1186
  /** What the writers' queue gave up on, once per reason, in the order it first happened. */
1051
1187
  degradations = new Map();
1052
- constructor(connection, descriptor, ownsConnection = true, transactionIdentity = connection, lockWaitMs = DEFAULT_NODE_SQLITE_LOCK_WAIT_MS, groupCommitHoldMs = DEFAULT_GROUP_COMMIT_HOLD_MS, openLock) {
1188
+ constructor(connection, descriptor, transactionIdentity = connection, lockWaitMs = DEFAULT_NODE_SQLITE_LOCK_WAIT_MS, groupCommitHoldMs = DEFAULT_GROUP_COMMIT_HOLD_MS, openLock) {
1053
1189
  this.lockWaitMs = lockWaitMs;
1054
1190
  this.groupCommitHoldMs = groupCommitHoldMs;
1055
1191
  this.transactionIdentity = transactionIdentity;
1056
- this.ownsConnection = ownsConnection;
1057
1192
  this.connection = connection;
1058
1193
  this.descriptor = descriptor;
1059
1194
  this.openLock = openLock;
1060
1195
  this.executor = this.createExecutor(() => true);
1061
1196
  if (typeof transactionIdentity === "string") {
1062
- this.writeQueue = new SqliteWriteQueue(transactionIdentity, (reason, cause) => this.degraded(reason, cause), () => databaseNow(connection.constructor));
1197
+ this.writeQueue = new SqliteWriteQueue(transactionIdentity, (reason, cause) => this.degraded(reason, cause), () => send(connection, { kind: "now" }));
1063
1198
  this.holderRecord = new SqliteHolderRecord(transactionIdentity, (cause) => this.degraded("holder-record-unavailable", cause));
1064
1199
  }
1065
1200
  }
@@ -1096,47 +1231,37 @@ class NodeSqliteDatabase {
1096
1231
  writerQueueStats() {
1097
1232
  return this.lockUse.stats(this.queueOp(() => this.writeQueue?.liveTickets().length ?? 0));
1098
1233
  }
1099
- driver(operation) {
1234
+ /**
1235
+ * Sends one request to the connection. A driver failure is a `StorageUnavailableError`, thrown at once by a
1236
+ * connection on the calling thread and rejected by one on a thread of its own.
1237
+ */
1238
+ call(request) {
1239
+ let answer;
1100
1240
  try {
1101
- return operation();
1241
+ answer = send(this.connection, request);
1102
1242
  }
1103
1243
  catch (cause) {
1104
1244
  throw unavailable(this.descriptor, cause);
1105
1245
  }
1246
+ if (!(answer instanceof Promise))
1247
+ return answer;
1248
+ return answer.catch((cause) => {
1249
+ throw unavailable(this.descriptor, cause);
1250
+ });
1106
1251
  }
1107
1252
  /**
1108
1253
  * One non-blocking `BEGIN IMMEDIATE`. node:sqlite runs `busy_timeout` synchronously, so a lock held by another
1109
- * process would freeze this process's event loop for the whole timeout. The attempt runs with `busy_timeout=0`
1110
- * and the connection's own value is restored before returning or throwing, so single statements outside a
1111
- * transaction keep it. Callers reach this only through `enqueue` and the transaction gate, so nothing else runs
1112
- * on the connection in between.
1254
+ * process would hold the connection's thread for the whole timeout. The attempt runs with `busy_timeout=0` and the
1255
+ * connection's own value is restored before answering, so single statements outside a transaction keep it.
1256
+ * Callers reach this only through `enqueue` and the transaction gate, so nothing else runs on the connection in
1257
+ * between.
1113
1258
  */
1114
1259
  tryBegin() {
1115
- this.driver(() => {
1116
- const configured = Number(this.connection.prepare("PRAGMA busy_timeout").get()?.timeout ?? 0);
1117
- this.connection.exec("PRAGMA busy_timeout=0");
1118
- let began = false;
1119
- try {
1120
- this.connection.exec("BEGIN IMMEDIATE");
1121
- began = true;
1122
- }
1123
- finally {
1124
- try {
1125
- this.connection.exec(`PRAGMA busy_timeout=${configured}`);
1126
- }
1127
- catch (restoreFailure) {
1128
- // Never hand back a transaction on a connection whose lock wait is no longer the configured one.
1129
- if (began)
1130
- this.connection.exec("ROLLBACK");
1131
- // biome-ignore lint/correctness/noUnsafeFinally: a failed restore must replace the attempt's outcome.
1132
- throw restoreFailure;
1133
- }
1134
- }
1135
- });
1260
+ return this.call({ kind: "begin" });
1136
1261
  }
1137
1262
  /** Changes whenever another connection commits to the database: the lock is being used, not held idle. */
1138
- dataVersion() {
1139
- return this.driver(() => Number(this.connection.prepare("PRAGMA data_version").get()?.data_version ?? 0));
1263
+ async dataVersion() {
1264
+ return (await this.call({ kind: "dataVersion" }));
1140
1265
  }
1141
1266
  /**
1142
1267
  * Takes the write lock without blocking the event loop. Nothing has run yet when `BEGIN IMMEDIATE` reports
@@ -1165,7 +1290,7 @@ class NodeSqliteDatabase {
1165
1290
  ticket = await this.queueFileOp(() => queue.join(waiting));
1166
1291
  }
1167
1292
  // Read only once this writer waits, so an uncontended transaction pays nothing for it.
1168
- let version = ticket === undefined ? undefined : this.dataVersion();
1293
+ let version = ticket === undefined ? undefined : await this.dataVersion();
1169
1294
  let stalledSince = performance.now();
1170
1295
  let lastCause;
1171
1296
  for (;;) {
@@ -1174,7 +1299,8 @@ class NodeSqliteDatabase {
1174
1299
  notices = await this.watchTicket(ticket, notices);
1175
1300
  const behind = ticket !== undefined && (await this.queueFileOp(() => ticket.behindOthers()));
1176
1301
  if (!behind) {
1177
- const refused = this.attemptBegin();
1302
+ const attempt = this.attemptBegin();
1303
+ const refused = attempt instanceof Promise ? await attempt : attempt;
1178
1304
  if (refused === undefined) {
1179
1305
  holding = true;
1180
1306
  this.acquired(waitStarted);
@@ -1188,7 +1314,7 @@ class NodeSqliteDatabase {
1188
1314
  }
1189
1315
  }
1190
1316
  // Only another connection's commit is progress; a queued writer measures its stall the same way.
1191
- const current = this.dataVersion();
1317
+ const current = await this.dataVersion();
1192
1318
  const committed = version !== undefined && current !== version;
1193
1319
  if (version === undefined)
1194
1320
  version = current;
@@ -1224,18 +1350,25 @@ class NodeSqliteDatabase {
1224
1350
  await this.holderRecord?.free();
1225
1351
  }
1226
1352
  }
1227
- /** One attempt at the lock: `undefined` once it is taken, or the SQLITE_BUSY that refused it. Anything else throws. */
1353
+ /**
1354
+ * One attempt at the lock: `undefined` once it is taken, or the SQLITE_BUSY that refused it. Anything else fails.
1355
+ * Answered at once on the calling thread, and as a promise by a connection on a thread of its own.
1356
+ */
1228
1357
  attemptBegin() {
1229
- try {
1230
- this.tryBegin();
1231
- return undefined;
1232
- }
1233
- catch (error) {
1358
+ const refusal = (error) => {
1234
1359
  const cause = error instanceof StorageUnavailableError ? error.cause : undefined;
1235
1360
  if (!isSqliteBusy(cause))
1236
1361
  throw error;
1237
1362
  return cause;
1363
+ };
1364
+ let attempt;
1365
+ try {
1366
+ attempt = this.tryBegin();
1238
1367
  }
1368
+ catch (error) {
1369
+ return refusal(error);
1370
+ }
1371
+ return attempt instanceof Promise ? attempt.then(() => undefined, refusal) : undefined;
1239
1372
  }
1240
1373
  /**
1241
1374
  * After a refused attempt, while other connections are committing through the lock, keeps attempting it on every
@@ -1250,7 +1383,7 @@ class NodeSqliteDatabase {
1250
1383
  const until = performance.now() + LOCK_RELEASE_RETRY_MS;
1251
1384
  for (let attempt = 0; attempt < LOCK_RELEASE_RETRY_ATTEMPTS && performance.now() < until; attempt++) {
1252
1385
  await new Promise((resolve) => setImmediate(resolve));
1253
- if (this.attemptBegin() === undefined)
1386
+ if ((await this.attemptBegin()) === undefined)
1254
1387
  return true;
1255
1388
  }
1256
1389
  return false;
@@ -1336,41 +1469,25 @@ class NodeSqliteDatabase {
1336
1469
  throw new StorageWriterQueueUnusableError(this.descriptor, cause);
1337
1470
  }
1338
1471
  }
1472
+ /**
1473
+ * Statements on the connection, each sent the moment it is called, so calls a transaction makes without awaiting
1474
+ * the ones before run in the order it made them, as on a connection that runs each one as it is called.
1475
+ */
1339
1476
  createExecutor(active) {
1340
- const execute = async (operation, params = []) => {
1477
+ const execute = async (request, params = []) => {
1341
1478
  if (!active())
1342
1479
  throw new StorageTransactionClosedError();
1343
1480
  const invalidIndex = params.findIndex((value) => typeof value === "string" && value.includes("\0"));
1344
1481
  if (invalidIndex !== -1)
1345
1482
  throw new StorageInvalidTextError(invalidIndex);
1346
- return this.driver(operation);
1347
- };
1348
- const statement = (sql) => {
1349
- const prepared = this.connection.prepare(sql);
1350
- prepared.setReadBigInts(true);
1351
- return prepared;
1483
+ return this.call(request);
1352
1484
  };
1353
1485
  return {
1354
- checkJsonbExtract: () => execute(() => {
1355
- try {
1356
- statement("SELECT jsonb_extract('[]', '$')");
1357
- return true;
1358
- }
1359
- catch (error) {
1360
- if (error instanceof Error && error.message === "no such function: jsonb_extract")
1361
- return false;
1362
- throw error;
1363
- }
1364
- }),
1365
- exec: (sql) => execute(() => this.connection.exec(sql)),
1366
- run: (sql, ...params) => execute(() => ({ changes: Number(statement(sql).run(...params).changes) }), params),
1367
- get: (sql, ...params) => execute(() => {
1368
- const row = statement(sql).get(...params);
1369
- return row === undefined ? undefined : normalizeRow(row);
1370
- }, params),
1371
- all: (sql, ...params) => execute(() => statement(sql)
1372
- .all(...params)
1373
- .map((row) => normalizeRow(row)), params),
1486
+ checkJsonbExtract: () => execute({ kind: "jsonbExtract" }),
1487
+ exec: (sql) => execute({ kind: "exec", sql }),
1488
+ run: (sql, ...params) => execute({ kind: "run", sql, params }, params),
1489
+ get: (sql, ...params) => execute({ kind: "get", sql, params }, params),
1490
+ all: (sql, ...params) => execute({ kind: "all", sql, params }, params),
1374
1491
  };
1375
1492
  }
1376
1493
  enqueue(operation) {
@@ -1430,7 +1547,8 @@ class NodeSqliteDatabase {
1430
1547
  const start = performance.now();
1431
1548
  await this.holderRecord?.trying();
1432
1549
  try {
1433
- if (this.attemptBegin() !== undefined) {
1550
+ const attempt = this.attemptBegin();
1551
+ if ((attempt instanceof Promise ? await attempt : attempt) !== undefined) {
1434
1552
  await this.holderRecord?.free();
1435
1553
  return false;
1436
1554
  }
@@ -1654,11 +1772,7 @@ class NodeSqliteDatabase {
1654
1772
  this.closePromise = this.tail.then(async () => {
1655
1773
  try {
1656
1774
  await this.holderRecord?.close();
1657
- this.driver(() => {
1658
- if (this.ownsConnection)
1659
- this.connection.close();
1660
- finalizeReleasedStatements();
1661
- });
1775
+ await this.call({ kind: "close" });
1662
1776
  }
1663
1777
  finally {
1664
1778
  await releaseOpenLock(this.openLock);
@@ -1702,18 +1816,22 @@ export function ordinarySqlitePath(location) {
1702
1816
  return location;
1703
1817
  }
1704
1818
  /**
1705
- * Opens `path` with SQLite, through the long-path form when it needs it, and has the connection report its location as
1706
- * the ordinary path, so every reader of it (identity, error messages, callers comparing paths) sees the path it was
1707
- * given whatever its length (#5139).
1819
+ * Opens an in-memory database (see `isInMemoryDatabase`) on the calling thread: it has no file, so neither opening it
1820
+ * nor its statements wait for the disk, and SQLite's busy handler never waits for it, since no connection of any
1821
+ * process holds a lock on it.
1822
+ */
1823
+ function openOnCallerThread(Database, path, readOnly) {
1824
+ const connection = new Database(path, { readOnly });
1825
+ return { connection: new CallerThreadConnection(connection, true), location: connection.location() };
1826
+ }
1827
+ /**
1828
+ * Opens `path` with SQLite on a thread of its own, through the long-path form when it needs it, and reports its
1829
+ * location as the ordinary path, so every reader of it (identity, error messages, callers comparing paths) sees the
1830
+ * path it was given whatever its length (#5139).
1708
1831
  */
1709
- function openConnection(Database, path, readOnly) {
1710
- const opened = sqliteFilePath(path);
1711
- const connection = new Database(opened, { readOnly });
1712
- if (opened !== path) {
1713
- const location = connection.location.bind(connection);
1714
- connection.location = (name) => ordinarySqlitePath(location(name));
1715
- }
1716
- return connection;
1832
+ async function openOnOwnThread(path, readOnly) {
1833
+ const { connection, location } = await ThreadConnection.open(path, { readOnly, openAs: sqliteFilePath(path) });
1834
+ return { connection, location: ordinarySqlitePath(location) };
1717
1835
  }
1718
1836
  export async function openNodeSqliteDatabase(path, { busyTimeoutMs = 5000, lockWaitMs = DEFAULT_NODE_SQLITE_LOCK_WAIT_MS, readOnly = false, groupCommitHoldMs, } = {}) {
1719
1837
  const holdMs = groupCommitHold(groupCommitHoldMs);
@@ -1727,6 +1845,7 @@ export async function openNodeSqliteDatabase(path, { busyTimeoutMs = 5000, lockW
1727
1845
  catch (cause) {
1728
1846
  throw new StorageAdapterLoadError("node:sqlite", cause);
1729
1847
  }
1848
+ loadedDatabaseSync ??= Database;
1730
1849
  const targetFile = sqliteTargetFilePath(path);
1731
1850
  let heldOpenLock;
1732
1851
  let connection;
@@ -1734,15 +1853,21 @@ export async function openNodeSqliteDatabase(path, { busyTimeoutMs = 5000, lockW
1734
1853
  if (!readOnly && targetFile !== undefined)
1735
1854
  await mkdir(dirname(targetFile), { recursive: true });
1736
1855
  heldOpenLock = await acquireOpenLock(targetFile, readOnly, busyTimeoutMs);
1737
- connection = openConnection(Database, path, readOnly);
1738
- connection.exec(`PRAGMA busy_timeout=${busyTimeoutMs}`);
1856
+ // A file-backed connection runs on a thread of its own, so opening it, waiting for its locks and its synced
1857
+ // commits never hold this thread (#5376).
1858
+ const opened = isInMemoryDatabase(path)
1859
+ ? openOnCallerThread(Database, path, readOnly)
1860
+ : await openOnOwnThread(path, readOnly);
1861
+ const configured = opened.connection;
1862
+ connection = configured;
1863
+ const exec = (sql) => send(configured, { kind: "exec", sql });
1864
+ await exec(`PRAGMA busy_timeout=${busyTimeoutMs}`);
1739
1865
  if (!readOnly) {
1740
- const writable = connection;
1741
1866
  // SQLite does not wait for another process's lock while it changes the mode; the switch waits itself.
1742
- await switchToWriteAheadLog((sql) => writable.exec(sql), busyTimeoutMs);
1743
- writable.exec("PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON");
1867
+ await switchToWriteAheadLog(exec, busyTimeoutMs);
1868
+ await exec("PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON");
1744
1869
  }
1745
- const location = connection.location();
1870
+ const location = opened.location;
1746
1871
  const identity = location === null
1747
1872
  ? connection
1748
1873
  : heldOpenLock?.target !== undefined && location === targetFile
@@ -1752,7 +1877,7 @@ export async function openNodeSqliteDatabase(path, { busyTimeoutMs = 5000, lockW
1752
1877
  await releaseOpenLock(heldOpenLock);
1753
1878
  heldOpenLock = await acquireOpenLock(identity, readOnly, busyTimeoutMs);
1754
1879
  }
1755
- const database = new NodeSqliteDatabase(connection, descriptor, true, identity, lockWaitMs, holdMs, heldOpenLock);
1880
+ const database = new NodeSqliteDatabase(connection, descriptor, identity, lockWaitMs, holdMs, heldOpenLock);
1756
1881
  Object.defineProperty(database, "readOnly", { value: readOnly });
1757
1882
  if (!readOnly)
1758
1883
  await database.openHolderRecord();
@@ -1760,7 +1885,8 @@ export async function openNodeSqliteDatabase(path, { busyTimeoutMs = 5000, lockW
1760
1885
  }
1761
1886
  catch (cause) {
1762
1887
  try {
1763
- connection?.close();
1888
+ if (connection !== undefined)
1889
+ await send(connection, { kind: "close" });
1764
1890
  }
1765
1891
  catch {
1766
1892
  // Preserve the opening failure if cleanup also fails.
@@ -1783,7 +1909,7 @@ export function wrapNodeSqliteDatabase(connection) {
1783
1909
  // SQLite does not wait for another process's lock while it changes the mode; the switch waits itself.
1784
1910
  switchToWriteAheadLogSync((sql) => connection.exec(sql), WRAPPED_BUSY_TIMEOUT_MS);
1785
1911
  connection.exec("PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON");
1786
- return new NodeSqliteDatabase(connection, descriptor, false, connection, undefined, undefined, heldOpenLock);
1912
+ return new NodeSqliteDatabase(new CallerThreadConnection(connection, false), descriptor, connection, undefined, undefined, heldOpenLock);
1787
1913
  }
1788
1914
  catch (cause) {
1789
1915
  void releaseOpenLock(heldOpenLock);