@bastani/atomic 0.10.14 → 0.10.15-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 (341) hide show
  1. package/CHANGELOG.md +17 -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 +3 -3
  6. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +3 -3
  7. package/dist/_shared/mode-shared-2QJSCUM6.js +3 -3
  8. package/dist/_shared/p1a-prewarm-XIU57JHF.js +3 -3
  9. package/dist/_shared/runtime-O4KCSG4C.js +2 -2
  10. package/dist/_shared/{sdk-B5LEWGGI.js → sdk-OHKMDJ74.js} +27 -5
  11. package/dist/_shared/{sdk-B5LEWGGI.js.map → sdk-OHKMDJ74.js.map} +1 -1
  12. package/dist/_shared/session-data-AHTU7IS6.js +2 -2
  13. package/dist/_shared/startup-0-0-Q3MWKUK4.js +2 -2
  14. package/dist/_shared/startup-0-1-M6OWAYHH.js +2 -2
  15. package/dist/_shared/{startup-0-2-5QHPCEON.js → startup-0-2-2HUMCPKX.js} +14 -16
  16. package/dist/_shared/startup-0-2-2HUMCPKX.js.map +1 -0
  17. package/dist/_shared/startup-0-3-4ZYBYQNM.js +3 -3
  18. package/dist/_shared/startup-0-4-ZMJV547D.js +3 -3
  19. package/dist/_shared/startup-0-5-YDW47QX6.js +3 -3
  20. package/dist/_shared/startup-10-0-TDQNBDDL.js +3 -3
  21. package/dist/_shared/startup-14-0-MLX36RBG.js +1 -1
  22. package/dist/_shared/startup-15-0-YUKGAC63.js +1 -1
  23. package/dist/_shared/startup-15-1-4S7FLMNG.js +6 -30
  24. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  25. package/dist/_shared/startup-8-0-34CBHPZH.js +3 -3
  26. package/dist/_shared/startup-8-1-LZFXSD3Z.js +3 -3
  27. package/dist/_shared/storage-command-7MGXLJGZ.js +2 -2
  28. package/dist/_shared/storage-status-K7PX2RXA.js +3 -3
  29. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  30. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  31. package/dist/builtin/intercom/index.bundle.mjs +1 -1
  32. package/dist/builtin/intercom/package.json +1 -1
  33. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  34. package/dist/builtin/mcp/package.json +1 -1
  35. package/dist/builtin/subagents/package.json +1 -1
  36. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  37. package/dist/builtin/web-access/index.bundle.mjs +1 -1
  38. package/dist/builtin/web-access/package.json +1 -1
  39. package/dist/cli/auth-cli.code.js +1 -1
  40. package/dist/cli/auth-cli.impl.js +3 -3
  41. package/dist/cli/auth-cli.js +3 -3
  42. package/dist/cli/blueprint-command.impl.js +3 -3
  43. package/dist/cli/blueprint-command.js +3 -3
  44. package/dist/cli/intercom-command.code.js +3 -3
  45. package/dist/cli/intercom-command.impl.js +3 -3
  46. package/dist/cli/intercom-command.js +3 -3
  47. package/dist/cli/list-models.impl.js +3 -3
  48. package/dist/cli/list-models.js +3 -3
  49. package/dist/cli/session-picker.code.js +1 -1
  50. package/dist/cli/session-picker.impl.js +3 -3
  51. package/dist/cli/session-picker.js +3 -3
  52. package/dist/cli/startup-ui.code.js +1 -1
  53. package/dist/cli/startup-ui.impl.js +3 -3
  54. package/dist/cli/startup-ui.js +3 -3
  55. package/dist/cli/storage-command.impl.js +3 -3
  56. package/dist/cli/storage-command.js +3 -3
  57. package/dist/cli/storage-search-session.code.js +1 -1
  58. package/dist/cli/storage-search-session.impl.js +3 -3
  59. package/dist/cli/storage-search-session.js +3 -3
  60. package/dist/cli/team-command.code.js +1 -1
  61. package/dist/cli/team-command.impl.js +3 -3
  62. package/dist/cli/team-command.js +3 -3
  63. package/dist/cli.js +2 -2
  64. package/dist/core/compaction/compactor.d.ts +0 -8
  65. package/dist/core/debug.impl.js +3 -3
  66. package/dist/core/debug.js +3 -3
  67. package/dist/core/export-html/card-projection.impl.js +3 -3
  68. package/dist/core/export-html/card-projection.js +3 -3
  69. package/dist/core/export-html/index.code.js +2 -2
  70. package/dist/core/export-html/index.impl.js +3 -3
  71. package/dist/core/export-html/index.js +3 -3
  72. package/dist/core/export-html/json-spans.impl.js +3 -3
  73. package/dist/core/export-html/json-spans.js +3 -3
  74. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  75. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  76. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  77. package/dist/core/export-html/tool-renderer.js +3 -3
  78. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  79. package/dist/core/extensions/jiti-loader.js +3 -3
  80. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  81. package/dist/core/extensions/jiti-static-loader.js +3 -3
  82. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  83. package/dist/core/extensions/loader-host-modules.js +3 -3
  84. package/dist/core/intercom-broker-control-host.code.js +1 -1
  85. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  86. package/dist/core/intercom-broker-control-host.js +3 -3
  87. package/dist/core/intercom-broker-control.code.js +2 -2
  88. package/dist/core/intercom-broker-control.impl.js +3 -3
  89. package/dist/core/intercom-broker-control.js +3 -3
  90. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  91. package/dist/core/package-manager-storage-adapters.js +3 -3
  92. package/dist/core/sdk.code.js +1 -1
  93. package/dist/core/sdk.impl.js +3 -3
  94. package/dist/core/sdk.js +3 -3
  95. package/dist/core/session-manager-core.js +3 -3
  96. package/dist/core/session-manager-list.impl.js +3 -3
  97. package/dist/core/session-manager-list.js +3 -3
  98. package/dist/core/session-manager.impl.js +3 -3
  99. package/dist/core/session-manager.js +3 -3
  100. package/dist/core/session-storage.impl.js +3 -3
  101. package/dist/core/session-storage.js +3 -3
  102. package/dist/core/storage/index.js +2 -2
  103. package/dist/core/storage/node-sqlite-thread.js +2 -2
  104. package/dist/core/storage/node-sqlite.js +2 -2
  105. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  106. package/dist/core/storage/offline-snapshot-file.js +3 -3
  107. package/dist/core/storage/provider.js +2 -2
  108. package/dist/core/storage/selection.js +2 -2
  109. package/dist/core/storage/session/branch-fork-source.code.js +2 -2
  110. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  111. package/dist/core/storage/session/branch-fork-source.js +3 -3
  112. package/dist/core/storage/session/card-view.impl.js +3 -3
  113. package/dist/core/storage/session/card-view.js +3 -3
  114. package/dist/core/storage/session/child-reader.code.js +2 -2
  115. package/dist/core/storage/session/child-reader.impl.js +3 -3
  116. package/dist/core/storage/session/child-reader.js +3 -3
  117. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  118. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  119. package/dist/core/storage/session/expanded-child-details.code.js +2 -2
  120. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  121. package/dist/core/storage/session/expanded-child-details.js +3 -3
  122. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  123. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  124. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  125. package/dist/core/storage/session/fork-row-index.js +3 -3
  126. package/dist/core/storage/session/fork-staging.code.js +1 -1
  127. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  128. package/dist/core/storage/session/fork-staging.js +3 -3
  129. package/dist/core/storage/session/fork-window.code.js +2 -2
  130. package/dist/core/storage/session/fork-window.impl.js +3 -3
  131. package/dist/core/storage/session/fork-window.js +3 -3
  132. package/dist/core/storage/session/history-pages.impl.js +3 -3
  133. package/dist/core/storage/session/history-pages.js +3 -3
  134. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  135. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  136. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  137. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  138. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  139. package/dist/core/storage/session/memory-session-store.js +3 -3
  140. package/dist/core/storage/session/pinned-branch-resume.code.js +2 -2
  141. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  142. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  143. package/dist/core/storage/session/released-history-files.code.js +1 -1
  144. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  145. package/dist/core/storage/session/released-history-files.js +3 -3
  146. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  147. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  148. package/dist/core/storage/session/session-resume.impl.js +3 -3
  149. package/dist/core/storage/session/session-resume.js +3 -3
  150. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  151. package/dist/core/storage/session/snapshot-cut.js +3 -3
  152. package/dist/core/storage/session/snapshot-history.code.js +2 -2
  153. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  154. package/dist/core/storage/session/snapshot-history.js +3 -3
  155. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  156. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  157. package/dist/core/storage/session/sql-session-store.js +3 -3
  158. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  159. package/dist/core/storage/session/tree-outline.js +3 -3
  160. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  161. package/dist/core/storage/session/tree-presentation.js +3 -3
  162. package/dist/core/storage/storage-status.impl.js +3 -3
  163. package/dist/core/storage/storage-status.js +3 -3
  164. package/dist/core/storage/team.impl.js +3 -3
  165. package/dist/core/storage/team.js +3 -3
  166. package/dist/core/structured-output/index.code.js +1 -1
  167. package/dist/core/structured-output/index.impl.js +3 -3
  168. package/dist/core/structured-output/index.js +3 -3
  169. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  170. package/dist/core/tasks/task-completion-entry.js +3 -3
  171. package/dist/core/tasks/task-file-history.code.js +2 -2
  172. package/dist/core/tasks/task-file-history.impl.js +3 -3
  173. package/dist/core/tasks/task-file-history.js +3 -3
  174. package/dist/core/tasks/task-reference-archive.code.js +2 -2
  175. package/dist/core/tasks/task-reference-archive.js +3 -3
  176. package/dist/core/tasks/task-reference-identity.js +3 -3
  177. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  178. package/dist/core/tasks/task-reference-stream.js +3 -3
  179. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  180. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  181. package/dist/core/tasks/task-view-source.impl.js +3 -3
  182. package/dist/core/tasks/task-view-source.js +3 -3
  183. package/dist/core/tools/read-url.impl.js +3 -3
  184. package/dist/core/tools/read-url.js +3 -3
  185. package/dist/core/worktree-snapshot/blob-store.js +2 -2
  186. package/dist/core/worktree-snapshot/errors.code.js +1 -1
  187. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  188. package/dist/core/worktree-snapshot/errors.js +3 -3
  189. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  190. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  191. package/dist/extensions/codemode/execute.impl.js +3 -3
  192. package/dist/extensions/codemode/execute.js +3 -3
  193. package/dist/extensions/codemode/renderer.impl.js +3 -3
  194. package/dist/extensions/codemode/renderer.js +3 -3
  195. package/dist/extensions/mcp/cli.code.js +1 -1
  196. package/dist/extensions/mcp/cli.impl.js +3 -3
  197. package/dist/extensions/mcp/cli.js +3 -3
  198. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  199. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  200. package/dist/extensions/mcp/cli.lazy.js +3 -3
  201. package/dist/extensions/mcp/runtime.code.js +1 -1
  202. package/dist/extensions/mcp/runtime.impl.js +3 -3
  203. package/dist/extensions/mcp/runtime.js +3 -3
  204. package/dist/index.d.ts +21 -1
  205. package/dist/index.js +2 -2
  206. package/dist/main-first-time-setup.code.js +1 -1
  207. package/dist/main-first-time-setup.impl.js +3 -3
  208. package/dist/main-first-time-setup.js +3 -3
  209. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  210. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  211. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  212. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  213. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  214. package/dist/modes/print-mode.js +1 -1
  215. package/dist/package-manager-cli.code.js +2 -2
  216. package/dist/package-manager-cli.impl.js +3 -3
  217. package/dist/package-manager-cli.js +3 -3
  218. package/dist/startup-files.json +1 -1
  219. package/dist/startup-stages/6.js +1 -1
  220. package/dist/utils/startup-database-spare.code.js +1 -1
  221. package/dist/utils/startup-database-spare.impl.js +3 -3
  222. package/dist/utils/startup-database-spare.js +3 -3
  223. package/dist/utils/tools-manager.impl.js +3 -3
  224. package/dist/utils/tools-manager.js +3 -3
  225. package/docs/background-tasks/reference.md +182 -0
  226. package/docs/background-tasks.md +98 -405
  227. package/docs/build.md +67 -27
  228. package/docs/changelog.mdx +1 -1
  229. package/docs/codemode.md +108 -39
  230. package/docs/compaction/branch-summaries.md +54 -0
  231. package/docs/compaction/custom-compactors.md +161 -0
  232. package/docs/compaction/memory-compaction.md +77 -0
  233. package/docs/compaction/reference.md +86 -38
  234. package/docs/compaction.md +51 -252
  235. package/docs/computer-use.md +169 -321
  236. package/docs/containerization.md +71 -57
  237. package/docs/custom-provider/api-reference.md +119 -25
  238. package/docs/custom-provider/oauth.md +114 -132
  239. package/docs/custom-provider/override.md +37 -27
  240. package/docs/custom-provider/registration.md +107 -83
  241. package/docs/custom-provider/streaming.md +85 -71
  242. package/docs/custom-provider.md +85 -52
  243. package/docs/development.md +39 -29
  244. package/docs/docs.json +76 -63
  245. package/docs/environment-variables.md +94 -44
  246. package/docs/extensions/api-reference.md +86 -43
  247. package/docs/extensions/authoring.md +162 -154
  248. package/docs/extensions/events.md +80 -25
  249. package/docs/extensions/examples.md +90 -85
  250. package/docs/extensions/ui.md +206 -82
  251. package/docs/extensions.md +79 -108
  252. package/docs/getting-started/authentication.md +67 -36
  253. package/docs/getting-started/first-session.md +53 -43
  254. package/docs/getting-started/installation.md +116 -89
  255. package/docs/getting-started/project-instructions.md +48 -34
  256. package/docs/guides/configuration.md +82 -20
  257. package/docs/guides/non-interactive.md +66 -24
  258. package/docs/guides/resume-on-any-machine.md +135 -82
  259. package/docs/guides/team-setup.md +114 -105
  260. package/docs/guides.md +76 -32
  261. package/docs/herdr.md +15 -16
  262. package/docs/how-atomic-works.md +140 -0
  263. package/docs/index.md +58 -44
  264. package/docs/intercom/operations.md +141 -151
  265. package/docs/intercom/reference.md +85 -108
  266. package/docs/intercom.md +84 -145
  267. package/docs/json.md +120 -67
  268. package/docs/keybindings.md +85 -49
  269. package/docs/libraries/agent-core.md +137 -275
  270. package/docs/libraries/ai.md +100 -84
  271. package/docs/libraries/codemode.md +210 -300
  272. package/docs/libraries/schema.md +59 -53
  273. package/docs/libraries/storage-postgres.md +49 -35
  274. package/docs/libraries/telemetry.md +153 -354
  275. package/docs/libraries/tui.md +265 -393
  276. package/docs/libraries.md +42 -26
  277. package/docs/llama-cpp.md +171 -161
  278. package/docs/mcp-servers.md +90 -51
  279. package/docs/models/choose-a-model.md +188 -0
  280. package/docs/models/reference.md +74 -30
  281. package/docs/models.md +153 -88
  282. package/docs/orchestration/migrating-workflows.md +23 -16
  283. package/docs/orchestration/patterns.md +39 -44
  284. package/docs/orchestration.md +65 -26
  285. package/docs/packages/authoring.md +51 -29
  286. package/docs/packages/reference.md +42 -21
  287. package/docs/packages.md +69 -58
  288. package/docs/programmatic.md +118 -24
  289. package/docs/prompt-templates.md +84 -83
  290. package/docs/providers/reference.md +43 -48
  291. package/docs/providers.md +219 -451
  292. package/docs/quickstart.md +140 -120
  293. package/docs/reference/cli.md +135 -97
  294. package/docs/reference.md +20 -18
  295. package/docs/rpc/examples.md +76 -20
  296. package/docs/rpc/extension-ui.md +64 -38
  297. package/docs/rpc/protocol.md +361 -110
  298. package/docs/rpc.md +57 -17
  299. package/docs/sdk/reference.md +409 -534
  300. package/docs/sdk/storage.md +53 -13
  301. package/docs/sdk/structured-decisions.md +82 -56
  302. package/docs/sdk/web-server.md +57 -43
  303. package/docs/sdk.md +106 -84
  304. package/docs/security.md +42 -64
  305. package/docs/session-format.md +62 -38
  306. package/docs/sessions.md +99 -214
  307. package/docs/settings.md +165 -195
  308. package/docs/shell-aliases.md +9 -6
  309. package/docs/skills/authoring.md +69 -48
  310. package/docs/skills/reference.md +51 -20
  311. package/docs/skills.md +99 -148
  312. package/docs/slash-commands.md +129 -0
  313. package/docs/storage/custom-adapters.md +160 -85
  314. package/docs/storage/jsonl.md +81 -66
  315. package/docs/storage/postgres/pgbouncer.md +120 -126
  316. package/docs/storage/postgres/tuning.md +120 -143
  317. package/docs/storage/postgres.md +314 -330
  318. package/docs/storage/sqlite.md +71 -42
  319. package/docs/storage.md +298 -302
  320. package/docs/subagents/authoring.md +55 -38
  321. package/docs/subagents/reference.md +73 -33
  322. package/docs/subagents.md +119 -187
  323. package/docs/terminal-setup.md +50 -38
  324. package/docs/termux.md +67 -41
  325. package/docs/themes/reference.md +23 -19
  326. package/docs/themes.md +142 -127
  327. package/docs/tmux.md +47 -55
  328. package/docs/tools.md +147 -109
  329. package/docs/tui/reference.md +166 -214
  330. package/docs/tui.md +196 -341
  331. package/docs/usage.md +118 -138
  332. package/docs/verification.md +79 -51
  333. package/docs/web-access.md +121 -101
  334. package/docs/windows.md +26 -27
  335. package/docs/worktree-snapshots/reference.md +245 -0
  336. package/docs/worktree-snapshots.md +71 -259
  337. package/package.json +8 -8
  338. package/dist/_shared/startup-0-2-5QHPCEON.js.map +0 -1
  339. package/docs/guides/intercom.md +0 -32
  340. package/docs/guides/orchestration.md +0 -28
  341. package/docs/guides/subagents.md +0 -37
