Skip to content

AI Agent Durable

Spinning Idea edited this page Oct 28, 2026 · 2 revisions

Durable AI Agents and Practical Solutions


1. Summary & Foundational Concepts

What Is a Durable AI Agent?

A Durable AI Agent is an autonomous software system capable of executing multi-step, long-running, and stateful workflows whose lifecycle, state, reasoning processes, and execution environment survive process terminations, infrastructure restarts, network dropouts, human intervention pauses, and software upgrades.

Unlike conventional conversational agents or simple API-based LLM chains - which reside purely in volatile memory and die when their execution thread terminates - a durable agent treats state, context, tool invocations, queued submissions, and domain data as persistent transactional artifacts.

┌─────────────────────────────────────────────────────────────────────────────┐
│                       TRADITIONAL EPHEMERAL AGENT                           │
│                                                                             │
│  User Prompt ──► [In-Memory Run Loop] ──► [Tool Call] ──► [LLM API]         │
│                         │                                                   │
│                    CRASH / RESTART                                          │
│                         ▼                                                   │
│                   *TOTAL LOSS*                                              │
│       (Mid-flight tool execution lost, queued instructions erased,         │
│          uncommitted side effects unknown, duplicate charges/bugs)          │
└─────────────────────────────────────────────────────────────────────────────┘

                                      VS

┌─────────────────────────────────────────────────────────────────────────────┐
│                           DURABLE AI AGENT                                  │
│                                                                             │
│  External Events ──► [Client Thin Layer] (Web, TUI, Slack, Webhook, Cron)   │
│                                │ (Watch & Steer via HTTP/Socket)            │
│                                ▼                                            │
│  ┌───────────────────────────────────────────────────────────────────────┐  │
│  │                PERSISTENT AGENT HARNESS (Host / VM / Edge)            │  │
│  │                                                                       │  │
│  │  1. Atomic State Commit ──► Persistent Store (SQLite / Postgres / KV) │  │
│  │  2. Deterministic Task Engine (Ownership Trees, Phases, Checkpoints)   │  │
│  │  3. Replay-Safe Tool Protocol (Distinguishes Idempotent vs Dangerous) │  │
│  │  4. Background Compaction Engine (Infinite runs inside finite window) │  │
│  │  5. Sandboxed Isolated Environment (Docker / MicroVM / Node Files)    │  │
│  └───────────────────────────────────────────────────────────────────────┘  │
│                                │                                            │
│                      CRASH / REBOOT / DEPLOY                                │
│                                ▼                                            │
│         [Zero-Downtime Re-open & Instant Resume from Exact State]            │
└─────────────────────────────────────────────────────────────────────────────┘

The Fundamental Flaw of Ephemeral Agents

Traditional agent frameworks (early LangChain chains, AutoGPT, naive Python/Node scripts) bind three fundamentally different concerns into a single ephemeral process:

  1. The Interaction Surface (the CLI, browser tab, or API connection).
  2. The Execution Engine (the loop invoking LLMs and calling tools).
  3. The State (chat memory, task queue, and filesystem modifications).

When an ephemeral agent crashes mid-task, several critical failures occur:

  • Orphaned Operations: A tool call may have already sent an email, charged a credit card, or created a Git branch, but because the response was never processed, restarting the script causes duplicate actions.
  • Torn Context: The conversation history saved by simple /resume mechanisms only captures completed turns. Any pending inputs, partially collected tool outputs, subagent conversations, or queued user instructions vanish.
  • Client Lock-in: The agent only lives as long as the terminal window or web browser session remains open. If your laptop goes to sleep, your multi-hour coding or research task is killed.

Chat History /resume vs. True Durable Execution

Most developers assume adding chat persistence (e.g., storing the conversation array in MongoDB or Redis) makes an agent "durable." As highlighted by both MindStudio and Earendil, transcript history is not run state:

Dimension Naive Transcript/resume True Durable Execution
What is Stored Text array of user and assistant messages Event journals, execution checkpoints, pending queues, active task ownership trees, and structured application state
Tool Crash Recovery Blindly re-runs the entire prompt or fails completely Identifies interrupted tool calls; re-executes only replay-safe tools; passes interrupted output to agent for dangerous tools
Duplicate Prevention None (risk of repeating side effects) Request idempotency keys + atomic transaction commits
Subagent Lifecycles Subagents are ephemeral threads that vanish on restart Hierarchical task trees where subagents are first-class durable tasks with their own rollback/abort policies
Context Window Overflows Crashes with providercontext_length_exceeded errors Non-destructive background compaction summarizes active turns while preserving full searchable history on disk
Client Decoupling Tied directly to the client connection The agent runs on a server/device; clients can disconnect, reconnect, watch, and steer from multiple surfaces

Key Takeaways from MindStudio & Earendil's Analysis

Based on the groundbreaking analyses by MindStudio and Earendil, several design truths define modern durable agent architecture:

  1. A Harness is Not Just a Wrapper, It is an Operating System for LLMs: A harness consists of storage, model interfaces, tool registries, and execution environments. It coordinates parallel conversations, manages tasks, and bounds memory usage.
  2. Idempotency and Replay Safety Must Be Tool-Declared: Automatic replaying of unconfirmed tool calls after a crash is a catastrophic antipattern. Safe tools (e.g., reading a file, searching a database) must explicitly declare replay: "safe". Unsafe tools (e.g., writing files, sending HTTP POSTs) must return an interrupted result, forcing the LLM to inspect what partially occurred and decide how to proceed.
  3. Documents Must Commit Atomically with Transcripts: Application state (such as task boards, issue status, and cart details) cannot live in a disconnected database from the LLM transcript. If the agent updates domain data, both the transcript entry and the typed domain document must commit inside the same atomic transaction.
  4. Proactive Over Reactive ("Works for you, then waits"): Durable agents shift the paradigm from reactive chatbots to proactive background workers. They monitor logs, queues, or webhooks, triage and execute long investigations autonomously, and pause at a human-in-the-loop checkpoint only when an irreversible action requires sign-off.
  5. Multiplayer Steering: Because agent state is committed to a persistent store, multiple clients (different team members, Slack bots, web dashboards, terminal TUIs) can connect to the running harness concurrently, observe live streaming tokens, and inject steering messages without breaking the agent loop.

