Pi
Pi is an open-source coding agent. Its durable engine, Pi Durable, writes every step to storage before it acts on it: an input that was submitted, a model request, a tool call and its result. A run that is cut off continues from where it stopped.
A harness is one copy of that engine with its storage. Only one process may own a storage at a time, so a harness fits a Durable Object exactly: one object, one SQLite database, one owner.
Take one small app: a Session Durable Object for the user sam, with two conversations. pr-142 is fixing a test, and notes is a chat. Both live in the object’s SQLite. pr-142 uses the coding tools, so it has a sandbox on Boat.
- models
- Fast
- tools
- add · bash
- files
- /home/user/repo
Install
Section titled “Install”pnpm add https://pkg.alchemy.run/@alchemy.run/pi/9c58f00 https://pkg.alchemy.run/@alchemy.run/ai/9c58f00bun add https://pkg.alchemy.run/@alchemy.run/pi/9c58f00 https://pkg.alchemy.run/@alchemy.run/ai/9c58f00npm install https://pkg.alchemy.run/@alchemy.run/pi/9c58f00 https://pkg.alchemy.run/@alchemy.run/ai/9c58f00yarn add https://pkg.alchemy.run/@alchemy.run/pi/9c58f00 https://pkg.alchemy.run/@alchemy.run/ai/9c58f00Pi itself needs no account. The model is yours, through any model Layer, and so is the sandbox platform, when the harness uses one.
Run processes on Pi
Section titled “Run processes on Pi”An AI.Process names no harness. Pi.HarnessLive provides AI.Harness and needs Pi’s storage. Provide it where the process’s other Layers are:
import * as AI from "@alchemy.run/ai";import * as Pi from "@alchemy.run/pi";import * as PiCloudflare from "@alchemy.run/pi/Cloudflare";import * as Layer from "effect/Layer";import { EngineerLive } from "./Engineer.process.ts";import { SmartLlama, Smart } from "./Models.ts";
export const Live = EngineerLive.pipe( Layer.provide(Layer.mergeAll(Pi.HarnessLive, Pi.CodingTools, AI.DefaultModel(Smart))), Layer.provide(Layer.mergeAll(PiCloudflare.DurableObjectStorage, SmartLlama)),);Pi.CodingTools is only needed when a process mentions a coding tool, and then so is an AI.Sandboxes Layer.
A session is the Pi conversation named <process>/<key>. Its first message creates the conversation with the process’s prose as its instructions and the mentioned tools as its tools. Each later message applies the prose again, so a deploy that changes a process changes its running sessions from their next message. send is a submission that queues behind a run in progress, prompt waits for it to settle, and messages is the conversation’s context.
Pi calls a tool by its own name: a process that mentions Deploy reads deploy in its prose. An MCP server’s tools are mcp__<server>__<tool>.
Yield the harness yourself
Section titled “Yield the harness yourself”Everything Pi has beyond processes, such as forks, compaction, extensions and a conversation’s live view, is on Pi.Harness. Yield it in a Durable Object’s outer Effect and list the models and tools it has:
import * as Cloudflare from "@alchemy.run/cloudflare";import * as Pi from "@alchemy.run/pi";import * as PiCloudflare from "@alchemy.run/pi/Cloudflare";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import { Add, AddLive, Fast, FastLive } from "./agent.ts";
const HarnessLive = Layer.mergeAll(FastLive, AddLive, PiCloudflare.DurableObjectStorage);
export default class Session extends Cloudflare.DurableObject<Session>()( "Session", Effect.gen(function* () { const harness = yield* Pi.Harness({ models: [Fast], tools: [Add] });
return Effect.gen(function* () { return { prompt: Effect.fn(function* (name: string, text: string, requestId: string) { const conversation = yield* harness.createConversation({ name }); const submission = yield* conversation.submit({ type: "input", content: text, requestId }); return (yield* submission.wait).status; }), }; }); }).pipe(Effect.provide(HarnessLive)),) {}Every model and tool listed becomes a requirement of the harness, so a Layer left out is a compile error. PiCloudflare.DurableObjectStorage keeps conversations in the object’s SQLite, so each object has its own and no other object can read them.
Conversations
Section titled “Conversations”A conversation is a transcript and what it runs with: a model, tools, extensions and instructions. You create it with a name of your choosing. Creating a name that exists returns the existing conversation unchanged, so the call is safe to repeat:
const conversation = yield* harness.createConversation({ name: "pr-142", tools: [Add, AI.Read], instructions: "Review only. Never edit files.",});model, tools, extensions, instructions, cwd and maxTurns each fall back to the harness’s default when left out. A run takes at most 100 tool rounds, then ends unanswered; set maxTurns to change the limit, or to null for none.
Submit an input
Section titled “Submit an input”submit stores the input and returns. The run that answers it goes on in the object, and wait resolves when it is done or unanswered:
const submission = yield* conversation.submit({ type: "input", content: "Why does the login test fail?", requestId: "msg-81",});const settled = yield* submission.wait;requestId makes the submission exactly-once: the same requestId returns the original submission, whether its run is going, finished, or was resumed by a later instance. Use the id of whatever caused the input, such as a message id or a webhook delivery id.
Steer, stop and change a run
Section titled “Steer, stop and change a run”whenBusy says what an input does when a run is going: steer adds it to that run, followUp queues it for after, and reject refuses it. abort withdraws queued inputs and stops the running work:
yield* harness.submit("pr-142", { type: "input", content: "Use pnpm, not npm.", whenBusy: "steer" });yield* harness.abort("pr-142");configure changes a conversation from its next model request. Tools and extensions are set exactly, or with add and remove; a field set to null goes back to the harness’s default:
yield* harness.configure("pr-142", { tools: { remove: [AI.Bash] } });yield* harness.configure("pr-142", { model: Smart, instructions: "Review only. Never edit files." });Read, reset and branch
Section titled “Read, reset and branch”context is what the model sees next, and watch is a Stream of the conversation as it changes. reset starts a new context with a handoff note, compact summarizes it to free room, and fork creates a new conversation that sees this one’s entries up to a point:
const { messages } = yield* conversation.context;yield* conversation.reset("We were fixing the flaky login test. Continue.");listConversations maps every name in the object to its conversation id. For anything these don’t cover, conversation.raw and harness.raw are Pi’s own handles.
A conversation uses the tools it was created with, or every tool on the harness when it names none. A tool not on the harness fails with NotOnHarness. Each call runs in the Durable Object, and a tool implemented on its class binds what it uses in the object’s outer Effect, where the harness is yielded.
Pi.CodingTools provides the six coding tools. bash, read, edit and write are Pi’s own, with Pi’s descriptions and parameters: read returns text with line numbers or an image, edit takes several exact replacements in one call, and bash keeps the end of long output and saves the rest to a file. Pi has no search tools, so Pi.Grep and Pi.Glob run grep and a bash glob in the sandbox. Each has its own Layer, for a harness that lists only some:
const ReadOnlyLive = Layer.mergeAll(Pi.Read, Pi.Grep, Pi.Glob).pipe(Layer.provideMerge(Sandbox));
const harness = yield* Pi.Harness({ models: [Fast], tools: [AI.Read, AI.Grep, AI.Glob] });An MCP server listed in tools is asked for its tools when the object first opens the harness. In a conversation’s tools, the server stands for every tool it has.
Code mode
Section titled “Code mode”On Pi every tool can go through code mode, Pi’s own coding tools included, so AI.CodeMode(AI.CodingTools, Add) gives the model a program as its only way to act. Pi’s system prompt gets a codemode section with the declarations of the tools a program may call, and it follows the conversation: a tool it has disabled is left out.
const HarnessLive = Layer.mergeAll( FastLive, AddLive, WithdrawLive, PiCloudflare.DurableObjectStorage, AI.CodeModeAsync.pipe(Layer.provide(AICloudflare.EvalQuickJS())),);
const harness = yield* Pi.Harness({ models: [Fast], tools: [AI.CodeMode(Add, Withdraw)] });A QuickJS evaluator runs a program deterministically, and Pi stores each tool call the program finishes. A program cut off by an eviction runs again from the top, gets the stored result for each call it already made, and continues from there. Under AICloudflare.EvalWorkerLoader() a program runs once, and one cut off fails.
Sandboxes
Section titled “Sandboxes”A Durable Object can’t run a process or hold a file system, so the coding tools work in a sandbox. Give Pi.CodingTools an AI.Sandboxes Layer, and Layer.provideMerge gives it to the harness too:
const HarnessLive = Layer.mergeAll( FastLive, PiCloudflare.DurableObjectStorage, Pi.CodingTools.pipe(Layer.provideMerge(Sandbox)),);The harness opens a conversation’s sandbox the first time one of its tools needs it, so a conversation that only chats never has one. The key comes from the Durable Object and the conversation, so two objects with a conversation of the same name never share a sandbox; conversation.sandboxKey is that key. A tool of yours reaches the same sandbox through AI.Sandbox.
Pi’s tools talk to a small daemon, pi-env, which the harness installs from npm in each new sandbox. Bake it into the image your sandboxes start from to skip the install.
A sandbox costs money while it runs. Suspend it when its conversation goes quiet, and remove it when the conversation is over:
yield* harness.suspendSandbox("pr-142");yield* harness.removeSandbox("pr-142");Extensions
Section titled “Extensions”An extension is a bundle a conversation selects by name: sections added to the system prompt, tools that come with it, and hooks on what the harness does. Use one for behavior that belongs to some conversations and not others, such as a review policy. A beforeTool hook sees each call before it runs, and Pi.block refuses it with a reason the model reads:
import * as Pi from "@alchemy.run/pi";import * as Effect from "effect/Effect";
export class Guard extends Pi.Extension<Guard>()( "guard", { sections: { policy: "Deploys need approval." } }, Effect.gen(function* () { return { hooks: { beforeTool: Effect.fn(function* (call) { return call.name === "deploy" ? Pi.block("Deploys need approval.") : undefined; }), }, }; }),) {}Returning { arguments } runs the call with those arguments instead. afterTool replaces a call’s result, beforeRequest replaces the messages of one model request, afterResponse sees each answer, and onYield can keep a run going with another message when the model stops. A section can also be an Effect, computed before each model request.
Extensions listed on the harness are selected by every conversation unless it says otherwise:
const harness = yield* Pi.Harness({ models: [Fast], extensions: [House] });yield* harness.createConversation({ name: "review", extensions: [Guard] });yield* harness.configure("review", { extensions: { remove: [House] } });Surviving a crash
Section titled “Surviving a crash”Cloudflare can evict a Durable Object at any moment: after a deploy, on a hardware fault, or when it has been idle. A Pi harness keeps the object’s alarm set for as long as there is work, and the alarm wakes a fresh instance that continues every unfinished run from its last stored step. You write no alarm handler.
A model request that was in flight is sent again. A tool call that had finished is not: its result is stored. A tool call that had started but not finished runs again only if its tool says that is safe:
export class RunTests extends AI.Tool<RunTests>()("run_tests", { description: "Run the test suite and report failures.", parameters: Schema.Struct({}), success: Schema.Struct({ exitCode: Schema.Number }), replay: "safe",}) {}Any other tool is not run again, and the model is told the call was interrupted.
Other hosts
Section titled “Other hosts”On a long-lived machine, such as a Fly Machine with a volume, an ECS task on EFS or a container with a mounted disk, the harness’s storage is a SQLite file, the coding tools run on the machine itself, and code mode runs on a worker thread. The harness, its models and its tools don’t change:
import * as AI from "@alchemy.run/ai";import * as Pi from "@alchemy.run/pi";import * as Layer from "effect/Layer";import { FastLive } from "./models.ts";import { AddLive } from "./Add.tool.ts";
export const HarnessLive = Layer.mergeAll( FastLive, AddLive, Pi.SqliteFile("/data/pi.sqlite"), Pi.CodingTools.pipe(Layer.provideMerge(Pi.LocalEnv({ cwd: "/workspace" }))), AI.CodeModeAsync.pipe(Layer.provide(AI.EvalQuickJS())),);Pi allows one owner per storage, so the file must belong to one process. A machine is not evicted while it has work, so there is no alarm: the harness resumes unfinished runs once, when the process starts. Every conversation works in the same file system under Pi.LocalEnv, so give each its own cwd. These need Node.js or Bun.
In tests, Pi.MemoryStorage keeps conversations in memory and loses them when the process ends.