Long-running runs
A run can stop for a person, a date or an external event, and continue later. This page shows where the state lives while it waits, and how to pick it up again.
Two ways to run a graph
app.run() | runCatalogGraph(app.definition) | |
|---|---|---|
| State between steps | In the CompiledGraph, in memory | Returned to you as plain JSON |
| Resume | app.resume(runId), same instance, same process | resumeCatalogGraph(definition, state), anywhere |
| Nodes that run | All | Agents, components, human gates, subgraphs, mapAgents, and the plain nodes you bind with nodes. Your own .node() functions and conditional-edge functions do not run. |
| Also | Streaming, timers and signals | Cancellation, a store for every checkpoint, record and replay |
Use app.run() while a run finishes within one process. Use the catalog runner when a run must
survive a restart or move between machines.
Resume in another process
runCatalogGraph returns the state when the run stops. Store it anywhere that holds JSON, and
hand it to resumeCatalogGraph later:
import { createGraph, model, resumeCatalogGraph, runCatalogGraph, type GraphState } from "@ailu-ai/graph-sdk";
const app = createGraph({ name: "contract-review" })
.channel("contract", { type: "string", default: "" })
.agentNode("review", { model: model.balanced, prompt: { system: "List the risky clauses." } })
.humanGate("legal-sign-off")
.agentNode("summarize", {
model: model.fast,
prompt: { system: "Summarize the review for the customer." },
outputChannel: "summary"
})
.edge("review", "legal-sign-off")
.edge("legal-sign-off", "summarize")
.compile();
// Process A: run until the gate, then save the state (a database row, a file, a queue message).
const paused = await runCatalogGraph(app.definition, { initialData: { contract: "..." } });
console.log(paused.status); // "suspended"
const saved = JSON.stringify(paused.state);
// Process B, hours later, maybe on another machine: load the state and resume.
const done = await resumeCatalogGraph(app.definition, JSON.parse(saved) as GraphState);
console.log(done.status); // "completed"
To resume a tool approval this way, pass the approved tools in the resume options:
resumeCatalogGraph(definition, state, { approvedTools: [{ name: "refund", requestedBy: "assistant", resolvedBy: "alice@example.com" }], tools, approvalEngine }).
Pass your tool handlers again (tools) on every call: they are code, not state. With
approvalEngine, the resume first checks that the engine approved what the run waits on (see
Governance).
Keep each checkpoint
runCatalogGraph returns the state when the run stops. To keep a run durable while it runs, so
that a process that dies at step 7 resumes from step 7 rather than from the start, pass a
checkpointer. The engine hands it every checkpoint the run writes (after each step, and when the
run suspends, is cancelled or fails) and waits for save before it goes on:
const checkpointer = {
// Keep it where you keep runs: `{ id, runId, graphState, createdAt }`.
save: async (checkpoint: Checkpoint) => {
await db.checkpoints.insert(checkpoint);
}
};
const outcome = await runCatalogGraph(definition, { initialData, nodes, checkpointer });
To pick a run up after a crash, load its latest checkpoint and pass its graphState to
resumeCatalogGraph, with the same checkpointer. A save that throws stops the run: the call
rejects, and no step runs past a checkpoint you could not keep. Without a checkpointer, nothing
changes: checkpoints stay in the engine's memory until the call returns.
Run your code as a step
A plain action node of a saved graph can run your code: bind it by id with nodes. A common
case is a step that acts after a person approves, such as sending a message:
import {
resumeCatalogGraph,
runCatalogGraph,
type GraphDefinition,
type HostNodeInput
} from "@ailu-ai/graph-sdk";
// A graph saved as data: a person approves, then `send` acts.
const definition = JSON.parse(`{
"id": "send-after-approval", "version": "1", "name": "send-after-approval",
"channels": {
"message": { "type": "string", "reducer": "replace" },
"receipt": { "type": "string", "reducer": "replace" }
},
"nodes": [
{ "id": "approve", "type": "human-gate", "label": "approve" },
{ "id": "send", "type": "action", "label": "send" }
],
"edges": [{ "id": "e1", "from": "approve", "to": "send", "type": "default" }],
"entryNodeId": "approve"
}`) as GraphDefinition;
// Stands in for your messaging API.
const postMessage = async (text: string): Promise<string> => `msg-${text.length}`;
// Your code for `send`. A retry of this step from the same checkpoint gets the same effect key:
// send at most once per key.
const receipts = new Map<string, string>();
const send = {
id: "send",
execute: async ({ channels, effectKey }: HostNodeInput) => {
const receipt = receipts.get(effectKey) ?? (await postMessage(String(channels.message)));
receipts.set(effectKey, receipt);
return { receipt };
}
};
const paused = await runCatalogGraph(definition, {
initialData: { message: "Invoice 42 is paid." },
nodes: [send]
});
console.log(paused.status); // "suspended": nothing sent yet
// Once a person approves: resume with the same binding — it is code, not state.
const done = await resumeCatalogGraph(definition, paused.state, { nodes: [send] });
console.log(done.state.channels.receipt); // "msg-19"
Your function receives the node's channels and returns the update. It also receives an
effectKey: the same value when this step runs again from the same checkpoint, for instance when
your worker retries the run, and a new value for the next run or the next pass in a loop. Perform
an external effect at most once per key.
With AILU_LLM_RECORD=1, the engine records what each bound step returned. A replay uses that
record and never calls the step again, so replaying a run never sends the message twice (see
Governance).
Wait for an external event
A node can suspend the run until your system delivers a named signal: a payment webhook, a message from another service, a manual action.
import { createGraph, readSignal, waitForSignal } from "@ailu-ai/graph-sdk";
const app = createGraph({ name: "order" })
.channel("paid", { type: "boolean", default: false })
// The run suspends here until your system delivers the "payment" signal.
.node("await-payment", async () => waitForSignal("payment"))
.node("ship", async (_input, state) => ({ paid: readSignal(state, "payment") !== undefined }))
.edge("await-payment", "ship")
.compile();
const waiting = await app.run();
console.log(waiting.status); // "suspended"
// Later, a webhook arrives: deliver the signal and the run continues.
const done = await app.signal(waiting.runId, "payment", { amount: 42 });
console.log(done.status, done.channels.paid); // "completed" true
waitForSignal(name, { wakeAt }) also wakes the run at wakeAt if the signal never comes.
Wait until a date
sleepUntil(date) suspends the run and records when to wake it. Ailu does not keep a clock
running: your scheduler (a cron job, a delayed queue message) calls resume at that time.
import { createGraph, readSuspendMeta, sleepUntil } from "@ailu-ai/graph-sdk";
const app = createGraph({ name: "reminder" })
.channel("sent", { type: "boolean", default: false })
// Suspend until a date. The engine records when to wake up; your scheduler resumes the run.
.node("wait", async () => sleepUntil("2030-01-01T09:00:00Z"))
.node("remind", async () => ({ sent: true }))
.edge("wait", "remind")
.compile();
const sleeping = await app.run();
console.log(readSuspendMeta(sleeping)); // { reason: "timer", wakeAt: "2030-01-01T09:00:00Z" }
// At wakeAt, your scheduler (cron, queue, ...) resumes the run.
const done = await app.resume(sleeping.runId);
console.log(done.channels.sent); // true
readSuspendMeta(state) tells you why a run is suspended: human-gate, interrupt (a tool
approval), timer or signal, with wakeAt or awaitingSignal.
Cancel a run
Pass an AbortSignal to the catalog runner. Aborting it stops the run at the next step: the
node in flight finishes, its checkpoint is saved, and the run ends with status "cancelled".
A cancelled run can still be resumed or replayed. Here the user's Stop is played by
your step:
import { createGraph, model, runCatalogGraph } from "@ailu-ai/graph-sdk";
const app = createGraph({ name: "long-job" })
.node("step1", async () => ({})) // a plain step: the catalog runner runs your binding for it
.agentNode("step2", { model: model.fast, prompt: { system: "Do the job." }, outputChannel: "work" })
.edge("step1", "step2")
.compile();
// Abort the controller to stop the run. The engine finishes the node in flight,
// saves its checkpoint, and returns with status "cancelled".
const controller = new AbortController();
const outcome = await runCatalogGraph(app.definition, {
signal: controller.signal,
nodes: [
{
id: "step1",
execute: () => {
controller.abort(); // e.g. the user clicks Stop while step1 runs
return {};
}
}
]
});
console.log(outcome.status); // "cancelled": step1 finished, step2 never started
The engine reads the signal between two steps and does not wait for onEvent handlers: an abort
made in one can be read a step later than the event that prompted it, or not at all if the run
has finished by then.
Next
- A complete example: Resume across processes.
- Record a run to replay it later: Governance.