Skip to content
Farm.js 0.2 is outRead the post

Build durable agents with Farm.js. Wait for a person, resume after a deploy.

Keep your agent framework and your web app. agent-unit saves each finished step, and Farm.js Infra can store the run, wake it on time, and collect the approval.

In this article 10 sections

Build durable agents with Farm.js. Wait for a person, resume after a deploy.

KinfeMichael Tariku · Nov 2026

A customer asks for a $36 refund. Your agent looks up the order, asks someone on the team to approve it, and waits. The reviewer answers the next morning. Overnight, you ship a new version of the app.

A durable agent saves its progress outside the process, so a run can continue after the request, the process, or the deployment that started it is gone.

This post builds that refund agent with agent-unit, the open-source run engine behind Farm.js's agent integration. You keep the agent framework you already use and the web app you already have. Farm.js Infra is optional. It can store runs, wake them on time, and give reviewers a place to answer.

Why an ordinary agent loop loses the refund

Most agent code is one long await inside a request handler. That works until the wait is longer than the process.

  • The request ends. Serverless functions have a time limit, and people close tabs. Nobody holds an HTTP request open overnight.
  • The process ends. A deploy replaces the server. The order the agent loaded and the question it asked lived in memory, so they go with it.
  • Starting over repeats work. Running the handler again from the top calls the model again. If the process died while the refund call was in flight, the customer can be refunded twice.

The fix is to write down each finished step and each open question, then continue from that record on whichever server receives the answer.

Save each step, pause for the person

Here is the whole agent, in agents/refund.ts. The order and the refund result are demo data, so the control flow is easy to see.

TypeScript
import { defineAgent } from "agent-unit";

export default defineAgent(async (input: { orderId: string }, run) => {
  const order = await run.step("load-order", async () => ({
    id: input.orderId,
    amountCents: 3600,
    currency: "USD",
  }));

  const decision = await run.interrupt<{ approved: boolean }>("approve-refund", order);

  if (!decision.approved) {
    return { orderId: order.id, status: "declined" };
  }

  return run.step("refund-order", async () => ({
    orderId: order.id,
    status: "refunded",
    amountCents: order.amountCents,
  }));
});

run.step runs a function once and saves its result in the run's journal. run.interrupt saves a question, with the details a reviewer needs, and parks the run. A parked run holds no request open and uses no compute.

This request starts a run.

HTTP
POST /agents/refund/runs
Content-Type: application/json

{"input":{"orderId":"bag-order-123"}}

The run gets an ID, and its status becomes interrupted with the order in the approve-refund payload. The next day, the reviewer's answer goes to that run.

HTTP
POST /runs/<run-id>/resume
Content-Type: application/json

{"answer":{"approved":true}}

The run finishes with {"orderId":"bag-order-123","status":"refunded","amountCents":3600}. Answering false returns "status":"declined" and never reaches the refund step. These are the engine's default paths; mounting it under /api/agents adds that prefix.

Here is what the two invocations do. The second can run on a different server, a day later, after a deploy.

Code
Tuesday, app v12    POST /agents/refund/runs
  load-order        runs, saves the order
  approve-refund    parks the run (interrupted)

Wednesday, app v13  POST /runs/<run-id>/resume
  load-order        replays the saved order
  approve-refund    returns { approved: true }
  refund-order      runs, completes the run

On resume, agent-unit calls the function from the top again. Finished steps return their saved results without running, and the interrupt returns the answer. That is why the agent reads like an ordinary async function.

Make the refund safe to repeat

A step is saved when it finishes. If the process dies during a step, recovery runs that step again. For a lookup, that costs nothing. For a refund, it has to be harmless.

Every step gets an idempotency key: an identifier that stays the same when that step runs again and differs for every other step and run. Give it to the payment provider, and a repeated call returns the original refund instead of creating a second one.

TypeScript
const refund = await run.step("refund-order", ({ idempotencyKey }) =>
  stripe.refunds.create({ payment_intent: order.paymentId }, { idempotencyKey }),
);

Here stripe is your authenticated client, and order.paymentId comes from your order database.

That leaves one rule for the code between steps: given the same saved results, it must make the same decisions. Keep network calls, the clock, and random values inside steps. Load the amount and the payment ID from the order record, and let the request supply only the order ID.

Keep the agent framework you use

The plain function makes the pause easy to see. An AI SDK agent asks for the same approval inside a tool.

TypeScript
// agents/support.ts
import { openai } from "@ai-sdk/openai";
import { stepCountIs, tool, ToolLoopAgent } from "ai";
import { useRun } from "agent-unit";
import { z } from "zod";