2. Core Challenges & Engineering Dilemmas of Durable Agents

1. Tool Replay & Side-Effect Non-Determinism

When an agent dies while executing an external API call, did the call succeed on the remote server before the local process crashed?

  • The At-Least-Once Danger: If the harness automatically retries the tool, an e-commerce agent might charge the customer twice.
  • The At-Most-Once Danger: If the harness skips the tool, the agent may assume an operation occurred when it did not.
  • Solution: Two-phase commit logic, deterministic request IDs, explicit replay: "safe" flags, and transactional abort hooks (e.g., Sagas).

2. Context Window Physics & Compaction

Durable agents can run for days, weeks, or indefinitely, accumulating millions of tokens. However:

  • LLMs have hard context limits (e.g., 128k, 200k, 1M, or 2M tokens).
  • Attention degrades over ultra-long contexts ("needle-in-a-haystack" degradation).
  • The Compaction Pattern: Durable agents run background compaction tasks before hitting context thresholds. The harness summarizes older turns into a clean system briefing placed at turn boundaries, while storing raw historical turns in cold database storage with vector/keyword indexing (search_history tool).

3. Execution Sandboxing and Environment Portability

Durable agents execute terminal commands, edit code, and browse the web.

  • If the agent runs directly on the host, a rogue command can brick the host.
  • If the agent runs in a cloud container, restarting or redeploying the container must not delete the working filesystem or browser profile.
  • Solution: Persistent volume mounts, Docker supervisors (e.g., OpenBot), or lightweight microVMs (e.g., Firecracker, Fly Machines, modal/e2b sandboxes).

4. Frontier Foundation Models for Durable Agents (Claude 5.5 & GPT-6 Generations)

Durable agents require significantly more rigorous capabilities from underlying foundation models than ephemeral chatbots:

  • Anthropic Frontier Models (Claude 5.5 Family):
    • Claude Sonnet 5.5 (claude-sonnet-5-5): The primary workhorse for agentic coding and knowledge workflows. Delivers 70.6% on Terminal-Bench 4.0, runs 30%+ faster than previous generations, includes 1M token context windows, and uses adaptive thinking to reason through multi-step failures without getting stuck in infinite loops.
    • Claude Opus 5.5 (claude-opus-5-5): Designed for deep architectural synthesis and high-complexity reasoning, running at significantly lower token consumption than earlier models.
    • Claude Fable 5.1 (claude-fable-5-1): Purpose-built for extreme long-horizon autonomous tasks and formal verification.
  • OpenAI Frontier Models (GPT-6 Family):
    • GPT-6.1 Sol (gpt-6.1-sol) / GPT-6 Sol (gpt-6-sol): OpenAI's flagship agentic reasoning models succeeding the older GPT-4o, GPT-5, and o3 lines. Engineered with native computer-use capabilities, robust schema adherence, and native support for asynchronous checkpoint resumes.
    • GPT-6 Luna (gpt-6-luna): Ultra-fast, cost-efficient model optimized for log triage, real-time telemetry classification, and fast routing within durable harnesses.
  • Why These Models Eclipse Older Generations (Claude 3.7 / GPT-4o / o3-mini):
    • Deterministic Structured Tool Calling: Older models frequently hallucinate optional tool parameters on resumption. The 5.5/6.x generation enforces strict schema determinism.
    • Adaptive Thinking: Rather than spending fixed token budgets on trivial steps, adaptive reasoning scales thinking tokens based on task difficulty.
    • Reduced Token Footprint: In long-running loops, Sonnet 5.5 and GPT-6 Sol use up to 30–40% fewer output tokens to complete the same multi-step task, dramatically reducing compaction frequency and API bills.

3. Directory of Available Solutions to Power Durable Agents in Practice

Here is a detailed breakdown of the premier open-source and enterprise frameworks powering durable AI agents in practice today.


Solution 1: Pi Durable (@earendil-works/pi-durable) & Durable Pi (disler/durable-pi)

Overview & Architecture

Pi Durable is an experimental, lightweight, zero-dependency framework released alongside Pi 1.0 by Earendil. Built on minimalism and malleability (~15,000 lines of TypeScript), it provides the foundational primitives for durable agent harnesses.

Durable Pi by Nathan Disler operationalizes Pi Durable into a distributed, multi-device agent network with proactive capabilities, web interfaces, and terminal TUIs.

  • Key Architectural Components:
    • Harness: Manages parallel conversations, model providers, tool registries, and execution environments.
    • Storage Engine: Pluggable storage (Node SQLite, JSONL, Memory, Cloudflare Durable Objects). SQLite only keeps active transcripts in memory; the rest remains on disk.
    • Tasks & Ownership Trees: Hierarchical execution units (defineTask) with phases (initial, waiting, terminal), policies (failFast), and rollback/abort handlers.
    • Atomic Typed Documents (defineDoc): Domain state (e.g., todos, tickets) stored and committed atomically with conversation transcripts.
    • Dynamic Malleability: Extensions and tools can be hot-reloaded and swapped on disk without stopping running conversations.
    • Compaction Engine: Non-blocking background compaction tasks summarize history before context limits are reached.

Step-by-Step Setup Guide

# 1. Clone the Durable Pi network repository
git clone https://github.com/disler/durable-pi.git
cd durable-pi

# 2. Configure Environment Variables
cp .env.example .env
# Edit .env and supply your OPENROUTER_API_KEY

# 3. Setup device network configuration
cp dpi-network.example.yaml dpi-network.yaml

# 4. Install dependencies (Node 24 required)
just install

# 5. Initialize the local device backend
just net up local

# 6. Build the web hub frontend
just hub build

# 7. Start the device backend daemon (runs agent server on :4780)
just backend run

# 8. In a separate terminal, launch the Web Hub UI (serves at http://localhost:4781)
just hub start

# 9. In another terminal, connect via terminal TUI to inspect and steer
just tui attach local

