Durable Agent Runs
medium10 mindurable-runs.ts
A deploy or a crash kills a long agent run halfway through a tool, and nobody finishes the task.
What it shows
- Turn on
durableso a run keeps a checkpoint after every step - Continue what a stopped process left with
cog.recoverRuns()at startup - A tool call that was running reaches the model as "outcome unknown", never runs twice
The code
durable-runs.ts
import { z } from 'zod';
import { Agent, Cogitator, tool } from '@cogitator-ai/core';
const apiKey = process.env.GOOGLE_API_KEY;
if (!apiKey) throw new Error('Set GOOGLE_API_KEY');
const cog = new Cogitator({
llm: { providers: { google: { apiKey } } },
memory: { adapter: 'sqlite', sqlite: { path: 'agent.db' } },
durable: { owner: 'report-host', takeoverOnRestart: true },
});
const exportReport = tool({
name: 'export_report',
description: 'Export the quarterly report as a PDF',
parameters: z.object({ quarter: z.string() }),
execute: async ({ quarter }) => {
await new Promise((resolve) => setTimeout(resolve, 30_000));
return `report-${quarter}.pdf`;
},
});
const reporter = new Agent({
id: 'reporter',
name: 'reporter',
model: 'google/gemini-3.5-flash-lite',
instructions: 'Export the report the user asks for, then say what you did in one sentence.',
tools: [exportReport],
});
const { resumed } = await cog.recoverRuns({ agents: [reporter] });
for (const { run, handle } of resumed) {
const result = await handle.result;
console.log(`Recovered ${run.runId}: ${result.output}`);
}
if (resumed.length === 0) {
console.log('Starting a run: press Ctrl+C during the export, then run this file again');
const result = await cog.run(reporter, { input: 'Export the Q3 report', threadId: 'q3' });
console.log(result.output);
}
await cog.close();Run it
install · bash
pnpm add @cogitator-ai/core @cogitator-ai/memory better-sqlite3 zodEnvironment
GOOGLE_API_KEYrun · bash
GOOGLE_API_KEY=your-key npx tsx durable-runs.tsOr run the full example from a clone of the repository (keys in .env):
repository · bash
npx tsx examples/core/30-durable-runs.ts