Skip to main content
By default, Atomic persists sessions in local SQLite at ~/.atomic/workflows/journal.sqlite (session_ table prefix). In SDK applications, you can choose any of the four supported backends per session, share one database connection across multiple sessions, or manage lifecycle explicitly through createAgentSessionRuntime() and SessionManager. For CLI setup, database role administration, migrations, and custom drivers, see Storage.

Choose a backend

@bastani/atomic vs. @bastani/atomic/storage

@bastani/atomic re-exports the entire @bastani/atomic/storage surface, so host applications can import from either entrypoint. Import directly from @bastani/atomic/storage in custom storage adapters, scripts, or utilities that only need SQLite handles, path helpers, or storage errors without loading the full agent runtime.

createAgentSession() recipes

Every recipe below closes its session (and any caller-owned store or database handle) inside try/finally.

Local SQLite

Pass { kind: "sqlite", path, prefix? } when you want Atomic to open the file and close it on session.dispose(). Open the database yourself with openNodeSqliteDatabase() when multiple sessions share one connection.

JSONL directory

Selection objects ({ kind: "jsonl", dir }) open JsonlSessionStore.open(dir, { exactDirectory: true }), writing flat <timestamp>_<hash>.jsonl files directly inside dir (matching --session-dir). Calling JsonlSessionStore.open(dir) directly defaults exactDirectory to false, creating per-working-directory subdirectories (--<encoded-cwd>--/*.jsonl). Pass { exactDirectory: true } when you want both paths to read the same layout.

In-memory

Atomic offers three in-memory configurations with different release and rehydrate behavior:
  1. SessionManager.inMemory(): Ephemeral private session with no external store handle. Cannot be released and rehydrated (not-reopenable); combining it with releaseWhenIdle rejects immediately in createAgentSession().
  2. Caller-owned new MemorySessionStore(): Keeps session history in process RAM across session.release() and runtime.rehydrate() without writing anything to disk. You own the store and close it with await store.close().
  3. Disk-spilling memory store via resolveSessionStore(cwd, { agentDir, sessionStore: { kind: "memory" } }): Writes released session history to private owner-only files (0700/0600) under <agentDir>/released-history/ to free RAM while idle, cleaning up files on close and process exit (throws SessionSpillError if a spill file is missing or corrupt).
Passing { kind: "memory" } or storage: { memory: true } directly to createAgentSession() creates a session-owned memory store that is closed and discarded on dispose(), so it cannot be rehydrated after release.

PostgreSQL 16+

Install the optional adapter alongside @bastani/atomic:
Before connecting from an SDK host:
  • PostgreSQL version: Atomic needs PostgreSQL 16 or newer.
  • Table prefix rules: On PostgreSQL, prefix must be lowercase and at most 24 characters (POSTGRES_MAX_STORAGE_PREFIX_LENGTH). Uppercase or oversized prefixes fail with StoragePrefixError.
  • Owner-role migrations: Run atomic storage migrate once as the database owner role before connecting with a least-privilege runtime role. See Set up the database.
Option A — Caller-owned openPostgresDatabase() (recommended for SDK hosts sharing one pool): Pass a username-only URL (embedded passwords are rejected with credential-in-url). Supply password as a string or an async callback invoked per new connection for secret rotation, or use cloud IAM with auth: "azure-entra" | "aws-iam" | "gcp-iam" (omitting password — passing both fails with conflicting-token).
See @bastani/atomic-storage-postgres for maxConnections, statementTimeoutMs, idleTimeoutMs, listenUrl, schema, proxy, socket, sdkSearchPaths, TLS, and cloud IAM role setup. Option B — Adapter selection { kind: "adapter", module: POSTGRES_ADAPTER_PACKAGE, ... }: Use { kind: "adapter" } when you want Atomic to open and close the adapter per session, or to reuse the same selection shape as settings.json. Pass credentials through secrets ({ env }, { file }, or SDK-only inMemorySecret(value) whose value serializes as [redacted] and is never passed to child processes).
{ kind: "adapter" } does not search your application’s local node_modules. Atomic resolves adapter package names from user-scope packages installed with atomic install (~/.atomic/agent/npm), directories passed in DefaultResourceLoader({ additionalExtensionPaths: [packageRoot] }), or paths relative to agentDir. If your app installed @bastani/atomic-storage-postgres only with npm install, use Option A (openPostgresDatabase()), install it in user scope (atomic install npm:@bastani/atomic-storage-postgres), pass its directory via additionalExtensionPaths, or pass a resolved file path (fileURLToPath(import.meta.resolve(POSTGRES_ADAPTER_PACKAGE))).
Atomic 0.10.11 removed libSQL and Turso support, including @bastani/atomic-storage-libsql, teamProfileSelection(), and LIBSQL_ADAPTER_PACKAGE. To move sessions off libSQL, see Moving off libSQL.

createAgentSessionRuntime() and SessionManager with explicit stores

Neither createAgentSessionRuntime() nor createAgentSessionFromServices() takes sessionStore or storage directly. Both take a pre-opened sessionManager: SessionManager, and every later newSession(), switchSession(), fork(), and rehydrate() call inherits the store from sessionManager.getSessionStore(). Pass interactive: true to createAgentSessionRuntime() only when attaching an interactive UI; when omitted (false), resuming a worktree snapshot starts the first turn while the blueprint build runs in the background unless resume.waitForBlueprint is set. Call runtime.takeResumeNotices() after switchSession() or rehydrate() to retrieve resume warnings once. Use these explicit-store SessionManager methods to open, resume, and inspect sessions against any SessionStore (SqlSessionStore, JsonlSessionStore, MemorySessionStore, or a store from resolveSessionStore()):

Complete runtime recipe with services reuse, release(), and rehydrate()

Reuse the services argument passed to your CreateAgentSessionRuntimeFactory so runtime.rehydrate() shares the existing ResourceLoader, ModelRuntime, and SettingsManager when the rehydrated session matches cwd. Tear down resources in strict reverse order: runtime.dispose() → store.close() → database.close().

Store ownership and teardown rules

  • Strict close order: Always close in order await runtime.dispose() (or await session.dispose()) → await store.close() → await database.close().
  • SqlSessionStore.close() semantics: Closing a SqlSessionStore leaves the underlying caller-owned SqliteDatabase open so other stores can continue using it, and calling store.close() a second time throws StoreClosedError. (Stores opened by StorageProvider wrap close() idempotently and close provider-owned databases when the last store closes.)
  • Avoid implicit store ownership with SessionManager.create(cwd): Calling SessionManager.create(cwd) or SessionManager.continueRecent(cwd) without a SessionStore resolves and opens an internal store on your behalf, and neither createAgentSession() nor createAgentSessionRuntime() closes that internally opened store on dispose(). In long-lived SDK hosts, always open the SessionStore explicitly (or pass sessionStore/storage directly to createAgentSession()) so no store handles or worker threads leak.
  • Await every write: Await every SessionManager mutation (appendMessage, appendCustomEntry, appendSessionInfo, etc.) — there is no flush(). See SessionManager API.

resolveSessionStore(), StorageProvider, and precedence

resolveSessionStore(cwd, options?)

resolveSessionStore(cwd, options?: SessionStorageOptions) resolves storage from your options, process environment, settings, or default SQLite and returns an open SessionStore. You own the returned store and must call await store.close() when finished.

StorageProvider

Use new StorageProvider() from @bastani/atomic/storage when you want programmatic pool sharing across selections without reading settings.json:
  • Matching selections on StorageProvider share one opened database handle and close it when the last store closes.
  • Caller-owned { kind: "database", database } handles are never closed by StorageProvider.
  • Opening { kind: "memory" } through StorageProvider enables <agentDir>/released-history/ spilling on releaseSession().

sessionStore vs. storage precedence

When createAgentSession() chooses a session store, the first source set wins:
  1. sessionManager (caller-owned SessionManager).
  2. sessionStore (either a SessionStore instance or a tagged StorageSelection: { kind: "sqlite", path, prefix? }, { kind: "jsonl", dir }, { kind: "memory" }, { kind: "database", database, prefix? }, or { kind: "adapter", module, options?, secrets?, prefix? }).
  3. storage (settings.json shape: { path, prefix? }, { database, prefix? }, { memory: true }, or { adapter, options?, secrets?, prefix? }. Does not accept { dir }; use sessionStore: { kind: "jsonl", dir } for JSONL).
  4. Process overrides (ATOMIC_SESSIONS_STORAGE, ATOMIC_STORAGE, --storage, --storage-file; see Selecting storage per process).
  5. Settings (sessions.storage, then top-level storage).
  6. Default local SQLite (~/.atomic/workflows/journal.sqlite).
A configured persistent store never silently falls back to memory when it fails to open.

Handling StorageError and Session*Error

Branch on exported guards and error classes rather than parsing error messages:
For the full list of storage error classes and cross-process serializeStorageError() / rehydrateStorageError(), see Storage errors and Session and storage errors.

Testing custom storage adapters

If you implement a custom SqliteDatabase driver or storage adapter, import registerSqliteDatabaseConformance() from @bastani/atomic/storage/testing to run Atomic’s conformance test suite (parameter binding, binary blobs, transactions, rollbacks, reopening, and typed error contracts) inside your own test runner:

Operator storage setup

PostgreSQL roles, TLS, proxies, poolers, migrations, atomic storage commands, and custom drivers.

@bastani/atomic-storage-postgres

PostgreSQL adapter options, PgBouncer auto-detection, cloud IAM, and SQL helpers.

Use the TypeScript SDK

createAgentSession(), workspaces, Intercom policies, and lifecycle hooks.

SessionManager API

Entry types, tree navigation, and session append methods, plus SDK API reference.