Code Implementation Example (Native Pi Durable)

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 { createRegistry, Harness, defineTool } from "@earendil-works/pi-durable";
import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node";
import { openNodeSqliteStorage } from "@earendil-works/pi-durable/storage/sqlite/node";
import { Type } from "@sinclair/typebox";

const context = BACKGROUND_CONTEXT;
const models = createModels();
models.setProvider(openaiProvider());

const registry = createRegistry();

// Define a tool with explicit replay safety
registry.install({
  name: "search_tool",
  tools: [
    defineTool({
      name: "search",
      description: "Search system records",
      parameters: Type.Object({ query: Type.String() }),
      replay: "safe", // <--- CRITICAL: Tells harness safe to re-run on restart
      execute: async (args) => {
        return { content: [{ type: "text", text: `Results for ${args.query}` }] };
      },
    }),
  ],
});

const storage = await openNodeSqliteStorage("./agent_state.sqlite");
const harness = await Harness.open(storage, {
  models,
  registry,
  env: ({ cwd }) => new NodeExecutionEnv({ cwd: cwd ?? process.cwd() }),
  settings: {
    compaction: { reserveTokens: 16384, backgroundTokens: 32768 },
  },
}, context);

const root = await harness.root(context, {
  // Configured with Anthropic Claude Sonnet 5.5 (or OpenAI GPT-6.1 Sol) for long-horizon agentic reasoning
  agent: {
    model: { provider: "anthropic", modelId: "claude-sonnet-5-5" }, // or provider: "openai", modelId: "gpt-6.1-sol"
    cwd: "./workspace",
  },
});

Costs

  • Framework: 100% Free and Open Source (MIT License).
  • Compute: Runs locally on your laptop, a Raspberry Pi, or any cheap Linux VPS ($4–$10/month).
  • LLM Calls: Pay-per-token directly to LLM providers (OpenAI, Anthropic, OpenRouter). Background compaction adds minor token overhead (~$0.01–$0.05 per compaction cycle).

Caveats & Shortcomings

  • Single-Process Storage Ownership: SQLite backend locks the file; multiple standalone processes cannot write concurrently to the same database file (one backend server must own the store while clients attach via HTTP/WebSocket).
  • Default SQLite Durability: Default SQLite sync settings do not protect against sudden catastrophic OS power cuts without tuning PRAGMA synchronous = FULL or WAL modes.
  • Pre-1.0 Experimental API: Method signatures and serialization formats are subject to changes.
  • Tool Author Burden: Replay safety is not automatic; developers must explicitly audit and flag every tool as replay: "safe" or handle interruption recovery.

Key Resources & Links


Solution 2: OpenDots (CopilotKit/OpenDots)

Overview & Architecture

OpenDots is an open-source, full-stack application template designed for persistent, always-on AI coworkers that operate across Web, Mobile, Voice/Phone calls, and Slack.

  • Key Architectural Components:
    • Specialist Dots: Isolated agents configured with custom instructions, distinct roles, tool restrictions, and persistent memory.
    • Dedicated Computer Environments (OpenBot): Each Dot has its own isolated containerized environment (Docker supervisor) with persistent browser profiles, virtual desktop displays, and filesystem storage that survive agent restarts.
    • Spaces (Living Document Workspaces): Durable documents stored in SQLite/Postgres. Dots write notes, revise pages, and organize drafts.
    • Human-in-the-Loop Review Cards: Destructive or side-effecting operations (e.g., executing shell scripts, saving pages, modifying remote services) trigger CopilotKit interactive review cards in chat, pausing execution until the user clicks Approve & Run or Decline.
    • Ecosystem Connectivity: Integrates with Composio (for Gmail, Google Calendar, GitHub, Salesforce) and MCP (Model Context Protocol) servers.

Step-by-Step Setup Guide

# 1. Clone the OpenDots repository
git clone https://github.com/CopilotKit/OpenDots.git
cd OpenDots

# 2. Install dependencies (PNPM recommended)
pnpm install

# 3. Configure environment variables
cp .env.example .env
# Set OPENAI_API_KEY, ANTHROPIC_API_KEY, and COPILOTKIT_RUNTIME_URL

# 4. (Optional) Setup OpenBot Container Sandbox for Isolated Computers
cd docker/openbot
docker compose up -d
cd ../..

# 5. Run Database Migrations (Prisma / SQLite / Postgres)
pnpm db:push

# 6. Start the local development server
pnpm dev
# Access the web interface at http://localhost:3000

Costs

  • Application Core: 100% Open Source (MIT License).
  • CopilotKit Intelligence: Free local Docker evaluation or self-hosted deployment; hosted enterprise tiers available for team management.
  • Compute / Sandboxes: Running Dockerized desktop/browser containers per agent requires at least 4GB–8GB RAM on a VPS or cloud cluster (~$20–$50/month).
  • Third-Party Integrations: Composio offers a generous free tier, with paid plans based on connected accounts and tool triggers.

Caveats & Shortcomings

  • Heavy Resource Footprint: Running persistent virtual desktop environments and Chromium browser profiles inside Docker containers for multiple Dots consumes substantial CPU and memory.
  • Alpha Stage: Active rapid development; schema migrations between versions may require manual database updates.
  • External Service Dependencies: Full functionality across text, phone, and Slack requires configuring multiple webhook endpoints, Twilio/Daily credentials, and Composio tokens.

Key Resources & Links


Solution 3: Devin (Cognition AI)

Overview & Architecture

Devin is the industry benchmark for autonomous, durable software engineering agents. Built from the ground up for multi-hour and multi-day workloads, Devin is fundamentally architected as a persistent cloud environment rather than a transient chat wrapper.

  • Key Architectural Components:
    • Persistent Cloud MicroVM Sandboxes: Every Devin session spins up a dedicated, isolated cloud VM with an active terminal, shell environment, code editor, and sandboxed Chromium browser.
    • Asynchronous Execution & Reconnectability: Sessions run completely decoupled from client devices. Users can initiate a task via Slack, CLI, Web, or IDE, disconnect for hours, and return to find work completed, tested, and staged.
    • Hierarchical Subagent Workflows: Devin spawns read-only exploration subagents (subagent_explore) and code execution subagents (subagent_general) in parallel, maintaining isolated context and execution trees.
    • Checkpointing & Git History Verification: Devin commits intermediate checkpoints to its working state, compiles code, runs test suites, and verifies fixes before declaring completion.
    • Steerability & Mid-Flight Intervention: Humans can pause, inject guidance, supply missing API keys, or interact directly with the browser/terminal while the agent is paused.

