@bastani/atomic 0.10.1 → 0.10.2-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 (295) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +6 -0
  3. package/dist/builtin/intercom/broker/watchdog.ts +4 -0
  4. package/dist/builtin/intercom/package.json +1 -1
  5. package/dist/builtin/mcp/package.json +1 -1
  6. package/dist/builtin/subagents/CHANGELOG.md +16 -0
  7. package/dist/builtin/subagents/README.md +2 -0
  8. package/dist/builtin/subagents/package.json +1 -1
  9. package/dist/builtin/subagents/skills/subagent/SKILL.md +3 -3
  10. package/dist/builtin/subagents/src/extension/index.bundle.mjs +269 -144
  11. package/dist/builtin/web-access/CHANGELOG.md +7 -0
  12. package/dist/builtin/web-access/index.bundle.mjs +9 -5
  13. package/dist/builtin/web-access/package.json +1 -1
  14. package/dist/cli/list-models.d.ts.map +1 -1
  15. package/dist/cli/list-models.js +1 -14
  16. package/dist/cli/list-models.js.map +1 -1
  17. package/dist/core/agent-session-export.d.ts.map +1 -1
  18. package/dist/core/agent-session-export.js +13 -9
  19. package/dist/core/agent-session-export.js.map +1 -1
  20. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  21. package/dist/core/agent-session-message-queue.js +6 -3
  22. package/dist/core/agent-session-message-queue.js.map +1 -1
  23. package/dist/core/agent-session-methods.d.ts +3 -0
  24. package/dist/core/agent-session-methods.d.ts.map +1 -1
  25. package/dist/core/agent-session-methods.js.map +1 -1
  26. package/dist/core/agent-session-nested-tools.d.ts.map +1 -1
  27. package/dist/core/agent-session-nested-tools.js +2 -1
  28. package/dist/core/agent-session-nested-tools.js.map +1 -1
  29. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  30. package/dist/core/agent-session-prompt.js +12 -0
  31. package/dist/core/agent-session-prompt.js.map +1 -1
  32. package/dist/core/agent-session-state.d.ts +6 -0
  33. package/dist/core/agent-session-state.d.ts.map +1 -1
  34. package/dist/core/agent-session-state.js +71 -4
  35. package/dist/core/agent-session-state.js.map +1 -1
  36. package/dist/core/agent-session-tool-hooks.d.ts.map +1 -1
  37. package/dist/core/agent-session-tool-hooks.js +9 -1
  38. package/dist/core/agent-session-tool-hooks.js.map +1 -1
  39. package/dist/core/agent-session-types.d.ts +2 -0
  40. package/dist/core/agent-session-types.d.ts.map +1 -1
  41. package/dist/core/agent-session-types.js.map +1 -1
  42. package/dist/core/agent-session.d.ts +3 -0
  43. package/dist/core/agent-session.d.ts.map +1 -1
  44. package/dist/core/agent-session.js +7 -0
  45. package/dist/core/agent-session.js.map +1 -1
  46. package/dist/core/cache-stats.d.ts +15 -0
  47. package/dist/core/cache-stats.d.ts.map +1 -1
  48. package/dist/core/cache-stats.js +40 -2
  49. package/dist/core/cache-stats.js.map +1 -1
  50. package/dist/core/diagnostic-writer.d.ts.map +1 -1
  51. package/dist/core/diagnostic-writer.js +2 -1
  52. package/dist/core/diagnostic-writer.js.map +1 -1
  53. package/dist/core/export-html/template.js +14 -4
  54. package/dist/core/extensions/context-types.d.ts +6 -0
  55. package/dist/core/extensions/context-types.d.ts.map +1 -1
  56. package/dist/core/extensions/context-types.js.map +1 -1
  57. package/dist/core/extensions/loader-api.d.ts.map +1 -1
  58. package/dist/core/extensions/loader-api.js +5 -2
  59. package/dist/core/extensions/loader-api.js.map +1 -1
  60. package/dist/core/queued-message-delivery.d.ts +100 -7
  61. package/dist/core/queued-message-delivery.d.ts.map +1 -1
  62. package/dist/core/queued-message-delivery.js +194 -4
  63. package/dist/core/queued-message-delivery.js.map +1 -1
  64. package/dist/core/resume-cache-checkpoint.d.ts +32 -0
  65. package/dist/core/resume-cache-checkpoint.d.ts.map +1 -0
  66. package/dist/core/resume-cache-checkpoint.js +67 -0
  67. package/dist/core/resume-cache-checkpoint.js.map +1 -0
  68. package/dist/core/sdk-types.d.ts +37 -0
  69. package/dist/core/sdk-types.d.ts.map +1 -1
  70. package/dist/core/sdk-types.js.map +1 -1
  71. package/dist/core/sdk.d.ts.map +1 -1
  72. package/dist/core/sdk.js +57 -28
  73. package/dist/core/sdk.js.map +1 -1
  74. package/dist/core/session-manager-core.d.ts.map +1 -1
  75. package/dist/core/session-manager-core.js +12 -3
  76. package/dist/core/session-manager-core.js.map +1 -1
  77. package/dist/core/session-manager-entries.d.ts +13 -0
  78. package/dist/core/session-manager-entries.d.ts.map +1 -1
  79. package/dist/core/session-manager-entries.js +38 -6
  80. package/dist/core/session-manager-entries.js.map +1 -1
  81. package/dist/core/settings-lock-directory.d.ts.map +1 -1
  82. package/dist/core/settings-lock-directory.js +2 -1
  83. package/dist/core/settings-lock-directory.js.map +1 -1
  84. package/dist/core/storage/node-sqlite-file-gate.d.ts +173 -0
  85. package/dist/core/storage/node-sqlite-file-gate.d.ts.map +1 -0
  86. package/dist/core/storage/node-sqlite-file-gate.js +1033 -0
  87. package/dist/core/storage/node-sqlite-file-gate.js.map +1 -0
  88. package/dist/core/storage/node-sqlite-thread.d.ts +33 -6
  89. package/dist/core/storage/node-sqlite-thread.d.ts.map +1 -1
  90. package/dist/core/storage/node-sqlite-thread.js +72 -2
  91. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  92. package/dist/core/storage/node-sqlite.d.ts.map +1 -1
  93. package/dist/core/storage/node-sqlite.js +216 -15
  94. package/dist/core/storage/node-sqlite.js.map +1 -1
  95. package/dist/core/storage/session/entry-structure.d.ts.map +1 -1
  96. package/dist/core/storage/session/entry-structure.js +39 -2
  97. package/dist/core/storage/session/entry-structure.js.map +1 -1
  98. package/dist/core/storage/session/session-resume.d.ts.map +1 -1
  99. package/dist/core/storage/session/session-resume.js +1 -0
  100. package/dist/core/storage/session/session-resume.js.map +1 -1
  101. package/dist/core/storage/session/session-search-index.d.ts.map +1 -1
  102. package/dist/core/storage/session/session-search-index.js +56 -9
  103. package/dist/core/storage/session/session-search-index.js.map +1 -1
  104. package/dist/core/storage/statement-sequence.d.ts +36 -0
  105. package/dist/core/storage/statement-sequence.d.ts.map +1 -0
  106. package/dist/core/storage/statement-sequence.js +22 -0
  107. package/dist/core/storage/statement-sequence.js.map +1 -0
  108. package/dist/core/system-prompt.d.ts.map +1 -1
  109. package/dist/core/system-prompt.js +13 -4
  110. package/dist/core/system-prompt.js.map +1 -1
  111. package/dist/core/tasks/heartbeat-notice.d.ts.map +1 -1
  112. package/dist/core/tasks/heartbeat-notice.js +2 -1
  113. package/dist/core/tasks/heartbeat-notice.js.map +1 -1
  114. package/dist/core/tool-loadout.d.ts +4 -2
  115. package/dist/core/tool-loadout.d.ts.map +1 -1
  116. package/dist/core/tool-loadout.js +27 -5
  117. package/dist/core/tool-loadout.js.map +1 -1
  118. package/dist/core/tools/history-regex-worker.d.ts.map +1 -1
  119. package/dist/core/tools/history-regex-worker.js +2 -1
  120. package/dist/core/tools/history-regex-worker.js.map +1 -1
  121. package/dist/core/tools/powershell.d.ts +22 -22
  122. package/dist/core/tools/sqlite-selector-connection.d.ts.map +1 -1
  123. package/dist/core/tools/sqlite-selector-connection.js +7 -0
  124. package/dist/core/tools/sqlite-selector-connection.js.map +1 -1
  125. package/dist/core/transformed-system-prompt.d.ts +92 -0
  126. package/dist/core/transformed-system-prompt.d.ts.map +1 -0
  127. package/dist/core/transformed-system-prompt.js +240 -0
  128. package/dist/core/transformed-system-prompt.js.map +1 -0
  129. package/dist/extensions/codemode/execute.js +1 -1
  130. package/dist/extensions/codemode/execute.js.map +1 -1
  131. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  132. package/dist/extensions/codemode/tool.js +16 -3
  133. package/dist/extensions/codemode/tool.js.map +1 -1
  134. package/dist/extensions/llama/ui.d.ts.map +1 -1
  135. package/dist/extensions/llama/ui.js +13 -8
  136. package/dist/extensions/llama/ui.js.map +1 -1
  137. package/dist/extensions/mcp/config.d.ts +2 -0
  138. package/dist/extensions/mcp/config.d.ts.map +1 -1
  139. package/dist/extensions/mcp/config.js +5 -0
  140. package/dist/extensions/mcp/config.js.map +1 -1
  141. package/dist/extensions/mcp/index.d.ts +4 -0
  142. package/dist/extensions/mcp/index.d.ts.map +1 -1
  143. package/dist/extensions/mcp/index.js +289 -64
  144. package/dist/extensions/mcp/index.js.map +1 -1
  145. package/dist/extensions/mcp/runtime.d.ts +1 -1
  146. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  147. package/dist/extensions/mcp/runtime.js +2 -2
  148. package/dist/extensions/mcp/runtime.js.map +1 -1
  149. package/dist/extensions/mcp/tool-records.d.ts +58 -0
  150. package/dist/extensions/mcp/tool-records.d.ts.map +1 -0
  151. package/dist/extensions/mcp/tool-records.js +129 -0
  152. package/dist/extensions/mcp/tool-records.js.map +1 -0
  153. package/dist/index.d.ts +1 -0
  154. package/dist/index.d.ts.map +1 -1
  155. package/dist/index.js +1 -0
  156. package/dist/index.js.map +1 -1
  157. package/dist/modes/interactive/components/agent-panel.d.ts +2 -4
  158. package/dist/modes/interactive/components/agent-panel.d.ts.map +1 -1
  159. package/dist/modes/interactive/components/agent-panel.js +65 -80
  160. package/dist/modes/interactive/components/agent-panel.js.map +1 -1
  161. package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
  162. package/dist/modes/interactive/components/compaction-boundary-message.js +3 -3
  163. package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
  164. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  165. package/dist/modes/interactive/components/footer.js +35 -28
  166. package/dist/modes/interactive/components/footer.js.map +1 -1
  167. package/dist/modes/interactive/components/notice-line.d.ts +16 -0
  168. package/dist/modes/interactive/components/notice-line.d.ts.map +1 -1
  169. package/dist/modes/interactive/components/notice-line.js +7 -0
  170. package/dist/modes/interactive/components/notice-line.js.map +1 -1
  171. package/dist/modes/interactive/components/prompt-slot.d.ts +1 -0
  172. package/dist/modes/interactive/components/prompt-slot.d.ts.map +1 -1
  173. package/dist/modes/interactive/components/prompt-slot.js +8 -4
  174. package/dist/modes/interactive/components/prompt-slot.js.map +1 -1
  175. package/dist/modes/interactive/components/task-board.d.ts +0 -1
  176. package/dist/modes/interactive/components/task-board.d.ts.map +1 -1
  177. package/dist/modes/interactive/components/task-board.js +6 -14
  178. package/dist/modes/interactive/components/task-board.js.map +1 -1
  179. package/dist/modes/interactive/components/task-row.d.ts.map +1 -1
  180. package/dist/modes/interactive/components/task-row.js +7 -6
  181. package/dist/modes/interactive/components/task-row.js.map +1 -1
  182. package/dist/modes/interactive/components/token-segment.d.ts +2 -1
  183. package/dist/modes/interactive/components/token-segment.d.ts.map +1 -1
  184. package/dist/modes/interactive/components/token-segment.js +2 -4
  185. package/dist/modes/interactive/components/token-segment.js.map +1 -1
  186. package/dist/modes/interactive/components/tree-selector-content.d.ts.map +1 -1
  187. package/dist/modes/interactive/components/tree-selector-content.js +2 -2
  188. package/dist/modes/interactive/components/tree-selector-content.js.map +1 -1
  189. package/dist/modes/interactive/components/working-run-meter.d.ts +0 -1
  190. package/dist/modes/interactive/components/working-run-meter.d.ts.map +1 -1
  191. package/dist/modes/interactive/components/working-run-meter.js +0 -9
  192. package/dist/modes/interactive/components/working-run-meter.js.map +1 -1
  193. package/dist/modes/interactive/extension-command-hold.d.ts +25 -0
  194. package/dist/modes/interactive/extension-command-hold.d.ts.map +1 -0
  195. package/dist/modes/interactive/extension-command-hold.js +45 -0
  196. package/dist/modes/interactive/extension-command-hold.js.map +1 -0
  197. package/dist/modes/interactive/interactive-agent-events.js +2 -1
  198. package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
  199. package/dist/modes/interactive/interactive-extension-context.js +18 -10
  200. package/dist/modes/interactive/interactive-extension-context.js.map +1 -1
  201. package/dist/modes/interactive/interactive-extension-custom-ui.js +3 -0
  202. package/dist/modes/interactive/interactive-extension-custom-ui.js.map +1 -1
  203. package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
  204. package/dist/modes/interactive/interactive-input-handling.js +54 -13
  205. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  206. package/dist/modes/interactive/interactive-model-routing.d.ts +6 -0
  207. package/dist/modes/interactive/interactive-model-routing.d.ts.map +1 -1
  208. package/dist/modes/interactive/interactive-model-routing.js +15 -9
  209. package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
  210. package/dist/modes/interactive/interactive-prompt-turn.js +4 -0
  211. package/dist/modes/interactive/interactive-prompt-turn.js.map +1 -1
  212. package/dist/modes/interactive/interactive-queueing.d.ts +7 -0
  213. package/dist/modes/interactive/interactive-queueing.d.ts.map +1 -1
  214. package/dist/modes/interactive/interactive-queueing.js +47 -1
  215. package/dist/modes/interactive/interactive-queueing.js.map +1 -1
  216. package/dist/modes/interactive/interactive-session-routing.js +6 -0
  217. package/dist/modes/interactive/interactive-session-routing.js.map +1 -1
  218. package/dist/modes/interactive/interactive-slash-commands.js +165 -65
  219. package/dist/modes/interactive/interactive-slash-commands.js.map +1 -1
  220. package/dist/modes/interactive/screen-hold.d.ts +3 -0
  221. package/dist/modes/interactive/screen-hold.d.ts.map +1 -1
  222. package/dist/modes/interactive/screen-hold.js +9 -1
  223. package/dist/modes/interactive/screen-hold.js.map +1 -1
  224. package/dist/modes/interactive-engine/engine-health.d.ts +11 -3
  225. package/dist/modes/interactive-engine/engine-health.d.ts.map +1 -1
  226. package/dist/modes/interactive-engine/engine-health.js +5 -4
  227. package/dist/modes/interactive-engine/engine-health.js.map +1 -1
  228. package/dist/modes/interactive-engine/engine-quit-intent.d.ts +7 -0
  229. package/dist/modes/interactive-engine/engine-quit-intent.d.ts.map +1 -1
  230. package/dist/modes/interactive-engine/engine-quit-intent.js +19 -0
  231. package/dist/modes/interactive-engine/engine-quit-intent.js.map +1 -1
  232. package/dist/modes/interactive-engine/isolated-runtime.d.ts +18 -0
  233. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  234. package/dist/modes/interactive-engine/isolated-runtime.js +56 -4
  235. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  236. package/dist/modes/interactive-engine/protocol.d.ts +7 -0
  237. package/dist/modes/interactive-engine/protocol.d.ts.map +1 -1
  238. package/dist/modes/interactive-engine/protocol.js +1 -0
  239. package/dist/modes/interactive-engine/protocol.js.map +1 -1
  240. package/dist/modes/rpc/agent-panel-bridge.d.ts.map +1 -1
  241. package/dist/modes/rpc/agent-panel-bridge.js +0 -13
  242. package/dist/modes/rpc/agent-panel-bridge.js.map +1 -1
  243. package/dist/modes/rpc/rpc-client-process.d.ts +14 -1
  244. package/dist/modes/rpc/rpc-client-process.d.ts.map +1 -1
  245. package/dist/modes/rpc/rpc-client-process.js +74 -10
  246. package/dist/modes/rpc/rpc-client-process.js.map +1 -1
  247. package/dist/modes/rpc/rpc-client.d.ts +27 -1
  248. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  249. package/dist/modes/rpc/rpc-client.js +81 -5
  250. package/dist/modes/rpc/rpc-client.js.map +1 -1
  251. package/dist/modes/rpc/rpc-event-buffer.d.ts +2 -0
  252. package/dist/modes/rpc/rpc-event-buffer.d.ts.map +1 -1
  253. package/dist/modes/rpc/rpc-event-buffer.js +9 -0
  254. package/dist/modes/rpc/rpc-event-buffer.js.map +1 -1
  255. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  256. package/dist/modes/rpc/rpc-mode.js +16 -3
  257. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  258. package/dist/modes/rpc/rpc-session-binding.d.ts +7 -1
  259. package/dist/modes/rpc/rpc-session-binding.d.ts.map +1 -1
  260. package/dist/modes/rpc/rpc-session-binding.js +10 -2
  261. package/dist/modes/rpc/rpc-session-binding.js.map +1 -1
  262. package/dist/utils/image-resize.d.ts.map +1 -1
  263. package/dist/utils/image-resize.js +2 -1
  264. package/dist/utils/image-resize.js.map +1 -1
  265. package/dist/utils/interactive-engine-bootstrap.d.ts +2 -0
  266. package/dist/utils/interactive-engine-bootstrap.d.ts.map +1 -1
  267. package/dist/utils/interactive-engine-bootstrap.js +1 -0
  268. package/dist/utils/interactive-engine-bootstrap.js.map +1 -1
  269. package/dist/utils/interactive-engine-env.d.ts +2 -0
  270. package/dist/utils/interactive-engine-env.d.ts.map +1 -1
  271. package/dist/utils/interactive-engine-env.js +1 -0
  272. package/dist/utils/interactive-engine-env.js.map +1 -1
  273. package/dist/utils/shell.d.ts.map +1 -1
  274. package/dist/utils/shell.js +2 -0
  275. package/dist/utils/shell.js.map +1 -1
  276. package/dist/utils/token-count.d.ts +8 -0
  277. package/dist/utils/token-count.d.ts.map +1 -0
  278. package/dist/utils/token-count.js +25 -0
  279. package/dist/utils/token-count.js.map +1 -0
  280. package/dist/utils/worker-threads.d.ts +18 -0
  281. package/dist/utils/worker-threads.d.ts.map +1 -0
  282. package/dist/utils/worker-threads.js +28 -0
  283. package/dist/utils/worker-threads.js.map +1 -0
  284. package/docs/background-tasks.md +13 -12
  285. package/docs/compaction.md +2 -2
  286. package/docs/development.md +1 -1
  287. package/docs/extensions/api-reference.md +5 -3
  288. package/docs/extensions/events.md +2 -0
  289. package/docs/mcp-servers.md +1 -1
  290. package/docs/settings.md +2 -0
  291. package/docs/storage.md +3 -1
  292. package/docs/subagents.md +6 -2
  293. package/docs/usage.md +1 -1
  294. package/npm-shrinkwrap.json +49 -49
  295. package/package.json +6 -6
