@noetaris/harness-store
v0.6.3
Published
Session store implementations for @noetaris/harness
Readme
@noetaris/harness-store
Session store implementations for @noetaris/harness. This package provides the SessionStore interface implementations needed to persist and manage agent execution state.
Overview
@noetaris/harness-store implements session persistence for the Harness agent framework. It decouples storage mechanics from the core harness, allowing you to choose or implement the storage backend that fits your application.
Currently provides:
- InMemorySessionStore — In-memory implementation for development, testing, and ephemeral sessions
- LocalFileSessionStore — File-system implementation that persists sessions as JSONL files, surviving process restarts
A run that stands on an error is saved with it: finalState.$error (also in checkpoint rows) holds the error as @noetaris/harness copied it, with its name, message, stack trace, cause and the error's own fields. LocalFileSessionStore writes them to the session's file. Keep secrets off error objects.
For production deployments, use a dedicated store package:
@noetaris/harness-store-redis— Redis-backed store with atomic Lua CAS and distributed claim/lease@noetaris/harness-store-postgres— PostgreSQL-backed store with full history and branching support
Installation
pnpm add @noetaris/harness-storeThis package has zero runtime dependencies — it does not declare @noetaris/harness
as a peer dependency and does not require it at runtime. The store implementations
satisfy the SessionStore contract via TypeScript structural typing, so @noetaris/harness
is only needed at build time if you want its SessionStore/StoredRun types for your
own code (install it as a dev dependency in that case).
Quick Start
import { InMemorySessionStore } from '@noetaris/harness-store'
const store = new InMemorySessionStore()API Reference
InMemorySessionStore
An in-memory session store that keeps the latest run for each session and maintains a complete history.
load(agentId: string, sessionId: string): Promise<StoredRun | null>
Loads the most recent run for a session.
const run = await store.load('my-agent', 'session-123')
if (run === null) {
console.log('No runs found for this session')
} else {
console.log(`Latest phase: ${run.phase}`)
}Returns:
- The most recent
StoredRunif one exists, ornullif no runs have been saved for this agent/session pair
save(agentId: string, sessionId: string, run: StoredRun): Promise<void>
Persists a run to the store. The run becomes the latest for this session and is appended to the session's history.
The core may pass a fourth argument, SaveOptions ({ lease? }). These stores have no claims, so they ignore it and check only the version.
const run: StoredRun = {
agentId: 'my-agent',
runId: 'run-abc123',
sessionId: 'session-123',
startedAt: new Date().toISOString(),
settledAt: new Date().toISOString(),
phase: 'completed',
initialState: { step: 0 },
finalState: { step: 5, result: 'success' },
}
await store.save('my-agent', 'session-123', run)loadHistory(agentId: string, sessionId: string): Promise<StoredRun[]>
Loads all runs for a session in insertion order (oldest first).
const allRuns = await store.loadHistory('my-agent', 'session-123')
console.log(`Session has ${allRuns.length} runs`)
allRuns.forEach((run, i) => {
console.log(`Run ${i}: ${run.runId} completed in ${run.phase}`)
})Returns:
- An array of all
StoredRunobjects for the session, in chronological order - Returns an empty array if no runs exist for the session
- Returns a defensive copy; mutations don't affect the store
branch(agentId: string, sessionId: string, runId: string): Promise<string>
Creates a new session by branching from a specific run in another session's history. The new session is initialized with the source run's final state.
try {
const newSessionId = await store.branch('my-agent', 'session-original', 'run-abc123')
console.log(`Created new session: ${newSessionId}`)
} catch (err) {
if (err instanceof BranchNotFoundError) {
console.log('Could not find the run to branch from')
}
}Returns:
- A new UUID v4 string for the branched session
Throws:
BranchNotFoundErrorif therunIdis not found in the source session's history
Behavior:
- Creates a seed
StoredRunwithphase: 'paused', nostep, and identicalinitialStateandfinalState, so the nextagent.run()on the new session runs from there - The seed's
branchedFromrecords the source:{ sessionId, runId, carrier? }(carrieris the source run's, when it has one). The new session's first run sees it asRunContext.branchedFrom, and@noetaris/harness-otellinks that run to the source run - Branching a seed points at the run that seed came from, since a seed never ran itself
- When a run id appears more than once in history (a paused run and the copy saved when its interrupt is answered, or the checkpoints of a run with
checkpoint: 'step'), the last record is used - The new session appears in its own history with a single run
- The source session is unaffected
- The seed has no
requestId, so no request of the source session is found in the new one
findRequest(agentId: string, sessionId: string, requestId: string): Promise<StoredRun | null>
Returns the newest run of the session saved with that requestId, or null when there is none.
@noetaris/harness calls it when agent.run() gets a requestId that the session's latest run
does not carry, so a late retry of an earlier request returns that request's outcome instead of
running it again.
const run = await store.findRequest('my-agent', 'chat-1', 'msg-1')
// the latest run of request msg-1 (after its resumes), or nullLocalFileSessionStore
A file-system-backed session store that persists each session as a JSONL file. Each line in the file is one StoredRun record, in append order.
File layout: {dir}/{agentId}/{sessionId}.jsonl
The dir directory does not have to exist. The constructor does not touch the disk. The first save() creates dir, with its missing parents, and the agent's directory in it (Node's default mode, less the process umask).
- Before the first save, and for any session that has no file:
load()andfindRequest()returnnull,loadHistory()returns[], andbranch()throwsBranchNotFoundError. None of them creates anything. - A
save()that fails the version check (ConcurrentModificationError) creates nothing either. - Any other file-system error is passed on as Node reports it. When
diris a file, every method rejects withENOTDIRon Linux, where this was checked. Other systems may report another code. Windows, for example, may reportENOENT, and the read methods then return nothing, as for a missing session. - When the process may not write to
dir, the read methods still work andsave()rejects withEACCES.
Ids are used as names almost as they are. Only %, /, \, <, >, :, ", |, ?, *, control characters and a leading . are percent-encoded (a/b → a%2Fb, .hidden → %2Ehidden), so every id gets its own file inside dir, and names like trợ-lý or phiên 1 stay readable.
An agent id or session id with a lone surrogate (such as '\ud800') is rejected with a TypeError by every method, before it touches the disk. The file system would write it as U+FFFD, so two different ids would share a file.
Changed layout. Earlier versions wrote
{dir}/{agentId}_{sessionId}.jsonl, where two different id pairs could share a file (a_b+canda+b_c) and an id containing../wrote outsidedir. Files in the old layout are not read; there is no migration.
Quick Start
import { LocalFileSessionStore } from '@noetaris/harness-store'
// ./sessions is created on the first save
const store = new LocalFileSessionStore({ dir: './sessions' })Constructor
new LocalFileSessionStore(options: { dir: string })| Option | Type | Description |
|--------|------|-------------|
| dir | string | Absolute or relative path to the directory where session files are stored. It does not have to exist: the first save() creates it, with its missing parents. |
Methods
All methods have the same signatures as InMemorySessionStore. See load, save, loadHistory, branch, and findRequest above for parameter details. findRequest reads the session's whole file, like loadHistory.
When to Use LocalFileSessionStore
Good for:
- Single-process services that need sessions to survive restarts
- Development and staging with durable state requirements
- Workloads where each agent runs on one machine
Not suitable for:
- Multi-process or multi-machine deployments (concurrent writes to the same file are unsafe)
- High-throughput workloads (file I/O per step)
Error Handling
BranchNotFoundError
Thrown when attempting to branch from a run that doesn't exist.
import { BranchNotFoundError } from '@noetaris/harness-store'
try {
await store.branch('my-agent', 'session-123', 'nonexistent-run')
} catch (err) {
if (err instanceof BranchNotFoundError) {
console.error(`Failed to branch: ${err.message}`)
}
}The error message includes the session ID and run ID for debugging:
branch target not found: sessionId=session-123, runId=nonexistent-runConcurrentModificationError
Thrown by save() when a concurrent write is detected via optimistic locking. The stored version did not match the expected version — another instance committed between your load and save.
import { ConcurrentModificationError } from '@noetaris/harness-store'
try {
await store.save('my-agent', 'session-123', run)
} catch (err) {
if (err instanceof ConcurrentModificationError) {
console.error(`Concurrent write conflict: ${err.message}`)
// err.sessionId — the session that conflicted
// err.attemptedVersion — the version that was rejected
}
}Thrown by InMemorySessionStore and LocalFileSessionStore.
LeaseNotFoundError
For custom stores with claims. extendClaim() throws it when the lease's claim is gone: it was released, or another instance took it over after it expired. InMemorySessionStore and LocalFileSessionStore have no claims and never throw it.
import { LeaseNotFoundError } from '@noetaris/harness-store'
try {
const newLease = await store.extendClaim(lease, { ttlMs: 10_000 })
} catch (err) {
if (err instanceof LeaseNotFoundError) {
console.error(`Lease gone: ${err.message}`)
// err.sessionId — the session whose claim was not found
}
}@noetaris/harness recognises the error by name, so a custom store may throw this class or its own error named 'LeaseNotFoundError'. What the harness does depends on who called extendClaim():
- At a step boundary (before every step but the first of a run that holds a claim): the run stops there and settles
$errorwithLeaseExpiredError, whosecauseis this error. No further step runs and nothing is saved. await ctx.keepAlive()in a step: the promise rejects with this error. Uncaught, it fails the step like any other error the step throws.ctx.keepAlive({ every })(background renewal): the error is ignored, and the run stops at the next step boundary.- A debug session (
agent.debug()): while it holds the run at a stop, it renews the claim every third of the claim TTL. The error is ignored there too. When the run goes on, it stops at the next step boundary.
When to Use InMemorySessionStore
Good for:
- Development and local testing
- Ephemeral agent sessions that don't need persistence across restarts
- Unit tests and integration tests
- Prototyping new harness features
Not suitable for:
- Production systems requiring durability
- Multi-process deployments (data lost on restart)
- Audit or compliance requirements
For production use, see @noetaris/harness-store-redis (multi-process, distributed) or @noetaris/harness-store-postgres (durable, full history).
Implementing Custom Stores
To create your own store, implement the SessionStore interface from @noetaris/harness:
import type { SessionStore, StoredRun, SaveOptions } from '@noetaris/harness'
export class MyCustomStore implements SessionStore {
async load(agentId: string, sessionId: string): Promise<StoredRun | null> {
// TODO: implement
}
async save(agentId: string, sessionId: string, run: StoredRun, options?: SaveOptions): Promise<void> {
// TODO: implement — with options.lease, check the claim first (see below), then the version
}
// Optional — enables session history queries
async loadHistory(agentId: string, sessionId: string): Promise<StoredRun[]> {
// TODO: implement
}
// Optional — enables session branching
async branch(agentId: string, sessionId: string, runId: string): Promise<string> {
// TODO: implement
}
// Optional — lets a late retry of an earlier request be returned instead of run again
async findRequest(agentId: string, sessionId: string, requestId: string): Promise<StoredRun | null> {
// TODO: implement — the newest run with this requestId, or null
}
// Optional — enables distributed claim/lease (Layer 2 concurrency)
async claim(agentId: string, sessionId: string, options: ClaimOptions): Promise<Lease | null> {
// TODO: implement — return Lease on success, null if already claimed
}
async release(lease: Lease): Promise<void> {
// TODO: implement — must never reject; swallow errors
}
async extendClaim(lease: Lease, options: ClaimOptions): Promise<Lease> {
// TODO: implement — throw LeaseNotFoundError if key absent or nonce mismatch.
// Called before every step but the first of a run that holds a claim, and from ctx.keepAlive()
}
}Fencing. If your store implements claim, make save check options.lease. When it is given, check — in the same atomic step as the version check, and before it — that the session's current claim is the one this lease was issued for. Compare your own claim id (a nonce in lease.token), never times. If it is not, write nothing and throw an Error whose name is 'LeaseLostError', whatever the version. The harness then stops the stale run with LeaseExpiredError. A store that ignores options keeps working, but a stale instance can overwrite the new owner's progress.
A run can have several records with the same runId (an answered interrupt; checkpoints with phase: 'running'). findRequest returns the newest one; a custom branch should use the last one.
A custom branch should save the same seed shape — phase: 'paused', no step, and branchedFrom — so the branched session runs and its first run can link to the source. The contract is documented on SessionStore.branch in @noetaris/harness.
loadHistory, branch, findRequest, claim, release, and extendClaim are optional — only load and save are required by the interface. Without findRequest, agent.run() recognises a retry only of the session's latest request. Implement claim/release/extendClaim to support multi-process distributed locking (Layer 2 concurrency). See the TypeScript interface in @noetaris/harness for the full contract.
License
MIT