Step-by-Step Setup Guide

# 1. Install Devin CLI globally (via npm or curl)
npm install -g devin-cli

# 2. Authenticate your CLI session
devin login

# 3. Initialize Devin inside your local project repository
cd /path/to/my-project
devin init

# 4. Start an asynchronous durable task
devin run "Refactor authentication layer to use OAuth2 PKCE and add unit tests"

# 5. Detach and let Devin execute in the cloud background
# (You can close your laptop or terminal)

# 6. Re-attach and inspect progress at any time
devin sessions
devin attach <session-id>

Costs

  • Enterprise / Professional Subscription Model: Paid SaaS tiers (starting around $500/month for team plans or per-seat engineering access).
  • Compute Included: Sandboxed cloud VMs, browser instances, and execution runtime are bundled into the subscription.
  • LLM Compute Included: High-end frontier reasoning models are managed and supplied directly by Cognition.

Caveats & Shortcomings

  • Closed-Source Platform: The underlying orchestration engine and VM lifecycle manager are proprietary SaaS technologies.
  • Cost Barrier: Tailored for enterprise software engineering organizations rather than casual hobbyist experimentation.
  • Domain Specialization: Highly optimized for coding, debugging, deployment, and developer workflows; less suited for generic arbitrary consumer chatbot apps.

Key Resources & Links


Solution 4: Temporal (Temporal AI Agents)

Overview & Architecture

Temporal is the enterprise standard for durable execution systems, powering mission-critical workflows at Stripe, Netflix, and Uber. Through its deterministic event sourcing model, Temporal has emerged as one of the most resilient backends for production AI agents.

  • Key Architectural Components:
    • Deterministic Workflow Functions: Agent loops are expressed as pure code workflows. Every workflow decision is recorded in an immutable append-only event history.
    • Non-Deterministic Activities: LLM calls, web searches, database writes, and bash commands are wrapped inside Temporal Activities. If an activity fails or times out, Temporal handles exponential backoff, jittered retries, and circuit breaking.
    • Replay-Driven Resumption: When a worker node crashes or redeploys, a new worker reloads the event history, replays the workflow to reconstruct the exact in-memory state, and executes subsequent steps without re-calling completed activities.
    • Durable Timers & Signals: Agents can sleep for days, wait for external webhooks, or pause indefinitely for human approval via Temporal Signals.

Step-by-Step Setup Guide

# 1. Install Temporal CLI
curl -sSf https://temporal.download/cli.sh | sh

# 2. Start the local Temporal development server
temporal server start-dev

# 3. Create a TypeScript/Python agent project
mkdir temporal-durable-agent && cd temporal-durable-agent
npm init -y
npm install @temporalio/workflow @temporalio/activity @temporalio/client @temporalio/worker openai

Code Implementation Example (Temporal Durable Agent)

// workflow.ts
import { proxyActivities, defineSignal, setHandler, condition } from '@temporalio/workflow';
import type * as activities from './activities';

const { callLLM, executeTool } = proxyActivities<typeof activities>({
  startToCloseTimeout: '5 minutes',
  retry: { maximumAttempts: 5 },
});

export const humanApprovalSignal = defineSignal<[boolean]>('humanApproval');

export async function durableAgentWorkflow(goal: string): Promise<string> {
  let approved = false;
  setHandler(humanApprovalSignal, (status) => { approved = status; });

  let state = { goal, stepsCompleted: [] as string[] };
  
  // Step 1: Query LLM (Activity is checkpointed in Temporal history)
  const plan = await callLLM(`Plan for: ${goal}`);
  
  // Step 2: Require Human Approval via Signal if plan involves high-risk actions
  if (plan.requiresApproval) {
    await condition(() => approved); // Sleeps durably in Temporal event history without burning CPU
  }

  // Step 3: Execute tool reliably via activity retry policies
  const result = await executeTool(plan.toolName, plan.toolArgs);
  return result;
}

Costs

  • Temporal Server Core: 100% Free and Open Source (MIT License, self-hostable via Docker/Kubernetes).
  • Temporal Cloud: Pay-as-you-go managed service based on Actions (around $0.000025 per Action).
  • LLM APIs: Standard direct provider billing.

Caveats & Shortcomings

  • Determinism Constraints: Workflow code must be 100% deterministic (no random UUIDs, direct Date.now(), or direct network calls inside the workflow function itself - all non-determinism must live in Activities).
  • Steep Learning Curve: Requires understanding distributed event sourcing, replay mechanics, and activity separation.
  • History Size Limits: Temporal limits single workflow execution histories to 50,000 events or 50MB, necessitating continueAsNew patterns for perpetual agent loops.

Key Resources & Links


Solution 5: Inngest (Inngest AgentKit & Serverless Durable Execution)

Overview & Architecture

Inngest is an event-driven durable execution engine designed for TypeScript and Python. It brings workflow-grade durability to serverless environments (AWS Lambda, Vercel, Cloudflare Workers, Next.js) without needing dedicated server daemons.

  • Key Architectural Components:
    • Step Functions (step.run, step.ai.wrap): Every LLM request and tool execution is encapsulated in a step. Completed steps are memoized; on failure or redeployment, Inngest resumes from the first unexecuted step.
    • Zero Server Infrastructure: Operates via HTTP endpoints on your existing web framework. Inngest manages the orchestration engine and communicates via secure webhooks.
    • Inngest AgentKit: High-level primitives for routing, network agents, state management, and multi-agent coordination.
    • Built-in Throttling & Concurrency Controls: Manages rate limits across model providers with automated queuing.

Step-by-Step Setup Guide

# 1. Install Inngest and AgentKit in your Next.js / Node project
npm install inngest @inngest/agent-kit

# 2. Run the local Inngest Dev Server
npx inngest-cli@latest dev

# 3. Create your durable agent endpoint
# (e.g. app/api/inngest/route.ts in Next.js)

