Save and restore
A checkpoint is a conversation as opaque bytes: its history and usage, up to 4 MiB. Store it without editing it, and restore it into a new session or engine. You don't need checkpoints to keep a session going; durability does that on its own. Use them to copy a conversation somewhere else.
Start sessions from a conversation
session.checkpoint() reads a session's history without changing it. Pass the bytes to createFxAgent(), and every new session the agent opens starts from that history:
const history = await agent.session(sessionId).checkpoint()
const forked = createFxAgent({ checkpoint: history })
forked.session().prompt('Now try a different approach.')
This suits a conversation template, or trying several directions from one point.
Save an engine's conversation
createFxEngine() keeps one conversation in memory. Call checkpoint() between turns and store the bytes:
import { createFxEngine } from 'libfx'
import { writeFile, readFile } from 'node:fs/promises'
const apiKey = process.env.AI_GATEWAY_API_KEY
if (!apiKey) throw new Error('Set AI_GATEWAY_API_KEY')
const options = { apiKey }
const engine = await createFxEngine(options)
const turn = engine.prompt('Explain a database index in one sentence.')
for await (const _ of turn) {}
await writeFile('conversation.fx', await engine.checkpoint())
await engine.close()
const restored = await createFxEngine({ ...options, checkpoint: await readFile('conversation.fx') })
const next = restored.prompt('Give me an example of that.')
for await (const event of next) {
if (event.type === 'text_delta') process.stdout.write(event.delta)
}
await restored.close()
checkpoint() rejects while a turn runs. Restoring a checkpoint doesn't restore credentials, the model, instructions, or tools, so supply them again. A checkpoint records the libfx version, tool set, and model that saved it. When any of them differs, the checkpoint still restores, and onEvent receives a checkpoint.mismatch event naming what changed.
Record as it runs
To keep an engine's conversation in your own storage as it happens, pass a persistence store instead of a checkpoint. The engine appends records as each turn runs, so a new engine on the same store can continue a turn the last process left open:
const engine = await createFxEngine({ apiKey, persistence: store })
const turn = engine.resume() // the open turn, or null when there is none
A store needs two methods and can add a third. The bytes are opaque, so it never has to understand them:
interface Persistence {
load(): Promise<{
checkpoint?: { data: Uint8Array; through: string }
journal?: Iterable<JournalRecord> | AsyncIterable<JournalRecord>
head?: string | null
}>
append(input: {
expected: string | null
idempotencyKey: string
data: Uint8Array
barrier: boolean
marks?: object[]
}): Promise<{ cursor: string }>
saveCheckpoint?(input: { through: string; data: Uint8Array }): Promise<void>
marks?: boolean
}
interface JournalRecord {
cursor: string
data: Uint8Array
}
load()returns the latest checkpoint and the records stored after it, oldest first, or{}for a new conversation. If your store keeps entries of its own after the last record, return the cursor the nextappend()should name ashead.append()stores one record and returns its cursor. Reject it withFxFencedErrorwhenexpectedisn't the last stored cursor, so two processes can't write one conversation. The engine sends oneappend()at a time.barrieristruewhen something waits for the record, such as a tool call with effects or the end of a turn. A store may acknowledge a record withbarrier: falsebefore it's durable, as long as it keeps records in order and acknowledges a barrier only once it and every record before it are durable.saveCheckpoint()stores a checkpoint covering the records throughthrough, soload()can skip them. Between turns, once the records since the last checkpoint reach 1 MiB, the engine saves a new one; setcheckpointAfterBytesto change that.- Set
marks: trueto receive each record'smarks, which say where turns start, yield, and end and which inputs a turn took, so your store can track turns without reading records.
createMemoryPersistence() is a reference store for tests. When a resumed turn left a tool call running, libfx calls the onAmbiguous function you pass to resume() for it. Return 'rerun' to run the call again under the same executionId.
With a store, prompt() and resume() also take yieldAt, a time in milliseconds since the epoch. The turn stops before its first model request after that time, with the stop reason yielded, and the next resume() continues it without telling the model it was interrupted.
When a turn's result resolves, the record that ends the turn is already stored. If that record can't be stored, result rejects.
A resumed turn first sends the reply the last process had started, as text_delta events, because the new engine saw none of it. If the last process had stored the turn's final reply but not the turn's end, resume() ends the turn with that reply instead of asking the model again.
Compatibility
Checkpoints retain image data and source references within the 4 MiB limit. libfx restores checkpoints from earlier versions, but versions before 0.0.13 cannot restore checkpoints made by 0.0.13 or later. Earlier libfx versions cannot read journals or snapshots that use the saved-image references introduced in 0.0.15.
Saved turns with context updates introduced in 0.0.16 use journal, snapshot, and checkpoint version 4, which libfx 0.0.15 cannot read. Upgrade every worker sharing a session store before starting new turns. libfx 0.0.16 reads earlier journals and snapshots. A journal or checkpoint whose format is newer than the reader supports fails to load with FxJournalVersionError.