@@ -8,7 +8,10 @@ import { promisify } from "node:util";
8
8
  import { isSharedArrayBuffer, isUint8Array } from "node:util/types";
9
9
  import { sqliteDialect } from "./dialect.js";
10
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";
11
+ import { fileIdentity, fileIdentityAsync } from "./file-identity.js";
12
+ import { connectionWaits, currentHoldScope, forgetPlans, heldElsewhere, holdFile, inBacklog, modeOf, releaseHold, runDeferred, runInHold, runTryingFirst, runWhenFree, sqliteBusyError, useFileLock, useWrappedFile, } from "./node-sqlite-file-gate.js";
13
+ import { ThreadConnection, } from "./node-sqlite-thread.js";
14
+ import { offerSequences } from "./statement-sequence.js";
12
15
  import { isSqliteBusy, switchToWriteAheadLog, switchToWriteAheadLogSync } from "./write-ahead-log.js";
13
16
  /** Loaded at the first degradation only, so opening a database does not load debug output. */
14
17
  let debugOutput;
@@ -952,6 +955,8 @@ const LOCK_RELEASE_RETRY_MS = 16;
952
955
  const LOCK_RELEASE_RETRY_ATTEMPTS = 1_000;
953
956
  /** Most transactions one group commit carries, so a batch cannot keep the write lock from other processes for long. */
