Storage
MemoryAdapter, IndexedDBAdapter, SupabaseAdapter — pick the one that matches the environment and wire it into SessionRuntime.
@pleach/core ships storage adapters that all implement the same
StorageAdapter interface. The application code that calls
runtime.createSession() or runtime.executeMessage() is the same
regardless of which adapter is wired.
import {
MemoryAdapter,
IndexedDBAdapter,
SupabaseAdapter,
createSupabaseAdapter,
type SupabaseAdapterConfig,
// Provider-agnostic Postgres — inject any pg-shaped client
PgStorageAdapter,
createPgStorageAdapter,
type PgStorageAdapterConfig,
type PgClientLike,
} from "@pleach/core/sessions";Cross-restart durability requires wiring an adapter
The runtime defaults to MemoryAdapter — everything lives in process
memory and disappears on restart. Session restore/resume across a restart
only works once you wire a durable StorageAdapter into
SessionRuntimeConfig.storage. The recommended provider-agnostic default is
PgStorageAdapter (inject
your own Postgres client); SupabaseAdapter is the hosted-Supabase option and
IndexedDBAdapter the browser option. Durable persistence of the event log
is a separate wiring step — pair with
createPgEventLogWriter as eventLogWriter.
createSupabaseAdapter(supabase, options?) takes the Supabase client as its
first argument and the optional SupabaseAdapterConfig fields as its
second. It is a thin wrapper over new SupabaseAdapter({ client, ...options });
the two build the same adapter. The adapter reads and writes through the
client you pass, so row-level security follows that client's own JWT.
@pleach/core/sessionsThe state-and-persistence cluster
Storage adapter is one of three concepts paired with checkpointing (the rewind axis) and sync version vector (the concurrent-writer axis). The cluster sits below the execution graph and above the schema bundle; together the three carry session state across restarts, rewinds, and concurrent writers. The full triplet framing lives at Concept clusters → State-and-persistence; the rest of this page is the deep dive on the adapter.
Picking an adapter
| Adapter | Environment | When to reach for it |
|---|---|---|
MemoryAdapter | Any | Tests, local dev, ephemeral demos — non-durable (default; lost on restart) |
IndexedDBAdapter | Browser | Offline-first PWAs, browser extensions, multi-device drafts |
PgStorageAdapter | Server (Node) | Recommended durable default. Any Postgres — node-postgres, Neon, RDS, pglite, Supabase's underlying pg — via an injected PgClientLike. See PgStorageAdapter. |
SupabaseAdapter | Server (Node) | Hosted Supabase specifically — PostgREST client, Realtime, row-level security through the client's own JWT |
| pglite (local) | Server (Node) | Durable local dev — chats survive a restart with no cloud account. Built into pleach dev --sql; see Durable local dev. |
All three implement the same interface — swapping is a one-line
change at runtime construction. The line is the storage field on
SessionRuntimeConfig: replace new MemoryAdapter() with
createSupabaseAdapter(supabase) and every call site
that already runs against runtime.createSession() or
runtime.executeMessage() keeps working. The StorageAdapter
interface is the contract that makes this swap safe — see
Common interface below for the exact shape.
MemoryAdapter
Zero config; everything lives in process memory and disappears on restart.
import { SessionRuntime } from "@pleach/core";
import { MemoryAdapter } from "@pleach/core/sessions";
const runtime = new SessionRuntime({
storage: new MemoryAdapter(),
userId: "user_123",
});This is also what a zero-config new SessionRuntime() falls back to —
pass no storage and no checkpointer and the runtime defaults to
MemoryAdapter + MemorySaver, warning on stderr that it did so.
Concretely: state lives in a Map<sessionId, SessionState> on the
adapter instance, listSessions is an iteration over that map's
values with the filter predicate applied in-process, and the next
restart starts from empty. Use it for unit tests that need a clean
session per beforeEach without a database round trip.
IndexedDBAdapter
Persists sessions to the browser's IndexedDB store. Survives page reloads; available offline.
import { SessionRuntime } from "@pleach/core";
import { IndexedDBAdapter } from "@pleach/core/sessions";
const runtime = new SessionRuntime({
storage: new IndexedDBAdapter({ databaseName: "pleach-sessions" }),
userId: currentUser.id,
clientId: getOrCreateClientId(),
});The constructor takes three options:
| Option | Default | Effect |
|---|---|---|
databaseName | "harness-sessions" | The IndexedDB database name |
version | 1 | The IndexedDB schema version; bump it to trigger an upgrade on next open |
dbName | — | Deprecated alias of databaseName. databaseName wins when both are set |
The adapter opens IndexedDB with a 5-second timeout — if another tab
holds an open connection with a different schema, the open fires
onblocked and the next call rejects with
IndexedDB open timed out — database may be blocked or unavailable.
The store auto-indexes on userId, organizationId, updatedAt, and
lastActiveAt so listSessions filters resolve without a table scan.
Pair with IndexedDBSaver for offline checkpointing and the
client-side sync coordinator to push changes to a server adapter
when the network returns — see Checkpointing
and @pleach/core/sync.
SupabaseAdapter
Persists sessions to a Postgres database via the Supabase client. RLS-bound when constructed from a per-request client.
import { createClient } from "@supabase/supabase-js";
import { SessionRuntime } from "@pleach/core";
import { createSupabaseAdapter } from "@pleach/core/sessions";
const supabase = createClient(
process.env.SUPABASE_URL!,
process.env.SUPABASE_SERVICE_ROLE_KEY!,
);
const runtime = new SessionRuntime({
storage: createSupabaseAdapter(supabase),
userId: req.user.id,
organizationId: req.user.orgId,
});SupabaseAdapterConfig takes client (required, passed first to createSupabaseAdapter) and three optional fields. Pass the optional ones as the second argument:
| Field | Default | Effect |
|---|---|---|
tableName | the shipped sessions table | Override if you renamed the table in your migrations |
enableRealtime | false | Subscribe via Supabase Realtime for cross-process change fan-out |
chatSessionLink | falls back to a registered link factory, if any | Inject a ChatSessionLink to mirror chatId → sessionId into the chat-to-session link table |
Schema
The adapter expects the harness schema bundle to be applied. Scaffold it once per project:
npx @pleach/core schema --apply --target ./supabase/migrationsThen run your usual Supabase migration flow (supabase db push,
or apply each *.sql by hand with psql). The bundle ships
CREATE ... IF NOT EXISTS DDL so re-running is safe.
Browser vs server clients
| Constructed from | Authority | Use case |
|---|---|---|
SUPABASE_ANON_KEY | RLS-bound to the signed-in JWT | Direct-from-browser writes |
SUPABASE_SERVICE_ROLE_KEY | Bypasses RLS | API routes, server-rendered pages |
userId and organizationId on the runtime are the scoping fields
the RLS policies in the schema bundle key against. Service-role
clients still need to set them so the audit ledger attributes
rows correctly.
PgStorageAdapter — provider-agnostic Postgres
The recommended durable default when you are not on hosted Supabase.
PgStorageAdapter implements the same StorageAdapter interface as
SupabaseAdapter, but talks raw SQL through an injected PgClientLike —
so it runs on any Postgres provider. PgClientLike is a minimal structural
type; anything with a parameterized query(sql, params) that resolves to
{ rows } satisfies it:
interface PgClientLike {
query<Row>(sql: string, params?: readonly unknown[]): Promise<{ rows: Row[] }>;
}That one seam is the "tune to any provider" mechanism — you construct your
own driver and pass it in. @pleach/core adds no Postgres driver as a
dependency: you own the client.
import { Pool } from "pg";
import { SessionRuntime } from "@pleach/core";
import { createPgStorageAdapter } from "@pleach/core/sessions";
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const runtime = new SessionRuntime({
storage: createPgStorageAdapter(pool),
userId: req.user.id,
});import { Pool } from "@neondatabase/serverless";
import { createPgStorageAdapter } from "@pleach/core/sessions";
const storage = createPgStorageAdapter(
new Pool({ connectionString: process.env.DATABASE_URL }),
);import { createPgStorageAdapter } from "@pleach/core/sessions";
// Bring your own client — RDS Data-API shim, a pooled pg client, pglite, …
const storage = createPgStorageAdapter(myPgClient, {
tableName: "my_sessions", // optional override
schemaName: "public", // optional schema qualifier
});PgStorageAdapterConfig accepts:
| Field | Default | Effect |
|---|---|---|
client | (required) | The injected PgClientLike — your Postgres driver |
tableName | the shipped sessions table | Override if you renamed the table |
schemaName | (unqualified) | Qualify the table (e.g. "pleach") for a namespaced deployment |
Semantics match SupabaseAdapter: full SessionState persisted as a JSONB
state column, soft delete via a deletion timestamp, and optimistic concurrency via
conditionalUpdate (a version-guarded UPDATE … RETURNING id, so it is
portable across drivers regardless of their affected-row-count conventions).
Schema
PgStorageAdapter targets the shipped sessions DDL —
the base sessions migration, the
same vanilla-Postgres-portable bundle pleach init scaffolds. Apply it once
(the DDL is CREATE … IF NOT EXISTS, so re-running is safe), then point the
adapter at it. Do not hand-write a divergent schema.
The shipped DDL types id (and the organization id) as UUID, so session.id
and organizationId must be UUID-shaped strings — the runtime mints UUIDv7
session ids by default. If you need non-UUID ids, point the adapter at a table
whose id columns are TEXT.
Durable event-log writer
Persisting sessions is one axis; persisting the event log (the source of
truth for restore, replay, and audit) is a separate one. Pair the adapter with
createPgEventLogWriter — the provider-agnostic sibling of the Supabase-bound
EventLogWriter, backed by the same PgClientLike:
import { createPgStorageAdapter } from "@pleach/core/sessions";
import { createPgEventLogWriter } from "@pleach/core/eventLog";
import { SessionRuntime } from "@pleach/core";
const runtime = new SessionRuntime({
storage: createPgStorageAdapter(pool),
eventLogWriter: createPgEventLogWriter(pool, {
tenant: { id: "acme" }, // optional multi-tenant attribution
}),
userId: req.user.id,
});It writes append-only rows to the shipped event-log table
(the base event-log migration), stamping a per-chat
sequence number, a payload hash, the tenant, the domain and kind, and
the severity. Writes are fire-and-forget (write() never throws into a hot
path; failures route to onError); flush() awaits the serialized write tail.
It stamps the hash chain (each row's hash and its predecessor's hash) on
every row that carries a chatId, in the same form EventLogWriter writes, so
verifyChainForChat verifies a chat either writer wrote.
| Option | Default | Effect |
|---|---|---|
stampChain | true | false leaves the hash columns empty. Only safe for chats with no chained rows yet; an unchained row above a chained one fails verification |
chainSigningKey | none (unkeyed v1) | A Buffer, a hex/base64 string or { secret, keyId }. New chats chain under keyed v2 (HMAC-SHA256); a chat with v1 rows stays v1 |
sequenceAllocator | "auto" | "auto" uses the database allocator functions from the base migrations when installed and callable, else the in-process allocator. "in-process" never calls them |
It doesn't write the v3 chain: it refuses a row for a chat already on v3
or an unknown canon, and charges it to flush() and onError. A chat that
holds rows from before chaining starts its chain on a segment anchor; verify
it with verifyChainForChat({ firstChainedSequenceNumber }), or the verifier
reports it as intact but discontinuous.
Concurrency: which allocator you get
With "auto", the writer calls a database function that reserves the next
ordinal and the chain head under one advisory lock and, after each chained
insert, a second function that commits the new chain head (compare-and-swap). Ordinals are
then unique across writer instances, and a row whose predecessor is still in
flight elsewhere starts a marked segment instead of forking the chain.
"auto" uses those functions only for the default table in the default or
public schema, and EXECUTE is granted to service_role only. A missing
function or grant switches the instance to the in-process allocator (cold-start
max-plus-one) for the rest of its life, with one warning. That allocator is
race-free within one instance but not across instances: two concurrent
writers for one chat can duplicate an ordinal, and the verifier then refuses
the chat. In a serverless or multi-pod deployment without those
database functions, guarantee one writer per chat. Mixing allocators on one chat voids
the cross-instance guarantee. The chat_id/session_id you pass must be
UUID-shaped (the shipped event-log columns are UUID).
Common interface
Every adapter implements the same shape. You rarely call it
directly — SessionRuntime does — but the type is exported for
testing and for writing custom adapters:
import type { StorageAdapter } from "@pleach/core";
interface StorageAdapter {
createSession(session: SessionState): Promise<void>;
getSession(id: string): Promise<SessionState | null>;
updateSession(id: string, session: SessionState): Promise<void>;
deleteSession(id: string): Promise<void>;
listSessions(filter?: SessionFilter): Promise<SessionSummary[]>;
conditionalUpdate?(
id: string,
session: SessionState,
expectedVersion: number,
): Promise<boolean>;
}listSessions returns SessionSummary[] — the light shape for
sidebar rendering, not the full SessionState. The summary carries
id, title, userId, organizationId, updatedAt, and
lastActiveAt; rendering 200 entries in a sidebar reads no message
bodies and no channel state. conditionalUpdate is optional.
It is a version-guarded write that returns false when the stored
version no longer matches. Today only session import calls it, and a
false there fails the import with a CONFLICT error. The runtime's
own session writes go through updateSession and never call it, and no
3003 error comes from it. Event log and checkpoint writes go
through their own interfaces (EventLogWriter, Checkpointer),
not through StorageAdapter.
For any Postgres store, reach for
PgStorageAdapter first —
inject your driver rather than reimplementing the interface. Build your own
adapter (Redis, DynamoDB, SQLite) only for non-Postgres stores by implementing
this interface against your store of choice. Pass it as storage on the
runtime config — application code stays unchanged.
Cache adapter
The optional cache field accepts a second StorageAdapter. The
cache is write-through on session create, update and resume: the
runtime writes the primary store, then writes the same state to the
cache. Single-session lookups are read-through: the runtime reads the
cache, falls back to the primary store on a miss, and fills the cache
from the hit. A delete drops the session from the cache. listSessions
always reads the primary store, never the cache. Typical pairing:
SupabaseAdapter as primary, an IORedisAdapter (BYO) as cache.
A concrete walk-through for a knowledge-base assistant: a user
opens a chat sidebar; the React layer reads
listSessions({ userId: "user-7", organizationId: "org-acme" }),
which reads Supabase, and a lookup of "session-018f-..." hits the
cache for the active session without a Postgres round trip. When the
next executeMessage mutates the session, the runtime writes Supabase
and then the cache, so the next lookup returns the new state.
Durable local dev
You don't need a cloud account to see durability work. pleach dev --sql
backs the playground route with a local pglite
(Postgres-in-WASM) store — so chats and checkpoints survive a server
restart, with no Docker and no Supabase project:
npm install @electric-sql/pglite # optional peer, one time
npx @pleach/core dev --sql # store lives under ./.pleach-dev-sqlBecause pglite is real Postgres, this is the only local option that
demonstrates the enforced multi-tenant boundary end-to-end: the same
current_tenant() GUC function + row-level-security policy that
SupabaseAdapter relies on in production runs in-process, so a cross-tenant
read is refused by the database, not just filtered in application code.
The same store backs a test battery in Pleach's CI, which asserts nine durable properties the in-memory default cannot show headlessly:
- Restart-restore reconstructed in-graph — a fresh
SessionRuntimepointed at the durable store callsresumeSession, then a follow-up turn continues the conversation through real graph execution (not a detachedreconstructSessionStatefold). - Per-tenant SQL cost rollup — a group-by-tenant query over the event log.
- RLS tenant isolation — the database refuses a cross-tenant read.
- Durable checkpoints — survive a restart at
_durability.level: "disk". @pleach/observepostgres()destination — each provider call recorded as a SQL-queryable row in the destination's calls table.- Time-travel fork —
TimeTravelAPI.forkcross-session lineage survives a restart. - SQL-queryable audit ledger — per-tenant FinOps and SOC2 (every call classified) rollups over the call ledger.
- Tamper-evident hash chain — a linkage verifier catches a deleted/reordered row; a content-hash recompute catches a mutated payload.
- Deterministic replay —
@pleach/replay'sReplayClientfolds the durable log over the injected reader; fold-from-DB byte-equalshydrateFromEvents, andcreateStrictHandleReplayconfirms independent replays don't diverge.
It's the executable reference for wiring your own SQL StorageAdapter +
Checkpointer + event-log writer + event reader (the agnostic
HarnessEventReader behind
runtime.events.iterate) + audit ledger + observe destination.
For SQLite, @pleach/core/store ships createSqliteDurableStore(dbPath), a
ready-made on-disk DurableStore (see below).
The Custom storage adapter recipe
shows how to hand-roll the same shape for another engine — note that SQLite can
attribute cost per tenant but cannot enforce RLS isolation; that needs
Postgres/pglite.
openSqliteRunRecords(dbPath) from @pleach/core/store adds two
opt-in SQLite tiers that createSqliteDurableStore doesn't apply: the
response tape (each provider response, for replay) and probe batches.
A local run then writes the same records a Postgres deployment writes,
and both stores can share one file. The probe-batches tier keeps one row
per batch that has probes. Batches with nothing in them, such as
heartbeats, fold into one row per chat, route, UTC hour and deployment,
and that row counts the requests. The handle's createTapeWriter,
createTapeReader and tapeRefs build the usual tape writer and
reader. Two limits: the tape writer drops a row it fails to write and
reports it to onError, so pass one that records failures when the tape
must be complete. It needs SQLite 3.35 or newer and throws
SqliteRunRecordsVersionError on an older one.
Key/value store: SupabaseStore
SupabaseStore from @pleach/core/store is the Supabase-backed
BaseStore: namespaced get, put, delete and, with an embedder, vector
search. Build one store per process and bind each request's principal
with withOwner:
import { SupabaseStore } from "@pleach/core/store";
const shared = new SupabaseStore(supabase, { embed, embedOnPut: true });
// Per request: same client, embedder and options, owner fixed for this view.
const store = shared.withOwner({ userId, organizationId });
await store.put(["notes", userId], "pref", { theme: "dark" });withOwner leaves the shared store owner-less, so one request's owner
never leaks into another's writes. organizationId must be a canonical
hyphenated UUID; anything else throws a TypeError, including on a
store used only for reads. An overwrite keeps the row's original
creation time.
The embedding column holds 1536 dimensions by default
(DEFAULT_EMBEDDING_DIMENSIONS). A vector of any other length, or one
holding a non-finite number, is not sent: the row is written without
an embedding and the store warns once. If you widened the column, pass
embeddingDimensions with its width. embedText chooses the text that
gets embedded (default: the value as JSON).
You can also fix the owner at construction with the owner option
({ userId?, organizationId? }). With it, put() writes the owner
columns. A field you leave out isn't sent, so an overwrite keeps the
row's existing value. Without owner, both columns stay NULL.
Re-apply the base schema tier before passing owner, since the
columns are new.
Paging a search
A search with no query returns rows in (namespace, key) order. The
namespace compares as its /-joined string and the key by Unicode code
point. The order doesn't depend on when a row was written, so deleting
and re-putting a row leaves it where it was. SupabaseStore,
MemoryStore and the SQLite store all give this order.
Two flags on the store say how far you can page:
searchPagingStablemeans repeated query-less calls walk one sequence,offsetmoves along it, and a short page means no rows remain. A row outside the requested namespace fails the page with an error rather than being dropped.searchKeysetPagingmeans the store honoursSearchOptions.after, a{ namespace, key }cursor (typeSearchCursor). It returns only rows strictly after the cursor. Afilterapplies first, then the cursor, thenoffsetandlimit.
import type { SearchCursor } from "@pleach/core/store";
let after: SearchCursor | undefined;
for (;;) {
const page = await store.search(["skills", orgId], { limit: 50, after });
handle(page);
if (page.length < 50) break;
const last = page[page.length - 1];
after = { namespace: last.namespace, key: last.key };
}Paging by cursor means a row deleted between two reads can't push a
later row out of reach. SupabaseStore refuses a cursor key that
contains a double quote or a backslash. A store without the flag ignores
after. A search with a query is unchanged: rows sort by score, ties
by namespace and then key.
DurableStore: one binding for the whole family
StorageAdapter is only the session-CRUD surface. A hosted agent also
needs a checkpointer, an event-log writer, an event reader, and a
recall/audit read path. DurableStore (from @pleach/core/store)
unifies all five behind one binding — it's the db arm the
standalone agent
takes.
import {
createMemoryDurableStore,
type DurableStore,
} from "@pleach/core/store";The interface bundles five surfaces:
| Member | Surface |
|---|---|
storage | Session CRUD (StorageAdapter) |
checkpointer | Checkpoints + time-travel (Checkpointer) |
eventLogWriter | Durable audit-ledger writes |
eventReader | runtime.events.iterate fold source |
events | Recall / audit-trail read (query(sessionId, filter?)) |
createMemoryDurableStore() is a zero-dependency in-memory
implementation — it composes MemoryAdapter, MemorySaver, and a
bounded event buffer (maxEventRows, default 10,000). Recall, the audit
ledger, and checkpoints all work with no external database; state
resets on process restart. It's the default when the standalone agent
is constructed without a db, which is what lets recall work with no
Supabase. Its event buffer keeps no row hashes and is not a chain
reader, so verifyChainForChat cannot check a memory-store chat. Use
createSqliteDurableStore (below) or a persistent store when you need
a verifiable chain.
Pass a real db — a DurableStore backed by SupabaseAdapter /
PgStorageAdapter and a persistent event log — to keep state across
restarts. The five members are the same interface either way.
For a single node with no external database,
createSqliteDurableStore(dbPath, { tenant?, now? }) is the on-disk
sibling of the memory store: one SQLite file backs sessions,
checkpoints, the event log and recall, and survives restarts. On
Node 22.5 or later it uses the built-in node:sqlite module, so no
native dependency is needed. On older Node it falls back to the
optional native better-sqlite3 dependency. Either driver is loaded
only when you call the factory, so importing @pleach/core/store
stays dependency-free.
import { createSqliteDurableStore } from "@pleach/core/store";
import { createPleachAgent } from "@pleach/core/quickstart";
const agent = createPleachAgent({
context: process.env.OPENROUTER_API_KEY,
db: createSqliteDurableStore("./pleach.db"),
});Composing a DurableStore from adapters you already hold
A SQL-backed host usually has the pieces already — a storage adapter,
a checkpointer, an event-log writer. composeDurableStore groups them
into one DurableStore binding without hand-shaping the object:
import { composeDurableStore } from "@pleach/core/store";
const db = composeDurableStore({
storage, // StorageAdapter
checkpointer, // Checkpointer
eventLogWriter, // durable audit-ledger writes
eventReader, // runtime.events.iterate fold source
events, // recall / audit-trail read
blob, // optional — offloaded-result write surface
close, // optional — teardown hook
});blob is a sixth, optional member: a BackendWriteSurface for
offloaded tool-result payloads too large to inline. When you don't
need durable blobs, createMemoryBlobStore() returns a zero-dependency
in-memory MemoryBlobStore (write, read, size) that satisfies
the surface for dev and test.
Where to go next
Async tasks
Long-running job dispatch + cancellation — the manager, the executor contract, and the per-thread reducer.
Cache & memoization
Runtime-side cache for prepared LLM inputs — the CacheBackend contract, the always-on memory default, and the four fingerprint gaps that keep hits correct across modes.