Selecting an adapter
An adapter module’s default export satisfiesStorageAdapterModule:
sessions.storage or top-level storage in settings, 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, host extension directories, or the agent directory—never from an embedding app’s node_modules.
Match installation method to how you open the adapter:
- Direct SDK handles (
{ kind: "database", database }): install the adapter in your app withnpm install, call its opener (such asopenPostgresDatabase()), and pass the handle tosessionStore: { kind: "database", database, prefix? }orSqlSessionStore.open(database, { prefix? }). See SDK session storage. - Adapter-resolved selections (
{ kind: "adapter", module },settings.json, orATOMIC_STORAGE): install in user scope withatomic install npm:<package>(without-l), or register a local package directory via--extension <dir>orDefaultResourceLoader({ additionalExtensionPaths }).
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.Options, secrets, and lifecycle
optionsandsecrets:optionsacceptsstring | number | boolean | null.secretsmaps secret names to{ env },{ file }, or (SDK only)inMemorySecret(value)({ value }), overriding same-named keys inoptions. Atomic strips one trailing\nor\r\nfrom{ file }secrets and leaves other whitespace intact.inMemorySecret()serializes as[redacted]and is refused outside the SDK (in-memory-secret-unsupported).contextandliveSecrets:contextsupplies{ agentDir, domain: "sessions" | "intercom", signal?, secret(name) }. Adapters that re-read rotating credentials per connection declareliveSecretsonStorageAdapterModule(for exampleliveSecrets: ["password"]): Atomic omits those names fromoptionsand expects the adapter to callawait context.secret(name), which throwsStorageConfigError(secret-missing) if absent fromsecrets.- Hook priority and errors: When an adapter exports both
openDatabaseandopenSessionStore,openSessionStoretakes priority for"sessions"whileopenDatabasehandles"intercom". Missing hooks throwStorageConfigError(adapter-domain-unsupported); module load failures throwStorageAdapterLoadError; connection failures throwStorageUnavailableError. - 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).StorageProvidershares 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 withcleanupCauseset.
Adapters from Atomic packages
An Atomic package can bundle adapters and their driver dependencies underatomic.storageAdapters in package.json:
atomic install npm:@example/atomic-mydb and reference it by package name:
<package>/<file-stem> (filename without extension, such as @example/atomic-mydb/mydb-adapter).
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>".
Resolution order for bare adapter package names:
- Extension package directories passed to the process (or inherited from the launching Atomic process).
- Packages in effective global settings (including legacy
~/.pi/agent/settings.jsonfor the default agent directory). Project packages are never searched. - Module resolution from the agent directory.
Bring your own driver
Wrap any SQLite-compatible (or PostgreSQL-dialect) driver into aSqliteDatabase with createSqliteDatabase(driver) from @bastani/atomic/storage. Driver hooks may return sync values or promises.
Required SqliteDriver hooks
Optional resilience, metadata, and concurrency hooks
Transaction options and concurrency scopes
When Atomic callsbeginTransaction(options), options (SqliteDriverTransactionOptions) specifies how to lock and pipeline the transaction:
concurrency(TransactionConcurrency, always set):{ kind: "serial", domain?: string }(default): runs as the sole writer for the whole database (whendomainis absent) or for a named scopedomain(a store passes a prefixed table name so independent domains or prefixes run in parallel onconcurrentTransactionsdrivers).{ kind: "fenced", audit, excludesSerial?: boolean }: runs underREAD COMMITTEDand locks only the rows the body touches; withexcludesSerial: true, also excludes whole-databaseserialtransactions. SQLite drivers treat both kinds asBEGIN IMMEDIATE.
readOnly: Opens a consistent read snapshot without taking a write lock. OnconcurrentTransactionsdrivers, a read-only transaction resolves once its reads finish and commits in the background (close()awaits it).lockWaitMs: Per-transaction lock wait override.relaxedDurability: Whentrue(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 examplesynchronous_commit = offon PostgreSQL).- Pipelining hints (
leading,leadingOnly,onCommit,lockIfLeadingFinds): OnpipelinedTransactionsdrivers, Atomic may supply initial statements inleadingto send alongsideBEGIN(or commit immediately behind them whenleadingOnly: true, callingonCommit?.()right before writingCOMMITso any later connection drop keepsoutcome: "unknown").lockIfLeadingFindslets aserialdomain transaction acquire locks in its first leading read only if a row matches. If any pipelined statement fails,commit()must fail so nothing commits.
Facade guarantees, retries, and queue bounds
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.
- Transient retries: Recognized transient failures reject with
StorageTransientError. Statements and batches that failed before writing make up toSTORAGE_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 withoutcome: "unknown"never retry automatically. - Transaction retries: Transactions re-run their callback only when called with
{ retryTransientFailures: true }(use only for side-effect-free callbacks; non-boolean values throwStorageConfigError). The first retry on a database emits a one-time process warning. - Call queue scheduling: Without
concurrentTransactions, calls execute one at a time. WithconcurrentTransactions, a call waits only for earlier unfinished calls it conflicts with: standalone statements/batches and whole-databaseserialtransactions (nodomain) conflict with all calls;serialtransactions with adomainconflict 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. - Stuck-call bounds: While an active call stalls without settling, queued priority batches (
{ priority: true }) fail afterSTORAGE_PRIORITY_CALL_MAX_WAIT_MS(10 seconds) and ordinary queued calls fail afterSTORAGE_QUEUED_CALL_MAX_WAIT_MS(60 seconds), both withStorageUnavailableError(withconcurrentTransactions, only calls blocked behind the stalled call fail). - WAL helper for local SQLite files: Call
switchToWriteAheadLog(exec, busyTimeoutMs)from@bastani/atomic/storageto enable WAL with retries onSQLITE_BUSYand WindowsSQLITE_IOERR_TRUNCATE(up tomin(5000, busyTimeoutMs)ms).
SqliteDatabase directly. Either way, validate your implementation with the conformance suite.
Custom driver adapter example
This complete example wraps Node.js’s built-innode:sqlite driver to show how createSqliteDatabase and StorageAdapterModule fit together. Save as custom-adapter.ts:
database without closing it.
Custom SessionStore contracts
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.
Required for history:// reads
Implement readEntryRange to power history:// reads and search without loading entire sessions into memory:
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().
Optional capability hooks
Optional fast-path read hooks
Stores implementing onlyload() still work, but implementing these methods avoids loading full session history into RAM:
Epochs, read-only stores, and forks
- Epochs: Keep
epochconstant acrossappend()calls, rotate it onreplace(),updateHeader(), or recreation, and reject writes with a mismatchedepochusingSessionConflictError. - Read-only and estimated summaries: Mark read-only stores so cleanup writes are skipped, and set
estimated: trueonSessionSummarywhen metadata is unindexed. - Forks and cloning:
/fork,/clone, andSessionManager.forkFrom()stream entries in pages (same-store forks copy all branches; cross-store forks copy active context and setparentInOtherStore: true; see/tree,/fork, and/clone).
Adapter conformance
Validate anySqliteDatabase adapter against the conformance suites exported from @bastani/atomic/storage/testing:
withSubjectcreates 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.withConnections(for multi-connection adapters) opens two handles on one fresh database and closes both afterward. Verifies concurrent write queuing and event-loop responsiveness.
@bastani/atomic/storage:
validateStoragePrefix(prefix, dialect?): validates optional table prefixes (ASCII letters, digits,_; cannot start withsqlite_, case-insensitively). Passing"postgres"also enforces lowercase andPOSTGRES_MAX_STORAGE_PREFIX_LENGTH(24).renderStorageIdentifiers("sessions", names, prefix): returns a frozen map of table names with thesession_prefix applied.assertStorageSchemaVersion(domain, found, supported): throwsStorageSchemaVersionErrorwhen stored and supported versions mismatch.