@@ -1,21 +1,21 @@
1
1
  ---
2
2
  title: "Custom storage adapters"
3
3
  sidebarTitle: "Custom adapters"
4
- description: "Select a storage adapter, ship one in an Atomic package, wrap your own SQL driver, implement a session store, and test it with the conformance suites."
4
+ description: "Build, package, configure, and test custom SQL or SessionStore storage adapters for Atomic."
5
5
  ---
6
6
 
7
- This page is for developers who want Atomic to keep sessions in a database it does not support out of the box. You do that with a **storage adapter**: a JavaScript or TypeScript module that opens a connection to your database and hands it to Atomic. Atomic's own [PostgreSQL](/storage/postgres) support is an adapter too. Only the built-in SQLite, JSONL, and in-memory stores work without one.
7
+ A **storage adapter** is a JavaScript or TypeScript module that connects Atomic to a database backend it does not support out of the box. Atomic's own [PostgreSQL](/storage/postgres) support is implemented as an adapter; only local SQLite, JSONL, and in-memory stores are built in.
8
8
 
9
- What kind of adapter you write depends on your database:
9
+ Choose the adapter hook that fits your database:
10
10
 
11
- - **A SQL database that runs SQLite's SQL**, such as a SQLite-compatible server, returns a `SqliteDatabase` from `openDatabase`. Atomic then keeps sessions and Intercom there. Atomic sends SQLite SQL to such an adapter, so the database must run it, or the adapter must translate it.
12
- - **Any other database** implements `openSessionStore` instead. It holds sessions only, so Intercom cannot route between machines through it.
13
-
14
- The page covers selecting an adapter, shipping one in an Atomic package, wrapping your own database driver, and testing the result.
11
+ | Backend type | Implement | Capabilities |
12
+ | --- | --- | --- |
13
+ | SQLite-compatible (or PostgreSQL-dialect) SQL database | `openDatabase(options, context)` returning `SqliteDatabase` | Full support for sessions, prefixes, snapshots, and multi-node Intercom |
14
+ | Non-SQL or custom document/KV database | `openSessionStore(options, context, { prefix? })` returning `SessionStore` | Sessions only (Intercom multi-node routing requires a SQL `openDatabase` adapter) |
15
15
 
