How to build agents that survive crashes with Pi Durable
By Flavio
Updated
Tagged: AI
Build a durable TypeScript agent with Pi Durable and SQLite. Test crash recovery, avoid duplicate requests, and understand which tools can safely run again.
Picture an agent spending twenty minutes digging into a bug, and then its Node process crashes. If you only saved the chat history, you can see what happened up to that point, but you can’t pick up where it left off. To resume unfinished work, you need to know which tool was mid-flight, what already completed, and which requests are still queued up.
Pi Durable saves all of that state as the agent runs. When the process dies and you reopen the database, the agent picks up the unfinished run.
It’s a TypeScript library from Earendil, the team behind Pi. Instead of using the regular Pi terminal app for interactive coding, you use Pi Durable when you’re building your own agent app with custom tools and your own UI.
The Syntax video “My Code Fixes Itself Now” shows a real example of this setup. A Sentry error kicks off an agent that investigates the bug, opens a pull request, and can be stopped and resumed mid-run. Sentry, GitHub, and the interface around it are custom app code built on top of Pi Durable.
We’ll build a much smaller version here so we can watch crash recovery happen up close. We’ll wire up a read-only tool that checks service status, store the agent’s state in SQLite, kill the Node process while the tool is running, and restart it with the same request.
You’ll also find eight interactive drawings across this tutorial. Click any drawing, or focus it and press Enter or Space, to step through its states.
Pi Durable is still experimental, so keep your package lockfile committed. The API can change between releases.
What Pi Durable stores
Every agent app has three pieces: a model, tools the model can call, and the loop that runs the conversation between them. People usually call that loop a harness.
Pi Durable is that harness. As the agent works, it writes both the conversation entries and the execution state to storage, treating each model call and each tool call as a durable task. You bring your model API credentials, your tool code, and a place to store the data.
The model still runs on its provider’s servers. In our setup, SQLite holds the agent’s state locally while the OpenAI model runs on OpenAI’s side.
Keep in mind that “durable” doesn’t mean the Node process stays alive forever. When the process crashes, everything stops until you, a process supervisor, or your container platform starts a new one. Pi Durable hands that new process the saved state so it can continue.
Create the project
You’ll need a current Node.js LTS release with the built-in node:sqlite module, plus an OpenAI API key that has access to the model we use below (model calls are billed to that API account).
Start by creating an empty project folder and installing the dependencies:
mkdir pi-durable-demo
cd pi-durable-demo
npm init -y
npm pkg set type=module
npm install --ignore-scripts @earendil-works/pi-durable @earendil-works/pi-ai @earendil-works/chord
npm install --save-dev --ignore-scripts tsx typescript @types/node
pi-ai talks to the model, chord supplies the state and cancellation primitives Pi Durable relies on, and tsx runs our TypeScript files directly.
We’ll put all of our code in two source files:
pi-durable-demo/
agent.ts
tools.ts
When you run the script, it creates agent.sqlite (and sometimes SQLite journal files too). Save this as .gitignore so the database files and any local credentials stay out of Git:
node_modules/
.env
agent.sqlite*
Give the agent a tool
To make recovery easy to watch, we want a slow, predictable tool. Our service_status tool reads from a small in-memory fixture where website is healthy and checkout is degraded after a deployment.
It also waits ten seconds before returning, which gives us plenty of time to kill the process right in the middle of the call. Save this file as tools.ts:
import { setTimeout as delay } from 'node:timers/promises'
import { Type } from '@earendil-works/pi-ai'
import { defineExtension, defineTool } from '@earendil-works/pi-durable'
const services = {
website: { status: 'healthy', lastDeploy: 'deploy-104' },
checkout: { status: 'degraded', lastDeploy: 'deploy-105' },
}
const serviceStatus = defineTool({
name: 'service_status',
description: 'Read the demo status for website or checkout',
parameters: Type.Object({
service: Type.Union([
Type.Literal('website'),
Type.Literal('checkout'),
]),
}),
replay: 'safe',
execute: async ({ service }, api, context) => {
api.output(`Checking ${service}...\n`)
console.log(`Tool started: ${service}`)
await delay(10000, undefined, { signal: context.abortSignal })
return {
output: [{ type: 'text', text: JSON.stringify(services[service]) }],
}
},
})
export const StatusTools = defineExtension({
name: 'status-tools',
tools: [serviceStatus],
})
This is demo data, so we aren’t hitting a live website or a real monitoring tool.
In tools.ts, parameters defines the allowed inputs (website or checkout) and validates them before the tool runs. api.output() emits progress while the tool works, the returned output goes back to the model, and context.abortSignal lets the ten-second delay stop early if the harness cancels the call.
The most important option is replay: 'safe'. That tells Pi Durable it’s fine to run this tool again if the process dies before it finishes. Since reading our fixture has no side effects, repeating it is harmless.
Wrapping the tool in an extension gives it a stable name in the registry. Make sure you register the same extension every time you reopen this agent’s database.
Open SQLite and submit a request
Next, let’s connect the model, the tool registry, and the SQLite database. Save this file as agent.ts:
import { BACKGROUND_CONTEXT } from '@earendil-works/chord/context'
import { createModels } from '@earendil-works/pi-ai/models'
import { openaiProvider } from '@earendil-works/pi-ai/providers/openai'
import {
AssistantEntry,
createRegistry,
Harness,
} from '@earendil-works/pi-durable'
import { openNodeSqliteStorage } from '@earendil-works/pi-durable/storage/sqlite/node'
import { StatusTools } from './tools.js'
const requestId = process.argv[2]
const prompt = process.argv.slice(3).join(' ')
if (!requestId || !prompt) {
throw new Error('Pass a request ID followed by a prompt')
}
if (!process.env.OPENAI_API_KEY) {
throw new Error('Set OPENAI_API_KEY before running the agent')
}
const context = BACKGROUND_CONTEXT
const models = createModels()
models.setProvider(openaiProvider())
const registry = createRegistry()
registry.install(StatusTools)
const harness = await Harness.open(
await openNodeSqliteStorage('./agent.sqlite'),
{ models, registry },
context,
)
try {
const root = await harness.root(context, {
agent: {
model: { provider: 'openai', modelId: 'gpt-6-sol' },
instructions: 'Use service_status for service questions. Explain the demo results briefly. Never claim to repair or deploy anything.',
},
})
harness.resume()
const submission = await root.submit(
{ type: 'input', content: prompt, requestId },
context,
)
console.log(`Submission: ${submission.id}`)
const settled = await submission.wait(context)
if (settled.status !== 'done' || settled.type !== 'input') {
throw new Error(`The input was not answered: ${JSON.stringify(settled)}`)
}
const answer = await root.commit(
(tx) => tx.entry(AssistantEntry, settled.answer),
context,
)
for (const message of answer?.model ?? []) {
if (message.role !== 'assistant') continue
for (const part of message.content) {
if (part.type === 'text') console.log(part.text)
}
}
} finally {
await harness.close(context)
}
You might spot the ./tools.js import at the top. With Node’s module resolution rules, TypeScript maps that .js path back to tools.ts, and tsx resolves it when running the source file.
A few methods in this file do the heavy lifting:
harness.root()creates the root conversation the first time you run the script and returns that same conversation whenever you reopen the database. Initial settings apply at creation time; if you want to update an existing conversation later, callroot.configure().harness.resume()kicks off recovery for any pending tasks. Submitting a request or callingwait()also starts the scheduler; callingresume()explicitly makes the restart flow easier to see.- A submission is a request admitted to the conversation, and its ID lets us track that exact request across restarts.
wait()blocks until the agent produces an answer, and the final transaction reads the assistant entry holding it.
The finally block shuts the harness down cleanly on a normal exit. A hard kill -9 skips finally completely, which is what we’ll test next.
Run the agent
First, export your OpenAI API key in your shell. In zsh, you can read it into the environment without echoing it to the screen or saving it in your shell history:
read -rs 'OPENAI_API_KEY?OpenAI API key: '
export OPENAI_API_KEY
Now run a status check for checkout:
npx tsx agent.ts incident-105 'Use service_status to check checkout. Explain the result.'
Here incident-105 is our own application’s request ID, separate from the submission ID that Pi Durable generates and prints.
You’ll see Tool started: checkout, then a ten-second pause, and then the fixture comes back to the model. The exact wording of the reply varies, and the model reports that checkout is degraded after deploy-105.
Our agent only knows about the one tool we gave it. It has no shell access, no file-editing tools, no deployment credentials, and no way to fix checkout on its own.
If you want to type-check both TypeScript files, run:
npx tsc --noEmit --strict --skipLibCheck --module nodenext --target esnext agent.ts tools.ts
Kill it halfway through
Now let’s crash the process while the tool is still running.
In your first terminal, start a new request:
npx tsx agent.ts incident-106 'Use service_status to check checkout. Explain the result.'
Wait until Tool started: checkout appears.
In a second terminal, list the running Node processes to find this script:
pgrep -fl 'agent.ts'
Look for the Node process running agent.ts and terminate it with kill -9 and its numeric PID. If tsx spawns both a launcher and a child process, kill the child running the TypeScript file, and double-check the command line before you send the signal.
Once the process exits, go back to your project folder and run the exact same command again:
npx tsx agent.ts incident-106 'Use service_status to check checkout. Explain the result.'
You’ll get back the same submission ID printed before the crash. Because service_status is marked replay-safe, it starts over, waits ten seconds, and returns its result.
Pi Durable resumes from saved checkpoints rather than freezing and restoring a JavaScript call stack mid-instruction. Because our tool died before its result was written to SQLite, it runs from the beginning again.
The same applies to an interrupted model call. Any partial response saved before the crash is marked as aborted instead of completed, so Pi Durable sends the model request again, which can mean another API charge.
In this test, the fixture stands in for a real monitoring integration, so what we’re verifying is persistence and replay: the submission survives the crash and the tool runs again.
Retry a request without creating a second job
Run the incident-106 command one more time now that it has finished.
This time it prints the same submission ID and the saved answer right away, without running the tool again.
Passing requestId prevents duplicate submissions when the same job gets retried. When you retry delivery of the same logical job, reuse its requestId. When you want a brand new status check, give it a new ID, even if the prompt text is word-for-word identical.
Never reuse an old requestId for a different prompt, because Pi Durable treats it as a lookup for the original job rather than a new question.
If you’re building a webhook handler, derive requestId from a stable event ID. If your rule is one investigation per incident, keep an incident-to-investigation mapping too, since monitoring tools often fire several different events for the same incident.
Decide which tools may run again
Now imagine swapping our fixture for a tool that sends an email.
The email provider accepts the message, and half a second later your Node process dies before Pi Durable saves the tool result. When the process comes back up, the local database has no way of knowing the email already went out. Running that tool again automatically would email the person twice.
That’s why tools default to unsafe replay. Keep that default for anything you can’t safely repeat. After a crash, the harness hands an interrupted result back to the model instead of automatically rerunning the tool.
Even then, you still have work to do in your own app code. Nothing stops the model from asking for a fresh tool call on the next turn, so your app has to guard against repeating an action whose outcome is unknown.
For side effects like sending an email or opening a pull request, pass an operation ID and use the external service’s idempotency support if it has one. If it doesn’t, check the external system first before trying again. And if you still can’t confirm what happened, pause and ask a human.
Only flip a tool with side effects to replay: 'safe' once the tool code itself handles retries safely.
| Operation | What to check before enabling replay |
|---|---|
| Read service status | Safe to repeat, though the status might have changed since the first read |
| Search issues | No data changes, though repeated queries can still cost money |
| Send an email | The provider deduplicates using the same operation ID |
| Create a pull request | Your app finds and reuses the existing PR for that operation |
| Deploy a release | The deployment system reconciles the operation and its outcome |
Submission deduplication and tool idempotency protect two different things. A stable requestId stops a second submission from being created, while the tool and the external service stop a side effect from firing twice. They cover two different layers:
Separate the transcript from the work
Pi Durable keeps two distinct things in storage: the transcript records what happened in the conversation, and tasks track the work needed to reach an answer.
When the model asks for a tool, that tool runs as a task owned by the generation task. Once the tool finishes, another model turn reads the result and answers the user.
Saving chat messages alone won’t get you through a crash, because your app also needs to know about work that already started and hasn’t produced a final reply yet.
You can also store your own typed application documents right alongside the transcript in Pi Durable, like a record tracking an incident’s investigation status. A single commit updates your documents, appends conversation entries, and queues tasks together in SQLite. Remote calls to GitHub or an email API still sit outside that transaction.
Connect more than one screen
The terminal script is just one way to feed work into a conversation. A web app or a Slack bot can talk to the same conversation through your server.
Keep a single process in charge of opening and owning a store, and have every other client talk to that process. Pi Durable doesn’t lock across processes, so you don’t want two separate harnesses opening the same database file.
When you’re building a UI, root.viewState(context) gives you a subscribable snapshot of the conversation with committed entries, live tool output, and queued inputs. If a client drops and reconnects, it reads the current state directly instead of trying to rebuild it from a stream it missed. Your server still takes care of transport, authentication, and authorization around it.
If you send a message while the conversation is busy, it queues up as a follow-up by default. To steer the active run at the next tool-round boundary instead, send a steering input:
await root.submit({
type: 'input',
content: 'Check website as well before answering.',
whenBusy: 'steer',
}, context)
Put that snippet inside the open harness’s try block, where root and context are already in scope. Your app also needs to accept a second request while the first submission is still waiting, otherwise this won’t run until the first turn finishes.
Steering waits for the current tool call to finish instead of interrupting it mid-execution. And cancelling a wait only stops that caller from waiting. If you want to stop the whole conversation, abort it explicitly.
Keep the storage when you deploy
SQLite is great for a single Node process, as long as the database file is still there after you deploy.
Containers wipe their temporary filesystem every time you replace them. Mount persistent storage, keep the database at the same path, and stop the old process before bringing up the new one so two owners never fight over the file.
Treat saved conversations and tool output like any other production data. They can hold private prompts and internal service details, so restrict access to the file and include it in your backups.
Pi Durable also ships with JSONL and in-memory storage adapters. In-memory is handy for tests because it disappears when the process exits. If you’re running outside Node, you can plug in another adapter, like a Cloudflare Durable Object, though you don’t need Cloudflare to use Pi Durable.
If the database file gets deleted, you can’t resume anything, so backups still matter. The built-in Node SQLite adapter also runs in WAL mode with synchronous = NORMAL. That recovers from a process crash, though a sudden machine power failure can still lose the newest commits, so pick your storage and backup setup for the failures you need to survive.
Long conversations still have context limits
Saving everything to disk means a conversation can grow longer than a model accepts in a single request.
Pi Durable handles this with compaction, summarizing older messages to make room for new work and passing that summary to the model on the next turn.
Summaries can drop details, so don’t rely on conversation history for facts your app has to keep. Store things like an incident ID, the repository, and the associated pull request in structured documents or your main database.
You’ll also build subagents yourself on top of Pi Durable’s primitives (conversations, ownership, tasks, and forks). The foreground and background subagent examples show how those pieces fit together.
From this demo to an agent that investigates errors
The Syntax demo starts when a monitoring event arrives, while our terminal script takes a request ID and a prompt. The next step is putting a webhook handler in front to produce those two values.
From there, your app wraps the agent in a simple flow:
- Verify the webhook and check that the event belongs to a project you handle.
- Find the existing investigation for that incident, or create a new one.
- Submit the investigation with its stable request ID.
- Give the agent narrow tools to read the error and work on an isolated copy of the repository.
- Run checks and prepare a pull request for review.
- Record the PR and tie later events for that incident back to the same investigation.
Pi Durable runs the persisted agent loop inside that flow. You own the webhook handling and the rules for changing code or talking to GitHub.
Start with a tool that reads one real service’s status. Keep the crash test, add a test for an interrupted unsafe action, and verify that a duplicate event doesn’t create a second investigation. Bring in the tools that change code once those paths behave the way you expect.
The upstream README documents the APIs we used here, and the runnable examples go further into recovery, approvals, UI events, and subagents. Earendil’s introduction to Pi Durable explains the design behind it.
If you’re deciding between this, Cloudflare Workflows, and Vercel’s Workflow SDK, start with Pi Durable, Cloudflare Workflows, or Vercel Workflow?.
Want me to talk about your product? You can sponsor this site.
Related posts about ai: