@bastani/atomic 0.10.7-alpha.1 → 0.10.8-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 (263) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/_shared/dist-KOELCESV.js +2 -2
  3. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  4. package/dist/_shared/lib-4PES5P4V.js +2 -2
  5. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +5 -5
  6. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +5 -5
  7. package/dist/_shared/mode-shared-2QJSCUM6.js +5 -5
  8. package/dist/_shared/p1a-prewarm-UQY3X2UK.js +3 -3
  9. package/dist/_shared/runtime-O4KCSG4C.js +2 -2
  10. package/dist/_shared/{sdk-WQIOHVKO.js → sdk-OSBEPR3Q.js} +2875 -12
  11. package/dist/_shared/sdk-OSBEPR3Q.js.map +1 -0
  12. package/dist/_shared/session-data-AHTU7IS6.js +3 -3
  13. package/dist/_shared/startup-0-0-TYUFUOJZ.js +2 -2
  14. package/dist/_shared/startup-0-1-W2G2UY7R.js +163 -163
  15. package/dist/_shared/startup-0-1-W2G2UY7R.js.map +1 -1
  16. package/dist/_shared/{startup-0-2-SZGQIWHI.js → startup-0-2-UXBUEOXW.js} +4 -4
  17. package/dist/_shared/{startup-0-2-SZGQIWHI.js.map → startup-0-2-UXBUEOXW.js.map} +1 -1
  18. package/dist/_shared/startup-0-3-T4DVFYWX.js +3 -3
  19. package/dist/_shared/startup-0-4-HN5EB4K7.js +3 -3
  20. package/dist/_shared/{startup-0-5-OHJNE6JH.js → startup-0-5-FD2P735I.js} +5 -5
  21. package/dist/_shared/{startup-0-5-OHJNE6JH.js.map → startup-0-5-FD2P735I.js.map} +1 -1
  22. package/dist/_shared/startup-10-0-TDQNBDDL.js +5 -5
  23. package/dist/_shared/startup-12-0-55AAXBJZ.js +2 -2
  24. package/dist/_shared/startup-14-0-MLX36RBG.js +17 -4
  25. package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
  26. package/dist/_shared/startup-15-0-YUKGAC63.js +3 -3
  27. package/dist/_shared/startup-15-1-4S7FLMNG.js +5 -5
  28. package/dist/_shared/startup-8-0-34CBHPZH.js +3 -3
  29. package/dist/_shared/{startup-8-1-SJW2GMAM.js → startup-8-1-4KANEHRA.js} +6 -6
  30. package/dist/_shared/{startup-8-1-SJW2GMAM.js.map → startup-8-1-4KANEHRA.js.map} +1 -1
  31. package/dist/_shared/storage-command-7MGXLJGZ.js +3 -3
  32. package/dist/_shared/task-reference-stream-JWMUZSJX.js +1 -1
  33. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  34. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  35. package/dist/builtin/intercom/index.bundle.mjs +1 -1
  36. package/dist/builtin/intercom/package.json +1 -1
  37. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  38. package/dist/builtin/mcp/package.json +1 -1
  39. package/dist/builtin/subagents/CHANGELOG.md +11 -0
  40. package/dist/builtin/subagents/package.json +1 -1
  41. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  42. package/dist/builtin/web-access/index.bundle.mjs +1 -1
  43. package/dist/builtin/web-access/package.json +1 -1
  44. package/dist/cli/auth-cli.code.js +3 -3
  45. package/dist/cli/auth-cli.impl.js +3 -3
  46. package/dist/cli/auth-cli.js +3 -3
  47. package/dist/cli/blueprint-command.code.js +2 -2
  48. package/dist/cli/blueprint-command.impl.js +3 -3
  49. package/dist/cli/blueprint-command.js +3 -3
  50. package/dist/cli/intercom-command.code.js +3 -3
  51. package/dist/cli/intercom-command.impl.js +3 -3
  52. package/dist/cli/intercom-command.js +3 -3
  53. package/dist/cli/list-models.impl.js +3 -3
  54. package/dist/cli/list-models.js +3 -3
  55. package/dist/cli/session-picker.code.js +1 -1
  56. package/dist/cli/session-picker.impl.js +3 -3
  57. package/dist/cli/session-picker.js +3 -3
  58. package/dist/cli/startup-ui.code.js +1 -1
  59. package/dist/cli/startup-ui.impl.js +3 -3
  60. package/dist/cli/startup-ui.js +3 -3
  61. package/dist/cli/storage-command.impl.js +3 -3
  62. package/dist/cli/storage-command.js +3 -3
  63. package/dist/cli/storage-search-session.code.js +2 -2
  64. package/dist/cli/storage-search-session.impl.js +3 -3
  65. package/dist/cli/storage-search-session.js +3 -3
  66. package/dist/cli/team-command.code.js +2 -2
  67. package/dist/cli/team-command.impl.js +3 -3
  68. package/dist/cli/team-command.js +3 -3
  69. package/dist/cli.js +2 -2
  70. package/dist/core/debug.impl.js +3 -3
  71. package/dist/core/debug.js +3 -3
  72. package/dist/core/export-html/card-projection.code.js +1 -1
  73. package/dist/core/export-html/card-projection.impl.js +3 -3
  74. package/dist/core/export-html/card-projection.js +3 -3
  75. package/dist/core/export-html/index.code.js +2 -2
  76. package/dist/core/export-html/index.impl.js +3 -3
  77. package/dist/core/export-html/index.js +3 -3
  78. package/dist/core/export-html/json-spans.impl.js +3 -3
  79. package/dist/core/export-html/json-spans.js +3 -3
  80. package/dist/core/export-html/oversized-render-inputs.code.js +1 -1
  81. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  82. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  83. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  84. package/dist/core/export-html/tool-renderer.js +3 -3
  85. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  86. package/dist/core/extensions/jiti-loader.js +3 -3
  87. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  88. package/dist/core/extensions/jiti-static-loader.js +3 -3
  89. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  90. package/dist/core/extensions/loader-host-modules.js +3 -3
  91. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  92. package/dist/core/extensions/runner-context.js +1 -1
  93. package/dist/core/intercom-broker-control-host.code.js +1 -1
  94. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  95. package/dist/core/intercom-broker-control-host.js +3 -3
  96. package/dist/core/intercom-broker-control.code.js +2 -2
  97. package/dist/core/intercom-broker-control.impl.js +3 -3
  98. package/dist/core/intercom-broker-control.js +3 -3
  99. package/dist/core/model-registry.js +1 -1
  100. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  101. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  102. package/dist/core/package-manager-storage-adapters.js +3 -3
  103. package/dist/core/sdk.code.js +3 -3
  104. package/dist/core/sdk.impl.js +3 -3
  105. package/dist/core/sdk.js +3 -3
  106. package/dist/core/session-claims.d.ts +30 -0
  107. package/dist/core/session-lifecycle-work.d.ts +74 -0
  108. package/dist/core/session-manager-core.js +4 -4
  109. package/dist/core/session-manager-list.impl.js +3 -3
  110. package/dist/core/session-manager-list.js +3 -3
  111. package/dist/core/session-manager.impl.js +3 -3
  112. package/dist/core/session-manager.js +3 -3
  113. package/dist/core/session-storage.code.js +1 -1
  114. package/dist/core/session-storage.impl.js +3 -3
  115. package/dist/core/session-storage.js +3 -3
  116. package/dist/core/storage/index.js +2 -2
  117. package/dist/core/storage/node-sqlite-thread.js +2 -2
  118. package/dist/core/storage/node-sqlite.js +2 -2
  119. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  120. package/dist/core/storage/offline-snapshot-file.js +3 -3
  121. package/dist/core/storage/provider.js +2 -2
  122. package/dist/core/storage/selection.js +2 -2
  123. package/dist/core/storage/session/branch-fork-source.code.js +2 -2
  124. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  125. package/dist/core/storage/session/branch-fork-source.js +3 -3
  126. package/dist/core/storage/session/card-view.impl.js +3 -3
  127. package/dist/core/storage/session/card-view.js +3 -3
  128. package/dist/core/storage/session/child-reader.code.js +2 -2
  129. package/dist/core/storage/session/child-reader.impl.js +3 -3
  130. package/dist/core/storage/session/child-reader.js +3 -3
  131. package/dist/core/storage/session/chunked-resume-projection.code.js +1 -1
  132. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  133. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  134. package/dist/core/storage/session/expanded-child-details.code.js +3 -3
  135. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  136. package/dist/core/storage/session/expanded-child-details.js +3 -3
  137. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  138. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  139. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  140. package/dist/core/storage/session/fork-row-index.js +3 -3
  141. package/dist/core/storage/session/fork-staging.code.js +1 -1
  142. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  143. package/dist/core/storage/session/fork-staging.js +3 -3
  144. package/dist/core/storage/session/fork-window.code.js +2 -2
  145. package/dist/core/storage/session/fork-window.impl.js +3 -3
  146. package/dist/core/storage/session/fork-window.js +3 -3
  147. package/dist/core/storage/session/history-pages.impl.js +3 -3
  148. package/dist/core/storage/session/history-pages.js +3 -3
  149. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  150. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  151. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  152. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  153. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  154. package/dist/core/storage/session/memory-session-store.js +3 -3
  155. package/dist/core/storage/session/pinned-branch-resume.code.js +2 -2
  156. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  157. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  158. package/dist/core/storage/session/released-history-files.code.js +1 -1
  159. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  160. package/dist/core/storage/session/released-history-files.js +3 -3
  161. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  162. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  163. package/dist/core/storage/session/session-resume.impl.js +3 -3
  164. package/dist/core/storage/session/session-resume.js +3 -3
  165. package/dist/core/storage/session/session-search-index.d.ts +39 -0
  166. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  167. package/dist/core/storage/session/snapshot-cut.js +3 -3
  168. package/dist/core/storage/session/snapshot-history.code.js +2 -2
  169. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  170. package/dist/core/storage/session/snapshot-history.js +3 -3
  171. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  172. package/dist/core/storage/session/sql-session-store.d.ts +400 -0
  173. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  174. package/dist/core/storage/session/sql-session-store.js +3 -3
  175. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  176. package/dist/core/storage/session/tree-outline.js +3 -3
  177. package/dist/core/storage/session/tree-presentation.code.js +1 -1
  178. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  179. package/dist/core/storage/session/tree-presentation.js +3 -3
  180. package/dist/core/storage/session/yield-turn.d.ts +3 -0
  181. package/dist/core/storage/storage-status.code.js +1 -1
  182. package/dist/core/storage/storage-status.impl.js +3 -3
  183. package/dist/core/storage/storage-status.js +3 -3
  184. package/dist/core/storage/team.code.js +1 -1
  185. package/dist/core/storage/team.impl.js +3 -3
  186. package/dist/core/storage/team.js +3 -3
  187. package/dist/core/storage/transfer-files.d.ts +74 -0
  188. package/dist/core/structured-output/index.code.js +1 -1
  189. package/dist/core/structured-output/index.impl.js +3 -3
  190. package/dist/core/structured-output/index.js +3 -3
  191. package/dist/core/tasks/task-completion-entry.code.js +1 -1
  192. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  193. package/dist/core/tasks/task-completion-entry.js +3 -3
  194. package/dist/core/tasks/task-file-history.code.js +2 -2
  195. package/dist/core/tasks/task-file-history.impl.js +3 -3
  196. package/dist/core/tasks/task-file-history.js +3 -3
  197. package/dist/core/tasks/task-reference-archive.code.js +3 -3
  198. package/dist/core/tasks/task-reference-archive.js +3 -3
  199. package/dist/core/tasks/task-reference-identity.js +3 -3
  200. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  201. package/dist/core/tasks/task-reference-stream.js +3 -3
  202. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  203. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  204. package/dist/core/tasks/task-view-source.code.js +1 -1
  205. package/dist/core/tasks/task-view-source.impl.js +3 -3
  206. package/dist/core/tasks/task-view-source.js +3 -3
  207. package/dist/core/tools/read-url.code.js +1 -1
  208. package/dist/core/tools/read-url.impl.js +3 -3
  209. package/dist/core/tools/read-url.js +3 -3
  210. package/dist/core/worktree-snapshot/blob-store.js +2 -2
  211. package/dist/core/worktree-snapshot/errors.code.js +1 -1
  212. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  213. package/dist/core/worktree-snapshot/errors.js +3 -3
  214. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  215. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  216. package/dist/extensions/codemode/execute.code.js +1 -1
  217. package/dist/extensions/codemode/execute.impl.js +3 -3
  218. package/dist/extensions/codemode/execute.js +3 -3
  219. package/dist/extensions/codemode/renderer.code.js +1 -1
  220. package/dist/extensions/codemode/renderer.impl.js +3 -3
  221. package/dist/extensions/codemode/renderer.js +3 -3
  222. package/dist/extensions/mcp/cli.code.js +2 -2
  223. package/dist/extensions/mcp/cli.impl.js +3 -3
  224. package/dist/extensions/mcp/cli.js +3 -3
  225. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  226. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  227. package/dist/extensions/mcp/cli.lazy.js +3 -3
  228. package/dist/extensions/mcp/runtime.code.js +1 -1
  229. package/dist/extensions/mcp/runtime.impl.js +3 -3
  230. package/dist/extensions/mcp/runtime.js +3 -3
  231. package/dist/index.d.ts +13 -3
  232. package/dist/index.js +11 -11
  233. package/dist/main-first-time-setup.code.js +1 -1
  234. package/dist/main-first-time-setup.impl.js +3 -3
  235. package/dist/main-first-time-setup.js +3 -3
  236. package/dist/main.js +1 -1
  237. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  238. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  239. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  240. package/dist/modes/interactive/components/user-message-selector-archive.code.js +1 -1
  241. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  242. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  243. package/dist/modes/print-mode.js +1 -1
  244. package/dist/package-manager-cli.code.js +4 -4
  245. package/dist/package-manager-cli.impl.js +3 -3
  246. package/dist/package-manager-cli.js +3 -3
  247. package/dist/startup-files.json +1 -1
  248. package/dist/startup-stages/10.js +1 -1
  249. package/dist/startup-stages/12.js +1 -1
  250. package/dist/startup-stages/8.js +1 -1
  251. package/dist/utils/startup-database-spare.code.js +1 -1
  252. package/dist/utils/startup-database-spare.impl.js +3 -3
  253. package/dist/utils/startup-database-spare.js +3 -3
  254. package/dist/utils/tools-manager.impl.js +3 -3
  255. package/dist/utils/tools-manager.js +3 -3
  256. package/docs/sdk/reference.md +85 -0
  257. package/docs/sdk.md +23 -1
  258. package/package.json +8 -8
  259. package/dist/_shared/fork-staging-maintenance-AIIUXOZQ.js +0 -19
  260. package/dist/_shared/fork-staging-maintenance-AIIUXOZQ.js.map +0 -1
  261. package/dist/_shared/sdk-WQIOHVKO.js.map +0 -1
  262. package/dist/_shared/sql-session-store-5FD3WBMZ.js +0 -2903
  263. package/dist/_shared/sql-session-store-5FD3WBMZ.js.map +0 -1