export default new ToolLoopAgent({
  model: openai("gpt-4.1-mini"),
  instructions: "Help with refunds. Use requestRefund for the order the customer names.",
  tools: {
    requestRefund: tool({
      description: "Ask a person to approve a demo refund.",
      inputSchema: z.object({ orderId: z.string() }),
      execute: async ({ orderId }) => {
        const decision = await useRun().interrupt<{ approved: boolean }>("approve-refund", {
          orderId,
        });
        return { orderId, approved: decision.approved };
      },
    }),
  },
  stopWhen: stepCountIs(5),
});

useRun() gives the tool the run it belongs to. Put the real refund behind the decision, and pass useRun().idempotencyKey(), the key for that tool call, to the payment provider. The model key stays in the server environment.

Each framework keeps its own way of asking.

Your agentExport from the agent fileHow it asks for approval
AI SDKA ToolLoopAgentuseRun().interrupt() in a tool
MastraA Mastra AgentTool approval or suspend()
OpenAI Agents SDKAn SDK AgentA tool with needsApproval: true
LangGraphA compiled graphinterrupt() in a node
Plain TypeScriptdefineAgent(...)run.interrupt()

agent-unit picks the adapter from the packages in your package.json, or you can name one with framework: "ai-sdk" in agent-unit.config.ts. The adapters keep model and tool results, or the framework's own checkpoints, so the engine can resume the run. Other frameworks can ship an adapter through defineAdapter. A framework with its own server and persistence can keep both through the server option, and then it owns its runs and recovery. Framework adapters and server options

Mount it in the app you already have

The engine is a Web Request → Response handler. Create it once.

TypeScript
// src/agent-server.ts
import { createAgentUnit } from "agent-unit/server";
import refund from "../agents/refund";

export const unit = createAgentUnit({
  agents: { refund },
  storage: "farmjs",
  basePath: "/api/agents",
});

In Hono, it is one route. Run your existing authentication and authorization before it.

TypeScript
app.all("/api/agents/*", (c) => unit.handler(c.req.raw));

In Next.js, it is a catch-all route at app/api/agents/[...path]/route.ts.

TypeScript
import { unit } from "@/src/agent-server";

export const GET = (request: Request) => unit.handler(request);
export const POST = GET;
export const DELETE = GET;

Without a host waitUntil, start and resume requests wait until the work finishes or pauses. Hosts that have one can pass it as unit.handler(request, { waitUntil }). A unit you create by hand receives its adapters explicitly, so an AI SDK agent also needs adapters: [aiSdkAdapter] from agent-unit/adapters/ai-sdk.

On Farm.js, a file is an agent

In a Farm.js app, the @farm.js/agent integration does the mounting. Install it with agent-unit and register it once.

TypeScript
// farm.config.ts
import { defineConfig } from "@farm.js/core";
import { agent } from "@farm.js/agent";

export default defineConfig({
  integrations: {
    agent: agent(),
  },
});

Each file in src/agents becomes an agent named after the file, served under /api/agent.

Code
src/agents/refund.ts           POST /api/agent/agents/refund/runs
src/agents/support/index.ts    POST /api/agent/agents/support/runs
src/agents/support/tools.ts    a helper the support entry imports
src/agents/_shared.ts          skipped

farm dev loads agents from source and reloads them when you save. farm build bundles them, with the adapters your dependencies select, into the server output for your deployment target. Farm.js middleware runs on these paths, so your app's own rules decide who can start, read, and answer a run. Renaming a file renames the agent, so check GET /api/agent/manifest.json after a rename.

The Durable Agents guide has the full request list.

The options the refund needs

agent() works with no options. Before the refund agent goes live, three are worth setting.

TypeScript
// farm.config.ts
import { defineConfig } from "@farm.js/core";
import { agent } from "@farm.js/agent";
import { getSessionUser } from "./src/server/session";

export default defineConfig({
  integrations: {
    agent: agent({
      storage: "farmjs",
      authorize: async (request, { action }) => {
        const user = await getSessionUser(request);
        if (!user) return false;
        return action === "start" || user.role === "reviewer";
      },
      onInterrupt: async ({ run, interrupt }) => {
        await fetch(process.env.SLACK_WEBHOOK_URL!, {
          method: "POST",
          body: JSON.stringify({ text: `${run.agent} is waiting on ${interrupt.name}` }),
        });
      },
    }),
  },
});
  • storage decides where runs live: "farmjs" for Farm.js Infra, or an unstorage driver such as Redis. Left out, the build picks Farm.js Infra when it has FARMJS_API_KEY and disk on a Node server, and a serverless build stops and asks you to choose.
  • authorize runs before every agent request. Along with the request, it gets the action (start, read, resume, cancel, and the rest) and, for an existing run, the agent and thread from the stored run. Here any signed-in customer can start a refund, and only a reviewer can do anything else. getSessionUser is your app's own session lookup.
  • onInterrupt is called once a run starts waiting on a person. Here it tells the team in Slack. It is best effort, so a Slack outage never fails the refund.