Code Implementation Example (Inngest AgentKit)

import { Inngest } from "inngest";
import { createAgent, createTool } from "@inngest/agent-kit";

export const inngest = new Inngest({ id: "durable-agent-system" });

const deployServiceTool = createTool({
  name: "deploy_service",
  description: "Deploys code to production cluster",
  handler: async (input, { step }) => {
    // Durable step execution
    return await step.run("trigger-deploy", async () => {
      const res = await fetch("https://api.cloud.com/deploy", { method: "POST" });
      return res.json();
    });
  },
});

export const deployAgentFunction = inngest.createFunction(
  { id: "proactive-deployment-agent" },
  { event: "incident.detected" },
  async ({ event, step }) => {
    const agent = createAgent({
      name: "Triage Agent",
      tools: [deployServiceTool],
      system: "Investigate and resolve incidents safely.",
    });

    const result = await agent.run(`Incident detected: ${event.data.errorDetails}`, { step });
    return result;
  }
);

Costs

  • Inngest Open Source: Dev server is free.
  • Inngest Cloud: Free tier includes 50,000 steps/month; paid plans start at $25/month.
  • Hosting: Can run on free or low-cost serverless tiers (Vercel, Cloudflare, Fly.io).

Caveats & Shortcomings

  • Serverless HTTP Timeouts: Long streaming responses must be carefully managed within serverless function execution timeout limits (e.g., 60s on basic Vercel tiers).
  • Hosted Orchestration Reliance: Self-hosting the Inngest orchestration cluster is more complex than running the managed cloud service.

Key Resources & Links


Solution 6: Vercel Workflows (workflow SDK & Vercel Managed Platform)

Overview & Architecture

Vercel Workflows brings native durable execution, reliability, and observability to asynchronous JavaScript, TypeScript, and Python without requiring manual queues, complex state machines, or external database plumbing.

Powered by the open-source Workflow SDK (workflow package) and workflow support in the Vercel Python SDK, Vercel Workflows allows developers to write standard async functions that can suspend for minutes, hours, or months, survive server crashes and continuous deployments, and resume execution with deterministic replay.

  • Key Architectural Components:
    • Directives ('use workflow' & 'use step'): Functions annotated with 'use workflow' act as durable orchestrators. Functions annotated with 'use step' are atomic, retriable execution units whose inputs and outputs are automatically recorded and memoized.
    • Zero Execution Timeouts: Eliminates standard serverless function timeouts (e.g. 15s or 60s). Workflows can pause, sleep (sleep()), or wait for external human review without keeping compute instances warm or consuming CPU cycles.
    • Managed Execution Stack:
      • Vercel Functions: Executes workflow orchestrators and step code across global edge and serverless regions.
      • Vercel Queues: Handles reliable background dispatch and event enqueuing without operational overhead.
      • Managed Persistence: Automatically journals run state, inputs, outputs, errors, and execution timelines in an optimized database with zero manual configuration.
    • AI SDK & Chat SDK Synergy: Built to integrate natively with Vercel's AI SDK (generateText, streamText) and Chat SDK for interactive human-in-the-loop Slack bots and web interfaces.
    • Agent Harness Portability (durable-harness): Bridges autonomous coding agents (Pi, Claude Code, OpenCode) with Workflow SDK persistence infrastructure so coding agent sessions resume after container or process interruptions.
    • Multi-Region Pinning & Skew Protection: Runs pin to the initiating region to eliminate cross-region round trips. In-flight workflows continue on their original deployment version while new runs execute on latest code.

Step-by-Step Setup Guide

# 1. Install the Workflow SDK and Vercel AI SDK
npm install workflow ai @ai-sdk/openai
# Or with pnpm / bun:
# pnpm add workflow ai @ai-sdk/openai

# 2. Configure environment variables in .env.local
OPENAI_API_KEY="your-openai-api-key"

# 3. Create your durable agent workflow (e.g. app/workflows/incident-agent.ts)

# 4. Trigger the workflow from an API Route or Server Action
# (e.g. app/api/triage/route.ts)

# 5. Deploy directly to Vercel (zero infra provisioning required)
vercel deploy

Code Implementation Example (Durable Agent Workflow with Vercel AI SDK)

// app/workflows/incident-agent.ts
import { generateText } from "ai";
import { anthropic } from "@ai-sdk/anthropic";

// Define an atomic, durable step with automatic retry policies and memoization
export async function triageLogStep(logs: string) {
  "use step";
  // Utilizing Claude Sonnet 5.5 with adaptive thinking (or OpenAI GPT-6.1 Sol) for deep root-cause triage
  const { text } = await generateText({
    model: anthropic("claude-sonnet-5-5"), // or openai("gpt-6.1-sol")
    prompt: `Analyze the following system error logs and identify root cause: ${logs}`,
  });
  return text;
}

export async function deployFixStep(patchDetails: string) {
  "use step";
  // Side-effecting step: will only execute once and memoize outcome
  const response = await fetch("https://api.github.com/repos/my-org/my-repo/dispatches", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.GITHUB_TOKEN}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ event_type: "apply_patch", client_payload: { patchDetails } }),
  });
  return response.ok ? "Patch deployed" : "Deployment failed";
}

// Durable orchestrator function
export async function durableIncidentWorkflow(rawLogs: string) {
  "use workflow";

  // Step 1: LLM Reasoning step (memoized on completion, retried on API outage)
  const diagnosis = await triageLogStep(rawLogs);

  // Step 2: Durable pause / human-in-the-loop sign-off (sleeps without burning compute)
  // Workflows can pause or wait for external webhook/hook callbacks

  // Step 3: Execute external side-effect safely
  const deployResult = await deployFixStep(diagnosis);

  return { diagnosis, deployResult };
}

Triggering the workflow:

// app/api/incident/route.ts
import { start } from "workflow/api";
import { durableIncidentWorkflow } from "@/workflows/incident-agent";

export async function POST(req: Request) {
  const { logs } = await req.json();

  // Launches durable execution in the region closest to the requester
  const run = await start(durableIncidentWorkflow, [logs], { region: "sfo1" });

  return Response.json({
    runId: run.id,
    statusUrl: run.url,
  });
}

