commit process dies reopen

Pi Durable

A library for building agents that survive their process.

Armin Ronacher · Earendil

What it is

Pi Durable in four sentences

01

A library for building agents

TypeScript. Runs wherever JavaScript runs: Node, Bun, Cloudflare Durable Objects.

02

Durability and scheduling

Every model request and tool call is a durable task with a checkpoint. A scheduler runs them.

03

Single-player and multiplayer

One person in a terminal, or a whole Slack channel steering the same agent.

04

Recovers and tracks state

Kill the process at any moment; a new one continues. Your state lives next to the transcript.

Why

Somebody has to recover the agent

Pi in your terminal

› fix the flaky login test
● bash npm test …
✗ process died
› continue
● picking up where it stopped

You notice. You type “continue”. You are the recovery mechanism.

An agent in Slack

ann@agent why did the deploy fail?
agent
container redeployed mid tool call
annhello??
ann@agent why did the deploy fail?

Nobody notices. The answer is lost, the deploy may have happened, and people ask twice.

The one rule

Nothing is shown before it is stored

user submits model streams tool prints one line of commitsatomic, in order storage shown only after the commit terminal Slack browser

One line of atomic commitsTranscript entries, tasks, and state change together, or not at all.

Streaming is committed tooTokens and tool output land in storage at most every 100 ms.

So recovery is reopeningA crash loses at most 100 ms. The screen is a window onto storage, not onto the process.

Code

Open a harness, ask a question

const registry = createRegistry();
registry.install(CodingTools); // read, write, edit, bash

const harness = await Harness.open(
  await openNodeSqliteStorage("./agent.sqlite"),
  { models, registry, env },
  context,
);
const root = await harness.root(context, {
  agent: { model: { provider: "openai", modelId: "gpt-6-sol" } },
});

const job = { type: "input", content: "Fix the flaky login test",
              requestId: "job-42" } as const;
const submission = await root.submit(job, context);
const settled = await submission.wait(context);

The registry holds the tools this process can run: here read, write, edit and bash.

A harness opens over storage. SQLite here; JSONL, memory or a Durable Object work the same.

The root conversation is created once and is the same after every restart.

submit() durably admits the input. A requestId makes it exactly-once.

wait() resolves with the answer, even across a crash.

Under the hood

One question, as tasks and records

What the user sees

Fix the flaky login test
Let me look at the failing test first…
search_issuesbash npm test
The test races the session cookie; I added a wait for the login redirect.

What storage holds

Submissions

S1input job-42placeddone

pi.live

partial: Let me look at the failing test first…
search_issues: running
bash: running 214 tests…
generation #2 streaming…

Entries

1pi.user Fix the flaky…
2pi.assistant 2 tool calls
3pi.tool-result 3 issues
4pi.tool-result 2 failing
5pi.assistant answer

Tasks

T1pi.generationpendingrunningwaitingdone
T2pi.tool searchrunningdone
T3pi.tool bashrunningdone
T4pi.generationrunningdone

Every change on this side is a commit. The chat on the left is drawn from it.

Durability

kill -9, then open it again

Process A

running the job

kill -9

The process is gone. Every row is still in storage, including bash halfway through and the queued steer.

Process B

opens the same storage

// a new process opens the same file
const harness = await Harness.open(
  await openNodeSqliteStorage("./agent.sqlite"),
  { models, registry, env },
  context,
);
harness.resume(); // continue pending tasks
const root = await harness.root(context);

// a client retrying after the crash:
await root.submit(job, context); // → S1 again

Submissions

S1input job-42placed
S2steer check stagingqueuedplaced
S1retry job-42same

Tasks

T1pi.generationwaitingdone
T2pi.tool searchdone
T3pi.tool bashrunningpendinginterrupted
T4pi.generationrunning

Entries

3pi.tool-result search: 3 issues
4pi.tool-result bash was interrupted and may have partially run · “120 passed…”
5pi.user check the staging logs first

No recovery code. Reopening moved one row from running to pending; the rest is the ordinary machinery.

Durability

Tools say whether they are safe to rerun

const searchIssues = defineTool({
  name: "search_issues",
  description: "Search the issue tracker",
  parameters: Type.Object({ query: Type.String() }),
  replay: "safe", // only reads: rerun after a crash
  execute: async (args, api) => {
    api.output(`searching for ${args.query}\n`);
    const text = await tracker.search(args.query);
    return { output: [{ type: "text", text }] };
  },
});