Two more come up as the app grows. tasks starts agent runs on a cron schedule, and presets gives one deploy target its own settings, such as Redis on Vercel and disk on a Node server. The Durable Agents guide has every option.

Let Farm.js Infra hold the run, the clock, and the decision

Storing a run, waking it, and answering it are separate jobs. Pick the ones your app needs.

What you needConfigurationWhere it happens
Hosted run historystorage: "farmjs"Farm.js Infra stores run state
Hosted wake-upsRuntime key and a deployment URLInfra calls the app when work is due
Approval inboxThe same key and URLAn owner or admin answers in Infra
Your Redis, Infra approvalsAGENT_UNIT_CLOCK=localYour timers wake runs

Create a project in Farm.js Infra and a project-scoped API key with agents:runtime, then set these on the server.

Environment
FARMJS_API_KEY=<project-scoped-runtime-key>
AGENT_UNIT_URL=https://agents.example.com
FARMJS_ENVIRONMENT=production

AGENT_UNIT_URL is your deployment's public HTTPS URL. The engine's base path is added to the callback routes, and they have to get through any deployment protection. By default, agent-unit dev stores runs on your disk and does not contact Infra. To try the hosted path, run the built deployment with the key and URL set. Storage and runtime configuration

Answer the refund from the dashboard

When the run reaches run.interrupt, the question appears under Agents → Approvals. An organization owner or admin can approve, reject, add a note, or cancel the run. Infra sends a signed callback to your deployment, and the engine resumes that exact pause with this answer.

TypeScript
{
  approved: true,
  by: "reviewer-id",
  note: "Return received."
}

The refund agent only reads approved. Add by and note to the decision type if you want them on record. A late answer cannot resume a later pause that has the same name. Keep the signed callback endpoints reachable through your middleware. Approval callbacks

Wake the run tomorrow

An agent can also park until a time passes.

TypeScript
await run.sleep("1d");
await run.step("send-reminder", ({ idempotencyKey }) =>
  sendReminder({ orderId: input.orderId, idempotencyKey }),
);

sendReminder is your delivery function, and it uses the key to send once. With hosted wake-ups, Infra calls your deployment when the run is due and your app runs the agent code. On Node, Bun, and Deno, in-process timers also handle due work, and Cloudflare's Durable Objects runtime uses its own alarms. Wake-up behavior by host

Keep your Redis

An app that already stores runs in Redis can keep them there and still use the approval inbox.

TypeScript
// agent-unit.config.ts
import { defineConfig } from "agent-unit";

export default defineConfig({
  storage: { driver: "redis", url: process.env.REDIS_URL },
});

Set AGENT_UNIT_CLOCK=local with the same runtime key. Infra then handles approvals only, and your own timers or a scheduled sweep recover runs and wake sleeping work.

Test the restart before you ship

The engine's test helper runs the agent against an in-memory store. This test parks a run, replaces the engine while the approval is pending, and answers the saved run from the new one.

TypeScript
import assert from "node:assert/strict";
import { createTestUnit } from "agent-unit/testing";
import refund from "./agents/refund";

const unit = createTestUnit({ refund });

const pending = await unit.run("refund", { orderId: "bag-order-123" });
assert.equal(pending.status, "interrupted");

unit.close();
const restarted = createTestUnit({ refund }, { storage: unit.storage });
const finished = await restarted.resume(pending.id, { approved: true });
assert.equal(finished.output.status, "refunded");

const another = await restarted.run("refund", { orderId: "bag-order-456" });
const declined = await restarted.resume(another.id, { approved: false });
assert.equal(declined.output.status, "declined");
restarted.close();

Then do it for real. Park a run on the deployed app, redeploy, and answer the saved run ID. Check that the lookup replays and that the payment provider sees the same idempotency key if an unfinished refund runs again.

Try it

Put the refund agent in agents/refund.ts and start the engine.

Terminal
npm install agent-unit
npx agent-unit dev

It serves the agents in agents/ at http://localhost:3000. Send the two requests from earlier, and restart the dev server between them to watch the run continue.

In a Farm.js app, install @farm.js/agent and agent-unit, register agent(), and move the file to src/agents/refund.ts. As the flow grows, Farm.js Infra's webhooks can deliver payment events to it, cron jobs can call a nightly reconciliation route, and previews let a teammate try it before it ships.

agent-unit · Durable Agents guide · Example app · Farm.js Infra

The agent code says what to do. The journal remembers what already happened. Whichever server is running when the answer arrives picks up from there.

Thanks for building with us.

Keep exploring