Costs

  • Workflow SDK Core: Open source library.
  • Vercel Workflows Platform: Usage-based pricing based on Events, Data Written, and Data Retained. Compute is only billed during active step execution; durable sleep and pause states incur zero compute cost.
  • LLM Calls: Direct billing via OpenAI / Anthropic or routing through Vercel AI Gateway with caching.

Caveats & Shortcomings

  • Vercel Ecosystem Affinity: While the Workflow SDK is open source, out-of-the-box zero-config queues, persistence, and dashboard observability are tightly coupled to deploying on Vercel.
  • Serverless Architectural Paradigm: Best suited for event-driven, step-based workflows; not designed to run persistent raw Docker containers with full desktop GUI virtual displays on the edge (use OpenDots/Devin for dedicated container/microVM setups).

Key Resources & Links


Solution 7: LangGraph & LangGraph Platform (LangChain)

Overview & Architecture

LangGraph is LangChain’s cyclical graph orchestration framework. It re-architected agent design away from linear DAGs to stateful cyclic graphs with native persistence.

  • Key Architectural Components:
    • Checkpointer Subsystem: Every node transition in the graph saves a snapshot via pluggable checkpointers (SqliteSaver, PostgresSaver, AsyncPostgresSaver).
    • Human-in-the-Loop Interrupts (interrupt()): Nodes can pause execution before calling sensitive tools. The state remains suspended in the checkpointer until an external API call resumes it.
    • Time-Travel Debugging & State Forking: Because every turn is a distinct checkpoint ID, developers can rewind state to a previous node, edit the transcript or variable state, and fork execution down a new path.
    • LangGraph Cloud / Platform: Managed infrastructure providing horizontal scaling, task queues, streaming APIs, and studio interfaces for deployed graphs.

Step-by-Step Setup Guide

# 1. Install LangGraph and Anthropic/Postgres checkpointer
pip install -U langgraph langchain-anthropic psycopg-pool

# 2. Or for TypeScript:
npm install @langchain/langgraph @langchain/anthropic @langchain/community

Code Implementation Example (LangGraph Checkpointed Agent)

import os
from typing import Annotated
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
from langgraph.checkpoint.sqlite import SqliteSaver
from langchain_anthropic import ChatAnthropic

class AgentState(TypedDict):
    # Using add_messages reducer to durably append new turns rather than overwrite
    messages: Annotated[list, add_messages]
    order_id: str
    status: str

def triage_node(state: AgentState):
    # Utilizing Claude Sonnet 5.5 (or OpenAI GPT-6.1 Sol via langchain-openai) for stateful multi-turn reasoning
    llm = ChatAnthropic(model="claude-sonnet-5-5")
    response = llm.invoke(state["messages"])
    return {"messages": [response], "status": "reviewed"}

# Setup cyclic or multi-node state graph
builder = StateGraph(AgentState)
builder.add_node("triage", triage_node)
builder.add_edge(START, "triage")
builder.add_edge("triage", END)

# Configure durable persistence backend
with SqliteSaver.from_conn_string("checkpoints.db") as memory:
    # interrupt_before enables human-in-the-loop intervention
    app = builder.compile(checkpointer=memory, interrupt_before=["triage"])
  
    # Run with a stable thread_id for state resumption across process restarts
    config = {"configurable": {"thread_id": "session-customer-42"}}
    events = app.stream({"messages": [("user", "Cancel my order")], "order_id": "1001"}, config)
    for event in events:
        print(event)

Costs

  • LangGraph Core: 100% Open Source (MIT License).
  • LangGraph Cloud / Platform: Paid managed tier for deployment ($0.0015 per node invocation or per-seat licensing); self-hosting available via Docker.

Caveats & Shortcomings

  • Framework Complexity: Working with channels, reducers, and schemas requires adapting to LangGraph's specific paradigm.
  • Large Checkpoint Overhead: By default, saving full state at every node transition in high-frequency graphs can cause rapid Postgres table bloat without automated vacuuming or snapshot pruning.

Key Resources & Links


Solution 8: Restate (Durable RPC & Virtual Objects for AI)

Overview & Architecture

Restate is a lightweight durable execution engine designed for event-driven microservices and AI workflows. Restate acts as a durable proxy and RPC layer between your code and the outside world.

  • Key Architectural Components:
    • Virtual Objects: An agent instance is modeled as a stateful Virtual Object with a unique ID (e.g., agent/support-user-123). Restate guarantees that calls to this ID are serialized, preventing race conditions.
    • Durable RPC & Suspensions: When an agent calls an LLM, Restate journals the call. If the LLM takes 60 seconds or fails, the handler suspends without holding a thread or connection.
    • Zero Database Boilerplate: State is stored via ctx.get("key") and ctx.set("key", value); Restate manages replication, consistency, and storage under the hood.

Step-by-Step Setup Guide

# 1. Download and run Restate Server locally
curl -sSL https://get.restate.dev | bash
restate-server

# 2. Initialize TypeScript service
npm install @restatedev/restate-sdk

Code Implementation Example (Restate Virtual Object Agent)

// agent-service.ts
import * as restate from "@restatedev/restate-sdk";

export const durableAgent = restate.object({
  name: "DurableAgent",
  handlers: {
    runTurn: async (ctx: restate.ObjectContext, input: { prompt: string }) => {
      // Retrieve persistent agent memory
      const history = (await ctx.get<string[]>("history")) ?? [];

      // Step 1: Journaled non-deterministic LLM call
      const decision = await ctx.run("reasoning-step", async () => {
        // e.g. Call OpenAI or Anthropic model
        return `Action plan for: ${input.prompt}`;
      });

      // Step 2: Side-effect execution (deduplicated by Restate journal)
      const executionResult = await ctx.run("execute-tool", async () => {
        return `Executed: ${decision}`;
      });

      // Save updated state
      history.push(`User: ${input.prompt}`);
      history.push(`Result: ${executionResult}`);
      ctx.set("history", history);

      return { decision, executionResult };
    },
  },
});

restate.endpoint().bind(durableAgent).listen(9080);