const deploy = defineTool({
  name: "deploy",
  description: "Deploy a version to production",
  parameters: Type.Object({ version: Type.String() }),
  // no replay: interrupted means the model is told
  execute: async (args) => {
    const text = await ci.deploy(args.version);
    return { output: [{ type: "text", text }] };
  },
});
1
commit the intenttool, final arguments, replay policy
2
run the tooloutside any transaction
3
commit the resultan entry the model sees

replay: "safe" runs again with the stored arguments.

Otherwise the model is told “interrupted”, with the output so far. Never repeated.

api.output() streams to every client, committed every 100 ms.

Scheduling

Your own work is a durable task too

type State = { phase: "wait" } | { phase: "deliver" };
const Reminder = defineTask<{ text: string; at: number }, State, null>({
  name: "app.reminder",
  version: 1,
  initial: () => ({ phase: "wait" }),
  phases: {
    wait: async (task, runtime, ctx) => {
      await runtime.sleep(task.input.at, ctx); // wall-clock deadline
      await runtime.commit(() => ({
        status: "running", checkpoint: { phase: "deliver" } }), ctx);
    },
    deliver: async (task, runtime, ctx) => {
      const chat = await runtime.conversation(task.conversationId, ctx);
      await chat!.submit({ type: "input", content: task.input.text,
        requestId: `reminder:${task.id}` }, ctx);
      await runtime.commit(() => ({ status: "terminal",
        outcome: { status: "completed", result: null } }), ctx);
    },
  },
  abort: (_task, runtime, ctx) => runtime.commit(() => ({
    status: "terminal", outcome: { status: "aborted" } }), ctx),
});

Mon 18:02“Remind me tomorrow at 9.” A tool creates the task.

Mon 18:02wait sleeping until Tue 09:00

Mon 23:40Redeployed. The task is still waiting.

Tue 03:12The laptop slept. Still waiting.

Tue 09:00deliver: the reminder arrives in the conversation, once.

Model requests, tool calls and compaction are tasks like this one, in one ownership tree: Esc aborts what a task owns, bottom-up.

Single-player and multiplayer

Every client watches the same committed state

// any client, any time: the current view, then changes
const view = await thread.viewState(context);
render(view.value);
view.subscribe((value) => render(value));

// anyone can steer the running conversation
await thread.submit({
  type: "input",
  content: "Check the staging logs first",
  whenBusy: "steer",
}, context);

// remote clients: the exact operations of every commit
const watch = await thread.watch(context);
watch.start(async (_value, ops) =>
  socket.send(JSON.stringify(ops)));
conversation committed state terminalyou Slackann browserlate: snapshot steer: queued placed at thenext boundary
["s", ["docs", "pi.live", "generation", "message"], …]

Tracking state

Your state, committed with the transcript

const Todos = defineDoc<{ items: string[] }>({
  kind: "app.todos",
  version: 1,
  scope: "conversation",
  history: "rewindable",
  fork: "asOf", // a fork sees the todos as of its fork point
  initial: () => ({ items: [] }),
});

// in a tool: the result and the change, one atomic commit
await api.commit(async (tx) => {
  const list = await tx.doc(Todos, api.conversationId);
  list.items.push(args.item);
}, ctx);

const todos = await harness.documentState(Todos, root.id, context);
todos?.subscribe((value) => renderTodos(value?.items ?? []));
one commit pi.tool-result“Added write docs” app.todospush("write docs") channel todos: 3 items thread (fork) as of the fork: 1 item ☐ write docs ☐ fix login test ☐ ship it

What you get

The benefits, for free

recovery

Survives crashes

Reopen the storage; every task continues from its checkpoint.

recovery

Exactly-once input

A retry with the same requestId returns the same submission.

honesty

Honest side effects

Safe tools rerun; everything else is reported as interrupted.

scheduling

Durable scheduling

Timers, retries and child tasks survive restarts.

scheduling

Esc that works

Abort flows down the ownership tree; cleanup runs bottom-up.

multiplayer

Many clients

Late join, steering, forks, all from committed state.

state

Consistent state

Documents commit with the transcript; forks see the right version.

malleable

Change it while it runs

Conversations store names, not code: reload and restart work the same.

anywhere

Runs anywhere

SQLite, JSONL, memory, Durable Objects; tools on any machine.