954
957
  const MAX_GROUP_COMMIT_TRANSACTIONS = 128;
958
+ /** Most statements one sequence request carries, so a message to the connection's thread stays small. */
959
+ const MAX_SEQUENCE_REQUEST_STATEMENTS = 256;
955
960
  /**
956
961
  * Default for how long a group commit runs its members before it commits them and takes the lock again for the
957
962
  * rest: a batch of cheap transactions in a process starved of CPU still lets other processes' writers in between.
@@ -1138,6 +1143,21 @@ class CallerThreadConnection {
1138
1143
  }
1139
1144
  }
1140
1145
  }
1146
+ /**
1147
+ * Gives back the file's word and closes `current`'s hold when the connection's thread exits: a thread that is gone
1148
+ * holds no lock, whatever the transaction's callback still does. Outside the database's methods, so the listener keeps
1149
+ * only the cell and the word, not the database.
1150
+ */
1151
+ function releaseOnExit(connection, current, lock) {
1152
+ connection.onExit(() => {
1153
+ lock.clear();
1154
+ const hold = current.hold;
1155
+ current.hold = undefined;
1156
+ releaseHold(hold);
1157
+ // A thread that is gone no longer uses the word, whether or not its database is ever closed.
1158
+ lock.release();
1159
+ });
1160
+ }
1141
1161
  /**
1142
1162
  * Sends one request to `connection`: a promise of its answer from a connection on a thread of its own, and the answer
1143
1163
  * itself from one on the calling thread, which runs it before returning, as node:sqlite does.
@@ -1160,6 +1180,13 @@ function sendable(value) {
1160
1180
  return value;
1161
1181
  return new Uint8Array(value);
1162
1182
  }
1183
+ function sendableStatement({ sql, params }) {
1184
+ return { sql, params: params.map(sendable) };
1185
+ }
1186
+ /** The index of the first text parameter holding NUL, which no statement may bind, or -1. */
1187
+ function invalidTextParam(params) {
1188
+ return params.findIndex((value) => typeof value === "string" && value.includes("\0"));
1189
+ }
1163
1190
  class NodeSqliteDatabase {
1164
1191
  descriptor;
1165
1192
  connection;
@@ -1181,11 +1208,33 @@ class NodeSqliteDatabase {
1181
1208
  holderRecord;
1182
1209
  openLock;
1183
1210
  lockUse = new WriteLockUse();
1211
+ /**
1212
+ * This connection's file, as `fileIdentity` names it, and its part in sharing the file with the process's other
1213
+ * connections to it: one on a thread of its own `holds` the file while it takes or holds its write lock, and one on
1214
+ * the calling thread `waits` for those holds before a statement that could wait for the lock on this thread.
1215
+ */
1216
+ fileGate;
1217
+ /**
1218
+ * The hold of the transaction this connection takes or holds the write lock for (see `FileHold`), in a cell of its
1219
+ * own that the thread's exit listener keeps, so the listener does not keep this database.
1220
+ */
1221
+ current = {};
1222
+ /** This connection's share of its file's lock word, which its thread moves as it takes and lets go of the lock. */
1223
+ fileLock;
1224
+ /** That this wrapped connection to its file is open, which scopes the holds of threaded ones (see `FileHold`). */
1225
+ wrappedUse;
1184
1226
  /** The ticket of the writer holding the lock, on its way out of the queue while the transaction runs. */
1185
1227
  leaving;
1186
1228
  /** What the writers' queue gave up on, once per reason, in the order it first happened. */
1187
1229
  degradations = new Map();
1188
- constructor(connection, descriptor, transactionIdentity = connection, lockWaitMs = DEFAULT_NODE_SQLITE_LOCK_WAIT_MS, groupCommitHoldMs = DEFAULT_GROUP_COMMIT_HOLD_MS, openLock) {
1230
+ constructor(connection, descriptor, transactionIdentity = connection, lockWaitMs = DEFAULT_NODE_SQLITE_LOCK_WAIT_MS, groupCommitHoldMs = DEFAULT_GROUP_COMMIT_HOLD_MS, openLock, fileGate) {
1231
+ this.fileGate = fileGate;
1232
+ if (fileGate?.role === "holds" && connection instanceof ThreadConnection) {
1233
+ this.fileLock = useFileLock(fileGate.file);
1234
+ releaseOnExit(connection, this.current, this.fileLock);
1235
+ }
1236
+ if (fileGate?.role === "waits")
1237
+ this.wrappedUse = useWrappedFile(fileGate.file, this);
1189
1238
  this.lockWaitMs = lockWaitMs;
1190
1239
  this.groupCommitHoldMs = groupCommitHoldMs;
1191
1240
  this.transactionIdentity = transactionIdentity;
@@ -1257,7 +1306,8 @@ class NodeSqliteDatabase {
1257
1306
  * between.
1258
1307
  */
1259
1308
  tryBegin() {
1260
- return this.call({ kind: "begin" });
1309
+ const lock = this.fileLock;
1310
+ return this.call(lock === undefined ? { kind: "begin" } : { kind: "begin", lockState: lock.buffer, lockTag: lock.tag });
1261
1311
  }
1262
1312
  /** Changes whenever another connection commits to the database: the lock is being used, not held idle. */
1263
1313
  async dataVersion() {
@@ -1361,14 +1411,27 @@ class NodeSqliteDatabase {
1361
1411
  throw error;
1362
1412
  return cause;
1363
1413
  };
1414
+ // Open from the moment BEGIN is sent: the connection's thread may take the lock while this thread runs on.
1415
+ const hold = this.fileGate?.role === "holds" ? holdFile(this.fileGate.file) : undefined;
1364
1416
  let attempt;
1365
1417
  try {
1366
1418
  attempt = this.tryBegin();
1367
1419
  }
1368
1420
  catch (error) {
1421
+ releaseHold(hold);
1369
1422
  return refusal(error);
1370
1423
  }
1371
- return attempt instanceof Promise ? attempt.then(() => undefined, refusal) : undefined;
1424
+ if (!(attempt instanceof Promise)) {
1425
+ this.current.hold = hold;
1426
+ return undefined;
1427
+ }
1428
+ return attempt.then(() => {
1429
+ this.current.hold = hold;
1430
+ return undefined;
1431
+ }, (error) => {
1432
+ releaseHold(hold);
1433
+ return refusal(error);
1434
+ });
1372
1435
  }
1373
1436
  /**
1374
1437
  * After a refused attempt, while other connections are committing through the lock, keeps attempting it on every
@@ -1421,6 +1484,9 @@ class NodeSqliteDatabase {
1421
1484
  * handed on is still noticed by that writer's recheck timer, so it never fails the transaction.
1422
1485
  */
1423
1486
  async released(committed) {
1487
+ const hold = this.current.hold;
1488
+ this.current.hold = undefined;
1489
+ releaseHold(hold);
1424
1490
  this.lockUse.released(committed);
1425
1491
  const recorded = this.holderRecord?.free();
1426
1492
  const leaving = this.leaving;
@@ -1477,18 +1543,93 @@ class NodeSqliteDatabase {
1477
1543
  const execute = async (request, params = []) => {
1478
1544
  if (!active())
1479
1545
  throw new StorageTransactionClosedError();
1480
- const invalidIndex = params.findIndex((value) => typeof value === "string" && value.includes("\0"));
1546
+ const invalidIndex = invalidTextParam(params);
1481
1547
  if (invalidIndex !== -1)
1482
1548
  throw new StorageInvalidTextError(invalidIndex);
1483
1549
  return this.call(request);
1484
1550
  };
1485
- return {
1551
+ const executor = {
1486
1552
  checkJsonbExtract: () => execute({ kind: "jsonbExtract" }),
1487
1553
  exec: (sql) => execute({ kind: "exec", sql }),
1488
1554
  run: (sql, ...params) => execute({ kind: "run", sql, params }, params),
1489
1555
  get: (sql, ...params) => execute({ kind: "get", sql, params }, params),
1490
1556
  all: (sql, ...params) => execute({ kind: "all", sql, params }, params),
1491
1557
  };
1558
+ // On the calling thread a sequence would hold the event loop for all of its statements.
1559
+ const connection = this.connection;
1560
+ if (connection instanceof ThreadConnection)
1561
+ offerSequences(executor, (sequence) => this.sendSequence(connection, sequence, active));
1562
+ return executor;
1563
+ }
1564
+ /**
1565
+ * Sends `sequence` to the connection's thread: `repeat` with the first statements as one request, and the rest in
1566
+ * requests of at most `MAX_SEQUENCE_REQUEST_STATEMENTS`, each taken from `statements` and sent once the one before it
1567
+ * has run. The thread reads the signal, through a flag shared with it, where a caller running the statements one at a
1568
+ * time would check it. A statement whose text holds NUL fails as `run` fails it, after the statements before it ran.
1569
+ */
1570
+ async sendSequence(connection, { repeat, statements, signal }, active) {
1571
+ const repeats = repeat !== undefined && repeat.times > 0 ? repeat : undefined;
1572
+ const repeatInvalid = repeats === undefined ? -1 : invalidTextParam(repeats.statement.params);
1573
+ if (repeatInvalid !== -1) {
1574
+ signal?.throwIfAborted();
1575
+ throw new StorageInvalidTextError(repeatInvalid);
1576
+ }
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);
1583
+ try {
1584
+ const pending = statements[Symbol.iterator]();
1585
+ let invalid = -1;
1586
+ let taken = false;
1587
+ let repeated = 0;
1588
+ for (let first = true; !taken || first; first = false) {
1589
+ const batch = [];
1590
+ while (!taken && batch.length < MAX_SEQUENCE_REQUEST_STATEMENTS) {
1591
+ const next = pending.next();
1592
+ if (next.done === true) {
1593
+ taken = true;
1594
+ break;
1595
+ }
1596
+ invalid = invalidTextParam(next.value.params);
1597
+ if (invalid !== -1) {
1598
+ taken = true;
1599
+ break;
1600
+ }
1601
+ batch.push(sendableStatement(next.value));
1602
+ }
1603
+ if (batch.length === 0 && !(first && repeats !== undefined))
1604
+ continue;
1605
+ if (!active())
1606
+ throw new StorageTransactionClosedError();
1607
+ signal?.throwIfAborted();
1608
+ const request = {
1609
+ kind: "sequence",
1610
+ ...(first && repeats !== undefined
1611
+ ? { repeat: { ...repeats, statement: sendableStatement(repeats.statement) } }
1612
+ : {}),
1613
+ statements: batch,
1614
+ ...(shared === undefined ? {} : { abort: shared }),
1615
+ };
1616
+ const answer = (await connection.request(request).catch((cause) => {
1617
+ throw unavailable(this.descriptor, cause);
1618
+ }));
1619
+ if ("aborted" in answer)
1620
+ throw signal?.reason;
1621
+ if (first)
1622
+ repeated = answer.repeated;
1623
+ }
1624
+ if (invalid !== -1) {
1625
+ signal?.throwIfAborted();
1626
+ throw new StorageInvalidTextError(invalid);
1627
+ }
1628
+ return repeated;
1629
+ }
1630
+ finally {
1631
+ watched?.removeEventListener("abort", raise);
1632
+ }
1492
1633
  }
1493
1634
  enqueue(operation) {
1494
1635
  if (this.closing)
@@ -1506,23 +1647,73 @@ class NodeSqliteDatabase {
1506
1647
  return this.enqueue(operation);
1507
1648
  }
1508
1649
  exec(sql) {
1509
- return this.enqueueStatement(() => this.executor.exec(sql));
1650
+ const made = this.holdScope();
1651
+ return this.enqueueStatement(() => this.besideHolds(made, { kind: "exec", sql }, false, () => this.executor.exec(sql)));
1510
1652
  }
1511
1653
  run(sql, ...params) {
1512
1654
  const bound = snapshotParams(params);
1513
- return this.enqueueStatement(() => this.executor.run(sql, ...bound));
1655
+ const made = this.holdScope();
1656
+ return this.enqueueStatement(() => this.besideHolds(made, { kind: "run", sql, params: bound }, true, () => this.executor.run(sql, ...bound)));
1514
1657
  }
1515
1658
  get(sql, ...params) {
1516
1659
  const bound = snapshotParams(params);
1517
- return this.enqueueStatement(() => this.executor.get(sql, ...bound));
1660
+ const made = this.holdScope();
1661
+ return this.enqueueStatement(() => this.besideHolds(made, { kind: "get", sql, params: bound }, true, () => this.executor.get(sql, ...bound)));
1518
1662
  }
1519
1663
  all(sql, ...params) {
1520
1664
  const bound = snapshotParams(params);
1521
- return this.enqueueStatement(() => this.executor.all(sql, ...bound));
1665
+ const made = this.holdScope();
1666
+ return this.enqueueStatement(() => this.besideHolds(made, { kind: "all", sql, params: bound }, true, () => this.executor.all(sql, ...bound)));
1667
+ }
1668
+ /**
1669
+ * Where a call to a connection on the calling thread is made, read when it is made: the transaction callbacks it is
1670
+ * made in, and whether it comes in behind a transaction (see `inBacklog`); see `besideHolds`.
1671
+ */
1672
+ holdScope() {
1673
+ if (this.fileGate?.role !== "waits")
1674
+ return undefined;
1675
+ return { scope: currentHoldScope(), backlog: inBacklog(this.fileGate.file) };
1676
+ }
1677
+ /**
1678
+ * Runs `call`, one call of a connection on the calling thread to a file, without holding this thread while another
1679
+ * connection of this process, on a thread of its own, takes or holds the file's write lock: SQLite's busy handler
1680
+ * would wait for that lock on this thread, which that connection's transaction needs to go on. While no such
1681
+ * transaction is starting or open, and for every other connection, the call runs at once, as it always has; so does
1682
+ * a call made inside that transaction's callback (`scope`), which the transaction waits for. Otherwise a single
1683
+ * statement (`request`, run synchronously) whose plan proves a refusal has done nothing is tried at once with a busy
1684
+ * timeout of 0 and, refused the lock, waits off this thread and is tried again (see `runTryingFirst`); any other runs
1685
+ * as it always has; a script of several statements waits until no transaction of this thread holds the lock (see
1686
+ * `modeOf`). A call made while an earlier call of the same connection waits is decided and run in its turn behind it
1687
+ * (see `runDeferred`). Parameters `call` refuses (text with a NUL) are refused before anything else, as `call` would
1688
+ * at once.
1689
+ */
1690
+ besideHolds(made, request, single, call) {
1691
+ if (made === undefined || this.fileGate?.role !== "waits" || !(this.connection instanceof CallerThreadConnection))
1692
+ return call();
1693
+ const { file } = this.fileGate;
1694
+ const gate = heldElsewhere(file, made.scope, made.backlog);
1695
+ if (gate === undefined)
1696
+ return call();
1697
+ const params = "params" in request ? request.params : [];
1698
+ if (params.some((value) => typeof value === "string" && value.includes("\0")))
1699
+ return call();
1700
+ const owner = this.connection;
1701
+ const database = owner.connection;
1702
+ const attempt = () => this.call(request);
1703
+ const busy = () => unavailable(this.descriptor, sqliteBusyError());
1704
+ if (connectionWaits(gate, database))
1705
+ return runDeferred(file, gate, owner, database, { sql: request.sql, params, single }, attempt, call, busy);
1706
+ const mode = modeOf(gate, owner, database, request.sql, params, single);
1707
+ if (mode === "as before")
1708
+ return call();
1709
+ if (mode === "script")
1710
+ return runWhenFree(file, gate, owner, database, call, busy);
1711
+ return runTryingFirst(file, gate, owner, database, attempt, call, busy);
1522
1712
  }
1523
1713
  /** Idle-only housekeeping: do not join a batch, wait behind an operation on this handle or another handle's
1524
1714
  * transaction, or get in front of writers already waiting on another process. */
1525
1715
  async tryMaintenance(callback) {
1716
+ const scope = currentHoldScope();
1526
1717
  const position = this.enqueued;
1527
1718
  let idle = false;
1528
1719
  void this.tail.then(() => {
@@ -1559,7 +1750,7 @@ class NodeSqliteDatabase {
1559
1750
  }
1560
1751
  this.acquired(start);
1561
1752
  return new Promise((resolve, reject) => {
1562
- void this.commitAlone({ callback, resolve: () => resolve(true), reject }).catch(reject);
1753
+ void this.commitAlone({ callback, resolve: () => resolve(true), reject, scope }).catch(reject);
1563
1754
  });
1564
1755
  });
1565
1756
  });
@@ -1603,6 +1794,7 @@ class NodeSqliteDatabase {
1603
1794
  resolve: resolve,
1604
1795
  reject,
1605
1796
  lockWaitMs: options?.lockWaitMs,
1797
+ scope: currentHoldScope(),
1606
1798
  };
1607
1799
  const last = this.waitingBatches.at(-1);
1608
1800
  if (last?.open === true && last.members.length < MAX_GROUP_COMMIT_TRANSACTIONS) {
@@ -1664,7 +1856,7 @@ class NodeSqliteDatabase {
1664
1856
  async commitAlone(queued) {
1665
1857
  let active = true;
1666
1858
  try {
1667
- const value = await queued.callback(this.createExecutor(() => active));
1859
+ const value = await runInHold(this.current.hold, queued.scope, () => queued.callback(this.createExecutor(() => active)));
1668
1860
  active = false;
1669
1861
  await this.executor.exec("COMMIT");
1670
1862
  await this.released(true);
@@ -1698,7 +1890,7 @@ class NodeSqliteDatabase {
1698
1890
  let active = true;
1699
1891
  try {
1700
1892
  await this.executor.exec(`SAVEPOINT ${savepoint}`);
1701
- const value = await queued.callback(this.createExecutor(() => active));
1893
+ const value = await runInHold(this.current.hold, queued.scope, () => queued.callback(this.createExecutor(() => active)));
1702
1894
  active = false;
1703
1895
  await this.executor.exec(`RELEASE ${savepoint}`);
1704
1896
  outcomes.push({ ok: true, value });
@@ -1771,10 +1963,14 @@ class NodeSqliteDatabase {
1771
1963
  this.closing = true;
1772
1964
  this.closePromise = this.tail.then(async () => {
1773
1965
  try {
1966
+ if (this.fileGate?.role === "waits")
1967
+ forgetPlans(this.fileGate.file, this.connection);
1774
1968
  await this.holderRecord?.close();
1775
1969
  await this.call({ kind: "close" });
1776
1970
  }
1777
1971
  finally {
1972
+ this.wrappedUse?.release();
1973
+ this.fileLock?.release();
1778
1974
  await releaseOpenLock(this.openLock);
1779
1975
  }
1780
1976
  });
@@ -1877,7 +2073,11 @@ export async function openNodeSqliteDatabase(path, { busyTimeoutMs = 5000, lockW
1877
2073
  await releaseOpenLock(heldOpenLock);
1878
2074
  heldOpenLock = await acquireOpenLock(identity, readOnly, busyTimeoutMs);
1879
2075
  }
1880
- const database = new NodeSqliteDatabase(connection, descriptor, identity, lockWaitMs, holdMs, heldOpenLock);
2076
+ // A file this process may also reach through a connection on the calling thread; see `FileHold`.
2077
+ const gateFile = typeof identity === "string" && connection instanceof ThreadConnection
2078
+ ? await fileIdentityAsync(identity)
2079
+ : undefined;
2080
+ const database = new NodeSqliteDatabase(connection, descriptor, identity, lockWaitMs, holdMs, heldOpenLock, gateFile === undefined ? undefined : { file: gateFile, role: "holds" });
1881
2081
  Object.defineProperty(database, "readOnly", { value: readOnly });
1882
2082
  if (!readOnly)
1883
2083
  await database.openHolderRecord();
@@ -1909,7 +2109,8 @@ export function wrapNodeSqliteDatabase(connection) {
1909
2109
  // SQLite does not wait for another process's lock while it changes the mode; the switch waits itself.
1910
2110
  switchToWriteAheadLogSync((sql) => connection.exec(sql), WRAPPED_BUSY_TIMEOUT_MS);
1911
2111
  connection.exec("PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON");
1912
- return new NodeSqliteDatabase(new CallerThreadConnection(connection, false), descriptor, connection, undefined, undefined, heldOpenLock);
2112
+ const gateFile = descriptor.location === ":memory:" ? undefined : fileIdentity(descriptor.location);
2113
+ return new NodeSqliteDatabase(new CallerThreadConnection(connection, false), descriptor, connection, undefined, undefined, heldOpenLock, gateFile === undefined ? undefined : { file: gateFile, role: "waits" });
1913
2114
  }
1914
2115
  catch (cause) {
1915
2116
  void releaseOpenLock(heldOpenLock);