Costs

  • Restate Engine: Open Source (BSL 1.1 / Apache 2.0).
  • Compute: Extremely lightweight single-binary Rust core; runs easily on small instances ($5/month).

Caveats & Shortcomings

  • Separate Daemon Requirement: Requires running and maintaining the Restate cluster binary alongside your application workers.
  • Newer AI Ecosystem: Newer than LangChain/Temporal, so fewer pre-built AI tool templates exist off-the-shelf.

Key Resources & Links


Solution 9: DBOS (Database-Oriented Operating System)

Overview & Architecture

DBOS is an innovative transactional operating system created by database pioneers Michael Stonebraker and Matei Zaharia. It replaces traditional OS/cloud middleware by running lightweight application functions directly on top of Postgres transactions.

  • Key Architectural Components:
    • Lightweight Durable Workflows: Decorate any TypeScript or Python function with @DBOS.workflow(). Every step is recorded in Postgres with sub-millisecond overhead.
    • Exactly-Once Execution Guarantees: Guarantees that agent tool executions and transitions occur exactly once, even during hardware failures or sudden crashes.
    • Integrated Auth & Logging: Application state, audit logs, and workflow histories live together in Postgres, queryable via SQL.

Step-by-Step Setup Guide

# 1. Initialize a DBOS TypeScript project
npx @dbos-inc/create@latest my-durable-agent
cd my-durable-agent

# 2. Start PostgreSQL via Docker and run
npm run start

Code Implementation Example (DBOS Transactional Agent)

// agent-service.ts
import { DBOS } from "@dbos-inc/dbos-sdk";

export class DurableAgentService {
  @DBOS.step()
  static async callLLMStep(prompt: string): Promise<string> {
    // LLM invocation recorded in PostgreSQL transaction log
    return `Plan for task: ${prompt}`;
  }

  @DBOS.step()
  static async executeToolStep(plan: string): Promise<string> {
    // External API invocation guaranteed to execute exactly once
    return `Completed execution of: ${plan}`;
  }

  @DBOS.workflow()
  static async agentWorkflow(task: string): Promise<{ plan: string; result: string }> {
    const plan = await DurableAgentService.callLLMStep(task);
    const result = await DurableAgentService.executeToolStep(plan);
    return { plan, result };
  }
}

Costs

  • DBOS Core: Open Source (Apache 2.0).
  • DBOS Cloud: Managed serverless Postgres application hosting available.

Caveats & Shortcomings

  • Postgres Coupling: Strictly requires PostgreSQL (not suitable for pure SQLite or key-value setups).
  • Relatively Young Ecosystem: Emerged recently; community patterns for agent-specific compaction and streaming are still evolving.

Key Resources & Links


Solution 10: LangChain Deep Agents

Overview & Architecture

Deep Agents is LangChain's open-source "agent harness" - an opinionated, batteries-included agent loop built directly on top of LangGraph's durable execution primitives. Rather than designing a custom state graph, you get a production-oriented agent tuned for long-horizon, multi-step work (research, coding, autonomous workflows) out of the box.

  • Key Architectural Components:
    • Planning Middleware (write_todos): The TodoListMiddleware gives agents a structured tool to decompose objectives, track progress, and adapt plans mid-run.
    • Subagent Delegation: Spawn general-purpose or specialized subagents, each running in an isolated context window, to parallelize independent subtasks without polluting the main thread.
    • Virtual Filesystem: Read, write, edit, and search over pluggable local, sandboxed, or remote filesystem backends - used both as a working surface and to offload large tool results out of the context window.
    • Context Management Middleware: Automatically summarizes long threads, offloads tool outputs to disk, and applies prompt caching to control cost and latency across long runs.
    • Persistent Memory & Skills: Pluggable BaseStore backends provide cross-session recall; on-demand "skills" let the agent load reusable behaviors.
    • Inherited LangGraph Durability: Because the harness compiles to a LangGraph graph, it natively supports checkpointer persistence, streaming, thread resumption, and interrupt()-style human-in-the-loop approval of tool calls.

Note: Comparison to LangGraph & LangGraph Platform (Solution 7)

Deep Agents is not a competitor to LangGraph - it is a layer on top of it:

  • LangGraph (framework): The low-level orchestration engine. You design the state schema, nodes, edges, reducers, and checkpointer wiring yourself. Maximum control, maximum effort.
  • Deep Agents (harness): A pre-built, opinionated agent that runs on LangGraph internally. It reuses LangGraph's checkpointers, stores, streaming, and interrupts, but ships the "deep agent" pattern - planning, filesystem, subagents, context management - as ready-made middleware.
  • LangGraph Platform / LangSmith (infrastructure): The managed deployment and observability layer. Both raw LangGraph graphs and Deep Agents can be deployed there, self-hosted via Docker, or run on LangSmith-managed infrastructure.

Rule of thumb: choose raw LangGraph when you need bespoke control flow or nonstandard agent topologies; choose Deep Agents when the standard plan→delegate→execute→persist pattern fits and you want durability without assembling the harness by hand.

Step-by-Step Setup Guide

# 1. Install the Deep Agents SDK (Python or TypeScript)
uv add deepagents            # Python
npm install deepagents       # JavaScript / TypeScript

# 2. Install a durable checkpointer backend for resumable state
uv add langgraph-checkpoint-postgres psycopg-pool

Code Implementation Example (Durable Deep Agent with Postgres Checkpointer)

from deepagents import create_deep_agent
from langgraph.checkpoint.postgres import PostgresSaver

# Durable state: every agent step checkpoints to Postgres, so a crashed
# run resumes from the last committed snapshot via the same thread_id.
with PostgresSaver.from_conn_string("postgresql://localhost:5432/agents") as checkpointer:
    checkpointer.setup()

    agent = create_deep_agent(
        model="anthropic:claude-sonnet-4-5",
        system_prompt="You are a durable autonomous research engineer.",
        checkpointer=checkpointer,
        # Optional: store=..., subagents=[...], tools=[...], interrupt_on={...}
    )

    config = {"configurable": {"thread_id": "agent-run-42"}}
    result = agent.invoke(
        {"messages": "Research durable execution engines and write a report"},
        config,
    )