16
16
  ## Selecting an adapter
17
17
 
18
- A storage adapter is a module whose default export satisfies `StorageAdapterModule`:
18
+ An adapter module's default export satisfies `StorageAdapterModule`:
19
19
 
20
20
  ```typescript
21
21
  import type { StorageAdapterModule } from "@bastani/atomic/storage";
@@ -28,33 +28,31 @@ export default {
28
28
  } satisfies StorageAdapterModule;
29
29
  ```
30
30
 
31
- Here `openMyDatabase` stands for your own code that connects to the database. [Custom driver adapter example](#custom-driver-adapter-example) shows a complete one.
32
-
33
- Select an adapter in `sessions.storage` or top-level `storage` in [settings](/settings#sessions), or pass `sessionStore: { kind: "adapter", module, options, secrets, prefix }` in the SDK. Relative module paths resolve from the agent directory (`~/.atomic/agent` by default). Bare package names resolve from user-scope [Atomic packages](#adapters-from-atomic-packages), host extension directories, or the agent directory, never from an embedding application's `node_modules`. Project settings follow the project trust boundary, and adapter code runs with Atomic's privileges.
34
-
35
- Choose the installation method that matches how you open the adapter:
31
+ Select an adapter in `sessions.storage` or top-level `storage` in [settings](/settings#sessions), or pass `sessionStore: { kind: "adapter", module, options, secrets, prefix }` in the SDK. Relative module paths resolve from the agent directory (`~/.atomic/agent` by default). Bare package names resolve from user-scope [Atomic packages](#adapters-from-atomic-packages), host extension directories, or the agent directory—never from an embedding app's `node_modules`.
36
32
 
37
- - **Direct SDK database handles (`{ kind: "database", database }`).** Install the package in your project with `npm install`, call the adapter's open function, such as `openPostgresDatabase()`, and pass the handle to `sessionStore: { kind: "database", database, prefix? }` or `SqlSessionStore.open(database, { prefix? })`. See [SDK session storage](/sdk/storage).
38
- - **Adapter-resolved selections (`{ kind: "adapter", module }`, `settings.json`, or `ATOMIC_STORAGE`).** Install the package in user scope with `atomic install npm:<package>` (without `-l`), or register a local package directory with `DefaultResourceLoader({ additionalExtensionPaths })` or `--extension`.
33
+ <Warning>
34
+ Adapter modules execute code with Atomic's full OS privileges. Project-level storage settings follow Atomic's [project trust boundary](/security)—review adapter packages carefully before trusting a project.
35
+ </Warning>
39
36
 
40
- Adapter modules can import `@bastani/atomic/storage` and `@bastani/atomic` directly in both npm installs and standalone binaries. This works for the adapter entry file and any ES module or TypeScript file it imports relatively (including `.mjs` files and `.js` files in `"type": "module"` packages). CommonJS files outside the entry file resolve from `node_modules` instead. List `@bastani/atomic` under `peerDependencies`, not `dependencies`.
37
+ Match installation method to how you open the adapter:
41
38
 
42
- `options` holds strings, numbers, booleans, or `null`. `secrets` maps secret names to `{ env }`, `{ file }`, or (in the SDK only) `inMemorySecret(value)` (`{ value }`), overriding same-named keys in `options`. Atomic strips one trailing `\n` or `\r\n` from `{ file }` secrets and keeps other whitespace intact. `inMemorySecret()` serializes as `[redacted]` and is refused outside the SDK (`in-memory-secret-unsupported`).
39
+ - **Direct SDK handles (`{ kind: "database", database }`):** install the adapter in your app with `npm install`, call its opener (such as `openPostgresDatabase()`), and pass the handle to `sessionStore: { kind: "database", database, prefix? }` or `SqlSessionStore.open(database, { prefix? })`. See [SDK session storage](/sdk/storage).
40
+ - **Adapter-resolved selections (`{ kind: "adapter", module }`, `settings.json`, or `ATOMIC_STORAGE`):** install in user scope with `atomic install npm:<package>` (without `-l`), or register a local package directory via `--extension <dir>` or `DefaultResourceLoader({ additionalExtensionPaths })`.
43
41
 
44
- `context` provides `agentDir`, `domain: "sessions" | "intercom"`, an optional `signal`, and `secret(name)` to reread `secrets[name]` on demand. An adapter that reads fresh credentials for each new connection (such as a rotated password file) declares `liveSecrets` on its `StorageAdapterModule` (for example `liveSecrets: ["password"]`). Atomic omits names listed in `liveSecrets` from `options` and expects the adapter to call `context.secret(name)`, which throws `StorageConfigError` (`reason: "secret-missing"`) when the secret is missing from `secrets`.
42
+ <Note>
43
+ **Packaging imports:** Adapters can import `@bastani/atomic/storage` and `@bastani/atomic` directly in both npm installs and standalone binaries—both in the adapter entry file and in any ES module or TypeScript file it imports relatively (`.ts`, `.mjs`, or `.js` under `"type": "module"`). CommonJS files outside the entry file resolve from `node_modules`. Declare `@bastani/atomic` in `peerDependencies`, never `dependencies`.
44
+ </Note>
45
45
 
46
- Adapter hooks and lifecycle:
46
+ ### Options, secrets, and lifecycle
47
47
 
48
- - Implement `openDatabase(options, context): Promise<SqliteDatabase>` for SQL-backed adapters so Atomic manages schemas, prefixes, and Intercom tables.
49
- - Implement `openSessionStore(options, context, { prefix? })` for non-SQL session stores. When both hooks exist, `openSessionStore` takes priority for sessions.
50
- - Missing hooks raise `StorageConfigError` (`reason: "adapter-domain-unsupported"`). Load failures raise `StorageAdapterLoadError`, and driver open failures raise `StorageUnavailableError`.
51
- - `new StorageProvider().openSessionStore(selection, context)` opens stores programmatically (`kind`: `"memory"`, `"jsonl"`, `"sqlite"`, `"database"`, or `"adapter"`). `loadStorageAdapter(module, context, hostModules)` loads an adapter module.
52
- - `StorageProvider` instances share one process-wide map of provider-owned databases across matching selections and close each owned database when its last returned store closes. Caller-owned `database` handles passed through `{ kind: "database", database }` are never closed by the provider.
53
- - If opening storage fails and closing its owned database also fails, Atomic throws the original opening error with a `cleanupCause` field holding the cleanup failure.
48
+ - **`options` and `secrets`:** `options` accepts `string | number | boolean | null`. `secrets` maps secret names to `{ env }`, `{ file }`, or (SDK only) `inMemorySecret(value)` (`{ value }`), overriding same-named keys in `options`. Atomic strips one trailing `\n` or `\r\n` from `{ file }` secrets and leaves other whitespace intact. `inMemorySecret()` serializes as `[redacted]` and is refused outside the SDK (`in-memory-secret-unsupported`).
49
+ - **`context` and `liveSecrets`:** `context` supplies `{ agentDir, domain: "sessions" | "intercom", signal?, secret(name) }`. Adapters that re-read rotating credentials per connection declare `liveSecrets` on `StorageAdapterModule` (for example `liveSecrets: ["password"]`): Atomic omits those names from `options` and expects the adapter to call `await context.secret(name)`, which throws `StorageConfigError` (`secret-missing`) if absent from `secrets`.
50
+ - **Hook priority and errors:** When an adapter exports both `openDatabase` and `openSessionStore`, `openSessionStore` takes priority for `"sessions"` while `openDatabase` handles `"intercom"`. Missing hooks throw `StorageConfigError` (`adapter-domain-unsupported`); module load failures throw `StorageAdapterLoadError`; connection failures throw `StorageUnavailableError`.
51
+ - **Programmatic pooling (`StorageProvider`):** `new StorageProvider().openSessionStore(selection, context)` opens `"memory"`, `"jsonl"`, `"sqlite"`, `"database"`, or `"adapter"` stores programmatically (`loadStorageAdapter(module, context, hostModules)` loads an adapter module directly). `StorageProvider` shares one process-wide map of provider-owned databases across matching selections and closes an owned database when its last returned store closes. Caller-owned handles (`{ kind: "database", database }`) are never closed by the provider. If opening fails and closing an owned database also fails, Atomic throws the opening error with `cleanupCause` set.
54
52
 
55
53
  ### Adapters from Atomic packages
56
54
 
57
- An [Atomic package](/packages) can bundle storage adapters and their driver dependencies by listing adapter paths under `atomic.storageAdapters` in `package.json`:
55
+ An [Atomic package](/packages) can bundle adapters and their driver dependencies under `atomic.storageAdapters` in `package.json`:
58
56
 
59
57
  ```json
60
58
  {
@@ -65,7 +63,7 @@ An [Atomic package](/packages) can bundle storage adapters and their driver depe
65
63
  }
66
64
  ```
67
65
 
68
- Install the package with `atomic install npm:@example/atomic-mydb` and select it by package name:
66
+ Install with `atomic install npm:@example/atomic-mydb` and reference it by package name:
69
67
 
70
68
  ```json
71
69
  {
@@ -77,57 +75,79 @@ Install the package with `atomic install npm:@example/atomic-mydb` and select it
77
75
  }
78
76
  ```
79
77
 
80
- The bare package name selects the first listed adapter. When a package exports several adapters, select one with `<package>/<name>` using the adapter filename without its extension (such as `@example/atomic-mydb/mydb-adapter`).
78
+ A bare package name selects the first listed adapter. For multi-adapter packages, select `<package>/<file-stem>` (filename without extension, such as `@example/atomic-mydb/mydb-adapter`).
81
79
 
82
- Host applications embedding Atomic can expose their own adapter without installing it separately. Pass the package directory via `--extension <dir>` or `additionalExtensionPaths: [packageRoot]` on `DefaultResourceLoader` before opening storage, then select `"adapter": "@example/app"` or `"@example/app/<name>"`.
80
+ Host applications can expose an adapter without installing it globally by passing the package directory via `--extension <dir>` or `DefaultResourceLoader({ additionalExtensionPaths: [packageRoot] })` before opening storage, then referencing `"@example/app"` or `"@example/app/<name>"`.
83
81
 
84
- Atomic resolves adapter package names in this order:
82
+ Resolution order for bare adapter package names:
85
83
 
86
84
  1. Extension package directories passed to the process (or inherited from the launching Atomic process).
87
- 2. Packages in effective global settings (including the older `~/.pi/agent/settings.json` for the default agent directory). Project packages are not searched.
85
+ 2. Packages in effective global settings (including legacy `~/.pi/agent/settings.json` for the default agent directory). Project packages are never searched.
88
86
  3. Module resolution from the agent directory.
89
87
 
90
- Child processes that Atomic starts (such as subagents and the Intercom broker) automatically inherit adapters resolved from the host's packages without reloading the host package. `atomic storage status` shows the resolved path when run inside such a process, and resolves from global settings or the agent directory when run directly from a shell.
88
+ Child processes launched by Atomic (subagents and the Intercom broker) inherit resolved host adapters automatically without reloading host packages.
91
89
 
92
90
  ## Bring your own driver
93
91
 
94
- To wrap a SQLite-compatible driver into a `SqliteDatabase`, call `createSqliteDatabase` from `@bastani/atomic/storage` with these driver hooks:
95
-
96
- - `descriptor` provides `{ adapter, location }` for diagnostics (redacted through `redact`).
97
- - `execute(sql, params)` runs one parameterized statement and returns `{ columns, rows, changes }`. Return integers as `bigint` to preserve 64-bit precision.
98
- - `executeMultiple(sql)` runs zero or more unparameterized statements.
99
- - `beginTransaction()` starts a write transaction and returns `{ execute, executeMultiple, commit, rollback, close? }`.
100
- - `close()` releases the driver connection.
101
- - `batch(statements)` (optional) executes `{ sql, params }` statements in one atomic write transaction sent as a single request. Provide this only when the driver sends the whole batch at once.
102
- - `redact(text)` (optional) strips credentials from error text. Use `redactSecrets(secrets)` to build one that removes raw, URI-encoded, and decoded forms.
103
- - `transientFailure(failure)` (optional) classifies retryable driver errors from structured fields (never message text) and returns `{ code, outcome, hop? }`. Set `outcome` to `"not-applied"` when the database cannot have changed, or `"unknown"` when the write may have committed. Set `hop: { name, failure }` when an intermediate hop such as a proxy failed before reaching the database.
104
- - `freeBytes()` (optional) returns writable free bytes on the filesystem holding a local database file, or `undefined`.
105
- - `openReader()` (optional) returns a driver with connections of its own on the same database, for reads. Atomic exposes it as `SqliteDatabase.openReader()`. The reader gets its own call queue and closes when the main database closes. Atomic's stores send only reads through it, so its connections may refuse writes. A store's read through it first waits for any of that store's own writes to the same data that have started but not finished, so a caller that starts a write and then reads without waiting still reads what it wrote.
106
- - `concurrentTransactions` (optional) marks a driver that runs each transaction on its own connection, as the PostgreSQL adapter does. Atomic then runs calls that cannot conflict at the same time. See the queue rules below.
107
- - `pipelinedTransactions` (optional) marks a transaction connection that accepts a statement before the previous one is answered. The PostgreSQL adapter sets it. Atomic then sends each statement of a transaction without waiting for the answer before it. It can also send a transaction's last writes together with its commit.
108
- - `beginTransaction` receives `leading`, the reads the transaction makes first. The driver may send them with the begin and answer the transaction's first calls from them.
109
- - `beginTransaction` receives `relaxedDurability: true` for a write whose loss in a server crash is harmless, such as a lease renewal. The driver may then answer the commit before the transaction reaches disk, as the PostgreSQL adapter does with `synchronous_commit = off`. Drivers may ignore it.
110
- - If a statement sent ahead of an earlier answer, or with the commit, fails, the driver's commit must fail, so nothing commits. The transaction then fails with that statement's error.
111
- - A statement whose connection broke after the commit was sent reports `outcome: "unknown"`, because the commit may have applied.
112
- - `concurrentReads` (optional) is a positive integer for a driver that runs reads on connections or streams of their own, up to that many at once. Atomic then runs read-only transactions, and statements outside a transaction that `readsOnly` accepts, beside each other. Every other call still waits for each call before it, and a read waits for the writes queued before it. With `concurrentTransactions` as well, Atomic runs at most this many reads at once.
113
- - `readsOnly(sql)` (optional) says whether a statement run outside a transaction only reads. With `concurrentReads` or `concurrentTransactions`, such a statement runs beside other reads. Answer `true` only for a statement that can never write.
114
- - On a driver with `concurrentTransactions`, a read-only transaction returns once its reads are answered. Its commit only ends the snapshot, so it finishes in the background, and `close()` waits for it.
115
-
116
- Driver hooks may return values or promises. Atomic runs one operation at a time unless the driver sets `concurrentTransactions`. It copies binary parameters on call, rejects NUL text bindings with `StorageInvalidTextError`, converts safe-range integers to `number`, expires transaction handles after settlement, and drains accepted work on `close()`. Unclassified driver errors reject with `StorageUnavailableError` (with redacted `cause`), and failed rollbacks reject with `StorageRollbackError`.
117
-
118
- Transient retry and queue bounds:
119
-
120
- - Recognized transient failures reject with `StorageTransientError`. Statements and batches that failed before writing retry up to `STORAGE_TRANSIENT_RETRY_ATTEMPTS` (5) times starting at 250 ms with exponential backoff and up to 20% jitter. Writes with `outcome: "unknown"` never retry automatically.
121
- - Transactions retry (re-running their callback) only when called with `{ retryTransientFailures: true }` and only for callbacks that have no external side effects. Non-boolean values throw `StorageConfigError`. The first retried failure on a database emits a one-time process warning.
122
- - On a driver with `concurrentTransactions`, a call waits only for earlier unfinished calls it conflicts with. Statements and batches outside a transaction, and serial transactions without a `domain`, conflict with every call. A serial transaction with a `domain` conflicts with others of the same domain. A read-only transaction waits for writes queued before it, but not for other read-only transactions or later writes. Conflicting calls run in call order, and calls that do not conflict, such as appends to different sessions, run concurrently. Other drivers run one call at a time.
123
- - While a call runs without settling, waiting priority batches (batches sent with `{ priority: true }`) fail after `STORAGE_PRIORITY_CALL_MAX_WAIT_MS` (10 seconds), and other waiting calls fail after `STORAGE_QUEUED_CALL_MAX_WAIT_MS` (60 seconds), both with `StorageUnavailableError`. On a driver with `concurrentTransactions`, only calls waiting behind the stuck call (directly or through other waiting calls) fail. Timers reset for each call that begins running.
124
- - For shared local SQLite files, enable WAL mode with `switchToWriteAheadLog(exec, busyTimeoutMs)` from `@bastani/atomic/storage`. It retries `SQLITE_BUSY` up to `busyTimeoutMs` and retries Windows `SQLITE_IOERR_TRUNCATE` for up to 5 seconds (or `busyTimeoutMs`, whichever is shorter).
125
-
126
- You can also implement `SqliteDatabase` directly. In either case, verify your implementation with the [conformance suite](#adapter-conformance).
92
+ Wrap any SQLite-compatible (or PostgreSQL-dialect) driver into a `SqliteDatabase` with `createSqliteDatabase(driver)` from `@bastani/atomic/storage`. Driver hooks may return sync values or promises.
93
+
94
+ ### Required `SqliteDriver` hooks
95
+
96
+ | Hook | Signature / behavior |
97
+ | --- | --- |
98
+ | `descriptor` | `{ adapter: string; location: string }` for diagnostics (`location` is passed through `redact`). |
99
+ | `execute(sql, params)` | Runs one parameterized statement and returns `{ columns, rows, changes }`. Return integers as `bigint` to preserve 64-bit precision. |
100
+ | `executeMultiple(sql)` | Runs zero or more unparameterized SQL statements. |
101
+ | `beginTransaction(options?)` | Starts a transaction and returns `{ execute, executeMultiple, commit, rollback, close? }`. |
102
+ | `close()` | Releases driver connections after accepted work drains. |
103
+
104
+ ### Optional resilience, metadata, and concurrency hooks
105
+
106
+ | Hook | Purpose |
107
+ | --- | --- |
108
+ | `dialect` | `StorageDialect` spoken by the backend (`sqliteDialect` when omitted, or `postgresDialect` from `@bastani/atomic/storage`). |
109
+ | `batch(statements, options?)` | Runs `{ sql, params }[]` atomically in a single write request (`options`: `{ lockWaitMs?, priority? }`). Provide only when the driver sends the whole batch in one round trip. |
110
+ | `redact(text)` | Strips secrets from diagnostic locations and error text. Build one with `redactSecrets(secrets)` to cover raw, URI-encoded, and decoded forms. |
111
+ | `transientFailure(failure)` | Classifies retryable driver errors from structured fields (never message text) into `{ code, outcome: "not-applied" \| "unknown", hop?: { name, failure } }`. Set `outcome: "not-applied"` only when the database could not have changed; set `hop` when an intermediate proxy failed before reaching the server. |
112
+ | `lockBusy(failure)` | Recognizes a `batch()` write-lock contention error that wrote nothing; Atomic retries outside its queue with randomized backoff up to `lockWaitMs`. |
113
+ | `payloadLimits` | `{ value?: number; response?: number }` byte limits reported in `StoragePayloadTooLargeError`. |
114
+ | `notifications` | `StorageNotifications` (`notify`, `listen`, `state`, optional `send`) for push wake-ups such as PostgreSQL `LISTEN`/`NOTIFY`. |
115
+ | `freeBytes()` | Returns writable free bytes on the filesystem holding a local database file, or `undefined`. |
116
+ | `openReader()` | Returns a read-only driver on dedicated connections (`SqliteDatabase.openReader()`). Reads through it wait for that store's own in-flight writes to the same data so read-your-writes holds, and it closes automatically with the main handle. |
117
+ | `takeOpenedCatalog()` | Returns the schema catalog read during initial connection open once (`StorageOpenedCatalog`), skipping duplicate schema queries on store open. |
118
+ | `databaseIdentity()` | Returns a canonical identity string shared only by handles targeting the exact same database and schema (or `undefined` when unknown, such as in memory). |
119
+ | `concurrentTransactions` | Set `true` if each transaction runs on its own connection (as in PostgreSQL) so non-conflicting transactions run in parallel. |
120
+ | `concurrentReads` | Positive integer capping concurrent read-only transactions and read-only statements on drivers with dedicated read connections/streams. |
121
+ | `readsOnly(sql)` | Returns `true` only when a statement run outside a transaction can never write; enables parallel read execution under `concurrentReads` or `concurrentTransactions`. |
122
+ | `pipelinedTransactions` | Set `true` if a transaction connection accepts statements before prior responses arrive, allowing Atomic to pipeline statements and batch final writes with `COMMIT`. |
123
+
124
+ ### Transaction options and concurrency scopes
125
+
126
+ When Atomic calls `beginTransaction(options)`, `options` (`SqliteDriverTransactionOptions`) specifies how to lock and pipeline the transaction:
127
+
128
+ - **`concurrency` (`TransactionConcurrency`, always set):**
129
+ - `{ kind: "serial", domain?: string }` (default): runs as the sole writer for the whole database (when `domain` is absent) or for a named scope `domain` (a store passes a prefixed table name so independent domains or prefixes run in parallel on `concurrentTransactions` drivers).
130
+ - `{ kind: "fenced", audit, excludesSerial?: boolean }`: runs under `READ COMMITTED` and locks only the rows the body touches; with `excludesSerial: true`, also excludes whole-database `serial` transactions. SQLite drivers treat both kinds as `BEGIN IMMEDIATE`.
131
+ - **`readOnly`:** Opens a consistent read snapshot without taking a write lock. On `concurrentTransactions` drivers, a read-only transaction resolves once its reads finish and commits in the background (`close()` awaits it).
132
+ - **`lockWaitMs`:** Per-transaction lock wait override.
133
+ - **`relaxedDurability`:** When `true` (never set on read-only transactions), the write is repeatable and losing it in a server crash is harmless (such as a lease heartbeat), so the driver may acknowledge commit before flushing to disk (for example `synchronous_commit = off` on PostgreSQL).
134
+ - **Pipelining hints (`leading`, `leadingOnly`, `onCommit`, `lockIfLeadingFinds`):** On `pipelinedTransactions` drivers, Atomic may supply initial statements in `leading` to send alongside `BEGIN` (or commit immediately behind them when `leadingOnly: true`, calling `onCommit?.()` right before writing `COMMIT` so any later connection drop keeps `outcome: "unknown"`). `lockIfLeadingFinds` lets a `serial` domain transaction acquire locks in its first leading read only if a row matches. If any pipelined statement fails, `commit()` must fail so nothing commits.
135
+
136
+ ### Facade guarantees, retries, and queue bounds
137
+
138
+ `createSqliteDatabase` automatically copies `Uint8Array` bindings on call, rejects NUL (`U+0000`) strings with `StorageInvalidTextError`, converts safe-range integers to `number`, expires transaction handles once settled, wraps unclassified driver errors in `StorageUnavailableError` (redacted), and rejects failed rollbacks with `StorageRollbackError`.
139
+
140
+ - **Transient retries:** Recognized transient failures reject with `StorageTransientError`. Statements and batches that failed before writing make up to `STORAGE_TRANSIENT_RETRY_ATTEMPTS` (**5**) total attempts—1 initial attempt plus up to 4 retries—starting at 250 ms with exponential backoff and up to 20% jitter. Writes with `outcome: "unknown"` never retry automatically.
141
+ - **Transaction retries:** Transactions re-run their callback only when called with `{ retryTransientFailures: true }` (use only for side-effect-free callbacks; non-boolean values throw `StorageConfigError`). The first retry on a database emits a one-time process warning.
142
+ - **Call queue scheduling:** Without `concurrentTransactions`, calls execute one at a time. With `concurrentTransactions`, a call waits only for earlier unfinished calls it conflicts with: standalone statements/batches and whole-database `serial` transactions (no `domain`) conflict with all calls; `serial` transactions with a `domain` conflict only with matching domains (and whole-database calls); read-only transactions wait for earlier writes but run in parallel with other reads and later writes.
143
+ - **Stuck-call bounds:** While an active call stalls without settling, queued priority batches (`{ priority: true }`) fail after `STORAGE_PRIORITY_CALL_MAX_WAIT_MS` (10 seconds) and ordinary queued calls fail after `STORAGE_QUEUED_CALL_MAX_WAIT_MS` (60 seconds), both with `StorageUnavailableError` (with `concurrentTransactions`, only calls blocked behind the stalled call fail).
144
+ - **WAL helper for local SQLite files:** Call `switchToWriteAheadLog(exec, busyTimeoutMs)` from `@bastani/atomic/storage` to enable WAL with retries on `SQLITE_BUSY` and Windows `SQLITE_IOERR_TRUNCATE` (up to `min(5000, busyTimeoutMs)` ms).
145
+
146
+ You can also implement `SqliteDatabase` directly. Either way, validate your implementation with the [conformance suite](#adapter-conformance).
127
147
 
128
148
  ### Custom driver adapter example
129
149
 
130
- This example wraps the SQLite driver built into Node.js, `node:sqlite`, to show how `createSqliteDatabase` and `StorageAdapterModule` fit together. A real adapter wraps the client library of your database in the same way. Save it as `custom-adapter.ts`:
150
+ This complete example wraps Node.js's built-in `node:sqlite` driver to show how `createSqliteDatabase` and `StorageAdapterModule` fit together. Save as `custom-adapter.ts`:
131
151
 
132
152
  ```typescript
133
153
  import { DatabaseSync } from "node:sqlite";
@@ -192,7 +212,7 @@ export default {
192
212
  } satisfies StorageAdapterModule;
193
213
  ```
194
214
 
195
- The default export lets settings select this module as an [adapter](#selecting-an-adapter), with the file in `options.path`. From the SDK, call your open function directly and pass the database to `createAgentSession`:
215
+ Use it through settings as an [adapter](#selecting-an-adapter), or pass a caller-owned handle directly in the SDK:
196
216
 
197
217
  ```typescript
198
218
  import { createAgentSession } from "@bastani/atomic";
@@ -213,22 +233,77 @@ Multiple stores can share one caller-owned `database` without closing it.
213
233
 
214
234
  ### Custom `SessionStore` contracts
215
235
 
216
- Non-SQL backends can implement `openSessionStore` directly (each session has one writer):
236
+ Non-SQL backends implement `openSessionStore` returning a `SessionStore` (imported from `@bastani/atomic/storage`). Required methods are `create`, `append`, `replace`, `load`, `readHeader`, `delete`, `list`, `findMostRecent`, and `close`.
237
+
238
+ #### Required for `history://` reads
217
239
 
218
- - **Required for `history://`.** Implement `readEntryRange(id, query)` honoring `fromSeq`, `toSeq`, `seqs`, `maxChars`, `largeEntryBytes`, `skipTypes`, and `signal`. When `query.seqs` lists sequence numbers, return only the entries at those numbers. A `history://` search reads the entries it found, and the lines around them, this way, in one call. A store that returns the whole range instead still gives the same results, but reads more. Return freshly owned UTF-8 JSON buffers and `{ entries: [{ seq, entry }], throughSeq, lastSeq }` without falling back to whole-session `load()`.
219
- - **Optional fast-path methods.** Implementing these avoids loading entire sessions into memory (stores implementing only `load()` still work with higher memory use):
240
+ Implement `readEntryRange` to power `history://` reads and search without loading entire sessions into memory:
220
241
 
221
- | Method | Purpose |
242
+ ```typescript
243
+ import type {
244
+ SessionEntriesPage,
245
+ SessionEntriesQuery,
246
+ SessionStore,
247
+ } from "@bastani/atomic/storage";
248
+
249
+ // Query and response shapes:
250
+ // SessionEntriesQuery: {
251
+ // fromSeq: number;
252
+ // toSeq: number;
253
+ // seqs?: readonly number[]; // specific ascending sequence numbers to return in one call
254
+ // maxChars?: number; // stop page before exceeding this character budget (unless first entry)
255
+ // largeEntryBytes?: number; // byte threshold for streaming rawChunks on oversized entries
256
+ // skipTypes?: readonly string[]; // entry types to omit from the page
257
+ // signal?: AbortSignal;
258
+ // }
259
+ // SessionEntriesPage: {
260
+ // lastSeq: number;
261
+ // throughSeq: number;
262
+ // entries: readonly { seq: number; entry: SessionEntry; rawChunks?: readonly Uint8Array[]; rawFormatVersion?: number }[];
263
+ // }
264
+ ```
265
+
266
+ When `query.seqs` is provided, return only entries at those sequence numbers so `history://` search fetches matches and surrounding context in a single call (returning the whole `[fromSeq, toSeq]` range remains valid but reads more). Return freshly owned UTF-8 buffers for `rawChunks` rather than falling back to whole-session `load()`.
267
+
268
+ #### Optional capability hooks
269
+
270
+ | Hook / property | Purpose |
222
271
  | --- | --- |
223
- | `readTail(id, fromSeq)` | Header and entries from `fromSeq`, plus earlier live state and omitted usage totals |
224
- | `readRange(id, startSeq, endSeq)` | Inclusive 1-based range with `seqs`, `lastSeq`, and `epoch` |
225
- | `findLatestCompaction(id, leafId?)` | Latest active compaction boundary, sequence, and retained start |
226
- | `readResume(id, leafId?)` | Atomic resume snapshot (header, active branch from compaction, live state, omitted totals, `deliveryOpIds`, `lastSeq`, `lastEntryId`, `leafId`, `epoch`) |
227
- | `findEntrySeq(id, entryId)` | 1-based entry sequence, or `undefined` |
228
- | `readEntrySizes` / `readEntryChunk` / `readScanPage` | Byte-bounded streaming exports and remote page reads |
272
+ | `putBlob(sessionId, data)` / `getBlob(sessionId, hash)` | Store and retrieve SHA-256 content-addressed tool output files (`tool-output://`); omitted stores throw `SessionBlobError` (`blobs-unsupported`). |
273
+ | `snapshotBlobs` (`SnapshotBlobStore`) | Content-addressed storage for [worktree snapshots](/worktree-snapshots); omit to disable snapshots. |
274
+ | `openMarkers` (`SessionOpenMarkerStore`) | Cross-host open-session tracking (`put`, `remove`, `list`) for delete protection and upgrade gating; falls back to local agent-dir files when omitted. |
275
+ | `chatRecords` | Reader-only chat metadata (such as subagent child records) stored outside the conversation tree. |
276
+ | `searchIndex` (`SessionSearchIndex`) | Indexed full-text search backing `history://` queries. |
277
+ | `createFork(header, entries, source, location?)` | Optimized or receipt-preserving fork creation (return `undefined` to fall back to standard copying). |
278
+ | `updateHeader(header, options)` | Update session header metadata in place (rotates `epoch`) without rewriting entries. |
279
+ | `releaseSession(sessionId)` | Advisory hint that no live handle holds the session, allowing in-memory stores to spill history to disk until reopened. |
280
+
281
+ #### Optional fast-path read hooks
229
282
 
230
- - **Epochs and indexes.** Keep `epoch` constant on appends, rotate it on `replace` or recreate, and reject mismatched `epoch` writes with `SessionConflictError`. Mark read-only stores `readOnly: true` to skip cleanup writes. Set `estimated: true` on `SessionSummary` when metadata is unindexed.
231
- - **Forks and cloning.** `/fork`, `/clone`, and `SessionManager.forkFrom` stream entries in pages (same-store forks copy all branches; cross-store forks copy current context and mark the parent in another store; see [`/tree`, `/fork`, and `/clone`](/sessions#tree-fork-and-clone)).
283
+ Stores implementing only `load()` still work, but implementing these methods avoids loading full session history into RAM:
284
+
285
+ | Method signature | Purpose |
286
+ | --- | --- |
287
+ | `readTail(sessionId, fromSeq): Promise<SessionTail>` | Header and entries from `fromSeq`, plus prior live state and omitted usage totals. |
288
+ | `readRange(sessionId, startSeq, endSeq, expectedEpoch?): Promise<SessionEntryRange>` | Inclusive 1-based entry range returning `entries`, `seqs`, `lastSeq`, and `epoch`. |
289
+ | `findLatestCompaction(sessionId, leafId?): Promise<SessionCompactionPoint \| undefined>` | Latest active compaction boundary, its sequence, and retained tail start sequence. |
290
+ | `readResume(sessionId, leafId?, options?): Promise<SessionResume>` | Single-call resume snapshot: header, active branch from compaction, live state, omitted totals, `recovery` (`SessionRecoveryState` carrying `admissionDigests`, `intercomDeliveredIds`, and optional `deliveryOpIds` for deduplicating replayed deliveries), `lastSeq`, `lastEntryId`, `leafId`, and `epoch`. |
291
+ | `readResumeAt(sessionId, leafId, throughSeq, options?): Promise<SessionResume>` | Resume snapshot bounded to a specific historical watermark (`throughSeq`). |
292
+ | `findEntrySeq(sessionId, entryId): Promise<number \| undefined>` | 1-based sequence number for an entry ID, or `undefined`. |
293
+ | `readEntrySizes(sessionId, startSeq, endSeq, limit?): Promise<SessionEntrySizes>` | Entry byte sizes for sizing paged history reads before decoding payloads. |
294
+ | `readEntryChunk(reference, offset, bytes?): Promise<Uint8Array>` | Stream raw UTF-8 bytes of an `OversizedSessionEntry` in chunks (rejects stale `epoch`). |
295
+ | `readScanPage(sessionId, startSeq, endSeq, epoch, limit, options?): Promise<SessionScanPage>` | Single-read byte-bounded forward scan page (with header, `epoch`, `lastSeq`, `throughSeq`, and optional oversized references) used by exports and remote readers. |
296
+ | `readTreeOutline(sessionId, fromSeq, toSeq, epoch?)` | Body-free tree structure metadata for `/tree` navigation without reading message content. |
297
+ | `readBranchSpan(sessionId, cut)` | Contiguous range on a single branch without reading sibling branches. |
298
+ | `readSnapshotCut(sessionId, options?)` | Index lookup locating `worktree_snapshot` entries without scanning bodies. |
299
+ | `readSelectedPage(sessionId, seqs, epoch, options?)` | Byte-bounded page of specific ascending sequences (forward or backward). |
300
+ | `readForkWindow(sessionId, entryId, options?)` | Active branch window and labels needed to fork from a specific entry. |
301
+
302
+ #### Epochs, read-only stores, and forks
303
+
304
+ - **Epochs:** Keep `epoch` constant across `append()` calls, rotate it on `replace()`, `updateHeader()`, or recreation, and reject writes with a mismatched `epoch` using `SessionConflictError`.
305
+ - **Read-only and estimated summaries:** Mark read-only stores so cleanup writes are skipped, and set `estimated: true` on `SessionSummary` when metadata is unindexed.
306
+ - **Forks and cloning:** `/fork`, `/clone`, and `SessionManager.forkFrom()` stream entries in pages (same-store forks copy all branches; cross-store forks copy active context and set `parentInOtherStore: true`; see [`/tree`, `/fork`, and `/clone`](/sessions#tree-fork-and-clone)).
232
307
 
233
308
  ## Adapter conformance
234
309
 
@@ -245,11 +320,11 @@ registerSqliteDatabaseConformance({ describe, it }, "my adapter", withSubject);
245
320
  registerSqliteConnectionConformance({ describe, it }, "my adapter connections", withConnections);
246
321
  ```
247
322
 
248
- - `withSubject` creates a fresh database per test case and passes `{ database, reopen, withRollbackFailure }` to the callback, cleaning up afterward. `reopen()` closes and reopens the same persistent database, and `withRollbackFailure(error, callback)` injects a rollback failure for the duration of `callback`. The suite verifies parameter binding, exact 64-bit integers, binary snapshots, NUL rejection, transaction ordering and expiration, commit and rollback errors, reopening, and close semantics.
249
- - `withConnections` (for adapters supporting multiple connections to one database) opens two database handles on the same fresh database and closes both afterward. The suite verifies concurrent write queuing and event-loop responsiveness.
323
+ - `withSubject` creates a fresh database per test and passes `{ database, reopen, withRollbackFailure }` to the callback, cleaning up afterward (`reopen()` closes and reopens the persistent database; `withRollbackFailure(error, callback)` injects a rollback failure). Verifies parameter binding, 64-bit integer precision, binary snapshots, NUL rejection, transaction ordering/expiration, commit/rollback errors, reopen persistence, and close semantics.
324
+ - `withConnections` (for multi-connection adapters) opens two handles on one fresh database and closes both afterward. Verifies concurrent write queuing and event-loop responsiveness.
250
325
 
251
- Helper utilities exported from `@bastani/atomic/storage` for custom adapters:
326
+ Helper utilities exported from `@bastani/atomic/storage`:
252
327
 
253
- - `validateStoragePrefix(prefix, dialect?)` validates optional table prefixes (ASCII letters, digits, and `_`, not starting with `sqlite_`, case-insensitively). Passing `"postgres"` also enforces lowercase and `POSTGRES_MAX_STORAGE_PREFIX_LENGTH` (24).
254
- - `renderStorageIdentifiers("sessions", names, prefix)` returns a frozen map of table names with the `session_` prefix applied.
255
- - `assertStorageSchemaVersion(domain, found, supported)` throws `StorageSchemaVersionError` when stored and supported versions differ.
328
+ - `validateStoragePrefix(prefix, dialect?)`: validates optional table prefixes (ASCII letters, digits, `_`; cannot start with `sqlite_`, case-insensitively). Passing `"postgres"` also enforces lowercase and `POSTGRES_MAX_STORAGE_PREFIX_LENGTH` (24).
329
+ - `renderStorageIdentifiers("sessions", names, prefix)`: returns a frozen map of table names with the `session_` prefix applied.
330
+ - `assertStorageSchemaVersion(domain, found, supported)`: throws `StorageSchemaVersionError` when stored and supported versions mismatch.