@@ -1,2903 +0,0 @@
1
- import "./rolldown-runtime-BGM3D5V3.js";
2
- import { SqlSnapshotBlobStore, snapshotIndexTables } from "../core/worktree-snapshot/blob-store.js";
3
- import { dialectOf, postgresJsonb } from "../core/storage/dialect.js";
4
- import { SessionBlobError, StorageError, StorageInvalidTextError, StorageSchemaVersionError } from "../core/storage/errors.js";
5
- import { renderStorageIdentifiers, storageMigrationTable, validateStoragePrefix } from "../core/storage/prefix.js";
6
- import { assertStorageSchemaVersion, assertStoredSchemaVersion } from "../core/storage/schema.js";
7
- import { applyStorageMigrationsTogether, statementBatch } from "../core/storage/statement-batches.js";
8
- import { sequenceRunner } from "../core/storage/statement-sequence.js";
9
- import { announceHistoryLoad, applySessionSummaryEntries, bindChatEpoch, boundedChatRecord, decodeChatOrder, decodeChatRecord, encodeChatOrder, firstChatOrders, hasHistoryLoadObserver, materializeSessionSummaryMetadata, nativeForkReader, noteSnapshotGeneration, registerArchiveLoad, registerForkScope, registerHistorySnapshot, sha256Hex, yieldTurn } from "./startup-0-0-TYUFUOJZ.js";
10
- import { SessionConflictError, SessionExistsError, SessionIdMismatchError, SessionNotFoundError, StorageUnavailableError as StorageUnavailableError$1, StoreClosedError as StoreClosedError$1 } from "../core/storage/session/errors.js";
11
- import { tryCleanupForkStaging } from "./fork-staging-maintenance-AIIUXOZQ.js";
12
- import { RESUME_UPGRADE_SOURCES, branchRanges, childCatalogCut, foldSessionResume, foreignResumeIds, isSessionResumeIndex, isUpgradableSessionResumeIndex, latestCompactionOf, readEarlierCompletionIntents, selectedPagePlan, sessionResumeFrom, sessionResumePlan, sessionResumeUpgrade, sessionTailFrom, snapshotCutOf, stateSeqsBefore, transcriptBranchSpan, validateSessionEntries, validateSessionHeader, validateSessionText } from "./startup-8-0-34CBHPZH.js";
13
- import { SqlSessionSearchIndex } from "./startup-0-1-W2G2UY7R.js";
14
- import { SESSION_HISTORY_CHUNK_BYTES, SESSION_HISTORY_PAGE_BYTES, entrySizeLimit } from "./settings-startup-4QCVCI53.js";
15
- // dist/core/storage/session/sql-chat-records.js
16
- /** Rows one read fetches at most. */
17
- const READ_PAGE_ROWS = 64;
18
- /**
19
- * The stored bytes (anchor and record) one read returns at most, after its first row. With the server's own overhead
20
- * for 64 rows it stays under a libSQL server configured for 150 KB responses; a capped record is under 25 KB.
21
- */
22
- const CHAT_READ_PAGE_BYTES = 12e4;
23
- /** Prompt ids one reverse lookup binds at most. */
24
- const ORDER_BATCH = 128;
25
- /**
26
- * The stored keys of a position's records (`L`) and of a prompt's reverse edge (`O`). Entry ids are any text, so only
27
- * a tag of its own keeps every position's key apart from every prompt's: a reverse lookup never matches a body.
28
- */
29
- const lineKey = (anchor) => `L${anchor}`;
30
- const orderKey = (promptId) => `O${promptId}`;
31
- /**
32
- * Each write runs in a transaction of its own, as every session write does, on the session writer's connection and
33
- * in its order. A statement outside a transaction would wait for another process's write lock in node:sqlite's busy
34
- * handler, which blocks the event loop for up to the busy timeout (#5682); a transaction waits for the lock without
35
- * blocking it. A transient failure runs the write again, as one statement outside a transaction would.
36
- */
37
- const SIDE_WRITE = { retryTransientFailures: true };
38
- /** A new physical table per format version; the main sessions schema (and all its old readers) stay unchanged. */
39
- function sqlChatRecords(database, sessions, table, index) {
40
- const dialect = dialectOf(database);
41
- let initialized;
42
- function initialize() {
43
- const create = () => database.transaction(async (tx) => {
44
- await tx.exec(`CREATE TABLE IF NOT EXISTS ${table} (
45
- position ${dialect.types.serialKey}, session_id TEXT NOT NULL REFERENCES ${sessions}(id) ON DELETE CASCADE,
46
- epoch TEXT NOT NULL, anchor TEXT NOT NULL, data TEXT NOT NULL)`);
47
- await tx.exec(`CREATE INDEX IF NOT EXISTS ${index} ON ${table}(session_id, epoch, anchor, position)`);
48
- }, SIDE_WRITE);
49
- initialized ??= create().catch(() => create()).catch((error) => {
50
- initialized = void 0;
51
- throw error;
52
- });
53
- return initialized;
54
- }
55
- const current = dialect.jsonText("summary_state", "epoch");
56
- const bytes = (column) => dialect.textByteLength(column);
57
- return {
58
- async append(owner, anchor, record) {
59
- record = boundedChatRecord(record);
60
- await initialize();
61
- const rows = [[lineKey(anchor), JSON.stringify({
62
- v: 1,
63
- ...record
64
- })]];
65
- if (record.kind === "promptBefore") rows.push([orderKey(record.promptId), encodeChatOrder({
66
- anchor,
67
- promptId: record.promptId
68
- })]);
69
- await database.transaction((tx) => tx.run(`INSERT INTO ${table} (session_id,epoch,anchor,data) ${rows.map(() => `SELECT id,?,?,? FROM ${sessions} WHERE id=? AND ${current}=?`).join(" UNION ALL ")}`, ...rows.flatMap(([key, data]) => [
70
- owner.epoch,
71
- key,
72
- data,
73
- owner.id,
74
- owner.epoch
75
- ])), SIDE_WRITE);
76
- },
77
- async has(owner) {
78
- return !!await database.get(`SELECT 1 AS present FROM ${table} WHERE session_id=? AND epoch=? LIMIT 1`, owner.id, owner.epoch).catch(() => void 0);
79
- },
80
- async read(owner, anchors) {
81
- if (!anchors.length) return [];
82
- const result = [];
83
- let after = 0;
84
- for (;;) {
85
- const rows = await database.all(`SELECT position,anchor,data,fetched FROM (
86
- SELECT position,anchor,data,count(*) OVER () AS fetched,
87
- row_number() OVER (ORDER BY position) AS page_row,
88
- sum(${bytes("anchor")}+${bytes("data")}) OVER (ORDER BY position) AS page_bytes
89
- FROM (SELECT position,anchor,data FROM ${table}
90
- WHERE session_id=? AND epoch=? AND position>? AND anchor IN (${anchors.map(() => "?").join(",")})
91
- ORDER BY position LIMIT ${READ_PAGE_ROWS}) AS candidates
92
- ) AS page WHERE page_row=1 OR page_bytes<=? ORDER BY position`, owner.id, owner.epoch, after, ...anchors.map(lineKey), CHAT_READ_PAGE_BYTES);
93
- for (const { anchor, data } of rows) {
94
- const record = decodeChatRecord(data);
95
- if (record) result.push({
96
- anchor: anchor.slice(1),
97
- record
98
- });
99
- }
100
- const last = rows[rows.length - 1];
101
- if (!last || Number(last.fetched) < READ_PAGE_ROWS && rows.length === Number(last.fetched)) return result;
102
- after = last.position;
103
- }
104
- },
105
- async readOrders(owner, promptIds) {
106
- const orders = [];
107
- for (let i = 0; i < promptIds.length; i += ORDER_BATCH) {
108
- const keys = promptIds.slice(i, i + ORDER_BATCH).map(orderKey);
109
- const rows = await database.all(`SELECT data FROM ${table} WHERE session_id=? AND epoch=? AND anchor IN (${keys.map(() => "?").join(",")}) ORDER BY position`, owner.id, owner.epoch, ...keys);
110
- for (const { data } of rows) {
111
- const order = decodeChatOrder(data);
112
- if (order) orders.push(order);
113
- }
114
- }
115
- return firstChatOrders(orders, promptIds);
116
- }
117
- };
118
- }
119
- // dist/core/storage/session/sql-session-store.js
120
- /**
121
- * The newest sessions schema this build reads and writes. Version 2 stores long entries in chunks (#4954), which a build
122
- * that knows only version 1 would read as stubs. A database stays at version 1, which older builds still open, until
123
- * this build writes its first chunked entry: that transaction moves the sessions meta to 2, and older builds refuse it
124
- * when next opened with `StorageSchemaVersionError`. Builds before 2 check only the meta row, on SQLite and Postgres alike.
125
- */
126
- const SESSION_SCHEMA_VERSION = 2;
127
- /** The sessions schema of a database without chunked entries, which older builds read too. */
128
- const SESSION_SCHEMA_VERSION_UNCHUNKED = 1;
129
- /** The schema domain of the session tables in the prefix's migration ledger. */
130
- const SESSION_DOMAIN = "sessions";
131
- /**
132
- * The most bytes of a chunked session blob one row holds. New blobs use a header row and rows of at most this size,
133
- * so their bound and returned values stay within it: libSQL servers cap a row and a bound value (sqld's default is
134
- * 5 MB) and a statement's response (10 MB), and the HTTP protocol carries a blob as base64 in JSON, about 1.4 MB for
135
- * this size. A different size needs different table names, because a blob's rows are addressed by their index.
136
- */
137
- const SESSION_BLOB_CHUNK_BYTES = 1048576;
138
- /**
139
- * The most bytes of an entry's JSON one row of the entries table holds. A longer entry is stored as a stub in its
140
- * entries row, which keeps its `type`, `id` and `parentId` for the snapshot reference index, and its UTF-8 JSON in
141
- * rows of at most this many bytes in the entry chunks table, written in the entry's transaction (#4954). Like
142
- * {@link SESSION_BLOB_CHUNK_BYTES} it stays well under the smallest backend limit, sqld's 5,000,000 bytes per value
143
- * and per row. Snapshot entries are never split: the reference index reads their whole JSON.
144
- */
145
- const SESSION_ENTRY_CHUNK_BYTES = 1048576;
146
- /**
147
- * The bytes of a chunked message's JSON an unindexed fork reads to learn its role. The role follows the entry's type,
148
- * IDs and timestamp, a few hundred bytes in.
149
- */
150
- const FORK_ROLE_PREFIX_BYTES = 4096;
151
- /**
152
- * The most characters one read of entries or listing rows returns, by the stored text's `length()`. A character is at
153
- * most four bytes of UTF-8 and a JSON escape at most doubles a character on a server's wire, so a page stays under
154
- * sqld's 10 MB response limit; a single row longer than this is a page of its own (#4954).
155
- */
156
- const SESSION_READ_PAGE_CHARS = 1048576;
157
- /** Maximum entries folded per resume metadata query. */
158
- const SESSION_RESUME_REBUILD = { pageEntries: 512 };
159
- /** Bound each write transaction while reusing the bytes already supplied to putBlob. */
160
- const LEGACY_BLOB_BATCH_CHUNKS = 16;
161
- const SESSION_TABLES = Object.freeze({
162
- meta: "meta",
163
- sessions: "sessions",
164
- entries: "entries",
165
- searchTexts: "search_texts",
166
- blobs: "blobs",
167
- blobChunks: "blob_chunks",
168
- entryChunks: "entry_chunks"
169
- });
170
- /**
171
- * The staging table of full-session clones from a handle this store cannot prove to be its own connection (#5594):
172
- * `<prefix>session_fork_staging`, created by the first such clone, never by an open, and not part of the sessions schema.
173
- */
174
- const SESSION_FORK_STAGING_TABLES = Object.freeze({ forkStaging: "fork_staging" });
175
- /** The schema domain, in the prefix's migration ledger, of the table of open sessions (#4971). */
176
- const SESSION_PRESENCE_DOMAIN = "session-presence";
177
- const SESSION_PRESENCE_TABLES = Object.freeze({ open: "open" });
178
- function windowIndex(state, seq) {
179
- return isSessionResumeIndex(state.windowResume, seq) ? state.windowResume : isSessionResumeIndex(state.resume, seq) ? state.resume : void 0;
180
- }
181
- /** An older client rebuilds summary_state.resume in its own format. Do not evict that valid projection
182
- * on a read: once either side sees a version-5 index, keep this version in its own field. */
183
- function windowFields(previous, index, seq, epoch) {
184
- if (previous?.resume?.version === 5 || previous?.windowResume) {
185
- const older = previous.resume;
186
- return {
187
- ...older?.version === 5 && older.seq === seq && older.epoch === epoch ? { resume: older } : {},
188
- ...index ? { windowResume: index } : {}
189
- };
190
- }
191
- return index ? { resume: index } : {};
192
- }
193
- const SEQ_BATCH = 500;
194
- /**
195
- * The rows one statement of a paged read fetches, by key after the previous page, before it keeps those that fit in
196
- * {@link SESSION_READ_PAGE_CHARS}: each statement reads a bounded batch rather than every remaining row, so a long
197
- * session or listing is read in linear time. A full batch quadruples the next fetch. A clipped batch keeps its fetch
198
- * size when its unreturned text is at most four pages; otherwise the next fetch is twice the returned rows.
199
- */
200
- const SESSION_READ_FETCH = {
201
- first: 1024,
202
- min: 1,
203
- max: 8192
204
- };
205
- const SESSION_READ_INLINE_BYTES = 4096;
206
- function nextFetch(limit, rows) {
207
- const kept = rows.length;
208
- const fetched = Number(rows[0]?.fetched ?? 0);
209
- const more = kept > 0 && kept < fetched;
210
- const batchChars = Number(rows[0]?.batch_chars ?? 0);
211
- const pageChars = Number(rows.at(-1)?.page_chars ?? 0);
212
- const next = kept === Math.min(limit, fetched) ? limit * 4 : batchChars - pageChars <= 4194304 ? limit : Math.max(SESSION_READ_FETCH.min, kept * 2);
213
- return {
214
- more,
215
- limit: Math.min(SESSION_READ_FETCH.max, next)
216
- };
217
- }
218
- /** `rows` split into runs, in order, of at most {@link SESSION_READ_PAGE_CHARS}; a longer row is a run of its own. */
219
- function pagesOf(rows) {
220
- const pages = [];
221
- let page = [];
222
- let chars = 0;
223
- for (const row of rows) {
224
- const size = Number(row.size ?? 0);
225
- if (page.length > 0 && chars + size > 1048576) {
226
- pages.push(page);
227
- page = [];
228
- chars = 0;
229
- }
230
- page.push(row);
231
- chars += size;
232
- }
233
- if (page.length > 0) pages.push(page);
234
- return pages;
235
- }
236
- /** An entry's JSON as its entries row stores it, and the UTF-8 chunks of a long one. */
237
- function storedEntry(entry, json) {
238
- if (json.length * 3 <= 1048576 || entry.type === "worktree_snapshot") return {
239
- json,
240
- chunks: []
241
- };
242
- const bytes = Buffer.from(json, "utf8");
243
- if (bytes.byteLength <= 1048576) return {
244
- json,
245
- chunks: []
246
- };
247
- const chunks = [];
248
- for (let offset = 0; offset < bytes.byteLength; offset += SESSION_ENTRY_CHUNK_BYTES) chunks.push(bytes.subarray(offset, offset + SESSION_ENTRY_CHUNK_BYTES));
249
- const stub = {
250
- type: entry.type,
251
- id: entry.id,
252
- parentId: entry.parentId ?? null
253
- };
254
- return {
255
- json: JSON.stringify(stub),
256
- chunks
257
- };
258
- }
259
- /** Each committed batch is its own durable checkpoint; the legacy bytes stay readable until publication. */
260
- async function migrateLegacyBlobBatch(tx, tables, sessionId, hash, data) {
261
- const params = [sessionId, hash];
262
- const row = await tx.get(`SELECT bytes FROM ${tables.blobs} WHERE session_id = ? AND hash = ? AND chunks = -1`, ...params);
263
- if (!row) return false;
264
- const progress = await tx.get(`SELECT COALESCE(max(idx) + 1, 0) AS next FROM ${tables.blobChunks} WHERE session_id = ? AND hash = ?`, ...params);
265
- const next = Number(progress.next);
266
- const chunks = Math.ceil(Number(row.bytes) / SESSION_BLOB_CHUNK_BYTES);
267
- const end = Math.min(next + LEGACY_BLOB_BATCH_CHUNKS, chunks);
268
- for (let index = next; index < end; index++) await tx.run(`INSERT INTO ${tables.blobChunks} (session_id, hash, idx, data) VALUES (?, ?, ?, ?)`, ...params, index, data.subarray(index * SESSION_BLOB_CHUNK_BYTES, (index + 1) * SESSION_BLOB_CHUNK_BYTES));
269
- if (end === chunks) await tx.run(`UPDATE ${tables.blobs} SET chunks = ?, data = X'' WHERE session_id = ? AND hash = ?`, chunks, ...params);
270
- return true;
271
- }
272
- /** Every listing column except search text, so an unchanged row keeps its cached summary. */
273
- const LISTING_COLUMNS = "id, cwd, internal, header_json, last_seq, modified_at, message_count, first_message, name, has_name, summary, summarized_through_id, revision";
274
- const LISTING_SELECT_COLUMNS = LISTING_COLUMNS.split(", ").map((column) => `s.${column}`).join(", ");
275
- /** The characters a listing row holds, its search text aside, for reading listings in pages (#4954). */
276
- const LISTING_SIZE = "length(id) + length(cwd) + length(header_json) + length(modified_at) + length(first_message) + COALESCE(length(name), 0) + COALESCE(length(summary), 0) + COALESCE(length(summarized_through_id), 0) + length(revision) + 256";
277
- /** Rows whose search text is read per query; well under SQLite's bound-parameter limit. */
278
- const LISTING_FETCH_BATCH = 500;
279
- /** Sessions one statement of a paced listing's project scan reads over a database server. */
280
- const LISTING_CWD_PAGE = 2e3;
281
- /**
282
- * Sessions one statement of a paced listing scans over this process's own SQLite connection, with a turn of the event
283
- * loop after each (#5480). Such a statement runs on the event loop and reads every row it scans; on a large store whose
284
- * pages are not cached a row can cost a disk read, so a few thousand rows per statement held the event loop for
285
- * seconds. A database server's statements do not hold the event loop, so listings over one keep larger statements.
286
- */
287
- const LISTING_SCAN_ROWS = 256;
288
- /** Stored project spellings a paced listing resolves at once; each is a chain of file system calls. */
289
- const LISTING_CWD_MATCHES = 64;
290
- const STUB_ENTRY = {
291
- type: "custom",
292
- id: "",
293
- parentId: null,
294
- timestamp: "1970-01-01T00:00:00.000Z",
295
- customType: ""
296
- };
297
- /** Listing scopes (visibility and project) kept at once; the picker uses two. */
298
- const LISTING_SCOPES = 8;
299
- /**
300
- * Session reads and writes use nothing but their transaction, so one that a transient failure of a database server
301
- * ended before it committed runs again (#4383); `append` and `replace` check `expectSeq` again on each run.
302
- */
303
- const SESSION_TRANSACTION = { retryTransientFailures: true };
304
- /** The largest content index or suffix length a task-reference query binds, an SQL `INTEGER` on every backend. */
305
- const TASK_REFERENCE_INTEGER = 2 ** 31 - 1;
306
- /**
307
- * A task-reference duplicate query's bounds, checked, and its candidates as `[seq, block or -1, suffix or 0]` rows:
308
- * integers only, so no entry ID is ever bound.
309
- */
310
- function taskReferenceDuplicateQuery(query) {
311
- const within = (value, min, max) => Number.isSafeInteger(value) && value >= min && value <= max;
312
- const { throughSeq, afterSeq = 0, limit = 64 } = query;
313
- const invalid = (what) => /* @__PURE__ */ new RangeError(`Invalid task-reference duplicate query: ${what}`);
314
- if (!within(throughSeq, 0, Number.MAX_SAFE_INTEGER)) throw invalid("throughSeq");
315
- if (!within(afterSeq, 0, Number.MAX_SAFE_INTEGER)) throw invalid("afterSeq");
316
- if (!within(limit, 1, 64)) throw invalid("limit");
317
- if (query.candidates.length > 100) throw invalid("too many candidates");
318
- return {
319
- candidates: query.candidates.map(({ seq, contentIndex, suffixChars }) => {
320
- if (!within(seq, 1, throughSeq)) throw invalid("candidate seq");
321
- if (contentIndex !== void 0 && !within(contentIndex, 0, TASK_REFERENCE_INTEGER)) throw invalid("candidate contentIndex");
322
- if (suffixChars !== void 0 && !within(suffixChars, 0, TASK_REFERENCE_INTEGER)) throw invalid("candidate suffixChars");
323
- return [
324
- seq,
325
- contentIndex ?? -1,
326
- contentIndex === void 0 ? suffixChars ?? 0 : 0
327
- ];
328
- }),
329
- afterSeq,
330
- limit
331
- };
332
- }
333
- /** A write revision: 32 random hex digits, the form SQLite's `lower(hex(randomblob(16)))` gave earlier builds. */
334
- function newRevision() {
335
- return Array.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("");
336
- }
337
- function summaryFromRow(row) {
338
- const header = JSON.parse(row.header_json);
339
- return {
340
- id: header.id,
341
- cwd: header.cwd,
342
- ...header.parentSessionId !== void 0 ? { parentSessionId: header.parentSessionId } : {},
343
- internal: header.internal === true,
344
- ...header.workflow !== void 0 ? { workflow: header.workflow } : {},
345
- ...row.name !== null ? { name: JSON.parse(row.name) } : {},
346
- hasName: row.has_name === 1,
347
- createdAt: header.createdAt,
348
- modifiedAt: row.modified_at,
349
- messageCount: row.message_count,
350
- firstMessage: JSON.parse(row.first_message),
351
- ...row.summary !== null ? { summary: JSON.parse(row.summary) } : {},
352
- ...row.summarized_through_id !== null ? { summarizedThroughId: row.summarized_through_id } : {},
353
- searchText: JSON.parse(row.search_texts_json).join(" ")
354
- };
355
- }
356
- /** Changes on every write: `revision` catches a rewrite that leaves every other listed column as it was. */
357
- function listingVersion(row) {
358
- return `${row.revision}\u0000${row.last_seq}\u0000${row.modified_at}\u0000${row.message_count}\u0000${row.has_name}\u0000${row.name}\u0000${row.summarized_through_id}\u0000${row.summary}\u0000${row.first_message}\u0000${row.header_json}`;
359
- }
360
- async function entryByteLengthOf(database) {
361
- const dialect = dialectOf(database);
362
- if (dialect.name !== "sqlite") return dialect.textByteLength;
363
- try {
364
- await database.get("SELECT octet_length('') AS bytes");
365
- return (expression) => `octet_length(${expression})`;
366
- } catch {
367
- return dialect.textByteLength;
368
- }
369
- }
370
- /**
371
- * The most bytes of statements a session write sends as one batch: an ordinary message's are far fewer. A larger
372
- * write, an import or a fork's whole window, runs its statements one at a time as they are made.
373
- */
374
- const STATEMENT_BATCH_BYTES = 1048576;
375
- /** About how many bytes `statement` carries: its text and its parameters. */
376
- function statementBytes(statement) {
377
- let bytes = statement.sql.length;
378
- for (const value of statement.params) if (typeof value === "string") bytes += value.length;
379
- else if (value instanceof Uint8Array) bytes += value.byteLength;
380
- else bytes += 8;
381
- return bytes;
382
- }
383
- var SqlSessionStore = class SqlSessionStore {
384
- database;
385
- dialect;
386
- tables;
387
- prefix;
388
- legacyBlobData;
389
- closed = false;
390
- cwdMatcher;
391
- snapshotBlobs;
392
- /** The blob table of this store's database, which appends check snapshot records against (#5077). */
393
- blobTable;
394
- /** Set by `open`, once the store exists (#4971). */
395
- openMarkers;
396
- searchIndex;
397
- chatStore;
398
- /**
399
- * Absent on a local libSQL file, which then behaves as before: @libsql/client waits for another process's write
400
- * lock on the calling thread, even to begin a transaction, so a side write would stop the event loop where an
401
- * ordinary turn-ending notice writes nothing (#5682).
402
- */
403
- get chatRecords() {
404
- const { adapter, location } = this.database.descriptor;
405
- if (adapter === "libsql" && /^file:/i.test(location)) return void 0;
406
- if (!this.chatStore) {
407
- const names = renderStorageIdentifiers("sessions", {
408
- rows: "chat_v1",
409
- byAnchor: "chat_v1_anchor"
410
- }, this.prefix);
411
- this.chatStore = sqlChatRecords(this.database, this.tables.sessions, names.rows, names.byAnchor);
412
- }
413
- return this.chatStore;
414
- }
415
- entryByteLength;
416
- chunkRowids;
417
- /** Session ids of each recently listed scope, valid while the store's change token is unchanged. */
418
- scopes = /* @__PURE__ */ new Map();
419
- /** Listed summaries of sessions that still exist at the cached version; never more than the store holds. */
420
- summaries = /* @__PURE__ */ new Map();
421
- /**
422
- * Settles when the latest listing has read and updated the caches. Listings take turns, so one listing's
423
- * pruning never drops summaries that another has fetched but not yet recorded under its scope.
424
- */
425
- listing = Promise.resolve();
426
- resumeIndexes = /* @__PURE__ */ new Map();
427
- forkStagingTable;
428
- /** The generation each recently read session's row held at a revision: see `generation`. */
429
- generations = /* @__PURE__ */ new Map();
430
- constructor(database, tables, prefix, cwdMatcher, snapshotBlobs, legacyBlobData, searchIndex, entryByteLength) {
431
- this.database = database;
432
- this.dialect = dialectOf(database);
433
- this.entryByteLength = entryByteLength;
434
- this.tables = tables;
435
- this.prefix = prefix ?? "";
436
- registerForkScope(this, () => ({
437
- kind: "sql",
438
- backing: this.database,
439
- prefix: this.prefix
440
- }));
441
- this.cwdMatcher = cwdMatcher;
442
- this.snapshotBlobs = snapshotBlobs;
443
- this.blobTable = snapshotBlobs;
444
- this.legacyBlobData = legacyBlobData;
445
- if (searchIndex !== void 0) this.searchIndex = searchIndex;
446
- registerHistorySnapshot(this, (sessionId, project) => {
447
- this.assertOpen();
448
- validateSessionText("sessionId", sessionId);
449
- return this.transaction(async (tx) => {
450
- const head = await this.historyHead(tx, sessionId);
451
- return project(head.epoch, head.lastSeq, (from, through, backward) => this.historyPacket(tx, sessionId, head.epoch, from, through, backward));
452
- }, SESSION_TRANSACTION);
453
- });
454
- this.forkStagingTable = renderStorageIdentifiers("sessions", SESSION_FORK_STAGING_TABLES, prefix).forkStaging;
455
- }
456
- /** Bind an existing transcript for the storage search command. No schema setup, markers or search index. */
457
- static async openTranscriptReader(database) {
458
- const tables = renderStorageIdentifiers("sessions", SESSION_TABLES);
459
- const reader = new SqlSessionStore(database, tables, void 0, void 0, SqlSnapshotBlobStore.forTranscriptReader(database), false, void 0, await entryByteLengthOf(database));
460
- await reader.assertReadableSchema(database);
461
- return reader;
462
- }
463
- static async open(database, options = {}) {
464
- validateStoragePrefix(options.prefix, dialectOf(database).name);
465
- const tables = renderStorageIdentifiers("sessions", SESSION_TABLES, options.prefix);
466
- let legacyBlobData = false;
467
- const createTables = async (tx, dialect) => {
468
- const { int, text, blob } = dialect.types;
469
- const strict = dialect.tableOptions;
470
- const json = (column) => dialect.jsonValid(column);
471
- const columnExists = (table, column) => {
472
- const probe = dialect.columnExists(table, column);
473
- return async () => await tx.get(probe.sql, ...probe.params) !== void 0;
474
- };
475
- const [versions] = await statementBatch(tx, [`CREATE TABLE IF NOT EXISTS ${tables.meta} (schema_version ${int} NOT NULL)${strict}`], [() => tx.all(`SELECT schema_version FROM ${tables.meta}`)]);
476
- for (const version of versions) assertStorageSchemaVersion("sessions", version.schema_version, 2, SESSION_SCHEMA_VERSION_UNCHUNKED);
477
- const tablesScript = `
478
- CREATE TABLE IF NOT EXISTS ${tables.sessions} (
479
- id ${text} PRIMARY KEY, cwd ${text} NOT NULL, created_at ${text} NOT NULL,
480
- header_json ${text} NOT NULL CHECK(${json("header_json")}), internal ${int} NOT NULL,
481
- last_seq ${int} NOT NULL, modified_at ${text} NOT NULL, message_count ${int} NOT NULL,
482
- first_message ${text} NOT NULL CHECK(${json("first_message")}),
483
- name ${text} CHECK(name IS NULL OR ${json("name")}), has_name ${int} NOT NULL,
484
- summary ${text} CHECK(summary IS NULL OR ${json("summary")}), summarized_through_id ${text},
485
- summary_state ${text} NOT NULL CHECK(${json("summary_state")}), revision ${text} NOT NULL DEFAULT ''${dialect.rowOrderColumn}
486
- )${strict};
487
- CREATE TABLE IF NOT EXISTS ${tables.entries} (
488
- session_id ${text} NOT NULL, seq ${int} NOT NULL, entry_id ${text} NOT NULL,
489
- entry_json ${text} NOT NULL CHECK(${json("entry_json")}), PRIMARY KEY(session_id, seq)${dialect.rowOrderColumn}
490
- )${strict};
491
- CREATE TABLE IF NOT EXISTS ${tables.searchTexts} (
492
- session_id ${text} NOT NULL, seq ${int} NOT NULL,
493
- text_json ${text} NOT NULL CHECK(${json("text_json")}), PRIMARY KEY(session_id, seq)
494
- )${strict};
495
- CREATE TABLE IF NOT EXISTS ${tables.blobs} (
496
- session_id ${text} NOT NULL, hash ${text} NOT NULL, bytes ${int} NOT NULL, chunks ${int} NOT NULL,
497
- PRIMARY KEY(session_id, hash)
498
- )${strict};
499
- CREATE TABLE IF NOT EXISTS ${tables.blobChunks} (
500
- session_id ${text} NOT NULL, hash ${text} NOT NULL, idx ${int} NOT NULL, data ${blob} NOT NULL,
501
- PRIMARY KEY(session_id, hash, idx)
502
- )${strict};
503
- `;
504
- const [revision, data] = await statementBatch(tx, [versions.length === 0 && {
505
- sql: `INSERT INTO ${tables.meta} VALUES (?)`,
506
- params: [SESSION_SCHEMA_VERSION_UNCHUNKED]
507
- }, tablesScript], [columnExists(tables.sessions, "revision"), columnExists(tables.blobs, "data")]);
508
- legacyBlobData = data;
509
- const [chunks] = legacyBlobData ? await statementBatch(tx, [], [columnExists(tables.blobs, "chunks")]) : [true];
510
- await statementBatch(tx, [!revision && `ALTER TABLE ${tables.sessions} ADD COLUMN revision ${text} NOT NULL DEFAULT ''`, !chunks && `ALTER TABLE ${tables.blobs} ADD COLUMN chunks ${int} NOT NULL DEFAULT -1`], []);
511
- };
512
- const orphanedEntryKeys = `SELECT k.session_id, k.seq
513
- FROM (SELECT DISTINCT session_id, seq FROM ${tables.entryChunks}) AS k
514
- WHERE NOT EXISTS (
515
- SELECT 1 FROM ${tables.entries} AS e
516
- WHERE e.session_id = k.session_id AND e.seq = k.seq AND e.chunks > 0
517
- )`;
518
- const removeOrphanedEntryChunks = {
519
- sql: `DELETE FROM ${tables.entryChunks} WHERE (session_id, seq) IN (${orphanedEntryKeys})`,
520
- params: []
521
- };
522
- /**
523
- * Long entries in chunks (#4954): the entry chunks table and the entries table's `chunks` column, 0 for an entry
524
- * stored whole, as every entry written before it was. Older builds read and write these tables unchanged, so the
525
- * sessions meta stays where it is until the first chunked entry (`insertEntries`). Setup is idempotent and runs
526
- * when the open finds the schema not current (`currentSchema`).
527
- */
528
- const addEntryChunks = async (tx, dialect) => {
529
- const { int, text, blob } = dialect.types;
530
- const probe = dialect.columnExists(tables.entries, "chunks");
531
- const [chunks] = await statementBatch(tx, [`
532
- CREATE TABLE IF NOT EXISTS ${tables.entryChunks} (
533
- session_id ${text} NOT NULL, seq ${int} NOT NULL, idx ${int} NOT NULL, data ${blob} NOT NULL,
534
- PRIMARY KEY(session_id, seq, idx)
535
- )${dialect.tableOptions};
536
- `], [() => tx.get(probe.sql, ...probe.params)]);
537
- await statementBatch(tx, [chunks === void 0 && `ALTER TABLE ${tables.entries} ADD COLUMN chunks ${int} NOT NULL DEFAULT 0`, database.readOnly !== true && removeOrphanedEntryChunks], []);
538
- };
539
- const presence = renderStorageIdentifiers("sessions", SESSION_PRESENCE_TABLES, options.prefix);
540
- const current = await SqlSessionStore.currentSchema(database, tables, presence.open, database.readOnly === true ? void 0 : orphanedEntryKeys);
541
- if (current !== void 0) {
542
- legacyBlobData = current.legacyBlobData;
543
- if (current.orphaned) await database.transaction(async (tx) => {
544
- await assertStoredSchemaVersion(tx, { sql: `SELECT schema_version FROM ${tables.meta}` }, "sessions", 2, "schema_version", SESSION_SCHEMA_VERSION_UNCHUNKED);
545
- await tx.run(removeOrphanedEntryChunks.sql);
546
- }).catch((error) => {
547
- if (error instanceof StorageSchemaVersionError) throw error;
548
- });
549
- } else await applyStorageMigrationsTogether(database, [{
550
- domain: SESSION_DOMAIN,
551
- steps: [{
552
- version: 1,
553
- up: createTables
554
- }, {
555
- version: 2,
556
- up: addEntryChunks
557
- }],
558
- options: { table: storageMigrationTable(options.prefix) }
559
- }, {
560
- domain: SESSION_PRESENCE_DOMAIN,
561
- steps: [{
562
- version: 1,
563
- up: (tx, dialect) => SqlSessionOpenMarkers.createTable(tx, dialect, presence.open)
564
- }, {
565
- version: 2,
566
- up: (tx, dialect) => SqlSessionOpenMarkers.addSchemaVersion(tx, dialect, presence.open)
567
- }],
568
- options: {
569
- table: storageMigrationTable(options.prefix),
570
- acceptNewer: true
571
- }
572
- }]);
573
- const staging = renderStorageIdentifiers("sessions", SESSION_FORK_STAGING_TABLES, options.prefix).forkStaging;
574
- const stagingProbe = dialectOf(database).tableExists(staging);
575
- const staged = database.readOnly === true || !database.tryMaintenance ? Promise.resolve(false) : database.get(stagingProbe.sql, ...stagingProbe.params).then((row) => row !== void 0, () => false);
576
- const opening = current === void 0 ? await SqlSnapshotBlobStore.open(database, options.prefix) : void 0;
577
- const [blobs, searchIndex, entryByteLength] = await Promise.all([
578
- opening ?? SqlSnapshotBlobStore.open(database, options.prefix),
579
- SqlSessionSearchIndex.open(database, tables, options.prefix),
580
- entryByteLengthOf(database)
581
- ]);
582
- const store = new SqlSessionStore(database, tables, options.prefix, options.cwdMatcher, blobs, legacyBlobData, searchIndex, entryByteLength);
583
- store.openMarkers = new SqlSessionOpenMarkers(database, presence.open, () => store.assertOpen());
584
- if (await staged) await store.cleanupForkStaging();
585
- return store;
586
- }
587
- /**
588
- * Removes, in a bounded number of short transactions, the staged rows of clones that stopped mid-copy and whose lease
589
- * lapsed (#5594). Housekeeping: nothing reads those rows, so a failure leaves them to a later open or clone.
590
- */
591
- async cleanupForkStaging() {
592
- try {
593
- await tryCleanupForkStaging(this.database, this.dialect, this.forkStagingTable);
594
- } catch {}
595
- }
596
- /**
597
- * What the open's setup would find, read without the write lock, when its schema steps would change nothing: every
598
- * table and column of both domains exists and the sessions meta holds only versions this build supports. Undefined
599
- * otherwise, and always on a database with versioned migrations, whose ledger the setup checks. Leftover entry
600
- * chunks are not part of the schema: `orphaned` tells whether the query `orphans` finds any, for the open to remove
601
- * them separately, and is false when it is not asked. The probes are read together, then the versions with that
602
- * query, so a current schema waits for two answers.
603
- */
604
- static async currentSchema(database, tables, open, orphans) {
605
- const dialect = dialectOf(database);
606
- if (dialect.versionedMigrations) return void 0;
607
- const probes = [
608
- ...[...Object.values(tables), open].map((table) => dialect.tableExists(table)),
609
- dialect.columnExists(tables.sessions, "revision"),
610
- dialect.columnExists(tables.entries, "chunks"),
611
- dialect.columnExists(tables.blobs, "chunks"),
612
- dialect.columnExists(open, "schema_version")
613
- ];
614
- const legacy = dialect.columnExists(tables.blobs, "data");
615
- const [legacyFound, ...found] = await Promise.all([legacy, ...probes].map((probe) => database.get(probe.sql, ...probe.params)));
616
- if (!found.every((row) => row !== void 0)) return void 0;
617
- const orphaned = orphans === void 0 ? void 0 : database.get(`SELECT 1 FROM (${orphans}) AS orphaned LIMIT 1`);
618
- orphaned?.catch(() => {});
619
- const versions = await database.all(`SELECT schema_version FROM ${tables.meta}`);
620
- if (versions.length === 0 || versions.some((row) => row.schema_version !== SESSION_SCHEMA_VERSION_UNCHUNKED && row.schema_version !== 2)) return void 0;
621
- return {
622
- legacyBlobData: legacyFound !== void 0,
623
- orphaned: await orphaned !== void 0
624
- };
625
- }
626
- /**
627
- * A transaction that first checks the sessions schema version again: a newer build may have upgraded the database
628
- * since this store opened it, and what it writes then is not this build's to read or write (#5065).
629
- */
630
- transaction(body, options) {
631
- return this.database.transaction(async (tx) => {
632
- await this.assertReadableSchema(tx);
633
- return body(tx);
634
- }, options);
635
- }
636
- /**
637
- * `transaction` for a body that only reads and writes the database. The version check is sent first, as there, but on
638
- * a connection thread the body's first reads go behind it without waiting for its answer: one wait for the thread
639
- * fewer. The body awaits `checked` before its first write, so nothing is written unless the version is one this build
640
- * reads (its answer came before the reads', so that costs no wait); a version this build does not support is the
641
- * failure reported, whatever the body met.
642
- */
643
- transactionCheckedAlongside(body, options) {
644
- return this.database.transaction(async (tx) => {
645
- if (sequenceRunner(tx) === void 0) {
646
- await this.assertReadableSchema(tx);
647
- return body(tx, Promise.resolve());
648
- }
649
- const checked = this.assertReadableSchema(tx);
650
- checked.catch(() => {});
651
- const outcome = await body(tx, checked).then((value) => ({ value }), (failure) => ({ failure }));
652
- await checked;
653
- if ("failure" in outcome) throw outcome.failure;
654
- return outcome.value;
655
- }, options);
656
- }
657
- assertReadableSchema(executor) {
658
- return assertStoredSchemaVersion(executor, { sql: `SELECT schema_version FROM ${this.tables.meta}` }, "sessions", 2, "schema_version", SESSION_SCHEMA_VERSION_UNCHUNKED);
659
- }
660
- get descriptor() {
661
- return {
662
- ...this.database.descriptor,
663
- ...this.prefix === "" ? {} : { prefix: this.prefix }
664
- };
665
- }
666
- async create(header, entries) {
667
- this.assertOpen();
668
- validateSessionHeader(header);
669
- validateSessionEntries(entries);
670
- return this.transactionCheckedAlongside(async (tx, checked) => {
671
- if (await tx.get(`SELECT id FROM ${this.tables.sessions} WHERE id = ?`, header.id)) throw new SessionExistsError(header.id);
672
- const summary = this.summaryWrite(header.id, {
673
- header,
674
- entries,
675
- lastSeq: entries.length
676
- });
677
- await checked;
678
- await this.writeEntries(tx, summary.statement, this.entryWrites(header.id, entries, 0, summary.texts));
679
- return {
680
- lastSeq: entries.length,
681
- epoch: summary.epoch
682
- };
683
- }, SESSION_TRANSACTION);
684
- }
685
- async createFork(header, entries, source) {
686
- if (this.create !== SqlSessionStore.prototype.create) return void 0;
687
- if (source.store !== this) {
688
- if ("read" in entries) return entries.kind === "complete-session" ? this.createStagedFork(header, entries, source) : void 0;
689
- if (source.receipts.size < 2) return void 0;
690
- return this.createStagedFork(header, { async *read() {
691
- for (const entry of entries) yield {
692
- entry,
693
- reference: source.receipts.get(entry.id)
694
- };
695
- } }, source);
696
- }
697
- if ("read" in entries) return this.createStreamedFork(header, entries, source);
698
- this.assertOpen();
699
- validateSessionHeader(header);
700
- validateSessionEntries(entries);
701
- return this.transaction(async (tx) => {
702
- if (await tx.get(`SELECT id FROM ${this.tables.sessions} WHERE id = ?`, header.id)) throw new SessionExistsError(header.id);
703
- const donor = await this.historyHead(tx, source.sessionId);
704
- if (source.epoch !== void 0 && donor.epoch !== source.epoch) throw new SessionConflictError(source.sessionId, 0, donor.lastSeq);
705
- const { texts, epoch } = await this.saveSummary(tx, header.id, {
706
- header,
707
- entries,
708
- lastSeq: entries.length
709
- });
710
- await this.insertEntries(tx, header.id, entries, 0, texts);
711
- for (const [i, entry] of entries.entries()) {
712
- const ref = source.receipts.get(entry.id);
713
- if (!ref) continue;
714
- if (source.sessionId !== ref.sessionId || donor.epoch !== ref.epoch || donor.lastSeq < ref.seq) throw new SessionConflictError(ref.sessionId, ref.seq, donor.lastSeq);
715
- const original = await tx.get(`SELECT chunks FROM ${this.tables.entries} WHERE session_id=? AND seq=? AND entry_id=?`, ref.sessionId, ref.seq, entry.id);
716
- if (!original) throw new SessionConflictError(ref.sessionId, ref.seq, donor.lastSeq);
717
- await tx.run(`DELETE FROM ${this.tables.entries} WHERE session_id=? AND seq=?`, header.id, i + 1);
718
- await tx.run(`INSERT INTO ${this.tables.entries} (session_id, seq, entry_id, entry_json, chunks) SELECT ?, ?, entry_id,entry_json,chunks FROM ${this.tables.entries} WHERE session_id=? AND seq=?`, header.id, i + 1, ref.sessionId, ref.seq);
719
- for (let part = 0; part < original.chunks; part++) {
720
- const { changes } = await tx.run(`INSERT INTO ${this.tables.entryChunks} (session_id, seq, idx, data) SELECT ?, ?, idx, data FROM ${this.tables.entryChunks} WHERE session_id=? AND seq=? AND idx=?`, header.id, i + 1, ref.sessionId, ref.seq, part);
721
- if (changes !== 1) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing chunk of session entry ${ref.seq}`));
722
- }
723
- }
724
- const remainingBlobs = [];
725
- for (const hash of source.hashes) if (!await this.copyForkBlob(tx, source.sessionId, header.id, hash)) remainingBlobs.push(hash);
726
- return {
727
- lastSeq: entries.length,
728
- epoch,
729
- remainingBlobs
730
- };
731
- }, SESSION_TRANSACTION);
732
- }
733
- /**
734
- * Clone a complete session, as `create` with every source entry and blob would, from a store on a handle this one
735
- * cannot prove to be its own connection (#5594). The source is read a page at a time into the staging table, never
736
- * while a transaction of this store is open, and the child is published in one transaction: see `fork-staging.ts`.
737
- * `remainingBlobs` names the blobs left to copy with `copySessionBlobs`: those the source no longer holds.
738
- */
739
- async createStagedFork(header, stream, source) {
740
- this.assertOpen();
741
- validateSessionHeader(header);
742
- const { createStagedFork } = await import("../core/storage/session/fork-staging.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
743
- return createStagedFork(this.forkStagingTarget(), header, stream, source);
744
- }
745
- /**
746
- * Creates the fork staging table unless it exists, as `atomic storage migrate` does as the owner role (#5594): a
747
- * runtime role without DDL privileges then stages bounded clones too. Opens never create it.
748
- */
749
- async prepareForkStaging() {
750
- this.assertOpen();
751
- const { cleanupForkStaging, ensureForkStagingTable } = await import("../core/storage/session/fork-staging.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
752
- await ensureForkStagingTable(this.database, this.dialect, this.forkStagingTable);
753
- await cleanupForkStaging(this.database, this.dialect, this.forkStagingTable, Number.POSITIVE_INFINITY);
754
- }
755
- forkStagingTarget() {
756
- return {
757
- database: this.database,
758
- dialect: this.dialect,
759
- table: this.forkStagingTable,
760
- tables: this.tables,
761
- legacyBlobData: this.legacyBlobData,
762
- entryChunkBytes: SESSION_ENTRY_CHUNK_BYTES,
763
- blobChunkBytes: SESSION_BLOB_CHUNK_BYTES,
764
- unchunkedSchemaVersion: SESSION_SCHEMA_VERSION_UNCHUNKED,
765
- chunkedSchemaVersion: 2,
766
- ownsBlobs: this.getBlob === SqlSessionStore.prototype.getBlob && this.putBlob === SqlSessionStore.prototype.putBlob,
767
- transaction: (body) => this.transaction(body, SESSION_TRANSACTION),
768
- saveSummary: (tx, header, lastSeq, summary, index) => this.saveSummary(tx, header.id, {
769
- header,
770
- entries: [],
771
- lastSeq
772
- }, summary, index),
773
- create: (header, entries) => this.create(header, entries),
774
- sourceStoredEntryChunks: (source) => {
775
- const store = nativeForkReader(source, "entry");
776
- return store instanceof SqlSessionStore && store.readEntryChunk === SqlSessionStore.prototype.readEntryChunk ? (reference, index) => store.readStoredEntryChunk(reference, index) : void 0;
777
- },
778
- rebuildResume: async (sessionId) => {
779
- await this.prepareResume(sessionId);
780
- },
781
- storedEntry,
782
- encode: (value) => this.encode(value),
783
- sourceEntryChunks: (source) => {
784
- const store = nativeForkReader(source, "entry");
785
- return store instanceof SqlSessionStore && store.readEntryChunk === SqlSessionStore.prototype.readEntryChunk ? (reference) => store.readStoredChunks(reference) : void 0;
786
- },
787
- sourceBlobParts: (source) => {
788
- const store = nativeForkReader(source, "blob");
789
- return store instanceof SqlSessionStore && store.getBlob === SqlSessionStore.prototype.getBlob ? (sessionId, hash, offset, legacyBytes) => store.readBlobPart(sessionId, hash, offset, legacyBytes) : void 0;
790
- }
791
- };
792
- }
793
- /**
794
- * The stored chunk row `index` of the entry `reference` names, whole, in its generation; undefined when the entry is
795
- * stored whole. One read where `readEntryChunk` would take one per 64 KiB of it (#5594).
796
- */
797
- async readStoredEntryChunk(reference, index) {
798
- this.assertOpen();
799
- return this.transaction(async (tx) => {
800
- const { sessionId, epoch, seq } = reference;
801
- const head = await this.historyHead(tx, sessionId);
802
- if (head.epoch !== epoch) throw new SessionConflictError(sessionId, seq, head.lastSeq);
803
- const row = await tx.get(`SELECT e.chunks, c.data FROM ${this.tables.entries} e LEFT JOIN ${this.tables.entryChunks} c
804
- ON c.session_id = e.session_id AND c.seq = e.seq AND c.idx = ? WHERE e.session_id = ? AND e.seq = ?`, index, sessionId, seq);
805
- if (!row) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing session entry ${seq}`));
806
- if (Number(row.chunks) === 0) return void 0;
807
- if (row.data == null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing chunk of session entry ${seq}`));
808
- return row.data;
809
- }, SESSION_TRANSACTION);
810
- }
811
- /** How many chunks the entry `reference` names is stored in, 0 when it is stored whole, in its generation. */
812
- async readStoredChunks(reference) {
813
- this.assertOpen();
814
- return this.transaction(async (tx) => {
815
- const { sessionId, epoch, seq } = reference;
816
- const head = await this.historyHead(tx, sessionId);
817
- if (head.epoch !== epoch) throw new SessionConflictError(sessionId, seq, head.lastSeq);
818
- const row = await tx.get(`SELECT chunks FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, seq);
819
- if (!row) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing session entry ${seq}`));
820
- return Number(row.chunks);
821
- }, SESSION_TRANSACTION);
822
- }
823
- /**
824
- * The bytes of a blob from `offset`, a multiple of {@link SESSION_BLOB_CHUNK_BYTES}, so a staged clone never holds
825
- * the whole of a large one (#5594): the stored chunk row there, or for a blob in the legacy one-row layout (`chunks`
826
- * -1), at most `legacyBytes` cut from its data column by the database, which loads that one value itself for each
827
- * cut; with `legacyBytes` 0, only its header. Nothing is converted or written.
828
- */
829
- async readBlobPart(sessionId, hash, offset, legacyBytes) {
830
- this.assertOpen();
831
- const cut = this.legacyBlobData && legacyBytes > 0;
832
- const legacy = cut ? "CASE WHEN b.chunks = -1 THEN substr(b.data, ?, ?) ELSE c.data END" : "c.data";
833
- const row = await this.database.get(`SELECT b.bytes, b.chunks, ${legacy} AS data FROM ${this.tables.blobs} b LEFT JOIN ${this.tables.blobChunks} c
834
- ON c.session_id = b.session_id AND c.hash = b.hash AND c.idx = ? WHERE b.session_id = ? AND b.hash = ?`, ...cut ? [offset + 1, legacyBytes] : [], Math.floor(offset / SESSION_BLOB_CHUNK_BYTES), sessionId, hash);
835
- if (row === void 0) return void 0;
836
- return {
837
- bytes: Number(row.bytes),
838
- chunks: Number(row.chunks),
839
- ...row.data == null ? {} : { data: row.data }
840
- };
841
- }
842
- async copyForkBlob(tx, sessionId, childId, hash) {
843
- if (this.getBlob !== SqlSessionStore.prototype.getBlob || this.putBlob !== SqlSessionStore.prototype.putBlob) return false;
844
- const blob = await tx.get(`SELECT bytes,chunks FROM ${this.tables.blobs} WHERE session_id=? AND hash=?`, sessionId, hash);
845
- if (!blob) return false;
846
- if (await tx.get(`SELECT hash FROM ${this.tables.blobs} WHERE session_id=? AND hash=?`, childId, hash)) return true;
847
- const columns = this.legacyBlobData ? ", data" : "";
848
- const { changes } = await tx.run(`INSERT INTO ${this.tables.blobs} (session_id,hash,bytes,chunks${columns}) SELECT ?,hash,bytes,chunks${columns} FROM ${this.tables.blobs} WHERE session_id=? AND hash=?${this.legacyBlobData ? " AND (chunks<>-1 OR length(data)=bytes)" : ""}`, childId, sessionId, hash);
849
- if (changes !== 1 || blob.chunks >= 0 && blob.chunks !== Math.ceil(blob.bytes / 1048576)) throw new SessionBlobError("blob-incomplete", {
850
- sessionId,
851
- hash,
852
- bytes: blob.bytes
853
- });
854
- for (let part = 0; part < blob.chunks; part++) if ((await tx.run(`INSERT INTO ${this.tables.blobChunks} (session_id,hash,idx,data) SELECT ?,hash,idx,data FROM ${this.tables.blobChunks} WHERE session_id=? AND hash=? AND idx=? AND length(data)=?`, childId, sessionId, hash, part, Math.min(1048576, blob.bytes - part * 1048576))).changes !== 1) throw new SessionBlobError("blob-incomplete", {
855
- sessionId,
856
- hash,
857
- bytes: blob.bytes
858
- });
859
- return true;
860
- }
861
- async createStreamedFork(header, stream, source) {
862
- this.assertOpen();
863
- validateSessionHeader(header);
864
- const { encodedForkRow } = await import("../core/storage/session/fork-row-bytes.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
865
- const { foldForkRow } = await import("../core/storage/session/fork-row-index.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
866
- return this.transaction(async (tx) => {
867
- if (await tx.get(`SELECT id FROM ${this.tables.sessions} WHERE id=?`, header.id)) throw new SessionExistsError(header.id);
868
- const head = await this.historyHead(tx, source.sessionId);
869
- if (source.epoch !== void 0 && head.epoch !== source.epoch) throw new SessionConflictError(source.sessionId, 0, head.lastSeq);
870
- const reader = new SqlSessionStore({
871
- descriptor: this.database.descriptor,
872
- dialect: this.dialect,
873
- readOnly: true,
874
- exec: tx.exec.bind(tx),
875
- get: tx.get.bind(tx),
876
- run: tx.run.bind(tx),
877
- all: tx.all.bind(tx),
878
- transaction: async (cb) => cb(tx),
879
- close: async () => {}
880
- }, this.tables, this.prefix, this.cwdMatcher, this.blobTable, this.legacyBlobData, void 0, this.entryByteLength);
881
- const { index: donorIndex } = await reader.prepareResume(source.sessionId);
882
- reader.readBranchSpan = async (id, cut) => transcriptBranchSpan(id, donorIndex, cut);
883
- const lookup = (id) => this.seqOfEntry(tx, header.id, id);
884
- let summary = applySessionSummaryEntries(void 0, []).state;
885
- let index = foldSessionResume(void 0, []);
886
- let seq = 0;
887
- const remainingBlobs = /* @__PURE__ */ new Set();
888
- const inlineSnapshot = async (ref) => {
889
- const text = (key) => this.dialect.jsonText("entry_json", key);
890
- const ty = (key) => this.dialect.jsonType("entry_json", key);
891
- const s = await tx.get(`SELECT entry_id AS id,${text("parentId")} AS parent,${text("timestamp")} AS stamp,${text("root")} AS root,${text("snapshotId")} AS snapshot,${text("captureMs")} AS capture,${ty("snapshot")} AS record,${ty("restore")} AS restore,${ty("unrestored")} AS unrestored,${text("degradedFrom")} AS degraded FROM ${this.tables.entries} WHERE session_id=? AND seq=? AND chunks=0 AND ${text("type")}='worktree_snapshot'`, ref.sessionId, ref.seq);
892
- if (!s) return void 0;
893
- return {
894
- type: "worktree_snapshot",
895
- id: s.id,
896
- parentId: s.parent,
897
- timestamp: s.stamp,
898
- root: s.root,
899
- snapshotId: s.snapshot,
900
- ...s.capture !== null ? { captureMs: Number(s.capture) } : {},
901
- ...s.record === "object" ? { snapshot: {} } : {},
902
- ...s.restore === "object" ? { restore: {} } : {},
903
- ...s.unrestored === "object" ? { unrestored: {} } : {},
904
- ...s.degraded ? { degradedFrom: s.degraded } : {}
905
- };
906
- };
907
- for await (const row of stream.read(reader, async (id) => await lookup(id) !== void 0, inlineSnapshot)) {
908
- index = await foldForkRow(index, row, lookup);
909
- const entry = row.entry;
910
- const listed = applySessionSummaryEntries(summary, [entry]);
911
- summary = listed.state;
912
- if (entry.type === "custom" && entry.customType === "atomic.tool-output") {
913
- const hash = entry.data?.hash;
914
- if (typeof hash === "string" && !remainingBlobs.has(hash) && !await this.copyForkBlob(tx, source.sessionId, header.id, hash)) remainingBlobs.add(hash);
915
- }
916
- if (!row.reference) await this.insertEntries(tx, header.id, [entry], seq, listed.texts);
917
- else if (row.inlineSnapshot) await this.writeInlineForkSnapshot(tx, reader, row.reference, header.id, seq, listed.texts, row.edits);
918
- else {
919
- const encoded = await encodedForkRow(reader, row);
920
- const chunks = Math.ceil(encoded.size / SESSION_ENTRY_CHUNK_BYTES);
921
- await tx.run(`INSERT INTO ${this.tables.entries} (session_id,seq,entry_id,entry_json,chunks) VALUES (?,?,?,?,?)`, header.id, seq + 1, entry.id, JSON.stringify({
922
- type: entry.type,
923
- id: entry.id,
924
- parentId: entry.parentId ?? null
925
- }), chunks);
926
- let n = 0;
927
- let used = 0;
928
- let buffer = new Uint8Array(SESSION_ENTRY_CHUNK_BYTES);
929
- const write = async () => {
930
- await tx.run(`INSERT INTO ${this.tables.entryChunks} (session_id,seq,idx,data) VALUES (?,?,?,?)`, header.id, seq + 1, n++, buffer.subarray(0, used));
931
- used = 0;
932
- };
933
- for await (const part of encoded.chunks()) for (let start = 0; start < part.length;) {
934
- const count = Math.min(part.length - start, buffer.length - used);
935
- buffer.set(part.subarray(start, start + count), used);
936
- start += count;
937
- used += count;
938
- if (used === buffer.length) await write();
939
- }
940
- if (used) await write();
941
- if (n !== chunks) throw new StorageError("Incomplete historical entry in fork");
942
- for (const { text } of listed.texts) await tx.run(`INSERT INTO ${this.tables.searchTexts} (session_id,seq,text_json) VALUES (?,?,?)`, header.id, seq + 1, this.encode(text));
943
- await tx.run(`UPDATE ${this.tables.meta} SET schema_version=? WHERE schema_version=?`, 2, SESSION_SCHEMA_VERSION_UNCHUNKED);
944
- }
945
- seq++;
946
- }
947
- const { epoch } = await this.saveSummary(tx, header.id, {
948
- header,
949
- entries: [],
950
- lastSeq: seq
951
- }, summary, index);
952
- return {
953
- lastSeq: seq,
954
- epoch,
955
- remainingBlobs: [...remainingBlobs]
956
- };
957
- }, SESSION_TRANSACTION);
958
- }
959
- /** Keep the legacy inline payload outside the iterator's yielded value and the caller's async frame:
960
- * neither may retain this row while the next SQLite result is being delivered. */
961
- async writeInlineForkSnapshot(tx, reader, ref, child, seq, texts, edits) {
962
- const original = (await reader.readRange(ref.sessionId, ref.seq, ref.seq, ref.epoch)).entries[0];
963
- if (original?.type !== "worktree_snapshot") throw new SessionConflictError(ref.sessionId, ref.seq, seq);
964
- await this.insertEntries(tx, child, [edits ? {
965
- ...original,
966
- ...edits
967
- } : original], seq, texts);
968
- }
969
- async append(sessionId, entries, options) {
970
- this.assertOpen();
971
- validateSessionText("sessionId", sessionId);
972
- return this.transactionCheckedAlongside(async (tx, checked) => {
973
- const { row: previous, state: summaryState } = await this.forWrite(tx, sessionId, options, true);
974
- validateSessionEntries(entries);
975
- await this.blobTable.assertStored(tx, entries.flatMap((entry) => entry.type === "worktree_snapshot" && entry.snapshot !== void 0 ? [entry.snapshot] : []));
976
- const lastSeq = previous.last_seq + entries.length;
977
- const summary = this.summaryWrite(sessionId, {
978
- header: JSON.parse(previous.header_json),
979
- entries,
980
- lastSeq
981
- }, summaryState, await this.appendedResume(tx, sessionId, windowIndex(summaryState, previous.last_seq), previous.last_seq, entries));
982
- const written = this.entryWrites(sessionId, entries, previous.last_seq, summary.texts);
983
- await checked;
984
- await this.writeEntries(tx, summary.statement, written);
985
- return { lastSeq };
986
- }, SESSION_TRANSACTION);
987
- }
988
- async replace(sessionId, header, entries, options) {
989
- this.assertOpen();
990
- validateSessionText("sessionId", sessionId);
991
- return this.transaction(async (tx) => {
992
- await this.forWrite(tx, sessionId, options);
993
- validateSessionHeader(header);
994
- validateSessionEntries(entries);
995
- if (header.id !== sessionId) throw new SessionIdMismatchError(sessionId, header.id);
996
- await this.searchIndex?.forgetWithin(tx, sessionId);
997
- await tx.run(`DELETE FROM ${this.tables.searchTexts} WHERE session_id = ?`, sessionId);
998
- await tx.run(`DELETE FROM ${this.tables.entryChunks} WHERE session_id = ?`, sessionId);
999
- await tx.run(`DELETE FROM ${this.tables.entries} WHERE session_id = ?`, sessionId);
1000
- const { texts, epoch } = await this.saveSummary(tx, sessionId, {
1001
- header,
1002
- entries,
1003
- lastSeq: entries.length
1004
- });
1005
- await this.insertEntries(tx, sessionId, entries, 0, texts);
1006
- return {
1007
- lastSeq: entries.length,
1008
- epoch
1009
- };
1010
- }, SESSION_TRANSACTION);
1011
- }
1012
- async updateHeader(header, options) {
1013
- this.assertOpen();
1014
- validateSessionHeader(header);
1015
- return this.transaction(async (tx) => {
1016
- const { row, state } = await this.forWrite(tx, header.id, options, true);
1017
- const epoch = newRevision();
1018
- const resume = windowIndex(state, row.last_seq);
1019
- await this.saveSummary(tx, header.id, {
1020
- header,
1021
- entries: [],
1022
- lastSeq: row.last_seq
1023
- }, {
1024
- ...state,
1025
- epoch
1026
- }, resume && {
1027
- ...resume,
1028
- epoch
1029
- });
1030
- return {
1031
- lastSeq: row.last_seq,
1032
- epoch
1033
- };
1034
- }, SESSION_TRANSACTION);
1035
- }
1036
- async load(sessionId) {
1037
- this.assertOpen();
1038
- validateSessionText("sessionId", sessionId);
1039
- if (hasHistoryLoadObserver()) {
1040
- const row = await this.database.get(`SELECT last_seq FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
1041
- if (row) announceHistoryLoad(row.last_seq);
1042
- }
1043
- return this.transaction((tx) => this.read(tx, sessionId), SESSION_TRANSACTION);
1044
- }
1045
- async readEntryRange(sessionId, query) {
1046
- this.assertOpen();
1047
- validateSessionText("sessionId", sessionId);
1048
- query.signal?.throwIfAborted();
1049
- const session = await this.database.get(`SELECT last_seq FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
1050
- if (!session) throw new SessionNotFoundError(sessionId);
1051
- const lastSeq = Number(session.last_seq);
1052
- const fromSeq = Math.max(1, query.fromSeq);
1053
- const toSeq = Math.min(query.toSeq, lastSeq);
1054
- if (fromSeq > toSeq) return {
1055
- lastSeq,
1056
- entries: [],
1057
- throughSeq: Math.max(toSeq, fromSeq - 1)
1058
- };
1059
- if (query.maxChars !== void 0 && query.maxChars <= 0) return {
1060
- lastSeq,
1061
- entries: [],
1062
- throughSeq: fromSeq - 1
1063
- };
1064
- const skippedSet = query.skipTypes === void 0 ? void 0 : new Set(query.skipTypes);
1065
- const skippedPrefixes = (query.skipTypes ?? []).map((type) => `{"type":${JSON.stringify(type)},`);
1066
- const largeBytes = query.largeEntryBytes ?? 0x7fffffff;
1067
- const rows = await this.database.all(`WITH sized AS (
1068
- SELECT seq, chunks, ${this.entryByteLength("entry_json")} AS raw_bytes,
1069
- ${this.entryByteLength("entry_json")} + chunks * ? AS bytes
1070
- FROM ${this.tables.entries}
1071
- WHERE session_id = ? AND seq >= ? AND seq <= ?
1072
- ),
1073
- paged AS (
1074
- SELECT seq, chunks, raw_bytes, count(*) OVER () AS remaining,
1075
- sum(bytes) OVER (ORDER BY seq) - bytes AS before_chars
1076
- FROM sized
1077
- )
1078
- SELECT p.seq, CASE WHEN p.chunks = 0 AND p.raw_bytes <= ? THEN e.entry_json END AS entry_json,
1079
- substr(e.entry_json, 1, 64) AS entry_head, p.chunks, p.remaining,
1080
- CASE WHEN p.chunks = 0 AND p.raw_bytes > ? AND substr(e.entry_json, 1, 8) <> '{"type":'
1081
- THEN ${this.dialect.jsonText("e.entry_json", "type")} END AS entry_type
1082
- FROM paged p
1083
- JOIN ${this.tables.entries} e ON e.session_id = ? AND e.seq = p.seq
1084
- WHERE p.before_chars < ?
1085
- ORDER BY p.seq`, SESSION_ENTRY_CHUNK_BYTES, sessionId, fromSeq, toSeq, largeBytes, largeBytes, sessionId, query.maxChars ?? Number.MAX_SAFE_INTEGER);
1086
- const entries = [];
1087
- for (const row of rows) {
1088
- query.signal?.throwIfAborted();
1089
- if (skippedPrefixes.some((prefix) => row.entry_head.startsWith(prefix))) continue;
1090
- const seq = Number(row.seq);
1091
- const chunks = Number(row.chunks);
1092
- if (chunks > 0) {
1093
- const rawChunks = await this.readRawEntryChunks(this.database, sessionId, seq, chunks, query.signal);
1094
- if (rawChunks.reduce((total, chunk) => total + chunk.byteLength, 0) > largeBytes) entries.push({
1095
- seq,
1096
- entry: STUB_ENTRY,
1097
- rawChunks
1098
- });
1099
- else {
1100
- const parsed = JSON.parse(Buffer.concat(rawChunks).toString("utf8"));
1101
- if (!skippedSet?.has(parsed.type)) entries.push({
1102
- seq,
1103
- entry: parsed
1104
- });
1105
- }
1106
- } else if (row.entry_json === null) {
1107
- if (row.entry_type !== null && skippedSet?.has(row.entry_type)) continue;
1108
- const rawChunks = await this.readInlineEntryBytes(sessionId, seq);
1109
- entries.push({
1110
- seq,
1111
- entry: STUB_ENTRY,
1112
- rawChunks
1113
- });
1114
- } else {
1115
- const parsed = JSON.parse(row.entry_json);
1116
- if (!skippedSet?.has(parsed.type)) entries.push({
1117
- seq,
1118
- entry: parsed
1119
- });
1120
- }
1121
- }
1122
- const last = rows.at(-1);
1123
- return {
1124
- lastSeq,
1125
- entries,
1126
- throughSeq: last !== void 0 && rows.length < Number(last.remaining) ? Number(last.seq) : toSeq
1127
- };
1128
- }
1129
- async readHeader(sessionId) {
1130
- this.assertOpen();
1131
- validateSessionText("sessionId", sessionId);
1132
- const row = await this.database.get(`SELECT header_json FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
1133
- return row ? JSON.parse(row.header_json) : void 0;
1134
- }
1135
- async delete(sessionId) {
1136
- this.assertOpen();
1137
- validateSessionText("sessionId", sessionId);
1138
- await this.transaction(async (tx) => {
1139
- await this.searchIndex?.forgetWithin(tx, sessionId);
1140
- await tx.run(`DELETE FROM ${this.tables.blobChunks} WHERE session_id = ?`, sessionId);
1141
- await tx.run(`DELETE FROM ${this.tables.blobs} WHERE session_id = ?`, sessionId);
1142
- await tx.run(`DELETE FROM ${this.tables.searchTexts} WHERE session_id = ?`, sessionId);
1143
- await tx.run(`DELETE FROM ${this.tables.entryChunks} WHERE session_id = ?`, sessionId);
1144
- await tx.run(`DELETE FROM ${this.tables.entries} WHERE session_id = ?`, sessionId);
1145
- await tx.run(`DELETE FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
1146
- }, SESSION_TRANSACTION);
1147
- }
1148
- /**
1149
- * Stores the blob as rows of at most {@link SESSION_BLOB_CHUNK_BYTES}, then publishes its header. Every statement
1150
- * commits by itself and writes only while the session exists, so no transaction stays open across round trips and
1151
- * `delete`, which removes a session's rows in one transaction, leaves none behind. A blob is readable only once its
1152
- * header is there, so a writer that stops part way leaves rows of its own session that `delete` removes, and storing
1153
- * the same bytes again completes or skips them. Bytes a session already holds are not sent again.
1154
- */
1155
- async putBlob(sessionId, data) {
1156
- this.assertOpen();
1157
- validateSessionText("sessionId", sessionId);
1158
- const stored = Uint8Array.from(data);
1159
- const blob = {
1160
- hash: await sha256Hex(stored),
1161
- bytes: stored.byteLength
1162
- };
1163
- const previous = await this.blobHeader(sessionId, blob.hash);
1164
- if (previous) {
1165
- if (previous.chunks === -1) while (await this.database.transaction((tx) => migrateLegacyBlobBatch(tx, this.tables, sessionId, blob.hash, stored))) await new Promise((resolve) => setTimeout(resolve, 0));
1166
- return blob;
1167
- }
1168
- const chunks = Math.ceil(blob.bytes / SESSION_BLOB_CHUNK_BYTES);
1169
- const { sessions, blobs, blobChunks } = this.tables;
1170
- const sessionExists = `EXISTS (SELECT 1 FROM ${sessions} WHERE id = ?)`;
1171
- for (let index = 0; index < chunks; index++) await this.database.run(`INSERT INTO ${blobChunks} (session_id, hash, idx, data) SELECT ?, ?, ?, ? WHERE ${sessionExists}
1172
- ON CONFLICT DO NOTHING`, sessionId, blob.hash, index, stored.subarray(index * SESSION_BLOB_CHUNK_BYTES, (index + 1) * SESSION_BLOB_CHUNK_BYTES), sessionId);
1173
- const { changes } = await this.database.run(`INSERT INTO ${blobs} (session_id, hash, bytes, chunks${this.legacyBlobData ? ", data" : ""})
1174
- SELECT ?, ?, ?, ?${this.legacyBlobData ? ", X''" : ""}
1175
- WHERE ${sessionExists} AND (SELECT count(*) FROM ${blobChunks} WHERE session_id = ? AND hash = ?) = ?
1176
- ON CONFLICT DO NOTHING`, sessionId, blob.hash, blob.bytes, chunks, sessionId, sessionId, blob.hash, chunks);
1177
- if (changes === 0 && !await this.blobHeader(sessionId, blob.hash)) throw new SessionNotFoundError(sessionId);
1178
- return blob;
1179
- }
1180
- /**
1181
- * Reads chunked blobs a row at a time, each returning at most {@link SESSION_BLOB_CHUNK_BYTES}. Legacy blobs
1182
- * are read in one query: slicing their data column repeatedly would reread the entire BLOB for every chunk.
1183
- * Rows never change once written. A session deleted meanwhile holds nothing; missing bytes are `blob-incomplete`.
1184
- */
1185
- async getBlob(sessionId, hash) {
1186
- this.assertOpen();
1187
- validateSessionText("sessionId", sessionId);
1188
- let header = await this.blobHeader(sessionId, hash);
1189
- if (header === void 0) return void 0;
1190
- if (header.chunks === -1) {
1191
- const row = await this.database.get(`SELECT data FROM ${this.tables.blobs} WHERE session_id = ? AND hash = ? AND chunks = -1`, sessionId, hash);
1192
- if (row) {
1193
- if (row.data.byteLength === header.bytes) return row.data;
1194
- throw new SessionBlobError("blob-incomplete", {
1195
- sessionId,
1196
- hash,
1197
- bytes: header.bytes
1198
- });
1199
- }
1200
- header = await this.blobHeader(sessionId, hash);
1201
- if (header === void 0) return void 0;
1202
- }
1203
- const data = new Uint8Array(header.bytes);
1204
- let offset = 0;
1205
- for (let index = 0; index < header.chunks; index++) {
1206
- const row = await this.database.get(`SELECT data FROM ${this.tables.blobChunks} WHERE idx = ? AND session_id = ? AND hash = ?`, index, sessionId, hash);
1207
- if (row?.data == null || offset + row.data.byteLength > data.byteLength) break;
1208
- data.set(row.data, offset);
1209
- offset += row.data.byteLength;
1210
- }
1211
- if (offset === data.byteLength) return data;
1212
- if (await this.blobHeader(sessionId, hash) === void 0) return void 0;
1213
- throw new SessionBlobError("blob-incomplete", {
1214
- sessionId,
1215
- hash,
1216
- bytes: header.bytes
1217
- });
1218
- }
1219
- async blobHeader(sessionId, hash) {
1220
- const row = await this.database.get(`SELECT bytes, chunks FROM ${this.tables.blobs} WHERE session_id = ? AND hash = ?`, sessionId, hash);
1221
- return row === void 0 ? void 0 : {
1222
- bytes: Number(row.bytes),
1223
- chunks: Number(row.chunks)
1224
- };
1225
- }
1226
- /**
1227
- * Lists from a per-scope cache revalidated on every call. A cheap change token, which moves on any commit
1228
- * from this or another connection, decides whether the scope is re-read. A scope listed for the first time
1229
- * is read exactly as an uncached listing; afterwards only its light columns are re-read and search text is
1230
- * read only for sessions whose stored listing columns changed. Listings of the same store take turns
1231
- * reading and updating the caches; the yielding below runs outside that turn.
1232
- */
1233
- async *list(query) {
1234
- this.assertListing(query);
1235
- if (query.cwd?.includes("\0")) throw new StorageInvalidTextError(0);
1236
- if (query.withoutSearchText) {
1237
- for await (const summary of this.listWithoutSearchText(query)) {
1238
- this.assertListing(query);
1239
- yield summary;
1240
- }
1241
- this.assertListing(query);
1242
- return;
1243
- }
1244
- const listed = this.listing.then(() => this.listScope(query));
1245
- this.listing = listed.then(() => {}, () => {});
1246
- const summaries = await listed;
1247
- for (const summary of summaries) {
1248
- this.assertListing(query);
1249
- yield summary;
1250
- }
1251
- this.assertListing(query);
1252
- }
1253
- /** Revalidates one scope's cache and resolves its summaries; called for one listing at a time. */
1254
- async listScope(query) {
1255
- this.assertListing(query);
1256
- await this.assertReadableSchema(this.database);
1257
- const token = await this.changeToken();
1258
- const key = JSON.stringify([
1259
- query.includeInternal === true,
1260
- query.cwd ?? null,
1261
- query.idPrefix?.toLowerCase() ?? null
1262
- ]);
1263
- const cached = this.scopes.get(key);
1264
- const scope = token !== void 0 && cached?.token === token && cached.ids.every((id) => this.summaries.has(id)) ? cached : {
1265
- token,
1266
- ids: await this.readScope(query, cached !== void 0)
1267
- };
1268
- this.scopes.delete(key);
1269
- this.scopes.set(key, scope);
1270
- for (const oldest of this.scopes.keys()) {
1271
- if (this.scopes.size <= LISTING_SCOPES) break;
1272
- this.scopes.delete(oldest);
1273
- }
1274
- if (scope !== cached) this.pruneSummaries();
1275
- return scope.ids.flatMap((id) => this.summaries.get(id)?.summary ?? []);
1276
- }
1277
- async findMostRecent(query) {
1278
- let latest;
1279
- for await (const summary of this.list(query)) if (!latest || Date.parse(summary.modifiedAt) > Date.parse(latest.modifiedAt)) latest = summary;
1280
- return latest;
1281
- }
1282
- async close() {
1283
- this.assertOpen();
1284
- this.closed = true;
1285
- this.scopes.clear();
1286
- this.summaries.clear();
1287
- }
1288
- /**
1289
- * `data_version` moves when another connection commits and `total_changes()` when this one writes, so
1290
- * together they cover writers in every process, but only on one connection: Atomic's own SQLite adapter serves
1291
- * every statement from one. Over an adapter that may not, such as a libSQL server whose every HTTP request is a
1292
- * new stream, neither moves, and no column of the sessions table changes on every write by every version, so
1293
- * there is no token and each listing revalidates its scope (#4805).
1294
- */
1295
- async changeToken() {
1296
- if (this.database.descriptor.adapter !== "node-sqlite") return void 0;
1297
- const { changeMarkers, rowOrder } = this.dialect;
1298
- const row = await this.database.get(`SELECT ${changeMarkers.columns},
1299
- (SELECT count(*) FROM ${this.tables.sessions}) AS sessions,
1300
- (SELECT max(${rowOrder()}) FROM ${this.tables.sessions}) AS last_row
1301
- ${changeMarkers.from}`);
1302
- return JSON.stringify(Object.values(row ?? {}).map(String));
1303
- }
1304
- async *listWithoutSearchText(query) {
1305
- await this.assertReadableSchema(this.database);
1306
- const scope = await this.scopeOf(query, true);
1307
- if (scope === void 0) return;
1308
- const order = this.dialect.rowOrder();
1309
- const bound = await this.database.get(`SELECT max(${order}) AS upper FROM ${this.tables.sessions}`);
1310
- const upper = Number(bound?.upper ?? 0);
1311
- const seen = /* @__PURE__ */ new Set();
1312
- const scanRows = this.listingScanRows(SESSION_READ_FETCH.max);
1313
- for (let after = 0, limit = Math.min(scanRows, SESSION_READ_FETCH.first); after < upper;) {
1314
- this.assertListing(query);
1315
- const rows = await this.database.all(`WITH scanned AS MATERIALIZED (
1316
- SELECT ${order} AS ord, CASE WHEN ${scope.where} THEN ${LISTING_SIZE} END AS size
1317
- FROM ${this.tables.sessions} WHERE ${order} > ? AND ${order} <= ?
1318
- ORDER BY ${order} LIMIT ?
1319
- ), keyed AS MATERIALIZED (
1320
- SELECT ord, row_number() OVER (ORDER BY ord) AS key_row, size FROM scanned
1321
- ), bound AS (SELECT max(ord) AS upto FROM keyed),
1322
- page AS (
1323
- SELECT ord, key_row, count(*) OVER () AS fetched,
1324
- row_number() OVER (ORDER BY ord) AS page_row,
1325
- sum(size) OVER () AS batch_chars,
1326
- sum(size) OVER (ORDER BY ord) AS page_chars
1327
- FROM keyed WHERE size IS NOT NULL
1328
- ), kept AS MATERIALIZED (
1329
- SELECT ord, key_row, fetched, batch_chars, page_chars FROM page
1330
- WHERE page_chars <= ? OR page_row = 1
1331
- )
1332
- SELECT bound.upto, kept.ord, kept.key_row, kept.fetched, kept.batch_chars, kept.page_chars,
1333
- ${LISTING_SELECT_COLUMNS}
1334
- FROM bound
1335
- LEFT JOIN kept ON 1 = 1
1336
- LEFT JOIN ${this.tables.sessions} AS s ON ${this.dialect.rowOrder("s")} = kept.ord
1337
- ORDER BY kept.ord`, ...scope.params, after, upper, limit, SESSION_READ_PAGE_CHARS);
1338
- const upto = rows[0]?.upto;
1339
- if (upto === null || upto === void 0) break;
1340
- const listed = rows.filter((row) => row.ord !== null);
1341
- for (const row of listed) if (!seen.has(row.id) && await scope.inScope(row)) {
1342
- seen.add(row.id);
1343
- yield summaryFromRow({
1344
- ...row,
1345
- search_texts_json: "[]"
1346
- });
1347
- }
1348
- const last = listed.at(-1);
1349
- const clipped = last !== void 0 && listed.length < Number(last.fetched);
1350
- after = clipped ? Number(last.ord) : Number(upto);
1351
- const batchChars = Number(listed[0]?.batch_chars ?? 0);
1352
- const pageChars = Number(last?.page_chars ?? 0);
1353
- const next = !clipped ? limit * 4 : batchChars - pageChars <= 4194304 ? limit : Math.max(SESSION_READ_FETCH.min, Number(last.key_row) * 2);
1354
- limit = Math.min(scanRows, next);
1355
- await yieldTurn();
1356
- }
1357
- this.assertListing(query);
1358
- }
1359
- async distinctCwds(paced, query) {
1360
- if (!paced) return (await this.database.all(`SELECT DISTINCT cwd FROM ${this.tables.sessions}`)).map((project) => project.cwd);
1361
- const order = this.dialect.rowOrder();
1362
- const page = this.listingScanRows(LISTING_CWD_PAGE);
1363
- const cwds = /* @__PURE__ */ new Set();
1364
- for (let after = 0;;) {
1365
- this.assertListing(query);
1366
- const rows = await this.database.all(`SELECT ${order} AS ord, cwd FROM ${this.tables.sessions} WHERE ${order} > ? ORDER BY ${order} LIMIT ?`, after, page);
1367
- for (const row of rows) cwds.add(row.cwd);
1368
- await yieldTurn();
1369
- if (rows.length < page) return [...cwds];
1370
- after = Number(rows.at(-1).ord);
1371
- }
1372
- }
1373
- /** The most sessions one statement of a paced listing scans: fewer when the statement holds the event loop. */
1374
- listingScanRows(overServer) {
1375
- return this.database.descriptor.adapter === "node-sqlite" ? LISTING_SCAN_ROWS : overServer;
1376
- }
1377
- async scopeOf(query, paced) {
1378
- const matchesCwd = query.cwd === void 0 ? void 0 : this.cwdMatcher?.(query.cwd) ?? ((candidate) => candidate === query.cwd);
1379
- let projectCwds;
1380
- if (matchesCwd) {
1381
- const distinct = await this.distinctCwds(paced, query);
1382
- const slice = paced ? LISTING_CWD_MATCHES : Math.max(1, distinct.length);
1383
- projectCwds = [];
1384
- for (let start = 0; start < distinct.length; start += slice) {
1385
- const matched = await Promise.all(distinct.slice(start, start + slice).map(async (cwd) => await matchesCwd(cwd) ? cwd : void 0));
1386
- for (const cwd of matched) if (cwd !== void 0) projectCwds.push(cwd);
1387
- if (paced && start + slice < distinct.length) {
1388
- this.assertListing(query);
1389
- await yieldTurn();
1390
- }
1391
- }
1392
- this.assertListing(query);
1393
- if (projectCwds.length === 0) return void 0;
1394
- }
1395
- const idPrefix = query.idPrefix?.toLowerCase();
1396
- return {
1397
- where: `(? = 1 OR internal = 0)${projectCwds ? ` AND cwd IN (${projectCwds.map(() => "?").join(", ")})` : ""}${idPrefix === void 0 ? "" : " AND substr(lower(id), 1, ?) = ?"}`,
1398
- params: [
1399
- query.includeInternal ? 1 : 0,
1400
- ...projectCwds ?? [],
1401
- ...idPrefix === void 0 ? [] : [idPrefix.length, idPrefix]
1402
- ],
1403
- inScope: (row) => !matchesCwd || matchesCwd(row.cwd)
1404
- };
1405
- }
1406
- /** The scope's session ids in store order, with a current summary cached for each. */
1407
- async readScope(query, listedBefore) {
1408
- const resolved = await this.scopeOf(query, false);
1409
- if (resolved === void 0) return [];
1410
- const { where: scope, params, inScope } = resolved;
1411
- const filterInScope = async (rows) => {
1412
- return (await Promise.all(rows.map(async (row) => await inScope(row) ? row : void 0))).filter((row) => row !== void 0);
1413
- };
1414
- if (listedBefore) {
1415
- const rows = await filterInScope(await this.readListingRows(scope, params));
1416
- this.assertListing(query);
1417
- const stale = rows.filter((row) => this.summaries.get(row.id)?.version !== listingVersion(row));
1418
- if (stale.length <= rows.length / 4) {
1419
- for (let start = 0; start < stale.length; start += 500) {
1420
- const ids = stale.slice(start, start + 500).map((row) => row.id);
1421
- const fetched = new Set((await this.readSummaries(`id IN (${ids.map(() => "?").join(", ")})`, ids)).map((row) => row.id));
1422
- for (const id of ids) if (!fetched.has(id)) this.summaries.delete(id);
1423
- this.assertListing(query);
1424
- }
1425
- return rows.flatMap((row) => this.summaries.has(row.id) ? [row.id] : []);
1426
- }
1427
- }
1428
- const rows = await filterInScope(await this.readSummaries(scope, params));
1429
- this.assertListing(query);
1430
- return rows.map((row) => row.id);
1431
- }
1432
- /**
1433
- * The listing rows `where` selects, without search text, in store order, a page per statement: each fetches the next
1434
- * {@link SESSION_READ_FETCH} rows by key and returns those whose cumulative text fits in
1435
- * {@link SESSION_READ_PAGE_CHARS}, the first always, so that no response passes a libSQL server's limit however many
1436
- * sessions there are (#4954) and no statement reads more than its batch.
1437
- */
1438
- async readListingRows(where, params) {
1439
- const order = this.dialect.rowOrder();
1440
- const rows = [];
1441
- for (let after = 0, limit = SESSION_READ_FETCH.first;;) {
1442
- const page = await this.database.all(`WITH sized AS MATERIALIZED (
1443
- SELECT ${LISTING_COLUMNS}, ${order} AS ord, ${LISTING_SIZE} AS size
1444
- FROM ${this.tables.sessions} WHERE (${where}) AND ${order} > ? ORDER BY ord LIMIT ?
1445
- ) SELECT ${LISTING_COLUMNS}, ord, fetched, batch_chars, page_chars FROM (
1446
- SELECT ${LISTING_COLUMNS}, ord, count(*) OVER () AS fetched,
1447
- row_number() OVER (ORDER BY ord) AS page_row,
1448
- sum(size) OVER () AS batch_chars,
1449
- sum(size) OVER (ORDER BY ord) AS page_chars
1450
- FROM sized
1451
- ) AS page WHERE (page_chars <= ? OR page_row = 1) AND page_row <= ? ORDER BY ord`, ...params, after, limit + 1, SESSION_READ_PAGE_CHARS, limit);
1452
- rows.push(...page);
1453
- const next = nextFetch(limit, page);
1454
- if (!next.more) return rows;
1455
- after = Number(page.at(-1).ord);
1456
- limit = next.limit;
1457
- }
1458
- }
1459
- /**
1460
- * Reads full listing rows, search text included, and caches their summaries, a page per statement as
1461
- * {@link readListingRows} reads, search text counted. A session whose search text alone is longer than a page has
1462
- * it read in pages of its own and joined here rather than by the database, whose string limit it may pass (#4954).
1463
- */
1464
- async readSummaries(where, params) {
1465
- const order = this.dialect.rowOrder();
1466
- const rows = [];
1467
- for (let after = 0, limit = SESSION_READ_FETCH.first;;) {
1468
- const page = await this.database.all(`WITH keyed AS MATERIALIZED (
1469
- SELECT ${LISTING_COLUMNS}, ${order} AS ord, ${LISTING_SIZE} AS size
1470
- FROM ${this.tables.sessions} AS s WHERE (${where}) AND ${order} > ? ORDER BY ord LIMIT ?
1471
- ), sized AS MATERIALIZED (
1472
- SELECT ${LISTING_COLUMNS}, ord, size,
1473
- (SELECT COALESCE(sum(length(text_json) + 1) + 1, 2) FROM ${this.tables.searchTexts} WHERE session_id = keyed.id) AS search_size
1474
- FROM keyed
1475
- ) SELECT ${LISTING_COLUMNS}, ord, fetched, batch_chars, page_chars, CASE WHEN search_size <= ? THEN (
1476
- SELECT COALESCE('[' || ${this.dialect.orderedConcat("text_json", "','", "seq")} || ']', '[]')
1477
- FROM (SELECT text_json, seq FROM ${this.tables.searchTexts} WHERE session_id = page.id ORDER BY seq)
1478
- ) END AS search_texts_json
1479
- FROM (
1480
- SELECT ${LISTING_COLUMNS}, ord, search_size, count(*) OVER () AS fetched,
1481
- row_number() OVER (ORDER BY ord) AS page_row,
1482
- sum(size + search_size) OVER () AS batch_chars,
1483
- sum(size + search_size) OVER (ORDER BY ord) AS page_chars
1484
- FROM sized
1485
- ) AS page WHERE (page_chars <= ? OR page_row = 1) AND page_row <= ? ORDER BY ord`, ...params, after, limit + 1, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, limit);
1486
- for (const row of page) {
1487
- const summaryRow = row.search_texts_json === null ? {
1488
- ...row,
1489
- search_texts_json: await this.readSearchTexts(row.id)
1490
- } : row;
1491
- this.summaries.set(row.id, {
1492
- version: listingVersion(summaryRow),
1493
- summary: summaryFromRow(summaryRow)
1494
- });
1495
- rows.push(summaryRow);
1496
- }
1497
- const next = nextFetch(limit, page);
1498
- if (!next.more) return rows;
1499
- after = Number(page.at(-1).ord);
1500
- limit = next.limit;
1501
- }
1502
- }
1503
- /** A session's search texts as one JSON array, read in pages of at most {@link SESSION_READ_PAGE_CHARS}. */
1504
- async readSearchTexts(sessionId) {
1505
- const sizes = await this.database.all(`SELECT seq, length(text_json) AS size FROM ${this.tables.searchTexts} WHERE session_id = ? ORDER BY seq`, sessionId);
1506
- const texts = [];
1507
- for (const page of pagesOf(sizes)) {
1508
- const rows = await this.database.all(`SELECT text_json FROM ${this.tables.searchTexts} WHERE session_id = ? AND seq >= ? AND seq <= ? ORDER BY seq`, sessionId, page[0].seq, page.at(-1).seq);
1509
- for (const row of rows) texts.push(row.text_json);
1510
- }
1511
- return `[${texts.join(",")}]`;
1512
- }
1513
- /**
1514
- * Keeps only summaries some cached scope still lists, so memory follows the live sessions. Runs in a
1515
- * listing's turn after it records its scope, when no other listing holds summaries it has not recorded.
1516
- */
1517
- pruneSummaries() {
1518
- const listed = new Set([...this.scopes.values()].flatMap((scope) => scope.ids));
1519
- for (const id of this.summaries.keys()) if (!listed.has(id)) this.summaries.delete(id);
1520
- }
1521
- assertOpen() {
1522
- if (this.closed) throw new StoreClosedError$1(this.descriptor);
1523
- }
1524
- assertListing(query) {
1525
- this.assertOpen();
1526
- query.signal?.throwIfAborted();
1527
- }
1528
- async read(tx, sessionId) {
1529
- const row = await tx.get(`SELECT header_json, last_seq,CASE WHEN ${this.dialect.jsonValid("summary_state")} THEN ${this.dialect.jsonText("summary_state", "epoch")} END AS chat_epoch,revision FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
1530
- if (!row) throw new SessionNotFoundError(sessionId);
1531
- const snapshot = {
1532
- header: JSON.parse(row.header_json),
1533
- entries: (await this.readRows(tx, sessionId)).map(({ entry }) => entry),
1534
- lastSeq: row.last_seq
1535
- };
1536
- if (typeof row.chat_epoch === "string") bindChatEpoch(snapshot.header, row.chat_epoch);
1537
- return noteSnapshotGeneration(this, snapshot, nativeLoad, row, "revision");
1538
- }
1539
- async readRows(tx, sessionId, filter = "", params = []) {
1540
- const entries = [];
1541
- for (let after = 0, limit = SESSION_READ_FETCH.first;;) {
1542
- const rows = await tx.all(`WITH sized AS MATERIALIZED (
1543
- SELECT seq, chunks, length(entry_json) AS size,
1544
- CASE WHEN ${this.dialect.textByteLength("entry_json")} <= ? THEN entry_json END AS inline_json
1545
- FROM ${this.tables.entries} WHERE session_id = ? AND seq > ?${filter === "" ? "" : ` AND ${filter}`} ORDER BY seq LIMIT ?
1546
- ), batch AS MATERIALIZED (
1547
- SELECT count(*) AS fetched, COALESCE(sum(size), 0) AS chars FROM sized
1548
- ), page AS (
1549
- SELECT seq, chunks, inline_json, fetched, chars AS batch_chars, 0 AS page_chars
1550
- FROM (SELECT seq, chunks, inline_json FROM sized ORDER BY seq LIMIT ?) AS fitting CROSS JOIN batch
1551
- WHERE batch.chars <= ?
1552
- UNION ALL
1553
- SELECT seq, chunks, inline_json, fetched, batch_chars, page_chars FROM (
1554
- SELECT seq, chunks, inline_json, batch.fetched, batch.chars AS batch_chars,
1555
- row_number() OVER (ORDER BY seq) AS page_row,
1556
- sum(size) OVER (ORDER BY seq) AS page_chars
1557
- FROM sized CROSS JOIN batch WHERE batch.chars > ?
1558
- ) AS windowed WHERE (page_chars <= ? OR page_row = 1) AND page_row <= ?
1559
- ) SELECT seq, COALESCE(inline_json, (
1560
- SELECT e.entry_json FROM ${this.tables.entries} AS e WHERE e.session_id = ? AND e.seq = page.seq
1561
- )) AS entry_json, chunks, fetched, batch_chars, page_chars FROM page ORDER BY seq`, SESSION_READ_INLINE_BYTES, sessionId, after, ...params, limit + 1, limit, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, limit, sessionId);
1562
- for (const entry of rows) {
1563
- const chunks = Number(entry.chunks);
1564
- const json = chunks === 0 ? entry.entry_json : await this.readEntryChunks(tx, sessionId, entry.seq, chunks);
1565
- entries.push({
1566
- seq: Number(entry.seq),
1567
- entry: JSON.parse(json)
1568
- });
1569
- }
1570
- const next = nextFetch(limit, rows);
1571
- if (!next.more) return entries;
1572
- after = Number(rows.at(-1).seq);
1573
- limit = next.limit;
1574
- }
1575
- }
1576
- async readSeqs(tx, sessionId, seqs) {
1577
- const entries = [];
1578
- for (let start = 0; start < seqs.length; start += SEQ_BATCH) {
1579
- const batch = seqs.slice(start, start + SEQ_BATCH);
1580
- entries.push(...await this.readRows(tx, sessionId, `seq IN (${batch.map(() => "?").join(", ")})`, batch));
1581
- }
1582
- return entries;
1583
- }
1584
- async resumeSource(tx, sessionId) {
1585
- const row = await tx.get(`SELECT header_json,last_seq,summary_state,revision FROM ${this.tables.sessions} WHERE id = ?${this.dialect.lockClause("share")}`, sessionId);
1586
- if (!row) throw new SessionNotFoundError(sessionId);
1587
- const stored = windowIndex(JSON.parse(row.summary_state), Number(row.last_seq));
1588
- const remembered = this.resumeIndexes.get(sessionId);
1589
- const index = isSessionResumeIndex(stored, Number(row.last_seq)) ? stored : remembered?.revision === row.revision ? remembered.index : void 0;
1590
- if (!index || !isSessionResumeIndex(index, Number(row.last_seq))) throw new SessionConflictError(sessionId, Number(row.last_seq), Number(row.last_seq));
1591
- return {
1592
- header: JSON.parse(row.header_json),
1593
- index,
1594
- row
1595
- };
1596
- }
1597
- async prepareResume(sessionId, leafId, throughSeq) {
1598
- attempts: for (let attempt = 0; attempt < 3; attempt++) {
1599
- const row = await this.database.get(`SELECT header_json,last_seq,summary_state,revision FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
1600
- if (!row) throw new SessionNotFoundError(sessionId);
1601
- const state = JSON.parse(row.summary_state);
1602
- const remembered = this.resumeIndexes.get(sessionId);
1603
- const currentIndex = windowIndex(state, Number(row.last_seq)) ?? (remembered?.revision === row.revision && isSessionResumeIndex(remembered.index, Number(row.last_seq)) ? remembered.index : void 0);
1604
- const limit = throughSeq ?? Number(row.last_seq);
1605
- if (limit > Number(row.last_seq)) throw new SessionConflictError(sessionId, limit, Number(row.last_seq));
1606
- const selected = leafId === void 0 ? void 0 : await this.seqOfEntry(this.database, sessionId, leafId) ?? 0;
1607
- const requested = selected !== void 0 && selected > limit ? 0 : selected;
1608
- if (currentIndex && limit === currentIndex.seq && (requested === void 0 || requested === currentIndex.leafSeq)) return {
1609
- index: currentIndex,
1610
- revision: row.revision
1611
- };
1612
- let index;
1613
- const sqlite = this.dialect.name === "sqlite";
1614
- const j = (...path) => sqlite ? this.dialect.jsonText("entry_json", ...path) : this.dialect.jsonAt({
1615
- column: "entry_json",
1616
- element: "parsed"
1617
- }, ...path);
1618
- const jsonType = (...path) => sqlite ? this.dialect.jsonType("entry_json", ...path) : `jsonb_typeof(parsed.value #> '{${path.join(",")}}')`;
1619
- const projected = [
1620
- "type",
1621
- "parentId",
1622
- "timestamp",
1623
- "customType",
1624
- "firstKeptEntryId",
1625
- "coveredThroughEntryId",
1626
- "provider",
1627
- "modelId",
1628
- "thinkingLevel",
1629
- "targetId",
1630
- "label",
1631
- "stageAdmissionKey",
1632
- "root",
1633
- "snapshotId",
1634
- "degradedFrom",
1635
- "captureMs"
1636
- ].map((key) => [key, j(key)]);
1637
- const messageKeys = [
1638
- "role",
1639
- "provider",
1640
- "model",
1641
- "usage",
1642
- "toolCallId"
1643
- ];
1644
- const dataKeys = [
1645
- "childId",
1646
- "version",
1647
- "index",
1648
- "agent",
1649
- "cwd",
1650
- "state",
1651
- "intercomSessionId",
1652
- "homeGroup",
1653
- "kind",
1654
- "worktree",
1655
- "type",
1656
- "timestamp",
1657
- "completionId",
1658
- "sessionId",
1659
- "askId",
1660
- "messageId",
1661
- "attemptId",
1662
- "runId",
1663
- "requestId",
1664
- "id",
1665
- "protectedReconciliationOf",
1666
- "historyOnly",
1667
- "toolCallId",
1668
- "ownerId",
1669
- "taskId",
1670
- "terminalStatus"
1671
- ];
1672
- const op = `CASE WHEN ${jsonType("data", "op")} = '${sqlite ? "text" : "string"}' THEN ${j("data", "op")} END`;
1673
- const deliveryOp = `chunks > 0 AND ${j("type")} = 'custom' AND ${j("customType")} = 'atomic-pooled-delivery-op'`;
1674
- const dataExpr = this.dialect.jsonObject([
1675
- ...dataKeys.map((key) => [key, [
1676
- "version",
1677
- "index",
1678
- "timestamp"
1679
- ].includes(key) ? `CASE WHEN ${jsonType("data", key)} IN ('integer','real','number') THEN CAST(${j("data", key)} AS ${this.dialect.types.real}) END` : key === "runId" ? `CASE WHEN ${j("customType")} NOT IN ('workflow.run.start','workflow.run.end') OR ${jsonType("data", key)} = '${sqlite ? "text" : "string"}' THEN ${j("data", key)} END` : j("data", key)]),
1680
- ["name", `CASE WHEN ${jsonType("data", "name")} = '${sqlite ? "text" : "string"}' THEN '' END`],
1681
- ["ts", `CASE WHEN ${jsonType("data", "ts")} IN ('integer','real','number') THEN 0 END`],
1682
- ["message", this.dialect.jsonObject([
1683
- "id",
1684
- "replyTo",
1685
- "expectsReply"
1686
- ].map((key) => [key, j("data", "message", key)]))],
1687
- ["op", op],
1688
- ...[
1689
- ["owner", "object"],
1690
- ["tasks", "array"],
1691
- ["groups", "array"]
1692
- ].map(([key, type]) => [key, `CASE WHEN ${jsonType("data", key)} = '${type}' THEN ${j("data", key)} WHEN ${jsonType("data", key)} IS NULL OR ${jsonType("data", key)} = 'null' THEN NULL ELSE '' END`]),
1693
- ...["messageIds", "askIds"].map((key) => [key, `CASE WHEN ${jsonType("data", key)} = 'array' THEN ${j("data", key)} END`]),
1694
- ...["queries", "urls"].map((key) => [key, `CASE WHEN ${jsonType("data", key)} = 'array' THEN '[]' ELSE NULL END`])
1695
- ]);
1696
- const detailsExpr = this.dialect.jsonObject([...dataKeys.map((key) => [key, j("details", key)]), ["message", this.dialect.jsonObject([
1697
- "id",
1698
- "replyTo",
1699
- "expectsReply"
1700
- ].map((key) => [key, j("details", "message", key)]))]]);
1701
- const dataFieldNames = this.dialect.name === "sqlite" ? `(SELECT COALESCE(json_group_array(key),'[]') FROM json_each(entry_json,'$.data'))` : `(SELECT COALESCE(json_agg(key)::text,'[]') FROM jsonb_object_keys(CASE WHEN jsonb_typeof(parsed.value->'data')='object' THEN parsed.value->'data' ELSE '{}'::jsonb END) AS key)`;
1702
- const binaryContent = sqlite && Number(row.last_seq) > 0 && this.database.supportsJsonbExtract && await this.database.supportsJsonbExtract();
1703
- const toolBlocks = sqlite ? this.dialect.jsonValues(binaryContent ? "jsonb_extract(entry_json, '$.message.content')" : j("message", "content")) : "jsonb_array_elements_text(parsed.value #> '{message,content}') AS blocks(value)";
1704
- const blockType = this.dialect.jsonText("value", "type");
1705
- const toolType = `CASE WHEN chunks > 0 AND ${sqlite ? "type = 'text' AND instr(value, '{')" : "strpos(value, '{')"} = 0 THEN NULL ELSE ${blockType} END`;
1706
- const columns = [
1707
- ["dataFields", `CASE WHEN ${deliveryOp} THEN '["op"]' WHEN ${j("type")} = 'custom' THEN ${dataFieldNames} ELSE '[]' END`],
1708
- ...projected,
1709
- ["message", this.dialect.jsonObject([...messageKeys.map((key) => [key, j("message", key)]), ...["toolsAdded", "toolsRemoved"].map((key) => [key, `CASE WHEN ${jsonType("message", key)}='array' THEN 1 END`])])],
1710
- ["data", `CASE WHEN ${deliveryOp} THEN ${this.dialect.jsonObject([["op", op]])} ELSE ${dataExpr} END`],
1711
- ["details", detailsExpr],
1712
- ["usage", j("usage")],
1713
- ["protectedReconciliation", j("protectedReconciliation")],
1714
- ["snapshot", `CASE WHEN ${jsonType("snapshot")} = 'object' THEN '{}' ELSE NULL END`],
1715
- ["restore", `CASE WHEN ${jsonType("restore")} = 'object' THEN 1 END`],
1716
- ["unrestored", `CASE WHEN ${jsonType("unrestored")} = 'object' THEN 1 END`],
1717
- ["compactionDetails", j("details", "strategy")],
1718
- ["toolCalls", `CASE WHEN ${j("message", "role")} = 'assistant' AND ${jsonType("message", "content")} = 'array' THEN
1719
- (SELECT count(*) FROM ${toolBlocks}
1720
- WHERE ${toolType} = 'toolCall') ELSE 0 END`]
1721
- ];
1722
- const select = columns.map(([key, expr]) => `${expr} AS ${this.dialect.identifier(`resume_${key.toLowerCase()}`)}`).join(", ");
1723
- const upgrade = requested === void 0 && limit === Number(row.last_seq) && isUpgradableSessionResumeIndex(state.resume, limit) ? sessionResumeUpgrade(state.resume) : void 0;
1724
- const list = (values) => values.map((value) => `'${value.replaceAll("'", "''")}'`).join(",");
1725
- const source = `chunks > 0 OR ${j("type")} IN (${list(RESUME_UPGRADE_SOURCES.types)})
1726
- OR (${j("type")} = 'message' AND ${j("message", "role")} = 'system')
1727
- OR (${j("type")} = 'custom' AND (${j("customType")} IN (${list(RESUME_UPGRADE_SOURCES.customTypes)})
1728
- OR ${j("customType")} NOT IN (${list(RESUME_UPGRADE_SOURCES.atomicCustomTypes)})))`;
1729
- const sources = !upgrade ? "" : sqlite ? ` AND (${source})` : ` AND EXISTS (SELECT 1 FROM (SELECT ${postgresJsonb("entry_json")} AS value OFFSET 0) AS parsed WHERE ${source})`;
1730
- const where = `WHERE session_id = ? AND seq > ? AND seq <= ?${sources}`;
1731
- const owner = "(SELECT id FROM bounds)";
1732
- const lo = "(SELECT lo FROM bounds)";
1733
- const hi = "(SELECT hi FROM bounds)";
1734
- const pageWhere = sqlite ? `WHERE session_id = ${owner} AND seq > ${lo} AND seq <= ${hi}${sources}` : where;
1735
- const page = `WITH ${sqlite ? "bounds(id,lo,hi) AS NOT MATERIALIZED (VALUES (?,?,?)), " : ""}page AS (
1736
- SELECT ${sqlite ? "" : "CASE WHEN chunks > 0 THEN session_id END AS session_id,"}seq,entry_id,chunks,entry_json FROM ${this.tables.entries}
1737
- ${pageWhere} ORDER BY seq LIMIT ${SESSION_RESUME_REBUILD.pageEntries}
1738
- )`;
1739
- const parts = (source) => `FROM ${this.tables.entryChunks} WHERE session_id = ${sqlite ? owner : `${source}.session_id`}
1740
- AND seq = ${source}.seq AND idx >= 0 AND idx < ${source}.chunks`;
1741
- const projection = sqlite ? `SELECT seq,entry_id,chunks,${select} FROM payloads ORDER BY seq` : `SELECT seq,entry_id,chunks,${select} FROM payloads
1742
- CROSS JOIN LATERAL (SELECT ${postgresJsonb("entry_json")} AS value OFFSET 0) AS parsed ORDER BY seq`;
1743
- const fits = sqlite ? "length(zeroblob(sum(length(data)))) IS NOT NULL" : "sum(octet_length(data)) < 1073741824";
1744
- const joined = sqlite ? `(SELECT group_concat(text, '') FROM (SELECT CAST(data AS TEXT) AS text ${parts("sized")} ORDER BY idx))` : `(SELECT convert_from(string_agg(data, ''::bytea ORDER BY idx), 'UTF8') ${parts("sized")})`;
1745
- const directPage = `${page}, sized AS ${sqlite ? "NOT MATERIALIZED" : "MATERIALIZED"} (
1746
- SELECT page.*, CASE WHEN chunks = 0 OR EXISTS (SELECT 1 ${parts("page")} GROUP BY seq
1747
- HAVING count(*) = page.chunks AND ${fits}) THEN 0 ELSE chunks END AS remaining FROM page${sqlite ? " LIMIT -1 OFFSET 0" : ""}
1748
- ), payloads AS MATERIALIZED (
1749
- SELECT seq,entry_id,CASE WHEN remaining = 0 THEN chunks ELSE -chunks END AS chunks,
1750
- CASE WHEN chunks > 0 AND remaining = 0 THEN ${joined} ELSE entry_json END AS entry_json
1751
- FROM sized
1752
- ) ${projection}`;
1753
- const keysPerEntry = 64;
1754
- const through = `${lo} + ${SESSION_RESUME_REBUILD.pageEntries}`;
1755
- const wide = sqlite && Number(row.last_seq) > 0 && Buffer.byteLength(sessionId) >= 512;
1756
- let inlinePage = wide && this.chunkRowids === void 0 ? `${page}, chunked AS MATERIALIZED (SELECT 1 FROM page WHERE chunks > 0 LIMIT 1),
1757
- payloads AS MATERIALIZED (SELECT seq,entry_id,chunks,entry_json FROM page WHERE NOT EXISTS (SELECT 1 FROM chunked)
1758
- UNION ALL SELECT 0,'',0,'{}' FROM chunked) ${projection}` : void 0;
1759
- const rowidPage = wide && this.chunkRowids !== false ? `${page},
1760
- keys AS MATERIALIZED (SELECT seq,idx,rowid AS rid FROM ${this.tables.entryChunks}
1761
- WHERE session_id = ${owner} AND seq > ${lo} AND seq <= ${hi} AND seq <= ${through} AND idx >= 0 AND idx < ${keysPerEntry}
1762
- ORDER BY seq,idx),
1763
- sized AS NOT MATERIALIZED (SELECT page.*, CASE WHEN chunks = 0 THEN NULL
1764
- WHEN seq <= ${through} AND chunks <= ${keysPerEntry} THEN (
1765
- SELECT CASE WHEN count(*) = page.chunks AND length(zeroblob(sum(length(c.data)))) IS NOT NULL
1766
- THEN CASE WHEN min(k.rid) > 0 AND min(k.rid - k.idx) = max(k.rid - k.idx) THEN min(k.rid) ELSE 0 END END
1767
- FROM keys k CROSS JOIN ${this.tables.entryChunks} c WHERE k.seq = page.seq AND k.idx < page.chunks AND c.rowid = k.rid)
1768
- WHEN EXISTS (SELECT 1 ${parts("page")} GROUP BY seq HAVING count(*) = page.chunks AND ${fits}) THEN -1 END AS first_rid
1769
- FROM page LIMIT -1 OFFSET 0),
1770
- payloads AS MATERIALIZED (SELECT seq,entry_id,CASE WHEN chunks > 0 AND first_rid IS NULL THEN -chunks ELSE chunks END AS chunks,
1771
- CASE WHEN first_rid IS NULL THEN entry_json WHEN first_rid < 0 THEN ${joined}
1772
- WHEN first_rid > 0 THEN (SELECT group_concat(text, '') FROM (SELECT CAST(data AS TEXT) AS text FROM ${this.tables.entryChunks}
1773
- WHERE rowid BETWEEN sized.first_rid AND sized.first_rid + (sized.chunks - 1) ORDER BY rowid))
1774
- ELSE (SELECT group_concat(CAST((SELECT data FROM ${this.tables.entryChunks} WHERE rowid = ids.rid) AS TEXT), '')
1775
- FROM (SELECT rid FROM keys k WHERE k.seq = sized.seq AND k.idx < sized.chunks ORDER BY k.idx LIMIT -1 OFFSET 0) ids)
1776
- END AS entry_json FROM sized)
1777
- ${projection}` : directPage;
1778
- const stubPage = `${page}, payloads AS (SELECT seq,entry_id,-chunks AS chunks,entry_json FROM page) ${projection}`;
1779
- let topology = currentIndex && requested !== void 0 ? branchRanges(currentIndex, requested) : void 0;
1780
- for (let pass = topology === void 0 ? 0 : 1; pass < 2; pass++) {
1781
- for (let after = 0; after < limit;) {
1782
- const args = [
1783
- sessionId,
1784
- after,
1785
- limit
1786
- ];
1787
- let rows;
1788
- try {
1789
- rows = await this.database.all(inlinePage ?? (this.chunkRowids ? rowidPage : directPage), ...args);
1790
- if (inlinePage && Number(rows[0]?.seq) === 0) {
1791
- inlinePage = void 0;
1792
- try {
1793
- this.chunkRowids = await this.database.get(`SELECT 1 WHERE NOT EXISTS (SELECT 1 FROM pragma_index_xinfo(?))
1794
- AND NOT EXISTS (SELECT 1 FROM pragma_table_xinfo(?) WHERE name = 'rowid' COLLATE NOCASE)`, this.tables.entryChunks, this.tables.entryChunks) !== void 0;
1795
- } catch {}
1796
- continue;
1797
- }
1798
- } catch (error) {
1799
- if (!(error instanceof Error && "code" in error && error.code === "payload-too-large")) throw error;
1800
- if (!await this.database.get(`SELECT 1 FROM ${this.tables.entryChunks}
1801
- WHERE session_id = ? AND seq IN (SELECT seq FROM ${this.tables.entries} ${where}
1802
- ORDER BY seq LIMIT ${SESSION_RESUME_REBUILD.pageEntries}) LIMIT 1`, sessionId, ...args).catch(() => void 0)) throw error;
1803
- rows = await this.database.all(stubPage, ...args);
1804
- }
1805
- if (rows.length === 0) break;
1806
- const batch = [];
1807
- let toolCalls = 0;
1808
- for (const entry of rows) {
1809
- const chunks = Number(entry.chunks);
1810
- let projected = entry;
1811
- if (chunks < 0) try {
1812
- const { chunkedResumeProjection } = await import("../core/storage/session/chunked-resume-projection.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
1813
- projected = await chunkedResumeProjection(entry, this.dialect.name === "postgres", () => this.entryChunks(sessionId, Number(entry.seq), -chunks, row.revision));
1814
- } catch (error) {
1815
- if ((await this.database.get(`SELECT revision FROM ${this.tables.sessions} WHERE id = ?`, sessionId))?.revision !== row.revision) continue attempts;
1816
- throw error;
1817
- }
1818
- const parsed = { id: entry.entry_id };
1819
- const decode = (value) => typeof value === "string" && (value.startsWith("{") || value.startsWith("[")) ? JSON.parse(value) : value;
1820
- for (const [key] of columns) {
1821
- const value = projected[`resume_${key.toLowerCase()}`];
1822
- parsed[key] = [
1823
- "dataFields",
1824
- "message",
1825
- "data",
1826
- "details",
1827
- "usage",
1828
- "snapshot",
1829
- "protectedReconciliation"
1830
- ].includes(key) ? decode(value) : value;
1831
- }
1832
- const message = parsed.message;
1833
- if (message && typeof message === "object") {
1834
- message.usage = decode(message.usage);
1835
- if (parsed.type === "message" && message.role === "assistant") toolCalls += Number(parsed.toolCalls ?? 0);
1836
- }
1837
- if (parsed.snapshot === null) delete parsed.snapshot;
1838
- if (parsed.type === "compaction") parsed.details = { strategy: parsed.compactionDetails };
1839
- if (parsed.type === "custom") {
1840
- const data = parsed.data;
1841
- const keys = parsed.dataFields ?? [];
1842
- for (const key of Object.keys(data)) if (!keys.includes(key)) delete data[key];
1843
- for (const key of keys) if (!(key in data)) data[key] = null;
1844
- }
1845
- for (const key of ["data", "details"]) {
1846
- const data = parsed[key];
1847
- if (data && typeof data === "object") {
1848
- data.message = decode(data.message);
1849
- data.owner = decode(data.owner);
1850
- data.tasks = decode(data.tasks);
1851
- for (const field of [
1852
- "groups",
1853
- "queries",
1854
- "urls",
1855
- "messageIds",
1856
- "askIds"
1857
- ]) if (field in data) data[field] = decode(data[field]);
1858
- if (data.timestamp !== null && data.timestamp !== void 0 && typeof data.timestamp === "string") data.timestamp = Number(data.timestamp);
1859
- if (parsed.type === "custom" && parsed.customType === "subagent-child") {
1860
- if (data.version !== null && data.version !== void 0) data.version = Number(data.version);
1861
- if (data.index !== null && data.index !== void 0) data.index = Number(data.index);
1862
- }
1863
- const message = data.message;
1864
- if (message?.expectsReply === 1 || message?.expectsReply === "true") message.expectsReply = true;
1865
- if (data.historyOnly === 1 || data.historyOnly === "true") data.historyOnly = true;
1866
- }
1867
- }
1868
- if (upgrade) upgrade.add(parsed, Number(entry.seq));
1869
- else batch.push(parsed);
1870
- }
1871
- if (upgrade) {
1872
- after = Number(rows.at(-1).seq);
1873
- if (after < limit) await yieldTurn();
1874
- continue;
1875
- }
1876
- const old = index ?? foldSessionResume(void 0, []);
1877
- const seqs = /* @__PURE__ */ new Map();
1878
- for (const id of foreignResumeIds(old, batch)) {
1879
- const seq = await this.seqOfEntry(this.database, sessionId, id);
1880
- if (seq !== void 0) seqs.set(id, seq);
1881
- }
1882
- index = foldSessionResume(index, batch, (id) => seqs.get(id), (seq) => topology === void 0 || topology.some(([a, b]) => seq >= a && seq <= b));
1883
- if (toolCalls > 0) index = {
1884
- ...index,
1885
- totals: {
1886
- ...index.totals,
1887
- toolCalls: index.totals.toolCalls + toolCalls
1888
- }
1889
- };
1890
- after = Number(rows.at(-1).seq);
1891
- if (after < Number(row.last_seq)) await yieldTurn();
1892
- }
1893
- if (pass !== 0 || !index || index.jumps.length === 0 && (requested === void 0 || requested === index.leafSeq)) break;
1894
- topology = branchRanges(index, requested ?? index.leafSeq);
1895
- index = void 0;
1896
- }
1897
- if (upgrade) index = upgrade.finish();
1898
- index = {
1899
- ...index ?? foldSessionResume(void 0, []),
1900
- epoch: state.epoch ?? row.revision
1901
- };
1902
- const current = await this.database.get(`SELECT revision,last_seq FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
1903
- if (current?.revision !== row.revision || Number(current.last_seq) !== Number(row.last_seq)) continue;
1904
- if (requested !== void 0) return {
1905
- index: {
1906
- ...index,
1907
- leafSeq: requested
1908
- },
1909
- revision: row.revision
1910
- };
1911
- this.resumeIndexes.set(sessionId, {
1912
- revision: row.revision,
1913
- index
1914
- });
1915
- while (this.resumeIndexes.size > 16) this.resumeIndexes.delete(this.resumeIndexes.keys().next().value);
1916
- await this.database.run(`UPDATE ${this.tables.sessions} SET summary_state = ? WHERE id = ? AND revision = ? AND last_seq = ?`, JSON.stringify({
1917
- ...state,
1918
- ...windowFields(state, index, index.seq, index.epoch),
1919
- epoch: index.epoch
1920
- }), sessionId, row.revision, row.last_seq).catch(() => void 0);
1921
- this.generations.delete(sessionId);
1922
- return {
1923
- index,
1924
- revision: row.revision
1925
- };
1926
- }
1927
- throw new SessionConflictError(sessionId, 0, 0);
1928
- }
1929
- async readTail(sessionId, fromSeq) {
1930
- this.assertOpen();
1931
- validateSessionText("sessionId", sessionId);
1932
- await this.prepareResume(sessionId);
1933
- const start = Math.max(1, fromSeq);
1934
- const { tail } = await this.transaction(async (tx) => {
1935
- const source = await this.resumeSource(tx, sessionId);
1936
- const stateSeqs = stateSeqsBefore(source.index, start);
1937
- if (hasHistoryLoadObserver()) announceHistoryLoad(stateSeqs.length + Math.max(0, source.index.seq - start + 1));
1938
- const state = await this.readSeqs(tx, sessionId, stateSeqs);
1939
- const entries = (await this.readRows(tx, sessionId, "seq >= ?", [start])).map(({ entry }) => entry);
1940
- return {
1941
- tail: sessionTailFrom(source.index, source.header, start, state, entries),
1942
- source
1943
- };
1944
- }, SESSION_TRANSACTION);
1945
- return tail;
1946
- }
1947
- async readRange(sessionId, startSeq, endSeq, expectedEpoch) {
1948
- this.assertOpen();
1949
- validateSessionText("sessionId", sessionId);
1950
- const start = Math.max(1, startSeq);
1951
- return this.transaction(async (tx) => {
1952
- const head = await this.historyHead(tx, sessionId);
1953
- if (expectedEpoch !== void 0 && expectedEpoch !== head.epoch) throw new SessionConflictError(sessionId, endSeq, head.lastSeq);
1954
- const entries = endSeq < start ? [] : await this.readRows(tx, sessionId, "seq >= ? AND seq <= ?", [start, endSeq]);
1955
- return {
1956
- startSeq: start,
1957
- entries: entries.map(({ entry }) => entry),
1958
- seqs: entries.map(({ seq }) => seq),
1959
- ...head
1960
- };
1961
- }, SESSION_TRANSACTION);
1962
- }
1963
- async historyHead(tx, sessionId, readOnly = false) {
1964
- const generation = this.generation(sessionId);
1965
- const row = await tx.get(`SELECT last_seq, revision, ${generation.sql} AS epoch FROM ${this.tables.sessions} WHERE id = ?${readOnly ? "" : this.dialect.lockClause("share")}`, ...generation.params, sessionId);
1966
- if (!row) throw new SessionNotFoundError(sessionId);
1967
- this.noteGeneration(sessionId, row.revision, Number(row.last_seq), row.epoch);
1968
- return {
1969
- lastSeq: Number(row.last_seq),
1970
- epoch: row.epoch
1971
- };
1972
- }
1973
- /** Size at most one page and return only fitting bodies, in the same snapshot as the header. The first
1974
- * oversized row is a chunk reference; its full inline value never crosses the driver boundary. */
1975
- async historyPacket(tx, sessionId, epoch, from, through, backward) {
1976
- const edge = backward ? through : from;
1977
- const rows = await tx.all(`WITH sizes AS MATERIALIZED (
1978
- SELECT e.seq, e.chunks, CASE WHEN e.chunks = 0 THEN ${this.entryByteLength("e.entry_json")} ELSE (e.chunks - 1) * ? +
1979
- (SELECT length(c.data) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx = e.chunks - 1) END AS bytes
1980
- FROM ${this.tables.entries} e WHERE e.session_id = ? AND e.seq BETWEEN ? AND ?
1981
- ), sized_page AS (
1982
- SELECT seq, chunks, bytes, sum(bytes) OVER (ORDER BY seq ${backward ? "DESC" : "ASC"}) AS cumulative FROM sizes
1983
- ) SELECT p.seq, p.chunks, p.bytes, CASE WHEN p.chunks = 0 AND p.bytes <= ? THEN e.entry_json END AS body
1984
- FROM sized_page p JOIN ${this.tables.entries} e ON e.session_id = ? AND e.seq = p.seq
1985
- WHERE p.bytes IS NULL OR p.cumulative <= ? OR p.seq = ? ORDER BY p.seq`, SESSION_ENTRY_CHUNK_BYTES, sessionId, from, through, SESSION_HISTORY_PAGE_BYTES, sessionId, SESSION_HISTORY_PAGE_BYTES, edge);
1986
- const items = [];
1987
- for (const row of rows) {
1988
- const seq = Number(row.seq);
1989
- const bytes = Number(row.bytes);
1990
- if (row.bytes === null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing final chunk of session entry ${seq}`));
1991
- if (bytes > 1048576) items.push({
1992
- kind: "oversized",
1993
- sessionId,
1994
- epoch,
1995
- seq,
1996
- bytes
1997
- });
1998
- else items.push({
1999
- seq,
2000
- entry: JSON.parse(row.body ?? await this.readEntryChunks(tx, sessionId, seq, Number(row.chunks)))
2001
- });
2002
- }
2003
- return items;
2004
- }
2005
- async readChildDisplayCut(sessionId, launch) {
2006
- const { childDisplayCut } = await import("../core/storage/session/card-view.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
2007
- const { index } = await this.prepareResume(sessionId);
2008
- if (typeof launch.launchLeafId !== "string") return childDisplayCut(index, launch);
2009
- return this.transaction(async (tx) => {
2010
- const head = await this.historyHead(tx, sessionId, true);
2011
- if (head.epoch !== index.epoch || head.lastSeq < index.seq) throw new SessionConflictError(sessionId, index.seq, head.lastSeq);
2012
- const row = await tx.get(`SELECT seq FROM ${this.tables.entries} WHERE session_id=? AND entry_id=? AND seq<=? ORDER BY seq DESC LIMIT 1`, sessionId, launch.launchLeafId, index.seq);
2013
- return childDisplayCut(index, launch, row === void 0 ? void 0 : Number(row.seq));
2014
- }, {
2015
- ...SESSION_TRANSACTION,
2016
- readOnly: true
2017
- });
2018
- }
2019
- /**
2020
- * A column expression of a sessions row's generation, `COALESCE(epoch, resume.epoch, revision)` of its summary state,
2021
- * that parses that state only when the row's revision or watermark is not the one this store last saw it at: every
2022
- * write gives the row a new revision, so the generation it held then still stands. A long session's summary state is
2023
- * hundreds of kilobytes, which a server would otherwise parse for every page and chunk an export reads (#5571).
2024
- */
2025
- generation(sessionId) {
2026
- const known = this.generations.get(sessionId);
2027
- return {
2028
- sql: `CASE WHEN revision = ? AND last_seq = ? THEN ? ELSE COALESCE(${this.dialect.jsonText("summary_state", "epoch")}, ${this.dialect.jsonText("summary_state", "resume", "epoch")}, revision) END`,
2029
- params: [
2030
- known?.revision ?? null,
2031
- known?.lastSeq ?? null,
2032
- known?.epoch ?? null
2033
- ]
2034
- };
2035
- }
2036
- noteGeneration(sessionId, revision, lastSeq, epoch) {
2037
- this.generations.delete(sessionId);
2038
- this.generations.set(sessionId, {
2039
- revision,
2040
- lastSeq,
2041
- epoch
2042
- });
2043
- while (this.generations.size > 16) this.generations.delete(this.generations.keys().next().value);
2044
- }
2045
- async readBranchSpan(sessionId, cut) {
2046
- this.assertOpen();
2047
- validateSessionText("sessionId", sessionId);
2048
- const { index } = await this.prepareResume(sessionId);
2049
- return transcriptBranchSpan(sessionId, index, cut);
2050
- }
2051
- /** Send only tree headings over the database connection. A chunk stub has no message role or
2052
- * timestamp; its caller streams those fields instead of joining or decoding the stored body. */
2053
- async readTreeOutline(sessionId, fromSeq, toSeq, epoch) {
2054
- this.assertOpen();
2055
- return this.transaction(async (tx) => {
2056
- const head = await this.historyHead(tx, sessionId);
2057
- if (epoch !== void 0 && head.epoch !== epoch || head.lastSeq < toSeq) throw new SessionConflictError(sessionId, toSeq, head.lastSeq);
2058
- const sqlite = this.dialect.name === "sqlite";
2059
- const j = (...path) => this.dialect.jsonText("entry_json", ...path);
2060
- const role = j("message", "role");
2061
- const content = j("message", "content");
2062
- const ctype = this.dialect.jsonType("entry_json", "message", "content");
2063
- const whites = " \n\v\f\r \xA0            \u2028\u2029   ";
2064
- const trim = sqlite ? "trim" : "btrim";
2065
- const hasText = sqlite ? `EXISTS(SELECT 1 FROM json_each(entry_json,'$.message.content') b WHERE CASE WHEN b.type='object' AND json_extract(b.value,'$.type')='text' THEN length(trim(json_extract(b.value,'$.text'),?))>0 END)` : `EXISTS(SELECT 1 FROM jsonb_array_elements((${content})::jsonb) b WHERE b->>'type'='text' AND length(btrim(b->>'text',?))>0)`;
2066
- const callIds = sqlite ? `(SELECT json_group_array(json_extract(b.value,'$.id')) FROM json_each(entry_json,'$.message.content') b WHERE CASE WHEN b.type='object' THEN json_extract(b.value,'$.type')='toolCall' AND json_type(b.value,'$.id')='text' END)` : `(SELECT json_agg(b->>'id')::text FROM jsonb_array_elements((${content})::jsonb) b WHERE b->>'type'='toolCall' AND jsonb_typeof(b->'id')='string')`;
2067
- return (await tx.all(`SELECT CASE WHEN ${role}='assistant' AND ${ctype}='array' THEN ${callIds} END calls,seq,entry_id,chunks,${j("type")} kind,${j("parentId")} parent,${j("timestamp")} stamp,${role} role,
2068
- CASE WHEN ${role}='assistant' AND COALESCE(${j("message", "stopReason")},'') IN ('','toolUse','stop') AND CASE WHEN ${ctype}='array' THEN NOT ${hasText} WHEN ${ctype}='${sqlite ? "text" : "string"}' THEN length(${trim}(${content},?))=0 ELSE TRUE END THEN 1 ELSE 0 END hidden,
2069
- CASE WHEN ${j("type")}='custom' AND ${j("customType")}='atomic.leaf' THEN 1 ELSE 0 END leaf_move,
2070
- CASE WHEN ${j("type")}='custom' AND ${j("customType")}='subagent-child' THEN 1 ELSE 0 END child_record,
2071
- CASE WHEN ${j("type")}='label' THEN ${j("targetId")} END target,CASE WHEN ${j("type")}='label' THEN substr(${j("label")},1,128) END label
2072
- FROM ${this.tables.entries} WHERE session_id=? AND seq BETWEEN ? AND ? ORDER BY seq LIMIT ?`, whites, whites, sessionId, fromSeq, toSeq, 64)).map((row) => Number(row.chunks) > 0 ? {
2073
- seq: Number(row.seq),
2074
- streamed: true
2075
- } : {
2076
- seq: Number(row.seq),
2077
- id: String(row.entry_id),
2078
- parentId: row.parent === null ? null : String(row.parent),
2079
- timestamp: String(row.stamp),
2080
- type: row.kind,
2081
- ...typeof row.role === "string" ? { role: row.role } : {},
2082
- ...Number(row.hidden) === 1 ? { hideAssistant: true } : {},
2083
- ...typeof row.calls === "string" && row.calls !== "[]" ? { callIds: JSON.parse(row.calls) } : {},
2084
- ...Number(row.leaf_move) === 1 ? { leafMove: true } : {},
2085
- ...Number(row.child_record) === 1 ? { childRecord: true } : {},
2086
- ...typeof row.target === "string" ? {
2087
- labelTarget: row.target,
2088
- label: typeof row.label === "string" ? row.label : void 0
2089
- } : {}
2090
- });
2091
- }, SESSION_TRANSACTION);
2092
- }
2093
- /** Sparse page of child state in one fenced read, bounded by the same byte and row caps as a transcript page. */
2094
- async readSelectedPage(sessionId, seqs, epoch, options = {}) {
2095
- this.assertOpen();
2096
- const limit = entrySizeLimit(options.limit);
2097
- const wanted = options.backward ? seqs.slice(-limit) : seqs.slice(0, limit);
2098
- if (!wanted.length) return { items: [] };
2099
- return this.transaction(async (tx) => {
2100
- const head = await this.historyHead(tx, sessionId);
2101
- if (head.epoch !== epoch || head.lastSeq < wanted.at(-1)) throw new SessionConflictError(sessionId, wanted.at(-1), head.lastSeq);
2102
- const tail = `(SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id=e.session_id AND c.seq=e.seq AND c.idx=e.chunks-1)`;
2103
- const rows = await tx.all(`SELECT seq,CASE WHEN chunks=0 THEN ${this.entryByteLength("entry_json")} ELSE (chunks-1)*?+${tail} END bytes FROM ${this.tables.entries} e WHERE session_id=? AND seq IN (${wanted.map(() => "?").join(",")}) ORDER BY seq`, SESSION_ENTRY_CHUNK_BYTES, sessionId, ...wanted);
2104
- const sizes = new Map(rows.map((row) => [Number(row.seq), row.bytes == null ? void 0 : Number(row.bytes)]));
2105
- const plan = selectedPagePlan(sessionId, wanted, head.lastSeq, (seq) => {
2106
- const bytes = sizes.get(seq);
2107
- if (bytes === void 0) throw new SessionConflictError(sessionId, wanted.at(-1), head.lastSeq);
2108
- return bytes;
2109
- }, options.backward);
2110
- if ("oversized" in plan) return { items: [{
2111
- kind: "oversized",
2112
- sessionId,
2113
- epoch,
2114
- ...plan.oversized
2115
- }] };
2116
- return { items: await this.readSeqs(tx, sessionId, plan.seqs) };
2117
- }, SESSION_TRANSACTION);
2118
- }
2119
- /**
2120
- * The snapshot entries of the session's resume index, read with the index and nothing else: no entry is read, and an
2121
- * index that does not cover the session as it stands is not rebuilt here (#5554).
2122
- */
2123
- async readSnapshotCut(sessionId, options = {}) {
2124
- this.assertOpen();
2125
- validateSessionText("sessionId", sessionId);
2126
- const row = await this.database.get(`SELECT last_seq,summary_state,revision FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
2127
- if (!row) throw new SessionNotFoundError(sessionId);
2128
- const lastSeq = Number(row.last_seq);
2129
- const remembered = this.resumeIndexes.get(sessionId);
2130
- const index = windowIndex(JSON.parse(row.summary_state), lastSeq) ?? (remembered?.revision === row.revision && isSessionResumeIndex(remembered.index, lastSeq) ? remembered.index : void 0);
2131
- if (index === void 0 || options.leafSeq !== void 0 && options.leafSeq > lastSeq) return void 0;
2132
- return snapshotCutOf(index, options.leafSeq);
2133
- }
2134
- async readEntrySizes(sessionId, startSeq, endSeq, limit) {
2135
- this.assertOpen();
2136
- validateSessionText("sessionId", sessionId);
2137
- return this.transaction(async (tx) => {
2138
- const head = await this.historyHead(tx, sessionId);
2139
- const lastChunk = `(SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx = e.chunks - 1)`;
2140
- const rows = await tx.all(`SELECT seq, CASE WHEN chunks = 0 THEN ${this.entryByteLength("entry_json")} ELSE (chunks - 1) * ? + ${lastChunk} END AS bytes FROM ${this.tables.entries} e WHERE session_id = ? AND seq BETWEEN ? AND ? ORDER BY seq LIMIT ?`, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, endSeq, entrySizeLimit(limit));
2141
- return {
2142
- ...head,
2143
- sizes: rows.map((row) => {
2144
- if (row.bytes === null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing final chunk of session entry ${row.seq}`));
2145
- return {
2146
- seq: Number(row.seq),
2147
- bytes: Number(row.bytes)
2148
- };
2149
- })
2150
- };
2151
- }, SESSION_TRANSACTION);
2152
- }
2153
- /**
2154
- * One statement, so one snapshot without a transaction: the session row (its generation, watermark and schema version)
2155
- * sorts first as sequence 0, then the page's entries with their sizes. The page ends at the last of up to `limit`
2156
- * entries whose running size fits a page, or is the first entry alone, whose JSON is left out when it is larger. Each
2157
- * page of a scan is then one round trip to a database server (#5571). With `select`, only the entries `selected` keeps
2158
- * are sized and read; the session row then also says how many were sized and the last of them, so the page knows how
2159
- * far it accounts for the range.
2160
- */
2161
- async readScanPage(sessionId, startSeq, endSeq, epoch, limit, options = {}) {
2162
- this.assertOpen();
2163
- validateSessionText("sessionId", sessionId);
2164
- const { select, trailingReference, referencePrefix } = options;
2165
- const generation = this.generation(sessionId);
2166
- const count = entrySizeLimit(limit);
2167
- const bytes = (row) => `CASE WHEN ${row}.chunks = 0 THEN ${this.entryByteLength(`${row}.entry_json`)} ELSE (${row}.chunks - 1) * ? + (SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id = ${row}.session_id AND c.seq = ${row}.seq AND c.idx = ${row}.chunks - 1) END`;
2168
- const head = `SELECT 0 AS seq, NULL AS bytes, NULL AS chunks, header_json AS entry_json, last_seq, revision,
2169
- ${generation.sql} AS epoch, (SELECT schema_version FROM ${this.tables.meta} LIMIT 1) AS schema_version`;
2170
- const filter = (row) => select ? ` AND ${this.selected(row, select)}` : "";
2171
- const selectParams = select === void 0 ? [] : this.selectedParams(select);
2172
- const json = this.dialect.name === "sqlite" ? "CAST(entry_json AS BLOB)" : "convert_to(entry_json, 'UTF8')";
2173
- const prefixLength = Math.max(1, Math.trunc(referencePrefix ?? 1) || 1);
2174
- const rows = !select && !trailingReference && referencePrefix === void 0 ? await this.database.all(`${head} FROM ${this.tables.sessions} WHERE id = ?
2175
- UNION ALL
2176
- SELECT seq, bytes, chunks, CASE WHEN bytes <= ? AND chunks = 0 THEN entry_json END, NULL, NULL, NULL, NULL FROM (
2177
- SELECT e.seq, e.chunks, e.entry_json, ${bytes("e")} AS bytes FROM ${this.tables.entries} e
2178
- -- The cut bounds the range itself, so the read stops there, however far the range goes.
2179
- WHERE e.session_id = ? AND e.seq BETWEEN ? AND (
2180
- SELECT COALESCE(max(CASE WHEN total <= ? THEN seq END), min(seq)) FROM (
2181
- SELECT seq, sum(bytes) OVER (ORDER BY seq) AS total FROM (
2182
- SELECT s.seq, ${bytes("s")} AS bytes FROM ${this.tables.entries} s
2183
- WHERE s.session_id = ? AND s.seq BETWEEN ? AND ? ORDER BY s.seq LIMIT ?
2184
- ) AS sized
2185
- ) AS run
2186
- )
2187
- ) AS page
2188
- ORDER BY seq`, ...generation.params, sessionId, SESSION_HISTORY_PAGE_BYTES, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, SESSION_HISTORY_PAGE_BYTES, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, endSeq, count) : await this.database.all(`WITH sized AS MATERIALIZED (
2189
- SELECT s.seq, ${bytes("s")} AS bytes FROM ${this.tables.entries} s
2190
- WHERE s.session_id = ? AND s.seq BETWEEN ? AND ?${filter("s")} ORDER BY s.seq LIMIT ?
2191
- ), cut AS (
2192
- SELECT COALESCE(
2193
- (SELECT max(seq) FROM (SELECT seq, sum(bytes) OVER (ORDER BY seq) AS total FROM sized) AS run WHERE total <= ?),
2194
- (SELECT min(seq) FROM sized)
2195
- ) AS seq
2196
- ), tail AS (
2197
- SELECT seq FROM sized
2198
- WHERE ${trailingReference ? "" : "1 = 0 AND "}seq = (SELECT min(seq) FROM sized WHERE seq > (SELECT seq FROM cut))
2199
- AND bytes > ? AND (SELECT bytes FROM sized WHERE seq = (SELECT seq FROM cut)) <= ?
2200
- )
2201
- ${head}, (SELECT count(*) FROM sized) AS sized, (SELECT max(seq) FROM sized) AS sized_last, NULL AS prefix
2202
- FROM ${this.tables.sessions} WHERE id = ?
2203
- UNION ALL
2204
- SELECT seq, bytes, chunks, CASE WHEN bytes <= ? AND chunks = 0 THEN entry_json END, NULL, NULL, NULL, NULL, NULL, NULL,
2205
- ${referencePrefix === void 0 ? "NULL" : `CASE WHEN bytes > ? THEN CASE WHEN chunks > 0
2206
- THEN (SELECT substr(c.data, 1, CAST(? AS INTEGER)) FROM ${this.tables.entryChunks} c WHERE c.session_id = ? AND c.seq = page.seq AND c.idx = 0)
2207
- ELSE substr(${json}, 1, CAST(? AS INTEGER)) END END`}
2208
- FROM (
2209
- SELECT e.seq, e.chunks, e.entry_json, ${bytes("e")} AS bytes FROM ${this.tables.entries} e
2210
- WHERE e.session_id = ? AND e.seq BETWEEN ? AND (SELECT seq FROM cut)${filter("e")}
2211
- UNION ALL
2212
- SELECT e.seq, e.chunks, e.entry_json, ${bytes("e")} AS bytes FROM ${this.tables.entries} e
2213
- WHERE e.session_id = ? AND e.seq = (SELECT seq FROM tail)
2214
- ) AS page
2215
- ORDER BY seq`, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, endSeq, ...selectParams, count, SESSION_HISTORY_PAGE_BYTES, SESSION_HISTORY_PAGE_BYTES, SESSION_HISTORY_PAGE_BYTES, ...generation.params, sessionId, SESSION_HISTORY_PAGE_BYTES, ...referencePrefix === void 0 ? [] : [
2216
- SESSION_HISTORY_PAGE_BYTES,
2217
- prefixLength,
2218
- sessionId,
2219
- prefixLength
2220
- ], SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, ...selectParams, SESSION_ENTRY_CHUNK_BYTES, sessionId);
2221
- const first = rows[0];
2222
- if (first === void 0 || Number(first.seq) !== 0) throw new SessionNotFoundError(sessionId);
2223
- assertStorageSchemaVersion("sessions", first.schema_version, 2, SESSION_SCHEMA_VERSION_UNCHUNKED);
2224
- const lastSeq = Number(first.last_seq);
2225
- this.noteGeneration(sessionId, first.revision, lastSeq, first.epoch);
2226
- if (epoch !== void 0 && first.epoch !== epoch) throw new SessionConflictError(sessionId, endSeq, lastSeq);
2227
- const read = {
2228
- header: JSON.parse(first.entry_json),
2229
- epoch: first.epoch,
2230
- lastSeq
2231
- };
2232
- const page = rows.slice(1);
2233
- for (const row of page) if (row.bytes === null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing final chunk of session entry ${row.seq}`));
2234
- const top = page.at(-1);
2235
- if (top === void 0) return {
2236
- ...read,
2237
- throughSeq: endSeq,
2238
- items: []
2239
- };
2240
- const throughSeq = first.sized !== void 0 && Number(first.sized) < count && Number(first.sized_last) <= Number(top.seq) ? endSeq : Number(top.seq);
2241
- const prefixes = /* @__PURE__ */ new Map();
2242
- const reference = (row) => {
2243
- if (row.prefix) prefixes.set(Number(row.seq), row.prefix);
2244
- return {
2245
- kind: "oversized",
2246
- sessionId,
2247
- epoch: read.epoch,
2248
- seq: Number(row.seq),
2249
- bytes: Number(row.bytes)
2250
- };
2251
- };
2252
- const oversized = (row) => Number(row.bytes) > SESSION_HISTORY_PAGE_BYTES;
2253
- const run = page.filter((row) => !oversized(row));
2254
- const references = page.filter(oversized).map(reference);
2255
- const withPrefixes = {
2256
- ...read,
2257
- throughSeq,
2258
- ...prefixes.size ? { prefixes } : {}
2259
- };
2260
- if (!run.length) return {
2261
- ...withPrefixes,
2262
- items: references
2263
- };
2264
- if (run.some((row) => Number(row.chunks) > 0)) {
2265
- const range = await this.readRange(sessionId, Number(run[0].seq), Number(run.at(-1).seq), read.epoch);
2266
- const seqs = new Set(run.map((row) => Number(row.seq)));
2267
- return {
2268
- ...withPrefixes,
2269
- lastSeq: range.lastSeq,
2270
- items: [...range.entries.map((entry, i) => ({
2271
- seq: range.seqs[i],
2272
- entry
2273
- })).filter((item) => seqs.has(item.seq)), ...references]
2274
- };
2275
- }
2276
- return {
2277
- ...withPrefixes,
2278
- items: [...run.map((row) => ({
2279
- seq: Number(row.seq),
2280
- entry: JSON.parse(row.entry_json)
2281
- })), ...references]
2282
- };
2283
- }
2284
- /**
2285
- * A condition on an entries row that holds for every entry `select` selects (and more): an entry larger than a page;
2286
- * on SQLite and libSQL, a message whose stored type and role say it is a tool result, or an assistant message with a
2287
- * tool call named other than `exceptCalls`, and any row that is not valid JSON; on Postgres, which would parse each
2288
- * row's JSON to read those, any row whose JSON holds a tool call block's `"toolCall"` or a result's `"toolResult"`,
2289
- * which `JSON.stringify`, the only writer of a row, always writes as such (it never escapes a letter).
2290
- */
2291
- selected(row, select) {
2292
- const json = `${row}.entry_json`;
2293
- if (this.dialect.name !== "sqlite") return `(${row}.chunks > 0 OR ${this.dialect.contains(json, `'"toolCall"'`)} OR ${this.dialect.contains(json, `'"toolResult"'`)})`;
2294
- return `(${row}.chunks > 0 OR NOT json_valid(${json}) OR json_extract(${json}, '$.type') = 'message' AND (
2295
- json_extract(${json}, '$.message.role') = 'toolResult'
2296
- OR json_extract(${json}, '$.message.role') = 'assistant' AND EXISTS (
2297
- SELECT 1 FROM json_each(${json}, '$.message.content') b
2298
- WHERE b.type = 'object' AND json_extract(b.value, '$.type') = 'toolCall' AND (${select.exceptCalls.length ? `json_type(b.value, '$.name') IS NOT 'text' OR json_extract(b.value, '$.name') NOT IN (${select.exceptCalls.map(() => "?").join(", ")})` : "1"})
2299
- )
2300
- ))`;
2301
- }
2302
- selectedParams(select) {
2303
- return this.dialect.name === "sqlite" ? select.exceptCalls : [];
2304
- }
2305
- /**
2306
- * One statement, so one snapshot without a transaction: the session row's generation, watermark and schema version
2307
- * with the bytes, from the entry's own JSON or from the one stored chunk that holds `offset`.
2308
- */
2309
- async readEntryChunk(reference, offset, bytes = SESSION_HISTORY_CHUNK_BYTES) {
2310
- this.assertOpen();
2311
- const { sessionId, epoch, seq } = reference;
2312
- const length = Math.min(Math.max(1, Math.trunc(bytes) || 1), SESSION_HISTORY_PAGE_BYTES);
2313
- const generation = this.generation(sessionId);
2314
- const json = this.dialect.name === "sqlite" ? "CAST(e.entry_json AS BLOB)" : "convert_to(e.entry_json, 'UTF8')";
2315
- const row = await this.database.get(`SELECT s.last_seq, s.revision, ${generation.sql} AS epoch,
2316
- (SELECT schema_version FROM ${this.tables.meta} LIMIT 1) AS schema_version, e.chunks,
2317
- CASE WHEN e.chunks > 0
2318
- THEN (SELECT substr(c.data, CAST(? AS INTEGER), CAST(? AS INTEGER)) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx = ?)
2319
- ELSE substr(${json}, CAST(? AS INTEGER), CAST(? AS INTEGER)) END AS data
2320
- FROM ${this.tables.sessions} s LEFT JOIN ${this.tables.entries} e ON e.session_id = s.id AND e.seq = ?
2321
- WHERE s.id = ?`, ...generation.params, offset % SESSION_ENTRY_CHUNK_BYTES + 1, length, Math.floor(offset / SESSION_ENTRY_CHUNK_BYTES), offset + 1, length, seq, sessionId);
2322
- if (!row) throw new SessionNotFoundError(sessionId);
2323
- assertStorageSchemaVersion("sessions", row.schema_version, 2, SESSION_SCHEMA_VERSION_UNCHUNKED);
2324
- this.noteGeneration(sessionId, row.revision, Number(row.last_seq), row.epoch);
2325
- if (row.epoch !== epoch) throw new SessionConflictError(sessionId, seq, Number(row.last_seq));
2326
- if (row.chunks === null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing session entry ${seq}`));
2327
- if (row.data === null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing chunk of session entry ${seq}`));
2328
- return row.data;
2329
- }
2330
- async findEntrySeq(sessionId, entryId) {
2331
- this.assertOpen();
2332
- validateSessionText("sessionId", sessionId);
2333
- validateSessionText("entry.id", entryId);
2334
- if (!await this.readHeader(sessionId)) throw new SessionNotFoundError(sessionId);
2335
- return this.seqOfEntry(this.database, sessionId, entryId);
2336
- }
2337
- /**
2338
- * Earlier entries that may save the same task reference as each candidate (#5593), in one statement on the session
2339
- * links' entry-ID index: the statement reads each candidate's ID at its sequence itself, so no entry ID is bound or
2340
- * returned, and no entry body is read. `undefined` while that index is still being built.
2341
- */
2342
- async findTaskReferenceDuplicateCandidates(sessionId, query) {
2343
- this.assertOpen();
2344
- validateSessionText("sessionId", sessionId);
2345
- const { candidates, afterSeq, limit } = taskReferenceDuplicateQuery(query);
2346
- return this.transaction(async (tx) => {
2347
- const head = await this.historyHead(tx, sessionId);
2348
- if (head.epoch !== query.epoch || head.lastSeq < query.throughSeq) throw new SessionConflictError(sessionId, query.throughSeq, head.lastSeq);
2349
- if (candidates.length === 0) return { seqs: [] };
2350
- const t = snapshotIndexTables(this.prefix);
2351
- const links = t.sessionLinks;
2352
- /**
2353
- * For each candidate `c`, the links row `s` at its sequence and then, with `earlier`, the rows `e` before it
2354
- * under an ID, each found through an index, never by walking the session. Postgres plans a lateral subquery
2355
- * behind `OFFSET 0` once per row before it; SQLite keeps a `CROSS JOIN`'s order. `+e.seq` keeps either from
2356
- * reading the session's rows by sequence instead of by ID.
2357
- */
2358
- const rowsOf = (earlier) => {
2359
- const keys = [[
2360
- "s",
2361
- "entry_id",
2362
- "s.session_id = ? AND s.seq = c.seq"
2363
- ]];
2364
- if (earlier !== void 0) keys.push([
2365
- "e",
2366
- "seq",
2367
- `e.session_id = ? AND e.entry_id = ${earlier} AND +e.seq < c.seq AND +e.seq > ?`
2368
- ]);
2369
- if (this.dialect.name !== "postgres") return `c ${keys.map(([alias]) => `CROSS JOIN ${links} ${alias}`).join(" ")} WHERE ${keys.map(([, , key]) => key).join(" AND ")}`;
2370
- return `c ${keys.map(([alias, column, key]) => `CROSS JOIN LATERAL (SELECT ${alias}.${column} FROM ${links} ${alias} WHERE ${key} OFFSET 0) ${alias}`).join(" ")}`;
2371
- };
2372
- const other = `CASE WHEN c.idx >= 0 THEN s.entry_id || ':' || CAST(c.idx AS TEXT)
2373
- WHEN c.suffix > 0 AND c.suffix <= length(s.entry_id) AND substr(s.entry_id, length(s.entry_id) - c.suffix + 1, 1) = ':'
2374
- THEN substr(s.entry_id, 1, length(s.entry_id) - c.suffix) END`;
2375
- const values = candidates.map(() => `(CAST(? AS ${this.dialect.types.int}), CAST(? AS INTEGER), CAST(? AS INTEGER))`);
2376
- const rows = await tx.all(`WITH c(seq, idx, suffix) AS (VALUES ${values.join(", ")}),
2377
- hits AS (SELECT e.seq AS seq FROM ${rowsOf("s.entry_id")} UNION SELECT e.seq FROM ${rowsOf(other)})
2378
- SELECT 0 AS kind, (SELECT CASE WHEN backfilled_through >= watermark THEN 1 ELSE 0 END FROM ${t.sources} WHERE source = 'session-entries') AS seq
2379
- UNION ALL SELECT 1, count(*) FROM ${rowsOf()}
2380
- UNION ALL SELECT 2, page.seq FROM (SELECT seq FROM hits ORDER BY seq LIMIT ?) page`, ...candidates.flat(), ...[
2381
- sessionId,
2382
- sessionId,
2383
- afterSeq,
2384
- sessionId,
2385
- sessionId,
2386
- afterSeq,
2387
- sessionId,
2388
- limit + 1
2389
- ]);
2390
- let indexed = false;
2391
- let found = 0;
2392
- const seqs = [];
2393
- for (const row of rows) if (Number(row.kind) === 0) indexed = Number(row.seq) === 1;
2394
- else if (Number(row.kind) === 1) found = Number(row.seq);
2395
- else seqs.push(Number(row.seq));
2396
- if (!indexed) return void 0;
2397
- if (found !== candidates.length) throw new SessionConflictError(sessionId, query.throughSeq, head.lastSeq);
2398
- seqs.sort((a, b) => a - b);
2399
- return seqs.length > limit ? {
2400
- seqs: seqs.slice(0, limit),
2401
- nextAfterSeq: seqs[limit - 1]
2402
- } : { seqs };
2403
- }, SESSION_TRANSACTION);
2404
- }
2405
- async readForkWindow(sessionId, entryId, options) {
2406
- this.assertOpen();
2407
- validateSessionText("sessionId", sessionId);
2408
- const { indexedForkWindow, forkMetadata, byteMetadata, locateFork } = await import("../core/storage/session/fork-window.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
2409
- return this.transaction(async (tx) => {
2410
- const snapshots = snapshotIndexTables(this.prefix);
2411
- const row = await tx.get(`SELECT header_json,last_seq,summary_state,revision,CASE WHEN EXISTS (SELECT 1 FROM ${snapshots.sources} WHERE source='session-entries' AND backfilled_through>=watermark) THEN (SELECT max(seq) FROM ${snapshots.sessionLinks} WHERE session_id=s.id AND entry_id=?) ELSE (SELECT max(seq) FROM ${this.tables.entries} WHERE session_id=s.id AND entry_id=?) END AS leaf_seq FROM ${this.tables.sessions} s WHERE s.id=?${this.dialect.lockClause("share")}`, entryId, entryId, sessionId);
2412
- if (!row) throw new SessionNotFoundError(sessionId);
2413
- const header = JSON.parse(row.header_json);
2414
- const state = JSON.parse(row.summary_state);
2415
- const count = Number(row.last_seq);
2416
- const cached = this.resumeIndexes.get(sessionId);
2417
- const ready = windowIndex(state, count) ?? (cached?.revision === row.revision ? cached.index : void 0);
2418
- const leaf = Number(row.leaf_seq);
2419
- if (!leaf) return void 0;
2420
- const metadata = async (seqs) => {
2421
- const result = [];
2422
- if (!seqs.length) return result;
2423
- const raw = this.dialect.name === "sqlite" ? "CAST(entry_json AS BLOB)" : "convert_to(entry_json,'UTF8')";
2424
- const size = this.dialect.textByteLength("entry_json");
2425
- const rows = await tx.all(`SELECT seq,chunks,${size} AS bytes,CASE WHEN chunks=0 AND ${size}<=512 THEN entry_json END AS body FROM ${this.tables.entries} WHERE session_id=? AND seq IN (${seqs.map(() => "?").join(",")}) ORDER BY seq`, sessionId, ...seqs);
2426
- for (const row of rows) {
2427
- const seq = Number(row.seq);
2428
- if (row.body !== null) result.push(forkMetadata(seq, JSON.parse(row.body)));
2429
- else if (Number(row.chunks) > 0) {
2430
- const { projectForkMetadata } = await import("../core/storage/session/chunked-resume-projection.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
2431
- result.push(await projectForkMetadata(seq, this.forkEntryChunks(tx, sessionId, seq, Number(row.chunks))));
2432
- } else result.push(await byteMetadata(seq, Number(row.bytes), async (offset, n) => {
2433
- const piece = await tx.get(`SELECT substr(${raw},?,?) AS part FROM ${this.tables.entries} WHERE session_id=? AND seq=?`, offset + 1, n, sessionId, seq);
2434
- if (!piece) throw new StorageError(`Session ${sessionId} entry ${seq} disappeared during its fork`);
2435
- return piece.part;
2436
- }));
2437
- }
2438
- return result;
2439
- };
2440
- const entries = this.tables.entries;
2441
- const j = (field) => this.dialect.jsonText("entry_json", field);
2442
- const selected = ready ? {
2443
- index: ready,
2444
- leaf,
2445
- extras: void 0
2446
- } : await locateFork({
2447
- ...foldSessionResume(void 0, []),
2448
- seq: count,
2449
- epoch: state.epoch ?? row.revision,
2450
- needsBranchRebuild: true
2451
- }, entryId, async (seqs) => {
2452
- const pg = this.dialect.name === "postgres";
2453
- const key = (...path) => pg ? this.dialect.jsonAt({
2454
- column: "entry_json",
2455
- element: "parsed"
2456
- }, ...path) : this.dialect.jsonText("entry_json", ...path);
2457
- const projection = this.dialect.jsonArray([
2458
- "entry_id",
2459
- key("parentId"),
2460
- key("type"),
2461
- key("customType"),
2462
- key("firstKeptEntryId"),
2463
- key("coveredThroughEntryId"),
2464
- key("details", "strategy"),
2465
- `CASE WHEN ${key("customType")} IN ('task-completion-intent','task-completion-ack') AND ${this.dialect.jsonAtIsText(pg ? {
2466
- column: "entry_json",
2467
- element: "parsed"
2468
- } : { column: "entry_json" }, "data", "completionId")} THEN ${key("data", "completionId")} END`,
2469
- key("message", "role")
2470
- ]);
2471
- const parsed = (await tx.all(`WITH projected AS MATERIALIZED (SELECT seq,chunks,CAST(${projection} AS TEXT) AS link FROM ${entries} ${pg ? `CROSS JOIN LATERAL (SELECT ${postgresJsonb("entry_json")} AS value OFFSET 0) AS parsed` : ""} WHERE session_id=? AND seq BETWEEN ? AND ?) SELECT seq,chunks,CASE WHEN ${this.dialect.textByteLength("link")}<=512 THEN link END AS link FROM projected ORDER BY seq`, sessionId, seqs[0], seqs.at(-1))).map((r) => ({
2472
- seq: Number(r.seq),
2473
- chunked: Number(r.chunks) > 0,
2474
- link: r.link === null ? void 0 : JSON.parse(r.link)
2475
- }));
2476
- const roles = /* @__PURE__ */ new Map();
2477
- const chunkedMessages = parsed.filter((r) => r.chunked && r.link?.[2] === "message").map((r) => r.seq);
2478
- if (chunkedMessages.length) {
2479
- const { messageRoleIn } = await import("../core/storage/session/chunked-resume-projection.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
2480
- for (let i = 0; i < chunkedMessages.length; i += SEQ_BATCH) {
2481
- const batch = chunkedMessages.slice(i, i + SEQ_BATCH);
2482
- const prefixes = await tx.all(`SELECT seq,substr(data,1,${FORK_ROLE_PREFIX_BYTES}) AS prefix FROM ${this.tables.entryChunks} WHERE session_id=? AND idx=0 AND seq IN (${batch.map(() => "?").join(",")})`, sessionId, ...batch);
2483
- for (const row of prefixes) roles.set(Number(row.seq), messageRoleIn(row.prefix));
2484
- }
2485
- }
2486
- const page = [];
2487
- for (const { seq, chunked, link } of parsed) {
2488
- const role = chunked ? roles.get(seq) : link?.[8];
2489
- if (!link || chunked && (link[2] === "custom" || link[2] === "compaction" || link[2] === "message" && role === void 0)) page.push(...await metadata([seq]));
2490
- else {
2491
- const [id, parentId, type, customType, first, covered, strategy, completionId] = link;
2492
- page.push({
2493
- seq,
2494
- id,
2495
- parentId,
2496
- type,
2497
- customType: customType ?? void 0,
2498
- completionId: completionId ?? void 0,
2499
- ...type === "message" && role === "system" ? { system: true } : {},
2500
- ...type === "compaction" && strategy === "verbatim-lines" ? { boundary: {
2501
- first,
2502
- covered: covered ?? void 0
2503
- } } : {}
2504
- });
2505
- }
2506
- }
2507
- return page;
2508
- }, true, SESSION_READ_FETCH.max);
2509
- const labelBody = `CASE WHEN chunks=0 AND ${this.dialect.textByteLength("entry_json")}<=512 THEN entry_json END`;
2510
- return indexedForkWindow(header, selected.index, selected.leaf, (lo, hi) => this.readRows(tx, sessionId, "seq BETWEEN ? AND ?", [lo, hi]), (seqs) => this.readSeqs(tx, sessionId, seqs), metadata, async function* (ranges, kinds, types = []) {
2511
- const filters = [];
2512
- if (types.length) filters.push(`${j("type")} IN (${types.map(() => "?").join(",")})`);
2513
- if (kinds.length) filters.push(`(${j("type")}='custom' AND (chunks>0 OR ${j("customType")} IN (${kinds.map(() => "?").join(",")})))`);
2514
- for (const [lo, hi] of ranges) for (let seq = lo; seq <= hi;) {
2515
- const labels = types.length === 1 && types[0] === "label";
2516
- const limit = labels ? SESSION_READ_FETCH.first : SESSION_READ_FETCH.max;
2517
- const rows = await tx.all(`SELECT seq,${j("type")} AS kind${labels ? `,${labelBody} AS body` : ""} FROM ${entries} WHERE session_id=? AND seq BETWEEN ? AND ? AND (${filters.join(" OR ")}) ORDER BY seq LIMIT ${limit}`, sessionId, seq, hi, ...types, ...kinds);
2518
- const deferred = rows.filter((r) => r.kind === "custom" || r.kind === "label" && !r.body).map((r) => Number(r.seq));
2519
- const projected = /* @__PURE__ */ new Map();
2520
- for (let i = 0; i < deferred.length; i += SEQ_BATCH) for (const m of await metadata(deferred.slice(i, i + SEQ_BATCH))) projected.set(m.seq, m);
2521
- for (const row of rows) yield projected.get(Number(row.seq)) ?? (row.body ? forkMetadata(Number(row.seq), JSON.parse(row.body)) : {
2522
- type: row.kind,
2523
- seq: Number(row.seq)
2524
- });
2525
- if (rows.length < limit) break;
2526
- seq = Number(rows.at(-1).seq) + 1;
2527
- }
2528
- }, {
2529
- ...selected.extras,
2530
- ...options
2531
- });
2532
- }, SESSION_TRANSACTION);
2533
- }
2534
- async *forkEntryChunks(tx, id, seq, count) {
2535
- for (let i = 0; i < count; i++) {
2536
- const row = await tx.get(`SELECT data FROM ${this.tables.entryChunks} WHERE session_id=? AND seq=? AND idx=?`, id, seq, i);
2537
- if (!row) throw new StorageError(`Session ${id} entry ${seq} is missing chunk ${i} of ${count}`);
2538
- yield row.data;
2539
- }
2540
- }
2541
- async readChildCatalogCut(sessionId) {
2542
- this.assertOpen();
2543
- return childCatalogCut((await this.prepareResume(sessionId)).index);
2544
- }
2545
- readResumeAt(sessionId, leafId, throughSeq, options) {
2546
- return this.resumeWindow(sessionId, leafId, throughSeq, options);
2547
- }
2548
- readResume(sessionId, leafId, options) {
2549
- return this.resumeWindow(sessionId, leafId, void 0, options);
2550
- }
2551
- async resumeWindow(sessionId, leafId, throughSeq, options) {
2552
- this.assertOpen();
2553
- validateSessionText("sessionId", sessionId);
2554
- if (leafId !== void 0) validateSessionText("entry.id", leafId);
2555
- for (let attempt = 0; attempt < 3; attempt++) {
2556
- const { index, revision } = await this.prepareResume(sessionId, leafId, throughSeq);
2557
- const resume = await this.transaction(async (tx) => {
2558
- const head = await tx.get(`SELECT header_json,revision FROM ${this.tables.sessions} WHERE id = ?${this.dialect.lockClause("share")}`, sessionId);
2559
- if (!head) throw new SessionNotFoundError(sessionId);
2560
- if (revision !== head.revision) return void 0;
2561
- const header = JSON.parse(head.header_json);
2562
- const { leafSeq } = index;
2563
- const plan = sessionResumePlan(index, index.leafSeq, options?.deferChildRecords);
2564
- announceHistoryLoad(plan.state.length + plan.branch.reduce((sum, [a, b]) => sum + b - a + 1, 0));
2565
- const branch = [];
2566
- for (const [start, end] of plan.branch) branch.push(...await this.readRows(tx, sessionId, "seq >= ? AND seq <= ?", [start, end]));
2567
- const state = await this.readSeqs(tx, sessionId, plan.state);
2568
- const leaf = leafSeq <= 0 ? void 0 : await tx.get(`SELECT entry_id FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, leafSeq);
2569
- const resume = sessionResumeFrom(index, header, branch, state, leaf?.entry_id ?? null, plan.children);
2570
- if (resume.compaction) await readEarlierCompletionIntents(index, resume, (seqs) => this.readSeqs(tx, sessionId, seqs));
2571
- return resume;
2572
- }, SESSION_TRANSACTION);
2573
- if (resume !== void 0) return resume;
2574
- }
2575
- throw new SessionConflictError(sessionId, 0, 0);
2576
- }
2577
- async findLatestCompaction(sessionId, leafId) {
2578
- this.assertOpen();
2579
- validateSessionText("sessionId", sessionId);
2580
- if (leafId !== void 0) validateSessionText("entry.id", leafId);
2581
- await this.prepareResume(sessionId);
2582
- const { point } = await this.transaction(async (tx) => {
2583
- const source = await this.resumeSource(tx, sessionId);
2584
- const { index } = source;
2585
- const leafSeq = leafId === void 0 ? index.leafSeq : await this.seqOfEntry(tx, sessionId, leafId) ?? -1;
2586
- const found = latestCompactionOf(index, leafSeq);
2587
- if (found === void 0) return {
2588
- point: void 0,
2589
- source
2590
- };
2591
- const [boundary] = await this.readSeqs(tx, sessionId, [found.seq]);
2592
- const leaf = await tx.get(`SELECT entry_id FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, leafSeq);
2593
- if (boundary === void 0 || leaf === void 0) return {
2594
- point: void 0,
2595
- source
2596
- };
2597
- return {
2598
- point: {
2599
- ...found,
2600
- entry: boundary.entry,
2601
- leafId: leaf.entry_id,
2602
- lastSeq: index.seq
2603
- },
2604
- source
2605
- };
2606
- }, SESSION_TRANSACTION);
2607
- return point;
2608
- }
2609
- /** The JSON of a long entry, from its chunks, one statement each. */
2610
- async readEntryChunks(tx, sessionId, seq, count) {
2611
- return Buffer.concat(await this.readRawEntryChunks(tx, sessionId, seq, count)).toString("utf8");
2612
- }
2613
- async readRawEntryChunks(tx, sessionId, seq, count, signal) {
2614
- const chunks = [];
2615
- for (let index = 0; index < count; index++) {
2616
- signal?.throwIfAborted();
2617
- const chunk = await tx.get(`SELECT data FROM ${this.tables.entryChunks} WHERE session_id = ? AND seq = ? AND idx = ?`, sessionId, seq, index);
2618
- if (chunk === void 0) throw new StorageError(`Session ${sessionId} entry ${seq} is missing chunk ${index} of ${count}`);
2619
- chunks.push(chunk.data);
2620
- if (signal !== void 0 && index + 1 < count) await yieldTurn();
2621
- }
2622
- return chunks;
2623
- }
2624
- async *entryChunks(sessionId, seq, count, revision) {
2625
- for (let index = 0; index < count; index++) {
2626
- const chunk = await this.database.get(`SELECT data FROM ${this.tables.entryChunks} WHERE session_id = ? AND seq = ? AND idx = ?
2627
- AND EXISTS (SELECT 1 FROM ${this.tables.sessions} WHERE id = ? AND revision = ?)`, sessionId, seq, index, sessionId, revision);
2628
- if (chunk === void 0) throw new StorageError(`Session ${sessionId} entry ${seq} is missing chunk ${index} of ${count}`);
2629
- yield chunk.data;
2630
- if (index + 1 < count) await yieldTurn();
2631
- }
2632
- }
2633
- async readInlineEntryBytes(sessionId, seq) {
2634
- if (this.dialect.name === "sqlite") {
2635
- const row = await this.database.get(`SELECT CAST(entry_json AS BLOB) AS data FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, seq);
2636
- return row ? [row.data] : [];
2637
- }
2638
- const row = await this.database.get(`SELECT entry_json FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, seq);
2639
- return row ? [new TextEncoder().encode(row.entry_json)] : [];
2640
- }
2641
- async forWrite(tx, sessionId, options, includeSummaryState = false) {
2642
- const row = await tx.get(`SELECT header_json, last_seq${includeSummaryState || options.epoch !== void 0 ? ", summary_state" : ""}
2643
- FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
2644
- if (!row) throw new SessionNotFoundError(sessionId);
2645
- const state = row.summary_state === void 0 ? void 0 : JSON.parse(String(row.summary_state));
2646
- if (row.last_seq !== options.expectSeq || options.epoch !== void 0 && state?.epoch !== options.epoch) throw new SessionConflictError(sessionId, options.expectSeq, row.last_seq);
2647
- return {
2648
- row,
2649
- state
2650
- };
2651
- }
2652
- async appendedResume(tx, sessionId, previous, lastSeq, entries) {
2653
- if (!isSessionResumeIndex(previous, lastSeq)) return void 0;
2654
- const seqs = /* @__PURE__ */ new Map();
2655
- for (const id of foreignResumeIds(previous, entries)) {
2656
- const seq = await this.seqOfEntry(tx, sessionId, id);
2657
- if (seq !== void 0) seqs.set(id, seq);
2658
- }
2659
- return foldSessionResume(previous, entries, (id) => seqs.get(id));
2660
- }
2661
- async seqOfEntry(executor, sessionId, entryId) {
2662
- const tables = snapshotIndexTables(this.prefix);
2663
- const source = await executor.get(`SELECT CASE WHEN backfilled_through >= watermark THEN 1 ELSE 0 END AS complete FROM ${tables.sources} WHERE source = 'session-entries'`);
2664
- if (Number(source?.complete) === 1) {
2665
- const linked = await executor.get(`SELECT seq FROM ${tables.sessionLinks} WHERE session_id = ? AND entry_id = ? ORDER BY seq DESC LIMIT 1`, sessionId, entryId);
2666
- return linked === void 0 ? void 0 : Number(linked.seq);
2667
- }
2668
- const row = await executor.get(`SELECT seq FROM ${this.tables.entries} WHERE session_id = ? AND entry_id = ? ORDER BY seq DESC LIMIT 1`, sessionId, entryId);
2669
- return row === void 0 ? void 0 : Number(row.seq);
2670
- }
2671
- async saveSummary(tx, sessionId, snapshot, previous, appendedResume) {
2672
- const { statement, texts, epoch } = this.summaryWrite(sessionId, snapshot, previous, appendedResume);
2673
- await tx.run(statement.sql, ...statement.params);
2674
- return {
2675
- texts,
2676
- epoch
2677
- };
2678
- }
2679
- /** The statement that saves the session's row as `saveSummary` saves it, with what `saveSummary` returns. */
2680
- summaryWrite(sessionId, snapshot, previous, appendedResume) {
2681
- const { header, lastSeq } = snapshot;
2682
- const { state: listed, texts } = applySessionSummaryEntries(previous, snapshot.entries);
2683
- const resume = previous === void 0 ? foldSessionResume(void 0, snapshot.entries) : appendedResume;
2684
- const epoch = resume?.epoch ?? previous?.epoch ?? newRevision();
2685
- const state = {
2686
- ...listed,
2687
- ...windowFields(previous, resume, lastSeq, epoch),
2688
- epoch
2689
- };
2690
- const summary = materializeSessionSummaryMetadata(header, state);
2691
- return {
2692
- statement: {
2693
- sql: `INSERT INTO ${this.tables.sessions}
2694
- (id, cwd, created_at, header_json, internal, last_seq, modified_at, message_count,
2695
- first_message, name, has_name, summary, summarized_through_id, summary_state, revision)
2696
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2697
- ON CONFLICT(id) DO UPDATE SET
2698
- cwd = excluded.cwd, created_at = excluded.created_at, header_json = excluded.header_json,
2699
- internal = excluded.internal, last_seq = excluded.last_seq, modified_at = excluded.modified_at,
2700
- message_count = excluded.message_count, first_message = excluded.first_message, name = excluded.name,
2701
- has_name = excluded.has_name, summary = excluded.summary,
2702
- summarized_through_id = excluded.summarized_through_id,
2703
- summary_state = excluded.summary_state, revision = excluded.revision`,
2704
- params: [
2705
- sessionId,
2706
- header.cwd,
2707
- header.createdAt,
2708
- this.encode(header),
2709
- header.internal ? 1 : 0,
2710
- lastSeq,
2711
- summary.modifiedAt,
2712
- summary.messageCount,
2713
- this.encode(summary.firstMessage),
2714
- summary.name === void 0 ? null : this.encode(summary.name),
2715
- summary.hasName ? 1 : 0,
2716
- summary.summary === void 0 ? null : this.encode(summary.summary),
2717
- summary.summarizedThroughId ?? null,
2718
- this.encode(state),
2719
- newRevision()
2720
- ]
2721
- },
2722
- texts,
2723
- epoch
2724
- };
2725
- }
2726
- async insertEntries(tx, sessionId, entries, lastSeq, texts) {
2727
- for (const { sql, params } of this.entryWrites(sessionId, entries, lastSeq, texts)) await tx.run(sql, ...params);
2728
- }
2729
- /**
2730
- * The statements that store `entries` after `lastSeq`, in order, each entry encoded only when its statements are
2731
- * taken: each entry's row and its chunks, the version step a first chunked entry takes, then the entries' search
2732
- * texts.
2733
- */
2734
- *entryWrites(sessionId, entries, lastSeq, texts) {
2735
- let chunked = false;
2736
- for (const [index, entry] of entries.entries()) {
2737
- const seq = lastSeq + index + 1;
2738
- const stored = storedEntry(entry, this.encode(entry));
2739
- chunked ||= stored.chunks.length > 0;
2740
- yield {
2741
- sql: `INSERT INTO ${this.tables.entries} (session_id, seq, entry_id, entry_json, chunks) VALUES (?, ?, ?, ?, ?)`,
2742
- params: [
2743
- sessionId,
2744
- seq,
2745
- entry.id,
2746
- stored.json,
2747
- stored.chunks.length
2748
- ]
2749
- };
2750
- if (stored.chunks.length > 0) yield {
2751
- sql: `DELETE FROM ${this.tables.entryChunks} WHERE session_id = ? AND seq = ?`,
2752
- params: [sessionId, seq]
2753
- };
2754
- for (const [chunk, data] of stored.chunks.entries()) yield {
2755
- sql: `INSERT INTO ${this.tables.entryChunks} (session_id, seq, idx, data) VALUES (?, ?, ?, ?)`,
2756
- params: [
2757
- sessionId,
2758
- seq,
2759
- chunk,
2760
- data
2761
- ]
2762
- };
2763
- }
2764
- if (chunked) yield {
2765
- sql: `UPDATE ${this.tables.meta} SET schema_version = ? WHERE schema_version = ?`,
2766
- params: [2, SESSION_SCHEMA_VERSION_UNCHUNKED]
2767
- };
2768
- for (const { index, text } of texts) yield {
2769
- sql: `INSERT INTO ${this.tables.searchTexts} (session_id, seq, text_json) VALUES (?, ?, ?)`,
2770
- params: [
2771
- sessionId,
2772
- lastSeq + index + 1,
2773
- this.encode(text)
2774
- ]
2775
- };
2776
- }
2777
- /**
2778
- * Runs the session row's statement, then `entries`' statements, in order. A write of up to
2779
- * {@link STATEMENT_BATCH_BYTES}, as an ordinary message is, goes to a connection thread as one batch that waits for
2780
- * it once. A larger one runs its statements one at a time as they are made, as before, so it never holds more than
2781
- * about that much of them, or sends it, at once.
2782
- */
2783
- async writeEntries(tx, summary, entries) {
2784
- const batch = [summary];
2785
- let bytes = statementBytes(summary);
2786
- const pending = entries[Symbol.iterator]();
2787
- for (let next = pending.next(); next.done !== true; next = pending.next()) {
2788
- batch.push(next.value);
2789
- bytes += statementBytes(next.value);
2790
- if (bytes <= STATEMENT_BATCH_BYTES) continue;
2791
- for (const { sql, params } of batch) await tx.run(sql, ...params);
2792
- for (let rest = pending.next(); rest.done !== true; rest = pending.next()) await tx.run(rest.value.sql, ...rest.value.params);
2793
- return;
2794
- }
2795
- await statementBatch(tx, batch, []);
2796
- }
2797
- encode(value) {
2798
- try {
2799
- return JSON.stringify(value);
2800
- } catch (cause) {
2801
- throw new StorageUnavailableError$1(this.descriptor, cause);
2802
- }
2803
- }
2804
- };
2805
- const nativeLoad = registerArchiveLoad(SqlSessionStore.prototype.load);
2806
- /** The running sessions that have a SQL store's sessions open, in a table every host sharing the store reads (#4971). */
2807
- var SqlSessionOpenMarkers = class {
2808
- static async createTable(tx, dialect, table) {
2809
- const { int, text } = dialect.types;
2810
- await tx.exec(`
2811
- CREATE TABLE IF NOT EXISTS ${table} (
2812
- session_id ${text} NOT NULL, token ${text} NOT NULL, pid ${int} NOT NULL, host ${text} NOT NULL,
2813
- heartbeat_at ${int} NOT NULL, PRIMARY KEY(session_id, token)
2814
- )${dialect.tableOptions};
2815
- `);
2816
- }
2817
- /**
2818
- * Each marker records the sessions schema version its process reads, so a build that upgrades the schema can tell
2819
- * that a process which would misread the upgraded schema still has a session open (#5065). Null for markers of
2820
- * builds before it. Additive, as every step of this domain must be.
2821
- */
2822
- static async addSchemaVersion(tx, dialect, table) {
2823
- const probe = dialect.columnExists(table, "schema_version");
2824
- if (await tx.get(probe.sql, ...probe.params) === void 0) await tx.exec(`ALTER TABLE ${table} ADD COLUMN schema_version ${dialect.types.int}`);
2825
- }
2826
- database;
2827
- table;
2828
- assertOpen;
2829
- constructor(database, table, assertOpen) {
2830
- this.database = database;
2831
- this.table = table;
2832
- this.assertOpen = assertOpen;
2833
- }
2834
- async put(sessionId, marker) {
2835
- this.assertOpen();
2836
- const now = dialectOf(this.database).nowMs;
2837
- await this.database.run(`INSERT INTO ${this.table} (session_id, token, pid, host, heartbeat_at, schema_version) VALUES (?, ?, ?, ?, ${now}, ?)
2838
- ON CONFLICT(session_id, token) DO UPDATE SET pid = excluded.pid, host = excluded.host,
2839
- heartbeat_at = excluded.heartbeat_at, schema_version = excluded.schema_version`, sessionId, marker.token, marker.pid, marker.host, 2);
2840
- }
2841
- async remove(sessionId, token) {
2842
- this.assertOpen();
2843
- await this.database.run(`DELETE FROM ${this.table} WHERE session_id = ? AND token = ?`, sessionId, token);
2844
- }
2845
- async list(sessionId) {
2846
- this.assertOpen();
2847
- const now = dialectOf(this.database).nowMs;
2848
- return (await this.database.all(`SELECT token, pid, host, ${now} - heartbeat_at AS age_ms FROM ${this.table} WHERE session_id = ?`, sessionId)).map((row) => ({
2849
- token: row.token,
2850
- pid: Number(row.pid),
2851
- host: row.host,
2852
- ageMs: Number(row.age_ms)
2853
- }));
2854
- }
2855
- };
2856
- export { LISTING_FETCH_BATCH, SESSION_BLOB_CHUNK_BYTES, SESSION_DOMAIN, SESSION_ENTRY_CHUNK_BYTES, SESSION_PRESENCE_DOMAIN, SESSION_PRESENCE_TABLES, SESSION_READ_FETCH, SESSION_READ_PAGE_CHARS, SESSION_RESUME_REBUILD, SESSION_SCHEMA_VERSION, SESSION_TABLES, SqlSessionStore };
2857
-
2858
- //# sourceMappingURL=sql-session-store-5FD3WBMZ.js.map
2859
- // __atomicOnDemandFailed: written by the build (scripts/in-place-update-gate.mjs). An import of this release's code on
2860
- // demand that fails in a process an in-place update left running says to restart.
2861
- function __atomicOnDemandFailed(error, feature) {
2862
- return (async () => {
2863
- const root = new URL("../", import.meta.url);
2864
- const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
2865
- const key = `${root.href}#0.10.7-alpha.1`;
2866
- let release = releases.get(key);
2867
- if (release === undefined) {
2868
- const current = (async () => {
2869
- for (const path of ["modes/interactive/interactive-mode-deps.js","_shared/chunk-CDOYTDYM.js","_shared/p0-cli-GUFK7TPN.js"]) {
2870
- try {
2871
- const held = await import(new URL(path, root).href);
2872
- if (typeof held.VERSION === "string") return { version: held.VERSION, name: held.APP_NAME };
2873
- } catch {
2874
- // Not a file this process can load: the next.
2875
- }
2876
- }
2877
- return undefined;
2878
- })().then((found) => {
2879
- if (found === undefined && releases.get(key) === current) releases.delete(key);
2880
- return found;
2881
- });
2882
- releases.set(key, current);
2883
- release = current;
2884
- }
2885
- const running = await release;
2886
- let installed;
2887
- try {
2888
- const { readFile } = process.getBuiltinModule("node:fs/promises");
2889
- installed = JSON.parse(await readFile(new URL("../package.json", root), "utf8")).version;
2890
- } catch {
2891
- // No installation to read, as in a bundle of the package: the release the process runs decides.
2892
- }
2893
- const updatedTo = typeof installed === "string" && installed !== "0.10.7-alpha.1" ? installed : running !== undefined && running.version !== "0.10.7-alpha.1" ? "0.10.7-alpha.1" : undefined;
2894
- if (updatedTo === undefined) throw error;
2895
- const application = typeof running?.name === "string" ? running.name : "atomic";
2896
- const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {
2897
- cause: error,
2898
- });
2899
- restart.name = "UpdatedInstallError";
2900
- restart[Symbol.for("atomic.on-demand-restart.v1")] = { application, updatedTo, feature };
2901
- throw restart;
2902
- })();
2903
- }