Costs

  • Software: 100% Free and Open Source (MIT License); ~30k GitHub stars.
  • Compute: Self-hosted on your own infrastructure (VPS, containers, serverless) or via managed LangSmith / LangGraph Platform deployment.
  • Model Tokens: Pay-per-token directly to whichever provider you configure (model-agnostic).
  • LangSmith: Optional observability - free developer tier, paid plans for team tracing and evaluation.

Caveats & Shortcomings

  • Harness, Not Turnkey Platform: You still supply orchestration triggers, external schedulers, and governance - the SDK is the agent loop, not a full factory.
  • Checkpoint-Granularity Durability: Durability is inherited from LangGraph checkpointers (snapshot-at-step-boundary), not event-sourced replay like Temporal or journaled RPC like Restate - non-deterministic tool side effects still need your own idempotency handling.
  • Ecosystem Coupling: Deeply embedded in LangChain/LangGraph idioms; teams outside that stack face additional ramp-up.

Key Resources & Links


4. Comprehensive Comparison Matrix

Solution Durability Mechanism Storage Engine Execution Sandbox Human-in-the-Loop Replay Safety Setup Complexity Primary Target Audience
Pi Durable / Durable Pi Atomic transaction commits & task ownership trees SQLite, JSONL, Memory, Cloudflare DO Local Node / Remote Host Execution Env Collaborative multi-client attach & steering Tool-Declared (replay: "safe") Low to Medium Developers building standalone agent apps, device networks, proactive agents
OpenDots Session state + CopilotKit Thread Persistence SQLite / Postgres Isolated Docker Desktop Containers (OpenBot) Interactive Review Cards in Chat UI Approval Required for Dangerous Tools Medium Teams building collaborative coworker workspaces with full desktop control
Devin Cloud VM Snapshots, Git State, Execution Tree Proprietary Cloud Infrastructure Sandboxed MicroVM per Session Web/Slack/CLI pause, takeover & steering Automated test suite verification Minimal (Turnkey SaaS) Software engineering teams requiring autonomous task resolution
Temporal Event-sourced deterministic workflow replay Cassandra, Postgres, MySQL, SQLite External Worker Processes Signals & Durable Conditions Activities with configurable retry & idempotency High Enterprise-grade mission-critical backends requiring five-nines reliability
Inngest Event-driven step memoization & execution graphs Inngest State Store (Postgres/Cloud) Serverless Functions (AWS Lambda, Vercel) step.waitForEvent / Durable Timeouts Step-level retry and deduplication keys Low Modern serverless and full-stack web app developers (Next.js/Node)
Vercel Workflows Workflow SDK deterministic step replay & queues Vercel Managed Persistence / KV Serverless / Fluid Compute Functions Chat SDK / Slack approval / hooks Step memoization ('use step') & retries Low Next.js, Node, and Python web developers building cloud agents on Vercel
LangGraph Cyclic graph state checkpointers SQLite, Postgres, Memory Custom Python / Node environment interrupt() and state editing Manual node transaction control Medium AI developers using the LangChain ecosystem who need state machines
Restate Durable RPC journaling & Virtual Objects Restate Log Engine (Rust) Microservice HTTP / Lambda Handlers Durable Suspensions & Signals Journaled invocation deduplication Medium Distributed systems engineers and microservice architectures
DBOS Transactional Postgres-backed workflow state PostgreSQL Lightweight Node / Python runtime Workflow signals & SQL queries Transactional exactly-once guarantees Low to Medium Backend developers prioritizing minimal overhead and unified SQL storage
Deep Agents LangGraph checkpointer snapshots (inherited) SQLite, Postgres, Memory + pluggable Store Custom Python / Node env; sandboxed or remote filesystems interrupt()-style tool approval Snapshot-at-step-boundary (not event-sourced) Medium Teams wanting a batteries-included durable agent harness on the LangChain stack

5. Architectural Decision Framework: Which Solution Should You Choose?

                        What is your primary design goal?
                                       │
     ┌─────────────────────────────────┼─────────────────────────────────┐
     ▼                                 ▼                                 ▼
[Building an Autonomous           [Building an Enterprise           [Building a Product or
 Developer / Coding Agent]         Backend Workflow / System]        Interactive AI Workspace]
     │                                 │                                 │
     ├─ Turnkey SaaS?                  ├─ Heavy Enterprise Microservices? ├─ Collaborative Coworker App
     │   └─► DEVIN                     │   └─► TEMPORAL                   │   with Desktop & Browser?
     │                                 │                                  │   └─► OPENDOTS
     └─ Self-Hosted / Flexible?       ├─ Vercel / Next.js Serverless?    │
         └─► PI DURABLE /              │   ├─ Native Vercel Platform?     └─ Multi-Client, Edge/Device
             DURABLE PI                │   │   └─► VERCEL WORKFLOWS          Network, Malleable Harness?
                                       │   └─ Multi-Cloud Serverless?         └─► PI DURABLE /
                                       │       └─► INNGEST                        DURABLE PI
                                       │
                                       ├─ Cyclical Graph Workflows?
                                       │   └─► LANGGRAPH
                                       │
                                       └─ Ultra-low latency Postgres?
                                           └─► DBOS

6. Synthesis: The Future of Durable Agent Systems

  1. Shift to Proactive Autonomous Execution: As showcased in the Durable Pi proactive incident demo, agents will no longer remain idle waiting for human chat prompts. They will observe telemetry, judge events using fast deterministic classifiers, perform deep multi-step diagnostic investigations in the background, commit checkpoints safely, and only alert human operators when ready for deployment sign-off.
  2. Standardization of Replay Protocols: The industry is converging toward the design pattern highlighted in Pi Durable and Vercel Workflows: external side effects must be decoupled from prompt replays. Tool definitions must specify replay safety, and harness engines must enforce idempotency keys across restarts.
  3. Infinite Memory via Multi-Tier Storage: Durable agents bridge the gap between volatile context windows and infinite operational lifespans. By combining non-blocking compaction at turn boundaries with cold transactional message archives, agents can operate continuously for months while retaining instantaneous recall of critical historical artifacts.

7. Primary Citations, Video Links & References

Clone this wiki locally