This is the full developer documentation for cairnflow
# Introduction
> What cairnflow is, and when to use it.
Cairnflow runs your handlers durably. Every step — a model call, a tool call, a payment — is recorded in a journal before the run moves on. When a process crashes, a deploy restarts your service or a connection drops, the run resumes from the last recorded step instead of starting over or running side effects twice.
You write ordinary TypeScript with the `@cairnflow/sdk` package, Python with the [`cairnflow` package](/docs/develop/python), or Go with the [`cairn` package](/docs/develop/go). Cairnflow calls your service over HTTP, keeps the journal, the state and the timers, and decides when each run continues.
## What you can build
[Section titled “What you can build”](#what-you-can-build)
| Use case | What cairnflow gives you | Start with |
| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
| **AI agents** | Model and tool calls as durable steps, tool approvals that wait on a durable promise, streams that reconnect after a reload, one turn at a time per chat | [Vercel AI SDK](/docs/agents/vercel-ai-sdk) |
| **Durable workflows** | Multi-step processes with one run per ID, waits of minutes or weeks, signals from outside | [Workflows](/docs/workflows/workflows) |
| **Stateful objects** | State per user, account or device behind a key, with one writer per key at a time | [Virtual objects and state](/docs/develop/state) |
| **Sagas and payments** | Recorded side effects, idempotency keys, compensation with `TerminalError` | [Errors and retries](/docs/develop/errors-retries) |
| **Schedules and background jobs** | Server-side cron with time zones, delayed sends, fan-out to child invocations | [Schedules](/docs/develop/schedules) |
| **Webhooks and events** | Acknowledge once durable, deduplicate with `Idempotency-Key`, concurrency and rate limits per scope | [Flow control](/docs/reference/flow-control) |
## Where your code runs
[Section titled “Where your code runs”](#where-your-code-runs)
**On a long-running server** — a container, a VM or Kubernetes — with `serve()` on Node.js 22.6 or newer. This is the best fit for agents: a replay cache keeps resumes cheap, and where HTTP/2 reaches your service, one streaming connection per run carries tokens and cancellation as they happen. On Cairnflow Cloud, streaming is opt-in; see [Deployments](/docs/cloud/deployments#transport).
**On a serverless function** — Vercel, Cloudflare Workers or AWS Lambda — with `fetchHandler`, the Fetch adapter, which Deno and Bun can serve too. This fits short workflows: a few steps with retries and timers, on the platform you already deploy to. See [Serverless](/docs/workflows/serverless).
## How it is built
[Section titled “How it is built”](#how-it-is-built)
All of cairnflow’s state lives on object storage — an S3-compatible bucket. The runtime nodes keep nothing on disk: a node takes ownership of a range of keys with a lease, and when it dies another node takes the range over from the bucket. A run is acknowledged only after its step is durable in the bucket.
## Next
[Section titled “Next”](#next)
* [Quickstart](/docs/quickstart) — a first durable run on your own machine.
* [Concepts](/docs/concepts) — services, virtual objects, workflows and the journal.
# Quickstart
> Install a release binary or run Docker, start a node on your own machine, and run a first durable invocation in two minutes.
This page runs everything on one machine: a cairnflow node, a small service, and the calls between them.
You need:
* a Cairnflow runtime — a prebuilt release archive below, or Docker (no Rust, no database);
* Node.js 22.18 or newer, which runs TypeScript files directly (Node.js 22.6 to 22.17 works with `node --experimental-strip-types`) — or Python ≥ 3.11 or Go ≥ 1.25.
Note
Cairnflow Cloud is in early-access waitlist — [join the waitlist](/#pricing). Until it opens, you run the runtime yourself, as this page does.
## 1. Install and start a node
[Section titled “1. Install and start a node”](#1-install-and-start-a-node)
**Option A — Prebuilt binaries** (Linux x86_64 below; the [releases page](https://github.com/cairnflowdev/cairnflow/releases) has Linux arm64 and macOS arm64 too):
```sh
A=cairnflow-v0.1.0-beta.0-x86_64-unknown-linux-musl
mkdir -p ~/.local/bin # or any directory on your PATH
curl -L "https://github.com/cairnflowdev/cairnflow/releases/download/v0.1.0-beta.0/$A.tar.gz" \
| tar -xz -C ~/.local/bin --strip-components=1 "$A/cairnflow" "$A/cairn" "$A/cairn-ctl" "$A/cairn-query-worker"
cairnflow --no-auth # dev switch: no API key, for a machine only you reach
```
**Option B — Docker:**
```sh
docker run -d --name cairnflow -p 127.0.0.1:8080:8080 \
--add-host=host.docker.internal:host-gateway \
-v cairnflow-data:/var/lib/cairnflow \
ghcr.io/cairnflowdev/cairnflow:v0.1.0-beta.0 --no-auth
cairn() { docker exec cairnflow cairn "$@"; } # the CLI is in the container
```
Four self-contained binaries ship together: `cairnflow` (the runtime), `cairn` (the CLI), `cairn-ctl` (the operator tool) and `cairn-query-worker`. The node listens on `127.0.0.1:8080` (`8081` is for other nodes), keeps all state under `./cairnflow-data`, and serves the web console at `http://127.0.0.1:8080/ui/`. To compile from source instead, see [Build from source](/docs/self-hosting#build-from-source).
## 2. Write a service
[Section titled “2. Write a service”](#2-write-a-service)
In a second terminal, install `@cairnflow/sdk` (zero runtime dependencies):
```sh
mkdir greeter && cd greeter
npm init -y && npm pkg set type=module
npm install @cairnflow/sdk
```
A service is a set of handlers. `ctx.run` journals the result of a step: after a crash or retry, the step is replayed from the journal instead of running again.
service.ts
```ts
import { serve, service } from "@cairnflow/sdk";
const greeter = service("Greeter", {
greet: async (ctx, name: string) => {
// Journaled: a retry after a crash does not run it again.
const upper = await ctx.run("upper", () => name.toUpperCase());
return `Hello, ${upper}!`;
},
});
await serve({ services: [greeter], port: 9080 });
```
Start it and leave it running:
```sh
node service.ts
```
`serve()` listens on `127.0.0.1` by default, which is all a node on the same machine needs. When running the runtime in Docker, pass `hostname: "0.0.0.0"` in `serve()` so the container can reach your service. It prints a warning that `identityKeys` is not set: a service that other machines can reach should check that requests really come from your node. See [Request identity](/docs/self-hosting/security#request-identity-signed-calls-to-your-services).
To write the service in Python or Go, see [Python SDK](/docs/develop/python) (`pip install cairnflow`) and [Go SDK](/docs/develop/go) (`go get github.com/cairnflowdev/cairnflow/sdk/go`). On Vercel or AWS Lambda, the same service runs behind `fetchHandler`: see [Serverless](/docs/workflows/serverless).
## 3. Register and invoke
[Section titled “3. Register and invoke”](#3-register-and-invoke)
In a third terminal, register the deployment so Cairnflow reads its services and handlers, then invoke `greet`:
```sh
cairn register http://127.0.0.1:9080 # with Docker: http://host.docker.internal:9080
cairn invoke Greeter greet --input '"world"'
```
The answer carries the invocation ID and the handler’s output, `"Hello, WORLD!"`. To fire and forget over HTTP, call `POST http://127.0.0.1:8080/invoke/Greeter/greet/send` instead: you get the invocation ID back as soon as it is durable.
## 4. Read the journal
[Section titled “4. Read the journal”](#4-read-the-journal)
Every step of the run is recorded. Inspect it with the `cairn` CLI:
```sh
cairn journal
```
It lists the input, the step and its result, and the output. Open `http://127.0.0.1:8080/ui/` in a browser to inspect journals, timelines and traces visually, retry or cancel runs, and query invocations with SQL.
## 5. Turn authentication on
[Section titled “5. Turn authentication on”](#5-turn-authentication-on)
`--no-auth` is only for local development on a machine only you reach. Without it, every route except `/health` requires an API key:
```sh
export CAIRNFLOW_ADMIN_KEY="cf_$(openssl rand -hex 24)" # bootstrap key, at least 32 bytes
export CAIRNFLOW_TOKEN="$CAIRNFLOW_ADMIN_KEY" # key sent by the `cairn` CLI
cairnflow # same directory, same data
```
For production, point the node at an S3-compatible bucket instead of a local directory: `--main-store s3://my-bucket/prefix` with the usual `AWS_*` environment variables.
## Next
[Section titled “Next”](#next)
* [Concepts](/docs/concepts)
* [Build an agent with the Vercel AI SDK](/docs/agents/vercel-ai-sdk)
* [Self-hosting](/docs/self-hosting): buckets, clusters, security and operations.
# Build with AI
> Copy-paste prompts and Markdown docs so your coding agent can add cairnflow to a project.
These docs are written to be read by coding agents as well as people. Paste one of the prompts below into Claude Code, Cursor, Codex, Copilot or any other agent, and it will find the pages it needs and wire up the SDK. Every prompt points the agent at Markdown versions of the docs, so it reads the real API instead of guessing.
## Add cairnflow to a project
[Section titled “Add cairnflow to a project”](#add-cairnflow-to-a-project)
For an existing TypeScript service or a new one. The agent installs the SDK, writes a first service with durable steps, exposes it with `serve()` or `fetchHandler`, and tells you how to register and invoke it.
Prompt: add cairnflow
```text
You are adding cairnflow to this TypeScript project. Cairnflow is a durable execution runtime:
handlers run inside my own HTTP service, and cairnflow records every step in a journal, so a crash
or a deploy resumes the run where it stopped instead of starting over or repeating side effects.
Read these first. They are Markdown pages written for agents:
- https://cairnflow.dev/llms.txt (index of all docs)
- https://cairnflow.dev/docs/quickstart.md
- https://cairnflow.dev/docs/concepts.md
- https://cairnflow.dev/docs/develop/durable-steps.md
Then:
1. Install the SDK: `npm install @cairnflow/sdk` (Node.js 22.6 or newer; the SDK has no
dependencies). Make sure `package.json` has `"type": "module"` if you run `.ts` files directly.
2. Create one service module. Use `service(name, handlers)` for stateless handlers,
`service(name, handlers, { type: "VIRTUAL_OBJECT" })` when state belongs to a key (a user, an
order, a chat), and `workflow(name, { run, ... })` for a process that runs once per ID.
3. Wrap every side effect (HTTP calls, database writes, payments, emails) in
`ctx.run("", () => ...)`. Step names are part of the journal: do not rename
them later and do not put configuration values in them.
4. Expose the service:
- on a long-running server: `serve({ services, port: Number(process.env.PORT ?? 9080), hostname: "0.0.0.0", identityKeys })`
- on Vercel, Cloudflare Workers or AWS Lambda: `fetchHandler({ services, identityKeys })` from
`@cairnflow/sdk/fetch` (see https://cairnflow.dev/docs/workflows/serverless.md)
5. Read `CAIRN_URL` and `CAIRN_KEY` from the environment. Read `CAIRN_IDENTITY_KEY` too and pass
`identityKeys: [process.env.CAIRN_IDENTITY_KEY]` when it is set; leave `identityKeys` out when it
is not (a node signs its requests only when it is configured to). Never hard-code keys.
6. Finish by showing me the two commands to run: register the deployment with
`POST $CAIRN_URL/deployments` and body `{"uri": ""}`, then invoke one
handler with `POST $CAIRN_URL/invoke//`, both with
`authorization: Bearer $CAIRN_KEY`. The URL must be reachable from the cairnflow node: with a
node on the same machine, `http://127.0.0.1:` works.
Rules for all handler code:
- No `Date.now()`, `Math.random()` or generated IDs outside `ctx.run`.
- Do not catch and swallow errors around `ctx` commands; rethrow what you do not handle.
- Throw `TerminalError` for failures a retry cannot fix (bad input, a refused payment).
- Keep results, state and call inputs small JSON values. Put files and images in `ctx.artifact`
and return the reference; keep data that later invocations need (such as a chat history) in
state, not in an artifact.
- Do not invent APIs. If something is not in the docs, ask me.
```
## Make a Vercel AI SDK agent durable
[Section titled “Make a Vercel AI SDK agent durable”](#make-a-vercel-ai-sdk-agent-durable)
For a chat agent that already uses `streamText` and `useChat`. The agent keeps your tools, prompts and UI, and moves the model and tool calls onto durable steps with approvals and a reconnecting stream.
Prompt: durable AI SDK agent
```text
This project has a chat agent built with the Vercel AI SDK v7 (`streamText` on the server,
`useChat` in the browser). Make it durable with cairnflow without rewriting it: every model call
and tool call becomes a journaled step, tools can wait for human approval, and the stream
reconnects after a page reload.
Read these first. They are Markdown pages written for agents:
- https://cairnflow.dev/docs/agents/vercel-ai-sdk.md
- https://cairnflow.dev/docs/agents/approvals.md
- https://cairnflow.dev/docs/agents/streaming.md
Server:
1. Install the SDK: `npm install @cairnflow/sdk` (Node.js 22.6 or newer; no runtime dependencies).
2. Move the `streamText` call into `chatObject("Chat", async (ctx, turn) => streamText({ ... }))`.
3. Wrap the model: `wrapLanguageModel({ model, middleware: cairnMiddleware(ctx) })`.
4. Wrap the tools: `cairnTools(ctx, tools, { approve: [] })`.
5. Pass `messages: await convertToModelMessages(turn.messages)` and `onError: turn.onError`.
6. `chatObject` stops after 5 attempts by default, so a provider that keeps failing does not retry
forever. To change it: `chatObject("Chat", run, { options: { retryPolicy: { maxAttempts: 3, onMaxAttempts: "PAUSE" } } })`.
7. Serve it: `serve({ services: [chat], port: Number(process.env.PORT ?? 9080), hostname: "0.0.0.0", identityKeys })`,
with `identityKeys: [process.env.CAIRN_IDENTITY_KEY]` when that variable is set and left out when
it is not.
Browser:
8. Create `const transport = cairnChatTransport({ baseUrl: "", service: "Chat" })`
and add the same-origin proxy route described in the guide.
9. Load the history when rendering the page with `await transport.messages(chatId)`, then call
`useChat({ id: chatId, transport, messages: initial, resume: true })`.
10. Approve tools with `transport.approve(chatId, approvalId, { approved })`, not with
`addToolApprovalResponse`.
Keep the existing tool definitions, prompts and UI components. Do not call the model or a tool
outside `cairnMiddleware` and `cairnTools`. `maxRetries` has no effect here: cairnflow retries a
failed step itself. On Cairnflow Cloud the browser gets each model step's text when the step
finishes, not token by token, unless the deployment is registered with `"transport": "declared"`
(see the streaming guide); do not promise live tokens without it. Do not invent APIs; if something
is not in the guide, ask me.
```
## Keep your agent on the rules
[Section titled “Keep your agent on the rules”](#keep-your-agent-on-the-rules)
Add this block to the instructions file your agent reads on every task (`AGENTS.md`, `CLAUDE.md`, `.cursor/rules/cairnflow.mdc`, `.github/copilot-instructions.md`). It keeps later changes inside cairnflow’s rules, such as never renaming a step that running invocations depend on.
AGENTS.md
```md
## cairnflow
This project uses cairnflow for durable execution. Docs for agents: https://cairnflow.dev/llms.txt
(append `.md` to any https://cairnflow.dev/docs/ URL to get the page as Markdown).
- Every side effect inside a handler goes through `ctx.run("", fn)`, or through
`cairnTools` / `cairnMiddleware` for Vercel AI SDK tools and models.
- Step names are part of the journal. Renaming a step breaks in-flight invocations; see
https://cairnflow.dev/docs/develop/versioning.md before renaming or reordering steps.
- No `Date.now()`, `Math.random()` or random IDs outside `ctx.run`.
- Never swallow errors around `ctx` commands. Throw `TerminalError` for failures a retry cannot fix.
- State (`ctx.get`, `ctx.set`) and durable promises exist only on virtual objects and workflows.
- Keep journaled values small; put files and images in `ctx.artifact` (its references are only
readable by the invocation that wrote them, so do not keep them in state for later turns).
```
## Docs in Markdown
[Section titled “Docs in Markdown”](#docs-in-markdown)
| What | Where |
| -------------------------------- | ----------------------------------------------------------------------- |
| Any page as Markdown | add `.md` to its URL, e.g. [`/docs/quickstart.md`](/docs/quickstart.md) |
| Copy a page for your agent | the **Copy page** button next to every page title |
| Index of all pages | [`/llms.txt`](/llms.txt) |
| All docs in one file | [`/llms-full.txt`](/llms-full.txt) |
| A shorter version without asides | [`/llms-small.txt`](/llms-small.txt) |
Tip
Agents work best with a narrow task and the one or two pages that cover it. Give it the Markdown link of the page you are reading (**Copy page → Copy Markdown link**) rather than the whole site.
# Concepts
> Services, virtual objects, workflows, the journal and the three rules of handler code.
## Invocations and the journal
[Section titled “Invocations and the journal”](#invocations-and-the-journal)
Each call to a handler is an **invocation**. While it runs, every `ctx` command — a step, a sleep, a call to another handler, a state write — is appended to the invocation’s **journal**. When the handler has to run again (after a crash, a deploy, or a wait), cairnflow replays it: commands that are already in the journal return their recorded result instead of running again, and the handler carries on from the first step that is not.
## Three kinds of service
[Section titled “Three kinds of service”](#three-kinds-of-service)
| Kind | Declared with | Has state | Runs |
| -------------- | ----------------------------------------------------- | -------------------- | --------------------------------------- |
| Service | `service(name, handlers)` | No | Any number at once |
| Virtual object | `service(name, handlers, { type: "VIRTUAL_OBJECT" })` | Yes, per key | One exclusive handler per key at a time |
| Workflow | `workflow(name, { run, … })` | Yes, per workflow ID | `run` once per ID |
A **virtual object** is addressed by a key — a chat ID, a user ID, an order number. Its state belongs to that key, and two exclusive handlers on the same key never run at the same time. That makes it the natural home for a conversation: the agent’s history lives in the object’s state.
State (`ctx.get`, `ctx.set`) and durable promises exist only on virtual objects and workflows. A plain service gets a `ServiceContext` without them.
## Durable steps
[Section titled “Durable steps”](#durable-steps)
```ts
const receipt = await ctx.run("charge", () => chargeCard(amount));
```
`ctx.run` runs the closure once and records the result. On replay the closure is not called again. The step’s name is part of the journal: renaming a step between two deploys stops in-flight invocations that reach it, so keep names stable and put configuration (model IDs, prompt versions) in span attributes instead.
## Waiting
[Section titled “Waiting”](#waiting)
`ctx.sleep`, calls to other handlers, durable promises and signals end the current turn instead of holding a connection. The invocation is suspended in storage and resumes when the result is there — seconds or weeks later. Nothing runs and nothing is billed as compute while it waits.
## Errors and retries
[Section titled “Errors and retries”](#errors-and-retries)
* A normal error thrown from a `ctx.run` closure fails the turn, and cairnflow retries it under the handler’s retry policy: completed steps are replayed, only the failed step runs again.
* `TerminalError` is for failures a retry cannot fix (bad input, a refused payment). It is recorded and can be caught, so you can compensate and carry on.
## The three rules of handler code
[Section titled “The three rules of handler code”](#the-three-rules-of-handler-code)
1. **Every side effect goes through `ctx.run`** (or a cairnflow wrapper such as `cairnTools`). The handler body runs again on every replay.
2. **No `Date.now()`, `Math.random()` or generated IDs outside `ctx.run`.** Replay must take the same path as the first run.
3. **Do not catch and swallow errors around `ctx` commands.** A suspended or failed turn stays suspended or failed whatever your `catch` does.
# Artifacts
> Keep large bytes out of the journal with ctx.artifact, and pass references between steps.
Step results, state and call inputs live in the journal, and the journal is replayed on every turn. Large values there make every turn slower and more expensive. **Artifacts** keep the bytes in object storage and put only a small reference in the journal.
```ts
const ref = await ctx.run("render", async () =>
ctx.artifact.put(await renderChart(data), { contentType: "image/png" }),
);
// ref = { sha256: "…", size: 48213, contentType: "image/png" }
```
Return the reference from `ctx.run`, not the bytes. The journal then holds a few dozen bytes, and the step is not re-run on replay.
## API
[Section titled “API”](#api)
```ts
interface ArtifactRef {
readonly sha256: string; // hex SHA-256 of the content
readonly size: number;
readonly contentType: string;
}
ctx.artifact.put(bytes: Uint8Array | string, opts?: { contentType?: string }): Promise;
ctx.artifact.get(ref: ArtifactRef | string): Promise;
```
* `put` accepts bytes or a string (encoded as UTF-8). `contentType` defaults to `application/octet-stream`.
* The reference is computed locally from the content; cairnflow stores the bytes before it processes the invocation’s next command.
* Content-addressed: putting the same bytes twice gives the same `sha256`.
* `get` accepts a reference or a bare `sha256` string.
## Limits
[Section titled “Limits”](#limits)
* One artifact can be at most 16 MiB minus 1 KiB. The SDK exports this as `ARTIFACT_MAX_BYTES`; `put` throws a `RangeError` above it.
* Your environment may also cap the total artifact bytes it keeps; on Cairnflow Cloud, see [Beta limits](/docs/cloud/limits).
## Reading an artifact back
[Section titled “Reading an artifact back”](#reading-an-artifact-back)
`ctx.artifact.get(ref)` first looks in the SDK process’s own memory (a 64 MiB cache of recent artifacts). On a different process — after a restart, or on another replica — it fetches the artifact from cairnflow, which you must configure once at startup:
```ts
import { configureArtifacts } from "@cairnflow/sdk";
configureArtifacts({
baseUrl: process.env.CAIRN_URL!,
headers: { authorization: `Bearer ${process.env.CAIRN_KEY}` },
});
```
Use a key that can invoke handlers. Without this, `get` throws when the artifact is not in memory.
Caution
`ctx.artifact.get` reads artifacts of the **current** invocation. To hand an artifact to another invocation, pass the bytes through a new `put` there, or read it over HTTP with the ID of the invocation that created it.
## Reading artifacts over HTTP
[Section titled “Reading artifacts over HTTP”](#reading-artifacts-over-http)
With a key that can invoke handlers:
```sh
# List the artifacts of an invocation.
curl "$CAIRN_URL/invocations/$ID/artifacts" -H "authorization: Bearer $CAIRN_KEY"
# -> {"artifacts": [{"sha256": "...", "size": 48213, "contentType": "image/png"}]}
# Download one.
curl "$CAIRN_URL/invocations/$ID/artifacts/$SHA256" \
-H "authorization: Bearer $CAIRN_KEY" -o chart.png
```
The response carries the content type given to `put` and is served as inert content: HTML, SVG, XML and PDF artifacts are always sent as downloads, never rendered in place.
## Lifetime
[Section titled “Lifetime”](#lifetime)
Artifacts belong to the invocation that created them. When the invocation is purged — explicitly or when its retention period ends — its artifacts go with it, and the HTTP routes answer `404`.
## When to use them
[Section titled “When to use them”](#when-to-use-them)
* Files and images produced or consumed by a step.
* Documents and model outputs that later steps of the same invocation, or a UI, read back.
Not for values carried from one invocation to the next, such as a chat history kept in state: `ctx.artifact.get` cannot read another invocation’s artifacts, and artifacts are purged with the invocation that wrote them. Keep such values in state; large ones are stored as segments automatically (see [Virtual objects and state](/docs/develop/state#state-api)).
On serverless platforms (`fetchHandler`), where the journal travels on every request, this matters even more — see [Serverless](/docs/workflows/serverless).
# Calling other handlers
> Durable request-response calls, one-way sends, idempotency keys, scopes, and attaching to invocations.
A handler can call any other handler in your environment. Calls are commands in the journal: they are made exactly once per invocation, and their results survive crashes and deploys.
```ts
// Wait for the result.
const plan = await ctx.call("Planner", "plan", task);
// Fire and forget.
ctx.send("Email", "welcome", { userId });
// A virtual object: pass the key.
const total = await ctx.call("Counter", "add", 5, { key: "user-42" });
```
## ctx.call
[Section titled “ctx.call”](#ctxcall)
```ts
call(service: string, handler: string, input: unknown, opts?: CallOptions): DurableFuture;
```
* The callee runs as its own invocation, with its own journal and retries.
* When the result is not there yet, the caller **suspends**; nothing waits in memory. It resumes when the callee finishes.
* If the callee fails, `await` throws a `TerminalError` with the callee’s code and message. The callee’s outcome is final, so retrying the caller would not change it.
* The returned `DurableFuture` combines with `ctx.all` and `ctx.race`, for example to fan out:
```ts
const notes = await ctx.all(
sections.map((section) =>
ctx.call("Researcher", "dig", { topic, section }, { name: `dig/${section}` }),
),
);
```
## ctx.send
[Section titled “ctx.send”](#ctxsend)
```ts
send(service: string, handler: string, input: unknown, opts?: CallOptions): void;
```
`ctx.send` records a one-way call and returns at once. It never suspends the caller. Use `delay` (ms) to run the callee later:
```ts
ctx.send("Reminders", "remind", { userId }, { delay: 3 * 24 * 3600_000 });
```
The callee of a send is detached work: it is not cancelled when the caller is cancelled.
## Options
[Section titled “Options”](#options)
| Option | Meaning |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key` | Key of the target virtual object or workflow |
| `idempotencyKey` | At most one invocation for the same target and key — see below |
| `name` | Label of the call in the journal and the console (default `service/handler`) |
| `delay` | `ctx.send` only: run the callee this many ms later |
| `scope` | Run the callee in a scope (see [Scopes](#scopes)). Absent: inherit the caller’s scope |
| `limitKey` | `l1` or `l1/l2`: concurrency bucket inside the scope. Requires a scope |
| `placement` | `"spread"`: deliberately spread unkeyed callees across partitions — see below |
| `tags` | Up to 8 `key: value` tags on the callee invocation. Keys match `[a-z0-9_.-]{1,32}`, values are at most 64 bytes; invalid tags are dropped and the call still runs |
## Idempotency keys
[Section titled “Idempotency keys”](#idempotency-keys)
Calls from a handler are already deduplicated by the journal: a replay never sends the same call twice. An `idempotencyKey` goes further: calls to the same target with the same key, from any invocation, refer to the **same** callee invocation. A second call returns the first call’s result (or waits for it) instead of running the handler again.
```ts
await ctx.call("Payments", "charge", order, { idempotencyKey: `charge-${order.id}` });
```
Deduplication lasts as long as the finished invocation is retained. After it is purged, the same key starts a new invocation.
## Scopes
[Section titled “Scopes”](#scopes)
A scope groups a tree of invocations that belong together — usually one user or one tenant of your product. Set it once at the root; every call below inherits it.
```ts
const agent = ctx.scoped(`user-${userId}`);
const plan = await agent.call("Planner", "plan", task);
// Inside Planner.plan, ctx.call("Search", ...) stays in the same scope.
```
* `ctx.scoped(scope, limitKey?)` returns a view with `call` and `send` only. Scope names use `[A-Za-z0-9_.-]`, 1 to 36 characters; a bad name throws a `TypeError` immediately.
* **A scope is part of identity.** `Cart/a` in scope `bob` is a different object, with different state, from `Cart/a` without a scope. Idempotency keys and durable promises are per scope too.
* **Everything in a scope lives together**, so calls within it stay local and fast. The price is that one scope is bounded by what a single partition can process. One scope per user or tenant is right; one per request, or one for the whole system, is not.
* A call can switch to another scope (`ctx.scoped("other")`), but cannot leave a scope for “no scope”.
## Spreading fan-out
[Section titled “Spreading fan-out”](#spreading-fan-out)
Unkeyed calls (no scope, no `key`, no `idempotencyKey`) are placed next to their caller by default, which keeps a whole call tree local. For a CPU-heavy fan-out you may want the opposite:
```ts
await Promise.all(files.map((f) => ctx.call("Resize", "run", f, { placement: "spread" })));
```
`placement` only changes where the callee runs, not its identity. It is ignored when the call has a scope (including an inherited one), a `key` or an `idempotencyKey`. Any other value than `"spread"` throws a `TypeError`.
## Attaching to another invocation
[Section titled “Attaching to another invocation”](#attaching-to-another-invocation)
If you have the ID of an invocation — from the client, from `/send`, or passed in the input — a handler can wait for its result or peek at it:
```ts
const result = await ctx.attach(reportInvocationId); // waits durably
const maybe = await ctx.getOutput(reportInvocationId); // null if not finished yet
```
Both throw a `TerminalError` if the target failed. `ctx.invocationId` is the current invocation’s ID, in the same format the HTTP API uses.
## Calls and cancellation
[Section titled “Calls and cancellation”](#calls-and-cancellation)
A hard cancel of an invocation also cancels the invocations it created with `ctx.call` and is still waiting for, all the way down the tree. Invocations created with `ctx.send` are not touched; cancel them by ID. See [Cancellation](/docs/develop/cancellation).
# Cancellation
> Cooperative cancel that lets your code clean up, hard cancel as the fallback, and how steps react.
There are two ways to cancel an invocation.
| | Cooperative (`mode=signal`) | Hard |
| --------------------- | ---------------------------------------------------------------------- | --------------------------------- |
| HTTP | `POST /invocations/{id}/cancel?mode=signal` | `POST /invocations/{id}/cancel` |
| Client | `handle.cancel()` (the default) | `handle.cancel({ mode: "hard" })` |
| Key needed | One that can invoke handlers | An admin key |
| Your code | Gets a `TerminalError` (code `409`) at its next wait, and can clean up | Gets no further turn |
| Ends as | Whatever your code does — usually `failed` with `409` | `failed` with code `572` |
| Needs your service up | Yes | No |
Both answer `{"cancelled": true|false, "status": ...}` once the invocation has stopped; `cancelled` says whether it really stopped. Cancelling an invocation that already finished is a no-op: `{"cancelled": false, "status": "completed"}`.
## Cooperative cancel
[Section titled “Cooperative cancel”](#cooperative-cancel)
Cairnflow delivers a cancel signal to the invocation. From then on, every **wait point** throws `TerminalError` with code `409`, so your `try/catch/finally` can undo what was done:
```ts
async run(ctx: Context, order: Order) {
const undo: Array<() => PromiseLike | void> = [];
try {
const charge = await ctx.run(
"charge",
(signal) => payments.charge(order, { signal }),
{ cancellable: true },
);
undo.push(() => ctx.run("refund", () => payments.refund(charge.id)));
await ctx.promise("shipped").get();
return "done";
} catch (e) {
if (e instanceof TerminalError) {
for (const step of undo.reverse()) await step();
ctx.send("Email", "orderCancelled", { orderId: order.id });
}
throw e;
}
}
```
Each undo step is registered only after its forward step has a result, and the list is rebuilt the same way on every replay.
In streaming mode (`BIDI_STREAM`, which `serve()` declares), a cancel that arrives in the middle of a turn reaches the handler at once. In request-response mode there is no channel into a running request: the cancel takes effect from the next turn. That is always the case with `fetchHandler`, and on Cairnflow Cloud also with `serve()` unless the deployment is registered with `"transport": "declared"` ([Deployments](/docs/cloud/deployments#transport)).
### What is and is not a cancellation point
[Section titled “What is and is not a cancellation point”](#what-is-and-is-not-a-cancellation-point)
| Command | After a cooperative cancel |
| ------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `await` on something not finished yet: `ctx.sleep`, `ctx.call`, `ctx.promise(...).get()`, `ctx.signal`, an awakeable, `ctx.all`, `ctx.race` | Throws `TerminalError` 409 |
| `ctx.run(name, fn)` (default) | **Runs normally.** Compensation steps are `ctx.run`, and they must work after a cancel |
| `ctx.run(name, fn, { cancellable: true })` | Does not start; throws 409. If the cancel arrives while the closure runs (streaming mode only), its `AbortSignal` fires |
| `ctx.send`, `ctx.set`, `ctx.clear` | Run normally |
| A result already in the journal | Returned normally |
This is why compensation code should use only `ctx.run` (not cancellable) and `ctx.send`: a `ctx.call` or a sleep in a `catch` block throws again at once.
### Cancellable steps
[Section titled “Cancellable steps”](#cancellable-steps)
Mark forward work that is expensive or pointless after a cancel — model calls, tool calls, long fetches — as `cancellable`:
```ts
const page = await ctx.run(
"fetch",
(signal) => fetch(url, { signal }).then((r) => r.text()),
{ cancellable: true },
);
```
* If the invocation is already cancelled and the step has no result yet, the closure does not run and `ctx.run` throws 409.
* If the cancel arrives while the closure runs (streaming mode only), the `AbortSignal` passed to the closure fires. Whatever the closure throws afterwards becomes a 409; nothing is recorded.
* If the closure ignores the signal and returns normally, its result is recorded as usual.
### The service must be reachable
[Section titled “The service must be reachable”](#the-service-must-be-reachable)
Cooperative cancel needs your code to run. If your service is down, the invocation keeps waiting for it. That is what the hard cancel is for.
## Hard cancel
[Section titled “Hard cancel”](#hard-cancel)
A hard cancel writes the terminal state directly, without asking your code:
* The invocation ends `failed` with code `572`. Callers waiting on it with `ctx.call` get that failure.
* If it held a virtual object’s key, the next invocation in the queue runs.
* A turn already running on your service is not cut off. It runs to its next natural stop; its steps have run (and cost what they cost), and its state writes still apply. Only its outcome is discarded.
* Pending timers and retries are discarded when they come due.
* Your `catch` blocks never run: a saga does not compensate on a hard cancel.
### Propagation to children
[Section titled “Propagation to children”](#propagation-to-children)
A hard cancel also cancels every invocation it created with `ctx.call` and is still waiting for, recursively down the tree. Calls not yet dispatched are never sent. Invocations started with `ctx.send` are detached work and are **not** cancelled; cancel them by ID.
## Choosing
[Section titled “Choosing”](#choosing)
Use cooperative cancel by default: it lets you refund, release and notify. Fall back to the hard cancel when the service cannot answer, or when you need the invocation stopped regardless of what its code does.
# Typed client
> Call services, objects and workflows from your app with @cairnflow/sdk/client.
`@cairnflow/sdk/client` calls your handlers from an application, a script or an edge function. It imports nothing from `node:*`, follows the cluster’s redirects, retries safely, and takes its types from your service definitions.
app.ts
```ts
import { connect, InvocationFailed } from "@cairnflow/sdk/client";
import type { orders, signup } from "./services.ts";
const c = connect({ url: process.env.CAIRN_URL!, apiKey: process.env.CAIRN_KEY! });
// Call and wait for the result.
const receipt = await c.service("OrderService").submit({ amount: 5 });
// Send and get a handle back at once.
const h = await c.service("OrderService").send.submit({ amount: 5 });
const result = await h.attach({ timeoutMs: 60_000 });
```
## Types from your services
[Section titled “Types from your services”](#types-from-your-services)
Export the definitions from the module that declares them and import them with `import type`. Only types cross over, so the client bundle does not pull in your service code or `node:http`:
services.ts
```ts
import { service, type ServiceContext } from "@cairnflow/sdk";
export const orders = service("OrderService", {
async submit(ctx: ServiceContext, input: { amount: number }) {
return { receipt: await ctx.run("charge", () => charge(input.amount)) };
},
});
```
`c.service("OrderService")` then exposes `submit(input, opts?)`, typed with the handler’s input and returning a promise of its output. The name string must match the service name; the type parameter only describes it.
## Targets
[Section titled “Targets”](#targets)
| Call | For |
| ---------------------------------------- | ------------------------ |
| `c.service(name, opts?)` | A plain service |
| `c.object(name, key, opts?)` | A virtual object, by key |
| `c.workflow(name, workflowId, opts?)` | A workflow, by ID |
| `c.invocation(id)` | Any invocation, by ID |
`opts` is `{ scope }` to address the target inside a [scope](/docs/develop/calls#scopes).
Each target exposes one function per handler, which calls and waits, plus `send.`, which returns an `InvocationHandle` as soon as the invocation is durable.
### Workflows
[Section titled “Workflows”](#workflows)
```ts
const wf = c.workflow("UserSignup", "u-1");
await wf.send.run({ email: "a@example.com" }); // start without waiting
await wf.click({ secret }); // a shared handler
const verified = await wf.attach(); // wait for run's result
const now = await wf.output(); // { ready: false } or { ready: true, value }
```
Calling `run` a second time for the same ID throws `AlreadyInvoked`, with the ID of the existing run.
## Invocation handles
[Section titled “Invocation handles”](#invocation-handles)
| Method | Meaning |
| --------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `id` | The invocation ID |
| `attach({ timeoutMs?, signal? })` | Wait until it finishes; returns the output |
| `output()` | `{ ready: false }` or `{ ready: true, value }`, without waiting |
| `status()` | Status, timestamps, and failure details |
| `signal(name, value?)` | Deliver a [signal](/docs/develop/promises-signals#signals) |
| `cancel({ mode? })` | Cooperative cancel by default; `{ mode: "hard" }` needs an admin key — see [Cancellation](/docs/develop/cancellation) |
Waiting uses long polls of 25 seconds each (`attachWaitMs`), below the idle timeout of common load balancers. A `503`, or a `429` that names no invocation, is retried after a backoff (honouring `Retry-After`). If `timeoutMs` runs out first, `attach` throws `AttachTimeout`; the invocation keeps running and you can attach again by ID.
## Call options
[Section titled “Call options”](#call-options)
| Option | Meaning |
| ---------------- | --------------------------------------------------------------------------------------------------------------- |
| `idempotencyKey` | Idempotency key for this call. Absent: generated once and reused across the client’s retries. `null`: send none |
| `timeoutMs` | Give up waiting after this long (calls only) |
| `signal` | `AbortSignal` to stop waiting |
| `limitKey` | Limit key, for calls in a scope |
| `logLevel` | Minimum `ctx.log` level for this invocation: `"debug"`, `"info"`, `"warn"` or `"error"` |
| `headers` | Extra request headers |
## Idempotency
[Section titled “Idempotency”](#idempotency)
Every call carries an `Idempotency-Key`. When you do not pass one, the client generates a random key and keeps it across its own retries, so a lost response or a network error never creates a second invocation. Pass your own key to deduplicate across processes or restarts:
```ts
await c.service("OrderService").submit(order, {
idempotencyKey: `order-${order.id}`,
});
```
The same key returns the same invocation: its result if it has finished, or a handle to wait on. `send.` returns a handle to that invocation even when it has already failed or is paused. Deduplication lasts as long as the finished invocation is retained. A workflow’s `run` needs no key: the workflow ID already makes it run once.
## Errors
[Section titled “Errors”](#errors)
| Error | When |
| ------------------ | ------------------------------------------------------------------------------------------------- |
| `InvocationFailed` | The invocation ended `failed`. It is a `TerminalError`, with `code`, `message` and `invocationId` |
| `InvocationPaused` | The invocation is `paused` (for example, retries exhausted). Has `code` and `invocationId` |
| `AlreadyInvoked` | A workflow `run` was called again for the same ID |
| `AttachTimeout` | `timeoutMs` ran out; the invocation is still running |
| `CairnHttpError` | Any other HTTP error (`400`, `401`, `403`, `404`, …), with `status` and `code` |
```ts
try {
await c.object("Cart", userId).checkout();
} catch (e) {
if (e instanceof InvocationFailed && e.code === 409) {
// business failure reported by the handler
} else {
throw e;
}
}
```
## Connect options
[Section titled “Connect options”](#connect-options)
| Option | Default | Meaning |
| -------------- | -------------- | ------------------------------------------------------------------ |
| `url` | — | Your environment’s endpoint |
| `apiKey` | — | Sent as `Authorization: Bearer` |
| `headers` | — | Extra headers on every request |
| `maxAttempts` | `8` | Attempts per request |
| `maxElapsedMs` | `30000` | Time budget per request, including waits between attempts |
| `attachWaitMs` | `25000` | Length of each long poll while waiting for a result |
| `followLeader` | `true` | Follow the cluster’s redirect to the node that owns the invocation |
| `fetch` | global `fetch` | Custom `fetch` implementation |
The client also exposes `c.promise(...)` and `c.awakeable(id)` for [promises and awakeables](/docs/develop/promises-signals), and `c.schedules` for [schedules](/docs/develop/schedules).
Caution
An API key in a browser bundle is visible to every user. Call cairnflow from your backend, or from an edge function that holds the key, and expose only what the browser needs.
The client has no delayed send; to run something later, use `ctx.send(..., { delay })` inside a handler.
# Durable steps
> ctx.run, what it guarantees, and what has to go inside it.
`ctx.run` runs a piece of code once and records its result in the invocation’s journal. When the handler replays — after a crash, a deploy or a wait — the step returns the recorded result and the closure is not called again.
```ts
const receipt = await ctx.run("charge", () => chargeCard(order.amount));
```
```ts
run(
name: string,
fn: (signal: AbortSignal) => Promise | T,
opts?: { cancellable?: boolean },
): Promise;
```
## What it guarantees
[Section titled “What it guarantees”](#what-it-guarantees)
1. The closure runs.
2. The SDK sends the result to cairnflow and **waits until it is durable** before the handler goes on. Only then do later steps run.
3. On every later replay, `ctx.run` returns the recorded result.
If the process dies **while the closure is running**, the result is unknown, so the closure runs again on the next attempt. This is the at-least-once part no runtime can remove: nobody knows how far a network call got. Make the work inside a step idempotent — for example, pass an idempotency key to the payment API derived from `ctx.invocationId` and the step name.
If the process dies **after** the result is durable, the step never runs again.
## The result is JSON
[Section titled “The result is JSON”](#the-result-is-json)
Results are stored with `JSON.stringify` and read back with `JSON.parse`, and the handler always continues with the stored value. Return plain data:
* `undefined` becomes `null`.
* A `Date` becomes a string; `Map` and `Set` become `{}`; class instances lose their methods.
* A result whose encoded frame is over 16 MiB is not sent: the step fails for good with a `TerminalError` of code `413`, recorded like any other result, so the closure does not run again.
* Put files and images in an [artifact](/docs/develop/artifacts) and return the reference. Large JSON results are stored as segments rather than inline; see [Payload](/docs/cloud/limits#payload) for the limits on Cairnflow Cloud.
Caution
Do not return secrets (API tokens, keys) from a step. Results are stored in the journal and shown in the console. Read secrets from the environment inside the closure instead.
## Step names are part of the journal
[Section titled “Step names are part of the journal”](#step-names-are-part-of-the-journal)
On replay, the SDK checks each command against the journal: its kind, its name (for `ctx.run`, the step name), and every other field it records, such as a call’s target, key and input. If a deploy renames a step, an in-flight invocation that reaches it stops in the `paused` state with code `570` (journal mismatch) instead of running the wrong code.
* Keep names stable across deploys.
* Do not put configuration in names (model IDs, prompt versions). Put them in [span attributes](/docs/develop/streams-logs) instead.
* Names built from data are fine when the data is deterministic, for example ``ctx.run(`dig/${section}`, ...)`` inside a loop over the input.
See [Deploying new versions](/docs/develop/versioning) for how to change step names safely.
## Errors inside a step
[Section titled “Errors inside a step”](#errors-inside-a-step)
| The closure throws | What happens |
| ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| A normal `Error` | Nothing is recorded. The current turn fails and is retried under the handler’s retry policy; on retry, completed steps replay and this closure runs again. Any `ctx` command after the failure throws `TurnFailed`, even if your code catches the error |
| `RunFailure(message, code)` or `TerminalError(message, code)` | The failure **is** recorded, and the SDK waits until it is durable. `ctx.run` then throws a `TerminalError` with that code and message, now and on every replay. The step never runs again. Catch it to compensate, or let it fail the invocation |
Use `RunFailure` or `TerminalError` when your code decides that a failure is permanent — a `410 Gone` from the other side, a vendor that has not answered after several attempts:
```ts
import { RunFailure } from "@cairnflow/sdk";
const note = await ctx.run(`dig/${section}`, async () => {
if (ctx.attempt >= 5) {
throw new RunFailure(`vendor did not answer after ${ctx.attempt} attempts`, 503);
}
return callVendor(section);
});
```
More in [Errors and retries](/docs/develop/errors-retries).
## Deterministic helpers
[Section titled “Deterministic helpers”](#deterministic-helpers)
The handler body outside `ctx.run` must take the same path on every replay. Use these instead of non-deterministic sources:
| Instead of | Use |
| -------------------------- | ---------------------------------------------------------------------------------- |
| `Math.random()` | `ctx.random()` — a seeded generator that replays the same sequence |
| `Date.now()`, `new Date()` | `await ctx.run("now", () => Date.now())` |
| `crypto.randomUUID()` | `await ctx.run("id", () => crypto.randomUUID())` |
| Your own invocation ID | `ctx.invocationId` |
| Retry counter | `ctx.attempt` — attempts since the handler last made progress (0 on the first run) |
Waits have their own deterministic form: `ctx.sleep` computes its wake-up time once and records it.
## What must go inside ctx.run
[Section titled “What must go inside ctx.run”](#what-must-go-inside-ctxrun)
Anything whose result can differ between two runs, or that touches the outside world:
* HTTP calls, model calls, tool calls, database reads and writes, sending email.
* Reading the clock or generating random IDs.
* Reading anything that can change between attempts (files, environment-dependent lookups) when the handler’s path depends on it.
Pure computation on the handler’s input and on previous step results can stay outside.
## Long steps and parallel steps
[Section titled “Long steps and parallel steps”](#long-steps-and-parallel-steps)
* Only the streaming transport (`BIDI_STREAM`) keeps the connection alive while a closure runs, so a long closure is not cut there. In request-response mode each turn is one HTTP request and must finish within the handler’s `inactivityTimeout`, and on a serverless platform within the platform’s time limit too. That is always the case with `fetchHandler`, and on Cairnflow Cloud it is also the case for `serve()` unless you register the deployment with `"transport": "declared"` ([Deployments](/docs/cloud/deployments#transport)).
* A step that runs past that limit is cut and retried: its closure runs again from the start, and without a retry policy the retries do not stop. Split long work into several shorter steps, or declare a longer `inactivityTimeout` for the handler ([Handler options](/docs/develop/services#handler-options)). The default and the upper bound on Cloud are in [Turn time limit](/docs/cloud/limits#turn-time-limit).
* Several steps can run at once with `Promise.all([ctx.run(...), ctx.run(...)])`. Results reach your code in the order they were recorded in the journal, so parallel branches take the same path on every replay. Code after `await ctx.run(...)` never runs in the same turn as that step’s closure: do not make a closure wait for something only that later code would do.
## Cancellation
[Section titled “Cancellation”](#cancellation)
By default a step is not interrupted by a cooperative cancel, so compensation steps still run. Mark forward steps (model calls, tools) with `{ cancellable: true }`: they do not start once the invocation is cancelled, and their closure receives an `AbortSignal` that fires if the cancel arrives mid-step (streaming mode only). See [Cancellation](/docs/develop/cancellation).
```ts
const page = await ctx.run(
"fetch",
(signal) => fetch(url, { signal }).then((r) => r.text()),
{ cancellable: true },
);
```
# Errors and retries
> Terminal errors, retried errors, retry policies and paused invocations.
A handler can end in three ways besides returning a value: fail for good, be retried, or pause until someone fixes the cause. Which one you get depends on what you throw.
| You throw | Outcome | Journal |
| ------------------------------ | --------------------------------------------------------------- | ------------------------------------------------------------- |
| `TerminalError(message, code)` | Invocation ends `failed` with `code` and `message`. Not retried | Kept; the failure is the result |
| Any other error | The turn fails and is **retried** with backoff | Kept; completed steps replay, only unfinished work runs again |
| `PauseError(message, code)` | Invocation is `paused`, waiting for an operator | Kept; `resume` continues from the same point |
All three are exported from `@cairnflow/sdk`.
## TerminalError
[Section titled “TerminalError”](#terminalerror)
Use it for failures a retry cannot fix: invalid input, a refused payment, a missing record.
```ts
import { TerminalError } from "@cairnflow/sdk";
if (typeof input?.amount !== "number") {
throw new TerminalError("amount must be a number", 400);
}
```
* `code` defaults to `500`. Use HTTP-style codes; the code and message reach the caller. A code that is not an integer from 0 to 2³²−1 becomes `500`.
* A caller using `/invoke` gets `500` with `{"status": "failed", "code": 400, "message": ...}`; the [typed client](/docs/develop/client) throws `InvocationFailed`, which is itself a `TerminalError`.
* A handler that called the failed one with `ctx.call` gets a `TerminalError` with the same code and message.
* You can catch a `TerminalError` and carry on — that is how you write compensation (sagas).
* Thrown inside a `ctx.run` closure, it becomes the step’s recorded result: the closure does not run again, and `ctx.run` throws the same error on every replay.
## Retried errors
[Section titled “Retried errors”](#retried-errors)
Any error that is not a `TerminalError` or `PauseError` fails the current **turn**. Cairnflow schedules another attempt with backoff. On the next attempt, steps already in the journal return their recorded results; only the work that did not finish runs again.
Inside a `ctx.run` closure the rule is strict: once a closure throws a normal error, the turn is dead even if your code catches the error. The next `ctx` command throws `TurnFailed`, and the turn ends as a failure to retry. Continuing past the error would let later steps depend on a result the retry is about to replace. If you want a step’s failure recorded so it never runs again, throw `RunFailure` or `TerminalError` from the closure — see [Durable steps](/docs/develop/durable-steps#errors-inside-a-step).
### Retry policy
[Section titled “Retry policy”](#retry-policy)
Without a policy, retries are unlimited with backoff starting at 100 ms, doubling, capped at 60 seconds. Set a policy per service or per handler:
```ts
service("Payments", { charge }, {
options: {
retryPolicy: {
initialInterval: 200,
maxInterval: 30_000,
exponentiationFactor: 2,
maxAttempts: 5,
onMaxAttempts: "PAUSE",
},
},
});
```
| Field | Default | Meaning |
| ---------------------- | --------- | ---------------------------------------------------------------------------- |
| `initialInterval` | `100` | First backoff, ms |
| `maxInterval` | `60000` | Largest backoff, ms |
| `exponentiationFactor` | `2` | Multiplier between attempts; must be at least 1 |
| `maxAttempts` | unlimited | Total attempts **including the first**; at least 1 |
| `onMaxAttempts` | `"PAUSE"` | `"PAUSE"` keeps the invocation for an operator; `"KILL"` ends it as `failed` |
When attempts run out, the invocation ends `paused` (or `failed` with `KILL`) with code `575`, and the message includes the last attempt’s error. `POST /invocations/{id}/resume` gives a paused invocation another round of attempts.
The policy is captured when the deployment is registered; changing it means registering a new deployment.
### Giving up on purpose
[Section titled “Giving up on purpose”](#giving-up-on-purpose)
`ctx.attempt` counts the attempts since the handler last made progress: `0` on a first run, and it resets every time the journal grows. Use it to stop retrying a dependency that is down for good:
```ts
import { RunFailure } from "@cairnflow/sdk";
const result = await ctx.run("call vendor", async () => {
if (ctx.attempt >= 3) {
throw new RunFailure("vendor did not answer after 3 attempts", 503);
}
return callVendor();
});
```
## Paused invocations
[Section titled “Paused invocations”](#paused-invocations)
An invocation is `paused` when it cannot continue without a person:
| Code | Cause | What to do |
| --------- | --------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| `570` | Journal mismatch: the code no longer matches the recorded steps | Fix the code or move the invocation — see [Deploying new versions](/docs/develop/versioning) |
| `575` | Retry attempts exhausted | Fix the cause, then resume |
| your code | You threw `PauseError` | Fix the cause, then resume |
Throw `PauseError` for problems that will not fix themselves but are worth keeping the work for — stock that must be restocked, a quota that must be raised:
```ts
import { PauseError } from "@cairnflow/sdk";
const inStock = await ctx.run("check stock", () => stock.count(sku));
if (inStock < input.quantity) {
throw new PauseError(`missing ${input.quantity - inStock} of ${sku}`);
}
```
`POST /invocations/{id}/resume` continues the invocation from where it stopped. The answer carries the status after continuing: it can complete, suspend, or pause again if nothing changed.
Caution
A paused invocation on a virtual object **keeps its place in the key’s exclusive queue**. Other exclusive invocations on that key wait until it is resumed, cancelled or finished.
A caller waiting with `/invoke` gets `409` with `{"status": "paused", "code": ..., "message": ...}`; the typed client throws `InvocationPaused`.
## Don’t swallow control flow
[Section titled “Don’t swallow control flow”](#dont-swallow-control-flow)
When your code awaits something that is not ready yet (a timer, a call, a signal, a step result not yet durable), the promise simply stays pending until the turn ends; nothing is thrown. The SDK throws its own errors only in a few cases, and none of them is an error of your code:
| Error | When |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `TurnFailed` | A `ctx` command after a step’s closure threw a normal error; the turn will be retried |
| `JournalMismatch` | A command does not match the journal; the invocation pauses with `570` |
| `Suspend` | A `ctx` command after the turn has already suspended, for example from code still running after it awaited something outside the SDK |
Catching them changes nothing: the turn still suspends, fails or pauses. If you need a broad `catch`, rethrow them:
```ts
import { JournalMismatch, Suspend, TurnFailed } from "@cairnflow/sdk";
try {
await doWork(ctx);
} catch (e) {
if (e instanceof Suspend || e instanceof TurnFailed || e instanceof JournalMismatch) throw e;
// handle your own errors here
}
```
For the full list of failure codes, see [Errors reference](/docs/reference/errors).
# Go SDK
> Write services, virtual objects and workflows in Go with the cairn package, serve them, and call them with the Go client.
The Go SDK, module `github.com/cairnflowdev/cairnflow/sdk/go` (package `cairn`), has the same model as the TypeScript SDK: handlers replay from a journal, side effects go through `cairn.Run`, and results reach your code in the order they were recorded. It needs Go 1.25 or newer and has no dependencies: `go.mod` has no `require`. It is licensed under Apache-2.0 and is in beta.
The rest of these docs show TypeScript. The concepts, limits, error codes and HTTP routes are the same in Go; this page lists what is spelled differently.
## Install
[Section titled “Install”](#install)
```sh
go get github.com/cairnflowdev/cairnflow/sdk/go
```
Releases are tagged `sdk/go/vX.Y.Z` (the current beta is `v0.1.0-beta.0`: `go get github.com/cairnflowdev/cairnflow/sdk/go@v0.1.0-beta.0`). To work against a local checkout instead:
```sh
go mod edit -replace=github.com/cairnflowdev/cairnflow/sdk/go=../cairnflow/sdk/go
```
```go
import (
cairn "github.com/cairnflowdev/cairnflow/sdk/go"
"github.com/cairnflowdev/cairnflow/sdk/go/client" // calling services from an app or a script
)
```
## A first service
[Section titled “A first service”](#a-first-service)
main.go
```go
package main
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
cairn "github.com/cairnflowdev/cairnflow/sdk/go"
)
type Order struct {
Amount int `json:"amount"`
}
type Receipt struct {
Receipt string `json:"receipt"`
Total int `json:"total"`
}
// charge is the side effect: a payment provider in real life.
func charge(ctx context.Context, amount int) (string, error) {
log.Printf("charging %d", amount)
return fmt.Sprintf("receipt-%d", amount), ctx.Err()
}
func submit(ctx cairn.ObjectContext, order Order) (Receipt, error) {
if order.Amount <= 0 {
return Receipt{}, cairn.TerminalErrorf(400, "amount must be positive") // bad data: retrying is useless
}
total, _, err := cairn.Get[int](ctx, "total") // false (and 0) = the key does not exist
if err != nil {
return Receipt{}, err
}
if err := cairn.Sleep(ctx, time.Second); err != nil { // durable: the timer lives in the store
return Receipt{}, err
}
receipt, err := cairn.Run(ctx, "charge", func(rc cairn.RunContext) (string, error) {
return charge(rc, order.Amount) // runs once per durable result; rc is a context.Context
})
if err != nil {
return Receipt{}, err
}
if err := cairn.Set(ctx, "total", total+order.Amount); err != nil {
return Receipt{}, err
}
return Receipt{Receipt: receipt, Total: total + order.Amount}, nil
}
// total runs in parallel with other handlers of the same key and only reads state.
func total(ctx cairn.ObjectSharedContext) (int, error) {
t, _, err := cairn.Get[int](ctx, "total")
return t, err
}
var orders = cairn.NewObject("OrderService",
cairn.Exclusive("submit", submit),
cairn.Shared("total", cairn.NoInput(total)))
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// Listens on every interface; 127.0.0.1:9080 is unreachable from outside a container.
err := cairn.Serve(ctx, ":9080", orders,
cairn.IdentityKeys(os.Getenv("CAIRN_IDENTITY_KEY")))
if err != nil {
log.Fatal(err)
}
}
```
Register and invoke it exactly as in the [Quickstart](/docs/quickstart): `POST /deployments` with the service’s public `https://` URL, then `POST /invoke/OrderService/submit?key=order-42`.
Every durable step is a function of the package that takes the context (`cairn.Get(ctx, …)`, `cairn.Run(ctx, …)`), so it can be generic in the type of its value. A step that can fail returns an `error`: return it from the handler as it is.
## Services and handlers
[Section titled “Services and handlers”](#services-and-handlers)
| Declared with | Kind |
| -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `cairn.NewService(name, handlers...)` | A plain service: no key, no state. Handlers are `cairn.Handler(name, fn)` with `fn func(cairn.Context, I) (O, error)` |
| `cairn.NewObject(name, handlers...)` | A virtual object: state per key. `cairn.Exclusive(name, fn)` takes a `cairn.ObjectContext`; `cairn.Shared(name, fn)` takes a `cairn.ObjectSharedContext` and only reads state |
| `cairn.NewWorkflow(name, handlers...)` | A workflow: exactly one `cairn.Main(name, fn)` taking a `cairn.WorkflowContext`, which runs once per workflow ID, plus any number of `cairn.Shared` handlers. Name the main handler `run`, as the other SDKs do by default |
* A handler without input is wrapped with `cairn.NoInput(fn)`; one without output returns `cairn.Void`.
* Input and output are JSON through `encoding/json`. An input that does not decode into the handler’s input type fails the invocation with a terminal error `400` before the handler runs.
* Writing state from a shared handler does not compile, and neither does `cairn.Get` on a plain service’s context.
* A mistake in a declaration (no handler, two handlers with one name, a workflow without one `Main`) panics at declaration time.
Handler options are trailing arguments of a handler, or `.With(...)` on the whole service: `WithRetryPolicy`, `WithInactivityTimeout`, `WithJournalRetention`, `WithLogLevel`, `WithRuntimeTrace` and `WithLogFlush`. Durations are `time.Duration` values. Their meaning is in [Handler options](/docs/develop/services#handler-options). As in TypeScript, a service that sets no inactivity timeout declares 15 minutes.
```go
signup := cairn.NewWorkflow("Signup",
cairn.Main("run", func(ctx cairn.WorkflowContext, email string) (string, error) {
// Waits, durably, until the shared handler below completes the promise.
return cairn.Promise[string](ctx, "code").Get()
}),
cairn.Shared("verify", func(ctx cairn.WorkflowSharedContext, code string) (cairn.Void, error) {
return cairn.Void{}, cairn.Promise[string](ctx, "code").Resolve(code)
}),
).With(cairn.WithRetryPolicy(cairn.RetryPolicy{
InitialInterval: time.Second,
MaxInterval: time.Minute,
ExponentiationFactor: 2,
MaxAttempts: 10,
OnMaxAttempts: cairn.PauseOnMaxAttempts,
}))
```
## The context
[Section titled “The context”](#the-context)
| | Go |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| State | `cairn.Get[T](ctx, k)` returns `(value, found, err)`; `cairn.Set(ctx, k, v)`, `cairn.Clear(ctx, k)`, `cairn.ClearAll(ctx)`, `cairn.StateKeys(ctx)` |
| Steps | `cairn.Run(ctx, name, func(rc cairn.RunContext) (T, error))`, `cairn.RunAsync(...)` (a future); option `cairn.Cancellable()` |
| Timers | `cairn.Sleep(ctx, d)`, `cairn.After(ctx, d)` (a future) |
| Calls | `cairn.Service[O](ctx, svc, handler)`, `cairn.Object[O](ctx, svc, key, handler)`, `cairn.Workflow[O](ctx, svc, id, handler)`, then `.Request(in)`, `.RequestFuture(in)` or `.Send(in, cairn.WithDelay(d))`; options `WithIdempotencyKey`, `WithScope`, `WithLimitKey`, `WithSpread` |
| Signals | `cairn.Signal[T](ctx, name)` (a future), `cairn.SendSignal(ctx, invocationID, name, v)` |
| Awakeables | `awk := cairn.Awakeable[T](ctx)`, `awk.ID()` for the outside system, then `awk.Result()` |
| Promises | `p := cairn.Promise[T](ctx, name)`: `p.Get()`, `p.GetFuture()`, `p.Peek()`, `p.Resolve(v)`, `p.Reject(code, msg)` |
| Other invocations | `cairn.Attach[T](ctx, invocationID)` (a future), `cairn.GetOutput[T](ctx, invocationID)`, `cairn.ContinueAsNew(ctx, input)` |
| Combinators | `cairn.WaitFirst(ctx, futs...)`, `cairn.Wait(ctx, futs...)`, `cairn.All(ctx, futs...)`, `cairn.Race(ctx, futs...)`; on a future, `f.Result()` and `f.Done()` |
| Streams, logs, traces | `s, err := ctx.Stream(name)` (`cairn.Durable()` to keep it), `s.Append(record)`, `s.Close()`; `ctx.Log()` is a `*slog.Logger`; `cairn.WithSpan(ctx, name, fn, attrs...)` |
| Artifacts | `ref, err := rc.Artifacts().Put(bytes, contentType)` inside a `Run` closure, `ctx.Artifacts().Get(ref.SHA256)` |
| Identity | `ctx.Key()`, `ctx.InvocationID()`, `ctx.Attempt()`, `ctx.Schedule()`, `ctx.Rand()`, `ctx.Random()`, `cairn.UUID(ctx)` |
A command is journaled when its future is created; waiting happens only in `Result` or in a combinator. That is how several steps run at once on one goroutine. When several futures are ready, the combinators pick by journal order, never by arrival time, so a replay takes the same path.
The rules of handler code are the same as in TypeScript. In Go they read as follows, with two additions (rules 1 and 4):
1. **Stay on the handler’s goroutine.** No `go` statements, channels, `sync` or `time.Sleep` in handler code to coordinate durable work: parallel work is futures plus a combinator. Concurrency inside a `Run` closure is fine.
2. Use `ctx.Rand()`, `ctx.Random()` or `cairn.UUID(ctx)`, not `math/rand`, `crypto/rand` or `time.Now`. Read the clock only inside `cairn.Run`.
3. **Do all I/O inside `cairn.Run`.** A `cairn.Context` is not a `context.Context`; a `Run` closure gets one, and must not touch the handler’s `ctx`.
4. **Issue the same commands in the same order.** Ranging over a map visits keys in a random order, so sort the keys before a loop that issues commands.
## Errors
[Section titled “Errors”](#errors)
| Returned from a handler | What happens |
| ---------------------------------------------- | ---------------------------------------------- |
| `cairn.TerminalErrorf(code, format, args...)` | The invocation fails without a retry |
| `cairn.PauseErrorf(format, args...)` | The invocation pauses until someone resumes it |
| `cairn.RetryableErrorf(code, format, args...)` | Retried like any other error, with a code |
| Any other `error`, or a panic | The turn fails and is retried with backoff |
Returned from a `Run` closure, a `*cairn.TerminalError` is recorded as the step’s result: the closure does not run again, and `cairn.Run` returns the same error on every replay. Check for one with `errors.As` or `cairn.IsTerminalError(err)`.
See [Errors and retries](/docs/develop/errors-retries) for codes and retry policies.
## Serving
[Section titled “Serving”](#serving)
| Entry point | Where |
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `cairn.Serve(ctx, addr, services...)` | The built-in server, until `ctx` ends. It serves HTTP/1.1 and cleartext HTTP/2 on one port |
| `cairn.HTTPHandler(services...)` | An `http.Handler` for a server of your own |
| `cairn.LambdaHandler(services...)` | AWS Lambda (Function URL or API Gateway HTTP API, payload v2), request-response mode only. Pass the handler to `lambda.Start` in your own `main` |
Unlike `serve()` in TypeScript, these default to request-response mode. For streaming mode pass `cairn.Bidi()`. On Cairnflow Cloud an `https://` endpoint is called in request-response mode unless you register it with `"transport": "declared"` ([Deployments](/docs/cloud/deployments#transport)).
Services and options are passed together, in any order:
| Option | Default | Meaning |
| --------------------------------------------------------------------------------------------------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `cairn.IdentityKeys(keys...)` | none | Identity keys of your environment; unsigned requests get `401`. Required by Cairnflow Cloud. Without it, a warning is logged once and the endpoint keeps no replay cache |
| `cairn.IdentityHosts(hosts...)` | none | The public hosts you registered, as `identityHosts` in [serve() options](/docs/develop/services#serve-options) |
| `cairn.Bidi()` | off | Declare streaming mode |
| `cairn.WithoutCompression()` | compression on | Stop accepting gzip request bodies and compressing large responses |
| `cairn.ReplayCache(...)`, `cairn.WithoutReplayCache()` | on with `IdentityKeys` (off on Lambda) | Keep the journal of running invocations in memory so only new entries are sent |
| `cairn.MaxProtocolVersion(v)` | `6` with `IdentityKeys`, else `5` | Pin an older protocol version |
| `cairn.SegmentOrigins(...)`, `cairn.ValueCacheBytes(n)`, `cairn.MaxValueBytes(n)`, `cairn.MaxTurnValueBytes(n)` | as in TypeScript | Downloading large values stored as segments |
## Client
[Section titled “Client”](#client)
app.go
```go
c := client.Connect(os.Getenv("CAIRN_URL"), client.WithAPIKey(os.Getenv("CAIRN_KEY")))
// Waits for the result.
r, err := client.Call[Receipt](ctx, c.Object("OrderService", "order-42"), "submit", Order{Amount: 100})
// Returns once the invocation is durable.
h, err := client.Send(ctx, c.Object("OrderService", "order-42"), "submit", Order{Amount: 5})
out, err := client.Attach[Receipt](ctx, h, client.Timeout(time.Minute))
```
* Targets: `c.Service(name)`, `c.Object(name, key)`, `c.Workflow(name, workflowID)`, `c.Awakeable(id)`, `c.Promise(service, key, name)`, `c.Schedules()`.
* `client.Call` waits; `client.Send` returns an invocation handle with `Status`, `Signal` and `Cancel`; `client.RunWorkflow` starts a workflow and waits for it.
* Every call carries a generated `Idempotency-Key`, kept across the client’s own retries (`client.IdempotencyKey(k)` sets one, `client.NoIdempotencyKey()` sends none). The client follows the `leader` of a `503` and waits for the `Retry-After` of a `429`.
* A handler’s terminal error arrives as `*client.InvocationFailed`; a wait that runs out is a `*client.AttachTimeout`, and the invocation keeps running.
* `c.ReadStream(ctx, invocationID, name)` iterates over a stream’s events and reconnects on its own, like `readStream` in [Streams, logs and traces](/docs/develop/streams-logs).
## Testing handlers
[Section titled “Testing handlers”](#testing-handlers)
The package `github.com/cairnflowdev/cairnflow/sdk/go/cairntest` runs a handler in the test process over the SDK’s real turn machine, with no runtime. Every turn replays the whole journal so far, so a test exercises replay too:
```go
inv := cairntest.New(orders, "submit", Order{Amount: 100}, cairntest.Key("o-1"))
st, err := inv.Run() // cairntest.Completed, Waiting, Failed, Paused or ContinuedAsNew
if err != nil || st != cairntest.Completed {
t.Fatal(st, err)
}
var r Receipt
if err := inv.Output(&r); err != nil {
t.Fatal(err)
}
```
## Not in the Go SDK
[Section titled “Not in the Go SDK”](#not-in-the-go-sdk)
* The Vercel AI SDK adapter (`chatObject`, `cairnMiddleware`, `cairnTools`, `cairnChatTransport`): it is specific to that TypeScript library.
# Local development
> Run your service on your own machine against a dev environment in Cairnflow Cloud, through an HTTPS tunnel whose URL does not change.
Cloud is in waitlist
This page is about developing against Cairnflow Cloud, which is not open yet — [join the waitlist](/#pricing) for early access. Today you can run the runtime yourself: with a node on your own machine, as in the [Quickstart](/docs/quickstart), you register `http://127.0.0.1:` and need no tunnel.
Cairnflow Cloud does not run your code: it calls your service over HTTPS. While you develop, that service can run on your own machine, as long as Cloud can reach it. This page covers that setup. To run the runtime itself on your machine instead, install a release binary or run Docker: see [Self-hosting](/docs/self-hosting).
## 1. Use a separate environment
[Section titled “1. Use a separate environment”](#1-use-a-separate-environment)
Create an environment for development, for example `dev`, next to `prod`. Each environment has its own endpoint, API keys, identity key and data, so nothing you register or run in `dev` touches `prod`. How many environments an organization can have is in [Account limits](/docs/cloud/limits#account-limits).
On the `dev` environment’s page, copy its endpoint and identity key, and create an Admin API key:
```sh
export CAIRN_URL=""
export CAIRN_KEY=""
export CAIRN_IDENTITY_KEY=""
```
## 2. Run the service on your machine
[Section titled “2. Run the service on your machine”](#2-run-the-service-on-your-machine)
service.ts
```ts
import { serve, service } from "@cairnflow/sdk";
const greeter = service("Greeter", {
greet: async (ctx, name: string) => {
const upper = await ctx.run("upper", () => name.toUpperCase());
return `Hello, ${upper}!`;
},
});
await serve({
services: [greeter],
port: Number(process.env.PORT ?? 9080),
identityKeys: [process.env.CAIRN_IDENTITY_KEY!],
});
```
Start it the way you run TypeScript in your project. `serve()` listens on `127.0.0.1` by default, which is all a tunnel on the same machine needs, and nothing else on your network can reach it. Keep `identityKeys`: the tunnel makes the service public, and the identity key is what refuses requests that do not come from your environment. Cloud refuses to register an endpoint without it.
## 3. Give it a public HTTPS URL that does not change
[Section titled “3. Give it a public HTTPS URL that does not change”](#3-give-it-a-public-https-url-that-does-not-change)
Cloud calls only `https://` endpoints on the public internet, so put a tunnel in front of the service. Choose one whose URL stays the same every time you start it: a deployment remembers the URL it was registered with, and invocations stay on the deployment they started on (see [When the URL changes](#when-the-url-changes)).
### Cloudflare Tunnel, named, on your own domain
[Section titled “Cloudflare Tunnel, named, on your own domain”](#cloudflare-tunnel-named-on-your-own-domain)
With a domain whose DNS is on Cloudflare, create a named tunnel once and give it a hostname:
```sh
cloudflared tunnel login
cloudflared tunnel create cairn-dev
cloudflared tunnel route dns cairn-dev cairn-dev.example.com
```
Point it at the service in `config.yml` in your `.cloudflared` directory:
config.yml
```yaml
tunnel:
credentials-file:
url: http://127.0.0.1:9080
```
Then run it whenever you work:
```sh
cloudflared tunnel run cairn-dev
```
The URL is `https://cairn-dev.example.com`, every time.
### ngrok with your dev domain
[Section titled “ngrok with your dev domain”](#ngrok-with-your-dev-domain)
Every ngrok account, including a free one, has a dev domain that does not change when the agent restarts, and `ngrok http` uses it unless you pass another domain with `--url`:
```sh
ngrok http 127.0.0.1:9080
```
The URL is your dev domain, shown when the agent starts.
### What to avoid
[Section titled “What to avoid”](#what-to-avoid)
* **Tunnels that get a new URL every time**, such as Cloudflare’s quick tunnels (`cloudflared tunnel --url …`, a new `trycloudflare.com` hostname on each start).
* **Long turns through a tunnel.** In request-response mode each turn is one HTTP request, and a tunnel or proxy can have its own limit on how long a request may take, on top of the [turn time limit](/docs/cloud/limits#turn-time-limit).
## 4. Register the tunnel URL
[Section titled “4. Register the tunnel URL”](#4-register-the-tunnel-url)
```sh
curl -X POST "$CAIRN_URL/deployments" \
-H "authorization: Bearer $CAIRN_KEY" \
-H "content-type: application/json" \
-d '{"uri":"https://cairn-dev.example.com"}'
```
Leave `transport` out: Cloud then calls the tunnel URL in request-response mode, which works through any tunnel. Invoke a handler to check the round trip:
```sh
curl -X POST "$CAIRN_URL/invoke/Greeter/greet" \
-H "authorization: Bearer $CAIRN_KEY" \
-H "content-type: application/json" \
-d '"world"'
```
The console of the `dev` environment shows each invocation step by step.
## Day-to-day
[Section titled “Day-to-day”](#day-to-day)
* **Restart the service freely.** A turn cut by a restart is retried, and the invocation replays from its journal. While your machine sleeps or the tunnel is down, invocations that need your service are retried with backoff until it answers again, or until their retry policy gives up.
* **Changing code in place affects running invocations.** They replay against whatever code answers at the URL. Renaming, adding, removing or reordering steps, or changing a call’s target or input, before the point an invocation reached pauses it with code `570`; see [Deploying new versions](/docs/develop/versioning).
* **Register again when you change services, handlers or their options** (retry policy, `inactivityTimeout`): they are read at registration. Each registration creates a new deployment, even for the same URL, and counts toward the environment’s [deployment limit](/docs/cloud/limits) until you remove it. `DELETE /deployments/{id}` removes one that is no longer current and has no invocations left on it.
## When the URL changes
[Section titled “When the URL changes”](#when-the-url-changes)
Every invocation stays on the deployment it started on, for its whole life, and a deployment always calls the URL it was registered with. If the tunnel’s URL changes (a quick tunnel, another ngrok domain, a new hostname) and you register the new URL, new invocations go to the new deployment, but the ones already running keep calling the old URL. They cannot reach it, so they are retried with backoff, and without a [retry policy](/docs/develop/errors-retries#retry-policy) they keep retrying until the old URL answers again.
Caution
Do not leave invocations on a URL you no longer control. Every attempt sends the invocation’s journal (its input and step results) to that URL, so whoever answers there next receives them.
Find them with `GET /deployments/{id}` of the old deployment (`pinnedInvocations` counts them), or list them with SQL on the console’s **Query** page or through [`POST /query`](/docs/query):
```sql
SELECT id, service, handler, class, last_failure_message
FROM sys_invocation
WHERE class IN ('active', 'paused') AND pinned_deployment = 'dp_…'
```
Then pick one way out for each:
* **Bring the old URL back.** Start a tunnel on the old hostname again; the invocations continue on their next retry. The code behind it must still match their journals.
* **Move them to the new deployment:** `POST /invocations/{id}/migrate?deployment=`. Cloud first replays the invocation on the new deployment and refuses with `409` if the code there no longer matches its journal; `&force=true` skips that check. In the console: **Migrate…** on the invocation.
* **Run them again on the new deployment:** `POST /invocations/{id}/restart?deployment=`. This starts a new invocation from the old one’s input (add `&from=` to keep the first `n` journal entries and their results); the old one ends, and callers waiting on it get the new one’s result. A workflow’s `run` cannot be restarted. In the console: **Restart from step…**.
* **End them:** a hard cancel, `POST /invocations/{id}/cancel`, does not need your service. In the console: **Cancel now**, also available as a bulk action.
Once no invocation is left on the old deployment, remove it with `DELETE /deployments/{id}`.
## Next
[Section titled “Next”](#next)
* [Deployments](/docs/cloud/deployments)
* [Deploying new versions](/docs/develop/versioning)
* [Beta limits](/docs/cloud/limits)
# Durable promises, signals and awakeables
> Wait for a person or an outside system, and complete the wait from another handler or over HTTP.
Three primitives let an invocation wait for something that happens outside it — an approval, a webhook, a click in an email. All three suspend the invocation durably: it can wait for weeks without holding a process.
| Primitive | Addressed by | Available in | Completed by |
| --------------- | ---------------------------- | -------------------------- | ------------------------------------------------------------- |
| Durable promise | service + key + promise name | Virtual objects, workflows | Another handler on the same object, or `POST /promises/...` |
| Signal | invocation ID + signal name | Every handler | `POST /invocations/{id}/signal`, `ctx.sendSignal`, the client |
| Awakeable | an opaque `awk_...` ID | Every handler | `POST /awakeables/{id}/resolve` |
Pick a **promise** when the outside system knows the object (a workflow ID, an order number). Pick an **awakeable** when you hand an ID to a third party and want nothing else exposed. Pick a **signal** when the sender already knows the invocation ID.
## Durable promises
[Section titled “Durable promises”](#durable-promises)
A promise is a named value that belongs to one object (a virtual object key or a workflow ID).
signup.ts
```ts
import { type Context, workflow } from "@cairnflow/sdk";
const signup = workflow("UserSignup", {
async run(ctx: Context, user: { email: string }) {
const secret = await ctx.run("secret", () => crypto.randomUUID());
await ctx.run("mail", () => sendVerification(user, secret));
const clicked = await ctx.promise("email-link-clicked").get();
return clicked === secret;
},
async click(ctx: Context, req: { secret: string }) {
await ctx.promise("email-link-clicked").resolve(req.secret);
},
});
```
| Method | Meaning |
| ------------------------ | ------------------------------------------------------------------------------ |
| `get()` | Wait until the promise is completed. A rejected promise throws `TerminalError` |
| `peek()` | `null` if not completed yet, without waiting |
| `resolve(value)` | Complete with a value. Throws `TerminalError` if already completed |
| `reject(message, code?)` | Complete with a failure. Throws `TerminalError` if already completed |
### Completing a promise over HTTP
[Section titled “Completing a promise over HTTP”](#completing-a-promise-over-http)
No extra handler is needed: an outside system can complete the promise directly with an API key that can invoke handlers.
```sh
# Resolve: the body is the value.
curl -X POST "$CAIRN_URL/promises/UserSignup/u-1/email-link-clicked/resolve" \
-H "authorization: Bearer $CAIRN_KEY" \
-H "content-type: application/json" -d '"s3cr3t"'
# Reject: waiters get a terminal error with this code and message.
curl -X POST "$CAIRN_URL/promises/UserSignup/u-1/email-link-clicked/reject" \
-H "authorization: Bearer $CAIRN_KEY" \
-H "content-type: application/json" -d '{"code": 403, "message": "link expired"}'
# Has it been completed yet?
curl "$CAIRN_URL/promises/UserSignup/u-1/email-link-clicked" \
-H "authorization: Bearer $CAIRN_KEY"
```
For an object in a scope, prefix the path with `/scope/{scope}`. With the [typed client](/docs/develop/client): `c.promise("UserSignup", "u-1", "email-link-clicked").resolve(value)`.
Properties you can rely on:
* **Completing twice is a no-op, not an error.** The second HTTP call answers `completed: false`. Webhook retries are safe without an extra idempotency key.
* **Completing before anyone waits still works.** The promise is durable; a `get()` that runs later returns the value at once.
## Signals
[Section titled “Signals”](#signals)
A signal is a named message delivered to one invocation. `ctx.signal(name)` returns a future you can await or race against a deadline:
```ts
const approval = await ctx.race([
ctx.signal<{ by: string }>("approve"),
ctx.sleep(24 * 3600_000),
]);
if (approval === undefined) throw new TerminalError("approval timed out", 408);
```
Send it from outside with the invocation ID:
```sh
curl -X POST "$CAIRN_URL/invocations/$ID/signal" \
-H "authorization: Bearer $CAIRN_KEY" \
-H "content-type: application/json" \
-d '{"signal": "approve", "value": {"by": "alice"}}'
```
From the client: `await c.invocation(id).signal("approve", { by: "alice" })`. From another handler: `ctx.sendSignal(invocationId, "approve", { by: "alice" })` — one-way, it does not wait.
* A signal without a value resolves to `null`.
* **A delivered signal stays delivered.** Sending the same signal again is a no-op. And once `approve` has arrived, every later `ctx.signal("approve")` in that invocation resolves at once with the same value — use a new name for a new round of waiting (`approve-2`).
* Signals sent to an invocation that has already finished are ignored.
## Awakeables
[Section titled “Awakeables”](#awakeables)
An awakeable is a wait point with a generated ID. Hand the ID to an outside system — inside a `ctx.run`, so it is sent once — then await the promise:
```ts
const { id, promise } = ctx.awakeable<{ approved: boolean }>();
await ctx.run("request approval", () => mailer.send(approver, id));
const answer = await ctx.race([promise, ctx.sleep(7 * 24 * 3600_000)]);
```
The outside system completes it with an API key of the same environment that can invoke handlers:
```sh
curl -X POST "$CAIRN_URL/awakeables/$AWAKEABLE_ID/resolve" \
-H "authorization: Bearer $CAIRN_KEY" \
-H "content-type: application/json" -d '{"approved": true}'
curl -X POST "$CAIRN_URL/awakeables/$AWAKEABLE_ID/reject" \
-H "authorization: Bearer $CAIRN_KEY" \
-H "content-type: application/json" -d '{"message": "denied", "code": 403}'
```
With the client: `c.awakeable(id).resolve(value)` or `c.awakeable(id).reject(message, code)`. A rejected awakeable throws `TerminalError` in the handler.
## Starting work that waits for a person
[Section titled “Starting work that waits for a person”](#starting-work-that-waits-for-a-person)
Start the invocation with `/send` (or `send.` in the client), not `/invoke`: holding an HTTP request open until someone clicks a button is what `/send` avoids. For a workflow, fetch the result later with `POST /workflow/{service}/{key}/attach` — it needs only the workflow ID, so the outside system does not have to store an invocation ID.
# Python SDK
> Write services, virtual objects and workflows in Python with the cairnflow package, serve them, and call them with the Python client.
The Python SDK, package `cairnflow`, has the same model as the TypeScript SDK: handlers replay from a journal, side effects go through `ctx.run`, and results reach your code in the order they were recorded. It needs Python 3.11 or newer and has no runtime dependencies. It is licensed under Apache-2.0 and is in beta (version `0.1.0b0`).
The rest of these docs show TypeScript. The concepts, limits, error codes and HTTP routes are the same in Python; this page lists what is spelled differently.
## Install
[Section titled “Install”](#install)
```sh
pip install cairnflow
```
To install from a local checkout of the repository instead: `pip install ./sdk/python`.
Two optional extras:
| Extra | Adds | Needed for |
| ------------------- | -------------- | ----------------------------------------------------------------------------- |
| `cairnflow[bidi]` | `h2` | Streaming mode (`BIDI_STREAM`) in the built-in server |
| `cairnflow[crypto]` | `cryptography` | Faster verification of request signatures; a pure-Python fallback is built in |
## A first service
[Section titled “A first service”](#a-first-service)
service.py
```python
import asyncio
import os
from dataclasses import dataclass
from cairnflow import Context, TerminalError, VirtualObject, serve
orders = VirtualObject("OrderService")
@dataclass
class Order:
amount: int
def charge(amount: int) -> str:
return f"receipt-{amount}" # a payment provider in real life
@orders.handler()
async def submit(ctx: Context, order: Order) -> dict:
if order.amount <= 0:
raise TerminalError("amount must be positive", 400) # retrying bad input is useless
total = (await ctx.get("total")) or 0 # None: the key does not exist
await ctx.sleep(1) # durable timer, in seconds
receipt = await ctx.run("charge", charge, order.amount)
ctx.set("total", total + order.amount)
return {"receipt": receipt, "total": total + order.amount}
@orders.handler(kind="shared") # runs alongside the exclusive handlers, reads state only
async def get_total(ctx: Context) -> int:
return (await ctx.get("total")) or 0
asyncio.run(
serve(
[orders],
host="0.0.0.0", # the default, 127.0.0.1, is unreachable from outside a container
port=int(os.environ.get("PORT", "9080")),
identity_keys=[os.environ["CAIRN_IDENTITY_KEY"]],
)
)
```
Register and invoke it exactly as in the [Quickstart](/docs/quickstart): `POST /deployments` with the service’s public `https://` URL, then `POST /invoke/OrderService/submit?key=order-42`.
## Services and handlers
[Section titled “Services and handlers”](#services-and-handlers)
| Declared with | Kind |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `Service(name)` | A plain service: no key, no state |
| `VirtualObject(name)` | A virtual object: state per key; handlers are exclusive unless declared `kind="shared"` |
| `Workflow(name)` | A workflow: exactly one `@wf.main()` handler (named `run` by default) that runs once per workflow ID, plus `@wf.handler()` shared handlers |
* A handler is `async def h(ctx)` or `async def h(ctx, input)`. The handler name defaults to the function name; pass `@svc.handler("name")` to choose another.
* Input and output are JSON. An input annotated with a dataclass or a Pydantic model is converted for you, and dataclasses and Pydantic models are serialized on the way out.
* Shared handlers must not write state; the runtime rejects their writes with code `571`.
Handler options go in `options=HandlerOptions(...)` on the service or on one handler. Durations are a `timedelta` or a number of **seconds** (the TypeScript SDK uses milliseconds):
```python
from datetime import timedelta
from cairnflow import HandlerOptions, RetryPolicy, Service
agent = Service(
"Agent",
options=HandlerOptions(
inactivity_timeout=timedelta(minutes=10),
retry_policy=RetryPolicy(max_attempts=5, on_max_attempts="PAUSE", initial_interval=0.2),
),
)
```
`HandlerOptions` fields: `inactivity_timeout`, `retry_policy`, `journal_retention`, `log_level`, `trace`, `log_flush`. `RetryPolicy` fields: `initial_interval`, `max_interval`, `exponentiation_factor`, `max_attempts`, `on_max_attempts`. Their meaning is in [Handler options](/docs/develop/services#handler-options). As in TypeScript, the SDK declares an `inactivity_timeout` of 15 minutes when you set none.
## The context
[Section titled “The context”](#the-context)
| | Python |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| State | `await ctx.get(k)`, `ctx.set(k, v)`, `ctx.clear(k)`, `ctx.clear_all()`, `await ctx.state_keys()` |
| Steps | `await ctx.run(name, fn, *args, cancellable=False, **kwargs)`; `fn` can be sync or async |
| Timers | `await ctx.sleep(seconds_or_timedelta, name="sleep")` |
| Calls | `await ctx.call(service, handler, input, key=..., idempotency_key=..., placement="spread")`, `ctx.send(..., delay=...)`, `ctx.scoped(scope, limit_key).call(...)` |
| Signals | `await ctx.signal(name)`, `ctx.send_signal(invocation_id, name, value)` |
| Awakeables | `awk_id, fut = ctx.awakeable()`, then `await fut` |
| Promises | `await ctx.promise(name).get()`, `.peek()`, `.resolve(v)`, `.reject(message, code)` |
| Other invocations | `await ctx.attach(invocation_id)`, `await ctx.get_output(invocation_id)`, `ctx.continue_as_new(input)` |
| Combinators | `await ctx.all([f1, f2])`, `await ctx.race([f1, f2])`; `asyncio.gather` over branches works too |
| Streams, logs, traces | `ctx.stream(name, durable=False).append(record)`, `ctx.log.info(msg, attrs)`, `async with ctx.trace.span(name) as s:` |
| Artifacts | `ref = ctx.artifact.put(data, "image/png")`, `await ctx.artifact.get(ref)`, `configure_artifacts(base_url, headers)` |
| Identity | `ctx.key`, `ctx.invocation_id`, `ctx.attempt`, `ctx.schedule` (a `(name, at_ms)` tuple or `None`), `ctx.random()` |
The rules of handler code are the same as in TypeScript, with one addition:
1. Use `ctx.random()`, not the `random` module.
2. Read the clock only inside `ctx.run`.
3. **Do all I/O inside `ctx.run`.** Handler code runs on a deterministic event loop that refuses network I/O on purpose; `ctx.run` functions run on the server’s normal event loop.
## Errors
[Section titled “Errors”](#errors)
* `TerminalError(message, code=500)` fails the invocation without a retry.
* `PauseError(message, code=500)` pauses it until someone resumes it.
* Any other exception fails the turn, which is retried with backoff.
* Raised inside a `ctx.run` function, `TerminalError` or `RunFailure` is recorded as the step’s result: the function does not run again, and `ctx.run` raises a `TerminalError` with the same code and message on every replay.
See [Errors and retries](/docs/develop/errors-retries) for codes and retry policies.
## Serving
[Section titled “Serving”](#serving)
| Entry point | Where |
| --------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| `await serve(services, host="127.0.0.1", port=9080, **options)` | The built-in server. `start(...)` does the same and returns the `asyncio.Server` |
| `app(services, **options)` | An ASGI application for uvicorn, hypercorn or any ASGI server |
| `cairnflow.aws_lambda.lambda_handler(services, **options)` | AWS Lambda (Function URL or API Gateway HTTP API, payload v2) |
Unlike `serve()` in TypeScript, these default to request-response mode. For streaming mode pass `protocol_mode="BIDI_STREAM"`: the built-in server then needs the `bidi` extra, and under ASGI it needs a server that speaks cleartext HTTP/2 on the same port as HTTP/1.1, such as hypercorn (uvicorn has no HTTP/2). On Cairnflow Cloud an `https://` endpoint is called in request-response mode unless you register it with `"transport": "declared"` ([Deployments](/docs/cloud/deployments#transport)).
Options, as keyword arguments:
| Option | Default | Meaning |
| --------------------------------------------------------------------------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `identity_keys` | none | Identity keys of your environment; unsigned requests get `401`. Required by Cairnflow Cloud. Without it, a warning is emitted once per process |
| `identity_hosts` | none | The public hosts you registered, as `identityHosts` in [serve() options](/docs/develop/services#serve-options) |
| `protocol_mode` | `"REQUEST_RESPONSE"` | Or `"BIDI_STREAM"` |
| `compression` | `True` | Accept gzip request bodies and compress large responses |
| `replay_cache` | `True` (`False` on Lambda) | Keep the journal of running invocations in memory so only new entries are sent |
| `max_protocol_version` | `6` | Pin an older protocol version |
| `segment_origins`, `value_cache_bytes`, `max_value_bytes`, `max_turn_value_bytes` | as in TypeScript | Downloading large values stored as segments |
## Client
[Section titled “Client”](#client)
app.py
```python
import asyncio
import os
from cairnflow import InvocationFailed, connect
async def main() -> None:
c = connect(os.environ["CAIRN_URL"], api_key=os.environ["CAIRN_KEY"])
order = c.object("OrderService", "order-42")
print(await order.call("submit", {"amount": 100})) # waits for the result
h = await order.send("submit", {"amount": 5}) # returns once the invocation is durable
try:
print(await h.attach(timeout=60))
except InvocationFailed as e:
print("failed:", e.code, e)
asyncio.run(main())
```
* Targets: `c.service(name)`, `c.object(name, key)`, `c.workflow(name, workflow_id)`, `c.invocation(id)`, `c.awakeable(id)`, `c.promise(service, key, name)`, `c.schedules`. Each target takes `scope=` where it applies.
* `call(handler, input, ...)` waits; `send(handler, input, ...)` returns an invocation handle with `attach`, `output`, `status`, `signal` and `cancel`. A workflow client adds `run`, `attach` and `output`.
* Every call carries a generated `Idempotency-Key`, kept across the client’s own retries; `idempotency_key=None` sends none. The client follows the `leader` of a `503` and waits for the `Retry-After` of a `429`.
* Errors: `InvocationFailed` (a `TerminalError`), `InvocationPaused`, `AlreadyInvoked`, `AttachTimeout`, `CairnHttpError`, as in the [typed client](/docs/develop/client).
* `connect` options: `headers`, `follow_leader`, `max_attempts` (8), `max_elapsed` (30 s), `attach_wait` (25 s), `timeout`, `connect_timeout` (10 s), `ssl_context`. Durations are in seconds.
* `read_stream(base_url, invocation_id, name, offset=0, headers=...)` is an async iterator over a stream’s events, like `readStream` in [Streams, logs and traces](/docs/develop/streams-logs).
Schedules use keyword arguments in snake case:
```python
await c.schedules.put(
"nightly-report",
cron="0 2 * * *",
time_zone="Europe/Berlin",
target={"service": "Report", "handler": "build"},
input={"full": True},
)
```
## Not in the Python SDK
[Section titled “Not in the Python SDK”](#not-in-the-python-sdk)
* The Vercel AI SDK adapter (`chatObject`, `cairnMiddleware`, `cairnTools`, `cairnChatTransport`): it is specific to that TypeScript library.
* A typed client generated from your service definitions: the Python client addresses handlers by name.
# Server-side schedules
> Run a handler on a cron expression or a fixed period, managed by cairnflow.
A schedule invokes a handler on a cron expression or every N milliseconds. Cairnflow stores the schedule and fires it; your service does not need a timer process or a cron host.
setup.ts
```ts
import { connect } from "@cairnflow/sdk/client";
const c = connect({ url: process.env.CAIRN_URL!, apiKey: process.env.CAIRN_KEY! });
await c.schedules.put("nightly-report", {
cron: "0 2 * * *",
timeZone: "Europe/Berlin",
target: { service: "Report", handler: "build" },
input: { full: true },
});
```
`put` creates or updates. Calling it again with the same definition is a no-op that does not move the next tick, so it is safe to call on every application start.
## Definition
[Section titled “Definition”](#definition)
Exactly one of `cron` or `everyMs` is required.
| Field | Meaning |
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `cron` | Five fields: minute, hour, day of month, month, day of week. Supports `*`, `,`, `-`, `/` and month and weekday names. Day of month and day of week combine with OR. No seconds field, no `L`, `W` or `#` |
| `timeZone` | IANA time zone for `cron`, default `UTC` |
| `everyMs` | Fixed period in ms, aligned to the Unix epoch. Must be at least the server’s minimum period (10 seconds unless your operator changed it) |
| `target` | `{ service, handler }`, plus `key` for a virtual object |
| `input` | JSON input for each run, at most 64 KiB encoded. Absent: no input |
| `overlap` | `"skip"`: if the previous run has not finished, skip this tick (default for targets without a key). `"allow"`: always fire (the only option for keyed or scoped targets) |
| `paused` | Create the schedule paused |
| `jitterMs` | Spread the fire time by a deterministic offset below this value, kept before the next tick |
| `limitKey` | Limit key passed to each run |
Schedule names are 1 to 128 characters from `[A-Za-z0-9._-]`, unique within the environment (and scope).
## Managing schedules
[Section titled “Managing schedules”](#managing-schedules)
```ts
await c.schedules.pause("nightly-report"); // no ticks until resumed
await c.schedules.resume("nightly-report"); // next tick counted from now, no catch-up
const run = await c.schedules.trigger("nightly-report"); // fire once now
await run.attach();
const s = await c.schedules.get("nightly-report"); // undefined if it does not exist
const all = await c.schedules.list();
await c.schedules.delete("nightly-report"); // false if it did not exist
```
* **`trigger`** fires once immediately, ignoring `paused` and `overlap`, and does not move the next tick. It returns an invocation handle. Pass `{ idempotencyKey }` to make retries safe: the same key gives the same run. Without one, the client generates a key and keeps it across its own retries.
* **`resume`** computes the next tick from the current time. Ticks missed while paused are not fired.
* **`delete`** removes the schedule. Runs it already started are not affected.
* **Changing a definition** with `put` recomputes the next tick from the current time.
* Every method takes an optional `{ scope }` for schedules inside a [scope](/docs/develop/calls#scopes).
`get` returns the definition plus:
| Field | Meaning |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `nextAt` | Next nominal tick (ms), `null` while paused |
| `fireAt` | When `nextAt` will actually fire, after jitter |
| `upcoming` | The next 10 ticks |
| `last` | Up to 10 recent ticks, newest last: `at`, `id` of the run, `outcome` (`fired` or `skipped`), and sometimes the run’s `status` |
| `fired`, `missed`, `skipped` | Counters |
`list` returns `{ schedules, partial, missing, missingRanges }`; `partial: true` means some part of the environment could not be read and the list may be incomplete.
Managing schedules needs a key that can invoke handlers. The same operations exist over HTTP under `/schedules/{name}` — see the [HTTP API reference](/docs/reference/http-api).
## Inside the handler
[Section titled “Inside the handler”](#inside-the-handler)
`ctx.schedule` tells a run which tick it belongs to:
```ts
const report = service("Report", {
async build(ctx, input: { full: boolean }) {
const tick = ctx.schedule; // { name, at } or undefined
const day = tick ? new Date(tick.at).toISOString().slice(0, 10) : "manual";
return ctx.run(`build ${day}`, () => buildReport(day, input.full));
},
});
```
* `at` is the nominal tick time in ms (for `trigger`, the time it was triggered), not the moment the run actually started. Use it as the business date of the run.
* `ctx.schedule` is `undefined` when the handler was invoked any other way.
## Missed ticks
[Section titled “Missed ticks”](#missed-ticks)
If cairnflow could not fire for a while (for example, a node was down across several ticks), the schedule fires **once**, for the most recent missed tick. The others are counted in `missed`, not replayed. Make runs that must cover a period read their range from `ctx.schedule.at` and catch up on their own if needed.
## Daylight saving time
[Section titled “Daylight saving time”](#daylight-saving-time)
Cron times are taken literally in the schedule’s time zone:
* A local time that does not exist (clocks jump forward) does **not** fire.
* A local time that happens twice (clocks fall back) fires **twice**.
Use `timeZone: "UTC"` (the default) for jobs that must run exactly once a day, or avoid local times between 1:00 and 3:00.
## Costs and limits
[Section titled “Costs and limits”](#costs-and-limits)
* Each tick is at least one durable write, so very short periods add up. Prefer minutes to seconds.
* Your environment may cap the number of schedules; creating one more fails with `409`. On Cairnflow Cloud, see [Beta limits](/docs/cloud/limits).
# Services and handlers
> Declare services, virtual objects and workflows, choose handler types, and serve them with serve().
A **service** is a named set of handlers. Cairnflow discovers the services your endpoint exposes, and calls each handler over HTTP when an invocation needs to run or resume.
service.ts
```ts
import { type Context, serve, service, TerminalError } from "@cairnflow/sdk";
const orders = service(
"OrderService",
{
async submit(ctx: Context, input: { amount: number }) {
if (typeof input?.amount !== "number" || input.amount <= 0) {
throw new TerminalError("amount must be a positive number", 400);
}
const soFar = (await ctx.get("total")) ?? 0;
const receipt = await ctx.run("charge", () => chargeCard(input.amount));
ctx.set("total", soFar + input.amount);
return { receipt, total: soFar + input.amount };
},
async total(ctx: Context) {
return (await ctx.get("total")) ?? 0;
},
},
{ type: "VIRTUAL_OBJECT", handlerTypes: { submit: "EXCLUSIVE", total: "SHARED" } },
);
await serve({ services: [orders], port: 9080, hostname: "0.0.0.0" });
```
## Three kinds of service
[Section titled “Three kinds of service”](#three-kinds-of-service)
| Declared with | Kind | Context type | State and durable promises |
| ----------------------------------------------------- | -------------- | ---------------- | -------------------------- |
| `service(name, handlers)` | Service | `ServiceContext` | No |
| `service(name, handlers, { type: "VIRTUAL_OBJECT" })` | Virtual object | `Context` | Yes, per key |
| `workflow(name, { run, ... })` | Workflow | `Context` | Yes, per workflow ID |
A plain service has no key, so there is no object for state to belong to. Its handlers receive a `ServiceContext`: the same as `Context` without `get`, `set`, `clear`, `clearAll`, `getKeys` and `promise`. Calling them is a compile error, and the runtime also rejects them with a terminal error (code `574`). If you need state, declare a virtual object and call it with a key — see [Virtual objects and state](/docs/develop/state).
Workflows are covered in [Workflows](/docs/workflows/workflows).
## Handler types
[Section titled “Handler types”](#handler-types)
| Type | Where | Behaviour |
| ----------- | ------------------------------------------------------------------- | -------------------------------------------------------------------- |
| `EXCLUSIVE` | Virtual objects (default) | One exclusive handler per key runs at a time; others queue behind it |
| `SHARED` | Virtual objects, workflows (default for every handler except `run`) | Runs alongside other invocations on the same key |
| `WORKFLOW` | Workflows | Set by `workflow()` on `run`; you do not set it yourself |
Set types per handler with `handlerTypes`. A handler you do not list is `EXCLUSIVE` in a virtual object and `SHARED` in a workflow.
Shared handlers cannot write state. Type them with `SharedContext` (a `Context` without `set`, `clear` and `clearAll`) so the compiler catches a write; `handlerTypes` does not change the type of `ctx` for you. The runtime enforces the rule too, in virtual objects and workflows alike: a write from a shared handler fails the invocation with a terminal `571` protocol violation.
## Handler signature
[Section titled “Handler signature”](#handler-signature)
```ts
type Handler = (ctx: Context, input: I) => Promise | O;
```
* **Input** is the request body parsed as JSON. If the body is not valid JSON, the handler receives it as a string. The `I` type is your declaration only: nothing checks the shape at runtime, so validate it and throw `TerminalError` (for example with code `400`) when it is wrong — retrying a bad payload never fixes it.
* **Output** is whatever you return, serialized with `JSON.stringify` (`undefined` becomes `null`).
* `ctx.key` is the object key (or workflow ID); it is empty in a plain service. `ctx.invocationId` is the invocation’s ID, the same one the HTTP API uses.
## Handler options
[Section titled “Handler options”](#handler-options)
Options are part of the deployment’s contract. Set them for the whole service with `options`, or per handler with `handlerOptions` (a handler’s options override the service’s):
```ts
service("Agent", { think, quick }, {
type: "VIRTUAL_OBJECT",
options: {
inactivityTimeout: 10 * 60_000,
retryPolicy: { maxAttempts: 5, onMaxAttempts: "PAUSE", initialInterval: 200 },
},
handlerOptions: { quick: { inactivityTimeout: 5_000 } },
});
```
| Option | Meaning |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `inactivityTimeout` | How long (ms) the runtime waits on your endpoint while it is silent within one turn — in practice, the longest `ctx.run` closure on `REQUEST_RESPONSE`. Greater than 0, at most one hour. When neither the handler nor the service sets it, the SDK declares 15 minutes |
| `retryPolicy` | Backoff and attempt limit — see [Errors and retries](/docs/develop/errors-retries) |
| `journalRetention` | How long (ms) to keep the journal of a finished invocation |
| `logLevel` | Minimum level kept by `ctx.log` (default `info`) — see [Streams, logs and traces](/docs/develop/streams-logs) |
| `trace` | `"runtime"` adds runtime spans (one per turn and per `ctx.run`); default `"off"` |
| `logFlushMs` | Flush durable log and stream records on this period (ms) even in the middle of a long `ctx.run`. Each flush is one extra write. `serve()` only |
The values are captured when you register a deployment. Changing them means registering a new deployment.
## serve() options
[Section titled “serve() options”](#serve-options)
`serve()` runs a Node.js HTTP server for your services. It answers both HTTP/1.1 and cleartext HTTP/2 on one port.
| Option | Default | Meaning |
| ------------------- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `services` | — | The service definitions to expose |
| `port` | `9080` | Port to listen on |
| `hostname` | `"127.0.0.1"` | Address to bind. Set `"0.0.0.0"` in a container, or nothing outside the machine can reach it |
| `identityKeys` | none | Identity keys (`publickeyv1_...`) of your environment. When set, every request must carry a valid signature from one of them, or it is refused with `401`. Required by Cairnflow Cloud |
| `identityHosts` | none | The public hosts you registered. The signature covers the request body and the host it was sent to; when this is set, the signed host must be one of these. When unset, it is compared with the request’s own `Host` header. Set it when a proxy in front of your service rewrites `Host` |
| `protocolMode` | `"BIDI_STREAM"` | Streaming over HTTP/2. Set `"REQUEST_RESPONSE"` if a proxy between cairnflow and your service only speaks HTTP/1.1 |
| `compression` | `true` | Accept gzip-compressed request bodies and compress responses when asked |
| `replayCache` | `true` | Keep the journal of running invocations in memory so cairnflow only sends new entries each turn. `{ maxBytes, ttlMs }` tunes it (defaults 64 MiB, 15 minutes) |
| `valueCacheBytes` | 64 MiB | Memory for segments of large values ([Payload](/docs/cloud/limits#payload)) the SDK has already downloaded. `0` keeps none |
| `maxValueBytes` | 64 MiB | Largest single value the SDK assembles from segments. A larger one fails the turn before anything is downloaded |
| `maxTurnValueBytes` | 256 MiB | Most bytes of segmented values one turn may assemble |
| `segmentOrigins` | any `http(s)` origin | Origins the SDK may download segments from. Leaving it unset is safe only with `identityKeys`, which signs the download URLs |
Each request body is capped at 256 MiB after decompression; a larger one gets `413`. If cairnflow speaks a newer protocol version than this SDK build supports (for example after you rolled the service back to an older SDK without registering it again), the endpoint answers `415` and the turn is retried; register the deployment again. `serve()` resolves to `{ port, url, close() }`. `close()` stops accepting connections and lets open invocation streams finish.
To rotate identity keys, add the new key to `identityKeys` before it becomes active, and remove the old one after.
Note
On platforms that only accept a `(Request) => Promise` function — Vercel, Cloudflare Workers, AWS Lambda — use `fetchHandler` instead of `serve()`. See [Serverless](/docs/workflows/serverless).
## Registering
[Section titled “Registering”](#registering)
Cairnflow reads your services from the endpoint’s discovery route. Deploy the service, then register its base URL:
```sh
curl -X POST $CAIRN_URL/deployments \
-H "authorization: Bearer $CAIRN_KEY" \
-H "content-type: application/json" \
-d '{"uri":"https://your-service.example.com"}'
```
Each registration creates a new, immutable deployment and makes it the current revision of every service in it. Invocations already running stay on the deployment they started on — see [Deploying new versions](/docs/develop/versioning). `GET /services` lists the handlers you can call and their effective types.
## Rules of handler code
[Section titled “Rules of handler code”](#rules-of-handler-code)
The handler body runs again every time an invocation is replayed. Put side effects in [durable steps](/docs/develop/durable-steps), do not read the clock or `Math.random()` outside one, and do not catch and swallow errors around `ctx` commands. See [Concepts](/docs/concepts).
# Virtual objects and state
> Keyed objects with durable state and one writer at a time.
A **virtual object** is a service whose invocations are addressed by a **key** — a chat ID, a user ID, an order number. Each key has its own state, and two exclusive handlers on the same key never run at the same time. You never create an object: calling a handler with a new key is enough.
counter.ts
```ts
import { type Context, serve, service, type SharedContext } from "@cairnflow/sdk";
const counter = service(
"Counter",
{
async add(ctx: Context, n: number) {
const total = ((await ctx.get("total")) ?? 0) + n;
ctx.set("total", total);
return total;
},
async reset(ctx: Context) {
ctx.clearAll();
},
async read(ctx: SharedContext) {
return (await ctx.get("total")) ?? 0;
},
},
{ type: "VIRTUAL_OBJECT", handlerTypes: { read: "SHARED" } },
);
await serve({ services: [counter], port: 9080, hostname: "0.0.0.0" });
```
Call it with a key:
```sh
curl -X POST "$CAIRN_URL/invoke/Counter/add?key=user-42" \
-H "authorization: Bearer $CAIRN_KEY" \
-H "content-type: application/json" -d '5'
```
`ctx.key` inside the handler is `"user-42"`.
## State API
[Section titled “State API”](#state-api)
| Call | Returns | Notes |
| ------------------------- | ----------------------- | ------------------------------------------ |
| `ctx.get(name)` | `T \| null` (awaitable) | `null` means the entry does not exist |
| `ctx.set(name, value)` | `void` | Does not wait. The value is stored as JSON |
| `ctx.clear(name)` | `void` | Removes one entry |
| `ctx.clearAll()` | `void` | Removes every entry of this object |
| `ctx.getKeys()` | `string[]` (awaitable) | Names of the object’s state entries |
State reads are recorded in the journal like every other command, so a replay sees the value that was read the first time, not whatever the state holds now.
Caution
`null` from `ctx.get` means **missing**, which is different from an empty value. Setting a key to `""` or `0` and reading it back gives you `""` or `0`, not `null` — keep the `?? default` pattern for “not set yet” only.
Values go through `JSON.stringify`: store plain data, not class instances, `Map`, `Set` or `Date` objects. A large value, such as a long chat history, is stored as segments outside the journal, and your code still reads and writes the whole value; see [Payload](/docs/cloud/limits#payload) for the limits on Cairnflow Cloud. Do not store an [artifact](/docs/develop/artifacts) reference in state to read in a later invocation: `ctx.artifact.get` reads only the artifacts of the current invocation.
## One writer per key
[Section titled “One writer per key”](#one-writer-per-key)
Exclusive handlers on one key form a queue. While an invocation holds the key — including while it sleeps, waits for a call, or waits for a promise — the next exclusive invocation on that key waits behind it. That is what makes a read-modify-write like `add` above safe without locks or transactions.
Two consequences:
* **A long wait blocks the key.** An exclusive handler that sleeps for a day holds the key for a day. If other work on the same key must keep flowing, move the waiting part into a separate invocation (a workflow, or a call to another object) and keep the exclusive handler short.
* **Calling `/invoke` on a busy key can return `202 waiting`.** The invocation is accepted and durable; it runs when the key frees up. Fetch the result later with `POST /invocations/{id}/attach`, or use the [typed client](/docs/develop/client), which does that for you.
## Shared handlers
[Section titled “Shared handlers”](#shared-handlers)
A `SHARED` handler runs without waiting in the key’s queue, so it can answer while an exclusive handler is suspended. Use it for reads: status pages, progress, “what is in the cart”.
Shared handlers only read state. They run alongside the exclusive ones, and a read-modify-write from both sides would lose updates, so the runtime rejects `set`, `clear` and `clearAll` from a shared handler with a terminal `571` protocol violation. Type shared handlers with `SharedContext`, which has no `set`, `clear` or `clearAll`, to catch the mistake at compile time. Move writes to an exclusive handler.
## Keys and scopes
[Section titled “Keys and scopes”](#keys-and-scopes)
* A key can be any string your callers agree on. Keep it stable: a different key is a different object with empty state.
* A call made inside a [scope](/docs/develop/calls#scopes) addresses a different object from the same call without a scope: `Cart/a` in scope `bob` and `Cart/a` with no scope have separate state and separate queues.
## Durable promises live here too
[Section titled “Durable promises live here too”](#durable-promises-live-here-too)
Virtual objects and workflows can also use `ctx.promise(name)`: a named, durable value that another handler or an outside system completes. See [Durable promises, signals and awakeables](/docs/develop/promises-signals).
# Streams, logs and traces
> Stream tokens and progress to a UI, write logs, and record spans with token counts.
Streams, logs and traces run **beside** the journal. Writing to them adds no command to the journal and no durable wait to the turn, and nothing is sent again on replay.
```ts
async run(ctx: Context, prompt: string) {
const ui = ctx.stream("ui");
ctx.log.info("starting", { prompt_len: prompt.length });
return ctx.trace.span("llm", async (span) => {
span.set({ model: "m-1" });
return ctx.run("llm", async () => {
let text = "";
for await (const tok of model.stream(prompt)) {
ui.append({ tok });
text += tok;
}
span.set({ input_tokens: 1200, output_tokens: text.length });
return text;
});
});
}
```
## Streams
[Section titled “Streams”](#streams)
`ctx.stream(name, opts?)` returns a writer:
| Method | Meaning |
| ---------------- | ------------------------------------------------------------------- |
| `append(record)` | Add a JSON record. Does not wait, does not throw, skipped on replay |
| `close()` | No more records after this |
Stream names are 1 to 128 bytes and cannot start with `$`. An invocation can have up to 16 streams.
### Ephemeral or durable
[Section titled “Ephemeral or durable”](#ephemeral-or-durable)
| | `ctx.stream("ui")` (default) | `ctx.stream("events", { durable: true })` |
| -------------- | -------------------------------------------------------------------------------------------- | ---------------------------------------------------- |
| Stored | In memory of the node running the invocation, 1 MiB per stream (oldest records drop first) | With the invocation, on the next durable write |
| Lives | While the current step runs; readable for 60 seconds after the invocation finishes or pauses | Until the invocation is purged |
| On node change | Lost: readers get `moved` then `reset`, and the retried step streams again from the start | Kept |
| Limit | 1 MiB per stream | 8 MiB for all durable user streams of one invocation |
Use the ephemeral stream for tokens and progress a UI shows live; the full output of a step still comes from the `ctx.run` result. Use a durable stream for records someone must be able to read later.
Append ephemeral records from **inside** the `ctx.run` closure that produces them: the closure runs only when the step really executes, so a replay does not re-emit old tokens.
Note
Records reach readers as they are appended only in streaming mode (`BIDI_STREAM`). In request-response mode, the default for `https://` endpoints on Cairnflow Cloud, the records of a turn travel with its response and reach readers together when the turn ends. See [Deployments](/docs/cloud/deployments#transport).
### Reading a stream
[Section titled “Reading a stream”](#reading-a-stream)
Streams are served as Server-Sent Events:
```sh
curl -N "$CAIRN_URL/invocations/$ID/streams/ui?from=0" \
-H "authorization: Bearer $CAIRN_KEY" -H "accept: text/event-stream"
```
| Event | Data |
| ------------ | ---------------------------------------------------------------------------------------- |
| `record` | `{offset, durable, step, attempt, k, data}` — `data` is what you appended |
| `gap` | `{offset, dropped}` — records dropped by a limit, or overwritten while the reader lagged |
| `superseded` | `{offset, step, attempt}` — that attempt of that step was replaced by a retry |
| `end` | `{next}` — the stream is sealed and fully read |
| `moved` | `{leader}` — the node serving the stream changed; reconnect |
| `reset` | After `moved`, ephemeral streams only: clear what you displayed, the step streams again |
Resume with `?from=` or the `Last-Event-ID` header. Reading a stream needs a key that can invoke handlers.
In TypeScript, `readStream` from `@cairnflow/sdk/client` handles reconnects, node changes and connection lifetimes, and yields every event (including `reset`, which a UI needs):
```ts
import { readStream } from "@cairnflow/sdk/client";
for await (const e of readStream(process.env.CAIRN_URL!, id, "ui", {
headers: { authorization: `Bearer ${process.env.CAIRN_KEY}` },
})) {
if (e.kind === "reset") clearOutput();
if (e.kind === "record") render(e.data);
}
```
Options: `from` (start offset, default 0), `headers`, `signal` (an `AbortSignal`), `retries` (consecutive failures before giving up, default 10). It throws `StreamError` (with `status` and `code`) when the stream cannot be read, for example `404`.
## Logs
[Section titled “Logs”](#logs)
`ctx.log.debug|info|warn|error(message, attrs?)` writes to the invocation’s durable log. Each record is tied to the step and attempt that wrote it.
* The minimum level is `info`; set `logLevel` in the handler options to change it.
* Like streams, log calls do not wait, do not throw, and are not repeated on replay.
* Records become durable with the invocation’s next durable write (a step result, a suspension, the end). Set `logFlushMs` in the handler options to also flush on a timer during a long step, at the cost of one write per flush.
* The log keeps up to 1 MiB per invocation; past that, records are dropped and a `gap` is recorded.
Read logs with an admin key:
```sh
curl "$CAIRN_URL/invocations/$ID/logs?level=warn&limit=100" \
-H "authorization: Bearer $CAIRN_KEY"
```
The answer is `{"records": [...], "next": ...}`; each record has `offset`, `step`, `attempt`, `ts`, `level`, `msg` and `attrs`. Fetch the next page with `from=`, or add `follow=1` to receive new records as Server-Sent Events. Filters: `level`, `attempt`, `from`, `limit` (default 1000).
## Traces
[Section titled “Traces”](#traces)
`ctx.trace.span(name, fn, attrs?)` records a span around `fn`. Spans nest by call scope, and `span.set(attrs)` adds attributes that are written when the span ends. If `fn` throws, the span ends with status `error` and the error is rethrown.
```ts
const plan = await ctx.trace.span("plan", async (s) => {
s.set({ model: "my-model", input_tokens: 1200 });
return ctx.run("llm", () => callModel());
});
```
Read the span tree with an admin key:
```sh
curl "$CAIRN_URL/invocations/$ID/spans" -H "authorization: Bearer $CAIRN_KEY"
```
The answer is `{"spans": [...], "tokens": {"input": ..., "output": ...}}`. Each node has `span_id`, `parent_id`, `name`, `start_ts`, `end_ts`, `status`, `attrs` and `children`; `unfinished: true` marks a span whose process died before it ended. `tokens` sums the `input_tokens` and `output_tokens` attributes of every span, so set them on your model-call spans.
* Span IDs are deterministic, so a replay that closes a span opened earlier matches it.
* The trace keeps up to 1 MiB per invocation.
* Set `trace: "runtime"` in the handler options to add spans from the runtime itself: one per turn and one per `ctx.run`.
The [Vercel AI SDK adapter](/docs/agents/vercel-ai-sdk) writes these spans and the `ui` stream for you.
# Timers and sleeping
> Durable sleeps, deadlines, and delayed calls.
`ctx.sleep(ms)` pauses an invocation for a duration. The timer is stored durably; nothing holds a process, a connection or memory while it waits, so sleeping for a week costs the same as sleeping for a second.
```ts
await ctx.sleep(24 * 3600_000); // one day
```
```ts
sleep(ms: number, name?: string): DurableFuture;
```
* The wake-up time is **absolute**: it is computed once, from the clock at the moment the sleep is first recorded, and stored in the journal. A replay does not start the timer again.
* `name` (default `"sleep"`) labels the entry in the journal and the console.
* When the sleep is not over yet, the turn ends and the invocation is **suspended**. It resumes when the timer fires, on whichever node owns it at that time.
* A timer fires at or shortly after its due time. Do not rely on millisecond precision.
## Deadlines with ctx.race
[Section titled “Deadlines with ctx.race”](#deadlines-with-ctxrace)
`ctx.sleep` returns a `DurableFuture`, so it combines with calls, signals, promises and awakeables. `ctx.race` resolves with whichever finished first **in journal order**, so every replay picks the same winner.
```ts
const approval = await ctx.race([
ctx.signal<{ by: string }>("approve"),
ctx.sleep(24 * 3600_000),
]);
if (approval === undefined) {
throw new TerminalError("nobody approved within 24 hours", 408);
}
```
A sleep resolves to `undefined`, which is how you tell that the deadline won.
To tell two futures apart when their values could look alike, create both first, race them, then compare their positions in the journal with `order()`:
```ts
const answer = ctx.promise("approval").get();
const deadline = ctx.sleep(30 * 60_000, "approval deadline");
await ctx.race([answer, deadline]);
if (answer.order() > deadline.order()) {
throw new TerminalError("approval timed out", 408);
}
const decision = await answer;
```
Do not use `ready()` for this: a late answer still lands in the journal, and from then on `ready()` returns `true` on every replay, so the same code would take a different branch.
## Waiting for many things
[Section titled “Waiting for many things”](#waiting-for-many-things)
`ctx.all([...])` waits for every future, like `Promise.all`, but suspends durably until all of them are done. If one of them failed, it throws that failure.
```ts
const [a, b] = await ctx.all([
ctx.call("Search", "query", "a"),
ctx.call("Search", "query", "b"),
]);
```
## Delayed calls
[Section titled “Delayed calls”](#delayed-calls)
To run another handler later instead of waiting yourself, send it with a delay. The handler that sends it does not wait and does not hold a key:
```ts
ctx.send("Reminders", "remind", { userId }, { delay: 3 * 24 * 3600_000 });
```
Like a sleep, the due time is computed once and recorded. Delays are only available from inside a handler; the client has no delayed send. For recurring work, use [server-side schedules](/docs/develop/schedules).
## Reading the clock
[Section titled “Reading the clock”](#reading-the-clock)
Do not call `Date.now()` in the handler body: a replay would see a different time and could take a different path. Read it inside a step:
```ts
const startedAt = await ctx.run("now", () => Date.now());
```
## Gotchas
[Section titled “Gotchas”](#gotchas)
* **A losing sleep still fires.** In a `race`, the sleep that loses keeps its timer and costs one durable write when it fires. Use long deadlines; do not poll with a loop of short sleeps.
* **Sleeping in an exclusive handler holds the key.** Other exclusive calls on the same virtual object wait until the sleep is over. Put long waits in a workflow or a plain service when the key must stay available.
* **Long loops grow the journal.** A loop that sleeps and polls forever adds entries every round. Restart it with a fresh journal from time to time with `ctx.continueAsNew(state)` — see [Deploying new versions](/docs/develop/versioning#long-running-loops).
* Your environment may limit the number of pending timers per invocation; on Cairnflow Cloud, see [Beta limits](/docs/cloud/limits).
# Deploying new versions
> Change handler code without breaking invocations that are already running.
Invocations can run for minutes or months, so a deploy usually happens while some are in flight. Cairnflow replays each of them against code, and the code must still match what the journal recorded. This page covers how deployments are pinned, what counts as a breaking change, and how to recover when something breaks.
## Invocations are pinned to their deployment
[Section titled “Invocations are pinned to their deployment”](#invocations-are-pinned-to-their-deployment)
Registering an endpoint creates a new, immutable **deployment** and makes it the current revision of every service it exposes.
* **New invocations** go to the current revision.
* **Running invocations stay on the deployment they started on**, for every later turn — even after the revision has moved on. A deploy never drags in-flight work onto new code by itself.
The safest way to ship a change is therefore to give each version its own URL:
1. Deploy the new code at a new URL (a new container, a versioned path, a new function alias).
2. Register it: `POST /deployments {"uri": ""}`. New invocations use it from now on.
3. Keep the old version running until no invocation is pinned to it. `GET /deployments/{id}` reports `pinnedInvocations`.
4. Remove the old deployment with `DELETE /deployments/{id}`. It answers `409` while the deployment is still a current revision or still has invocations pinned to it.
How you run several versions side by side depends on your platform — see [Deployments](/docs/cloud/deployments).
## What breaks a running invocation
[Section titled “What breaks a running invocation”](#what-breaks-a-running-invocation)
If you replace code **in place** (same URL), in-flight invocations replay against the new code. On replay, the SDK checks each command against the journal: its **kind** (a step, a sleep, a call, a state read…), its **name** (for `ctx.run`, the step name), and every other field it recorded, such as a call’s target service, handler, key and input. When they differ, the invocation stops `paused` with code `570` (journal mismatch). It does not run the wrong code, and it does not retry on its own: a retry would only hit the same mismatch.
| Change | Effect on an invocation already past that point |
| ----------------------------------------------------------------------------- | -------------------------------------------------------- |
| Rename a `ctx.run` step | Pauses with `570` when it reaches the step |
| Add, remove or reorder `ctx` commands before the point it reached | Pauses with `570` where the commands stop lining up |
| Change a call’s target service, handler, key or input | Pauses with `570` at that call |
| Change the body of a step that already has a result | Nothing: the recorded result is used |
| Change the value written by `ctx.set`, a sleep’s duration or a send’s `delay` | Nothing: these values are recorded once and not compared |
| Add code after the last command it reached | Nothing: it runs the new code from there |
Not every semantic change is caught: what a recorded step returned is never checked against the new code. When in doubt, deploy at a new URL.
Keep step names stable, and keep configuration (model IDs, prompt versions) out of them — put it in [span attributes](/docs/develop/streams-logs#traces).
## Check before you switch
[Section titled “Check before you switch”](#check-before-you-switch)
Replays can be tested without running any of the new code’s side effects. Both checks are read-only: no closure of the new code runs and nothing is written.
```sh
# Replay a sample of unfinished invocations of a service against a deployment.
curl -X POST "$CAIRN_URL/deployments/$NEW_DP/replay-check?service=OrderService&sample=20" \
-H "authorization: Bearer $CAIRN_KEY"
# -> {"checked": ..., "matched": ..., "failures": ..., ...}
# Replay one invocation against a deployment.
curl -X POST "$CAIRN_URL/invocations/$ID/replay?deployment=$NEW_DP" \
-H "authorization: Bearer $CAIRN_KEY"
# -> {"matches": true, "upto": 7} or {"matches": false, "mismatchAt": ..., "expected": ..., "got": ...}
```
To register a deployment without making it current, add `?activate=false`, run the checks, then move each service yourself:
```sh
curl -X POST "$CAIRN_URL/deployments?activate=false" \
-H "authorization: Bearer $CAIRN_KEY" -H "content-type: application/json" \
-d '{"uri":"https://v2.example.com"}'
curl -X PUT "$CAIRN_URL/services/OrderService/revision" \
-H "authorization: Bearer $CAIRN_KEY" -H "content-type: application/json" \
-d '{"deployment": "dp_new", "expect": "dp_old"}'
```
`expect` makes the move conditional: it only happens if the current revision is still `dp_old`, so two people rolling back at once cannot both win. The same call rolls back to an older deployment.
## Recovering a paused invocation
[Section titled “Recovering a paused invocation”](#recovering-a-paused-invocation)
An invocation paused with `570` can continue in two ways:
* **Restore the code it expects** at the URL it is pinned to (for example, bring the old step name back), then `POST /invocations/{id}/resume`.
* **Move it to a deployment whose code matches** with `POST /invocations/{id}/migrate?deployment=`. Migrate replays the invocation on the target first and refuses (`409`, with the report) if it does not match. `&force=true` skips that check.
Migrate is also the way to move a healthy invocation onto newer code on purpose.
## Long-running loops
[Section titled “Long-running loops”](#long-running-loops)
An agent loop or a poller that runs forever keeps growing its journal, and every replay walks the whole journal. `ctx.continueAsNew(input)` ends the current invocation and starts a new one for the same target, with an empty journal and `input` as its input:
```ts
async loop(ctx: Context, s: { step: number; done: boolean }) {
for (let i = 0; i < 50 && !s.done; i++) {
s = await ctx.run(`step ${s.step}`, () => next(s));
}
if (!s.done) ctx.continueAsNew(s);
return s;
}
```
* The line after `continueAsNew` never runs.
* The new invocation runs on the service’s **current revision**, which makes it a natural upgrade point for long-lived loops.
* Callers waiting on the old invocation, and its idempotency key, move to the new one; they receive the final result of the chain. The old invocation ends with `{"continuedAsNew": ""}`.
## Handler options are part of the deployment
[Section titled “Handler options are part of the deployment”](#handler-options-are-part-of-the-deployment)
Retry policies, timeouts and other handler options are captured when a deployment is registered. Changing them means registering a new deployment; invocations already pinned to the old one keep the old options.
The same goes for the SDK’s protocol version. If you roll a service back to an older SDK build at the same URL without registering it again, cairnflow may speak a newer protocol version than that build supports. The endpoint then answers `415` instead of running the handler, and the turn is retried under the retry policy. Register the deployment again.
# Human approval
> Make an agent wait for a person before a tool runs, and answer from the chat, an admin page or a webhook.
Some tools should not run on the model’s word alone: a refund, an email to a customer, a database change. With `cairnTools(ctx, tools, { approve })` such a tool waits on a **durable promise** until someone answers. The invocation is suspended in storage while it waits, so it can wait minutes or days without holding a process, a connection or memory. If the answer is no, the tool never runs.
## Declare which tools need approval
[Section titled “Declare which tools need approval”](#declare-which-tools-need-approval)
agent.ts
```ts
import { cairnTools } from "@cairnflow/sdk";
// A list of tool names…
const guarded = cairnTools(ctx, tools, { approve: ["refund"] });
// …or a function of the tool name and its input.
const byAmount = cairnTools(ctx, tools, {
approve: (name, input) => name === "refund" && (input as { amount: number }).amount > 100,
});
```
Approval needs `ctx.promise`, so the tools must run in a virtual object or a workflow. A `chatObject` is a virtual object. In a plain service, a tool that needs approval fails with a terminal error instead of waiting.
## What happens during a turn
[Section titled “What happens during a turn”](#what-happens-during-a-turn)
1. The model calls `refund`. `cairnTools` records the request in a step and sends a `tool-approval-request` chunk to the UI. The tool part in `useChat` gets the state `approval-requested` and an `approval.id`.
2. The tool waits on the promise named by that approval ID. The turn suspends.
3. Someone resolves the promise with `{ approved, reason? }`.
4. Approved: the tool runs as a durable step and the model sees its result. Rejected: the tool does not run, the UI part becomes `output-denied`, and the model receives `{ denied: true, reason }` as the tool result, so it can tell the user.
The saved history records the decision on the tool part (`approval: { id, approved, reason }`), so a reloaded chat shows the same thing the live one did.
The approval ID is derived from the tool call: `approvalIdOf(toolCallId)` returns it, and it is also the `approval.id` on the UI part.
## Answer from the chat page
[Section titled “Answer from the chat page”](#answer-from-the-chat-page)
chat.tsx
```tsx
const transport = cairnChatTransport({ baseUrl: "/cairn", service: "Chat" });
// In your message renderer:
if (part.type === "tool-refund" && part.state === "approval-requested") {
const id = part.approval.id;
return (
<>
>
);
}
```
Use `transport.approve`, not the AI SDK’s `addToolApprovalResponse`. The latter belongs to the AI SDK’s own `needsApproval` flow, which ends the turn and sends the whole chat again. Here the invocation stays alive, suspended on the promise, and `approve` resolves it; every page connected to the chat sees the tool run.
## Answer from somewhere else
[Section titled “Answer from somewhere else”](#answer-from-somewhere-else)
The approver does not have to be the person chatting. `transport.approve` is one HTTP call, and an admin page, a Slack interaction webhook or a script can make the same call with an API key:
```sh
curl -X POST "$CAIRN_URL/promises/Chat/$CHAT_ID/$APPROVAL_ID/resolve" \
-H "authorization: Bearer $CAIRN_KEY" \
-H "content-type: application/json" \
-d '{"approved": true}'
```
slack-webhook.ts
```ts
// After verifying the Slack request and reading chatId and approvalId from your button's value:
await fetch(`${process.env.CAIRN_URL}/promises/Chat/${chatId}/${approvalId}/resolve`, {
method: "POST",
headers: {
authorization: `Bearer ${process.env.CAIRN_KEY}`,
"content-type": "application/json",
},
body: JSON.stringify({ approved: false, reason: "Rejected in Slack" }),
});
```
The route is `POST /promises/{service}/{key}/{approvalId}/resolve`, where `{key}` is the chat ID. An **Invoke only** key is enough. With a scope, prefix the path with `/scope/{scope}`.
Properties you can rely on:
* **Answering twice is a no-op, not an error.** A promise completes once; a second resolve reports that it did not complete anything (`completed: false`). Webhook retries are safe without an idempotency key. `transport.approve` checks that case: resending the same decision succeeds, and a different decision (another tab or approver answered first) throws.
* **An answer that arrives early is not lost.** The promise is durable; a waiter that reaches it later reads the result.
* **Reject by resolving with `approved: false`.** That is the path the adapter turns into `output-denied` and a `{ denied: true }` tool result.
To check whether a request was answered: `GET /promises/Chat/{chatId}/{approvalId}`.
## Pending requests survive a reload
[Section titled “Pending requests survive a reload”](#pending-requests-survive-a-reload)
The `ui` stream is temporary: it lives in memory and only promises to hold the step that is running. A turn that has been waiting for approval for more than about a minute releases what it streamed, and a change of leader loses it entirely. So a page opened later cannot rely on the stream to show the approval buttons.
`cairnTools` therefore also keeps each pending request in the object’s state until it is answered, and the `messages` handler of `chatObject` returns it: while a turn waits, the history ends with an assistant message (its ID is the running invocation’s ID) carrying the tool part in state `approval-requested`. Initialise `useChat` with `await transport.messages(chatId)` and the buttons are there after a reload, on another device, or a week later.
## List what is waiting
[Section titled “List what is waiting”](#list-what-is-waiting)
For an admin page that lists open approvals across chats, use the [query API](/docs/query). Find chats with a running turn, then read each one’s pending requests:
```sql
SELECT key, id, created_at
FROM sys_invocation
WHERE service = 'Chat' AND handler = 'send' AND class = 'active'
ORDER BY created_at
LIMIT 100
```
```sql
SELECT name, waiter_id
FROM sys_promise_waiter
WHERE service = 'Chat' AND key = 'chat-42'
```
`sys_promise_waiter` lists promises that someone is waiting on and that are not completed yet. `transport.messages(chatId)` gives the same requests with the tool name and input, ready to render.
## Waiting costs nothing
[Section titled “Waiting costs nothing”](#waiting-costs-nothing)
While it waits, the invocation runs no code and holds no connection. Nothing is billed as compute. Each approval adds one journal entry and one durable wait to the turn.
## Next
[Section titled “Next”](#next)
* [Streaming to the browser](/docs/agents/streaming)
* [Durable promises and signals](/docs/develop/promises-signals)
# Agents without chatObject
> Build your own agent handler with cairnMiddleware and cairnTools, and the contract the chat transport expects.
`chatObject` covers the common case: one chat per key, history in state, the browser on `useChat`. When you need something else (history in your own database, several agents behind one chat, an agent that runs without a browser) use the two building blocks directly:
* `cairnMiddleware(ctx)` makes each model call a durable step and streams its UI chunks.
* `cairnTools(ctx, tools, opts?)` makes each tool call a durable step, with optional approval.
Both work in any handler that has a `ctx`. Approval needs `ctx.promise`, so it needs a virtual object or a workflow.
## A background agent in a workflow
[Section titled “A background agent in a workflow”](#a-background-agent-in-a-workflow)
No browser, no chat: a workflow runs once per ID, survives crashes and deploys, and can wait for an approval before publishing.
research.ts
```ts
import { stepCountIs, streamText, wrapLanguageModel } from "ai";
import { anthropic } from "@ai-sdk/anthropic";
import { cairnMiddleware, cairnOnError, cairnTools, workflow } from "@cairnflow/sdk";
const research = workflow("Research", {
run: async (ctx, topic: string) => {
const result = streamText({
model: wrapLanguageModel({
model: anthropic("claude-sonnet-5-5"),
middleware: cairnMiddleware(ctx),
}),
tools: cairnTools(ctx, tools, { approve: ["publish"] }),
prompt: `Research ${topic} and publish a short brief.`,
stopWhen: stepCountIs(10),
onError: cairnOnError(ctx),
});
for await (const _ of result.fullStream) {
// Drain the stream; every model and tool call is journaled as it completes.
}
return await result.text;
},
});
```
Start it with `POST /invoke/Research/run/send?key=`, and answer the approval with `POST /promises/Research///resolve`. The approval ID is the `approvalIdOf(toolCallId)` of the tool call; see [Human approval](/docs/agents/approvals).
## Your own chat object
[Section titled “Your own chat object”](#your-own-chat-object)
The browser transport does not require `chatObject`. It needs a virtual object, keyed by chat ID, with three handlers that keep this contract:
| Handler | Type | Receives | Must |
| -------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `send` (or the name in the transport’s `handler` option) | exclusive | A JSON body: `chatId`, `trigger`, and `message` (the new user message) or `messages` (with `sendHistory: true`); optional `messageId`, `after`, `body` | Write the turn’s UI chunks to the `ui` stream (`cairnMiddleware` and `cairnTools` do it). While it runs, make `active` return its invocation ID |
| `active` | shared | nothing | Return the invocation ID of the running `send`, or `null` |
| `messages` | shared | nothing | Return the history as `UIMessage[]` |
Details the transport relies on:
* It sends to `POST /invoke/{service}/{handler}/send?key=` and reads the invocation ID from the answer, then reads `GET /invocations/{id}/streams/ui`.
* It emits its own `start` chunk with `messageId` set to the invocation ID, and its own `finish` chunk; `start` and `finish` records on the stream are ignored. Use the invocation ID as the assistant message ID in the history you save, so the saved message matches the one the page built.
* `transport.approve(chatId, approvalId, …)` resolves the promise `approvalId` on the object `{service}/{chatId}`. Tool approvals must therefore wait on the same object that received the message, which is what `cairnTools(ctx, …)` inside `send` does.
### Example: also keep the transcript in your database
[Section titled “Example: also keep the transcript in your database”](#example-also-keep-the-transcript-in-your-database)
support.ts
```ts
import { convertToModelMessages, stepCountIs, streamText, wrapLanguageModel, type UIMessage } from "ai";
import { anthropic } from "@ai-sdk/anthropic";
import {
cairnMiddleware,
cairnOnError,
cairnTools,
service,
TerminalError,
type ChatRequest,
type Context,
} from "@cairnflow/sdk";
const support = service(
"Support",
{
async send(ctx: Context, req: ChatRequest) {
ctx.set("active", ctx.invocationId);
try {
const saved = (await ctx.get("messages")) ?? [];
const history = req.message === undefined ? saved : [...saved, req.message as UIMessage];
const result = streamText({
model: wrapLanguageModel({
model: anthropic("claude-sonnet-5-5"),
middleware: cairnMiddleware(ctx),
}),
tools: cairnTools(ctx, tools, { approve: ["refund"] }),
messages: await convertToModelMessages(history),
stopWhen: stepCountIs(8),
onError: cairnOnError(ctx),
});
let final: UIMessage[] = history;
for await (const _ of result.toUIMessageStream({
originalMessages: history,
generateMessageId: () => ctx.invocationId,
onFinish: (e) => {
final = e.messages;
},
})) {
// The chunks already went to the `ui` stream from the middleware and tools.
}
ctx.set("messages", final);
// A side effect, so it goes through ctx.run.
await ctx.run("save-transcript", () => db.transcripts.save(ctx.key, final));
ctx.clear("active");
return { id: ctx.invocationId };
} catch (e) {
// Clear only on a terminal failure. A transient error is retried from the journal,
// and a state change here would make the retry's journal differ.
if (e instanceof TerminalError) ctx.clear("active");
throw e;
}
},
async active(ctx: Context) {
return (await ctx.get("active")) ?? null;
},
async messages(ctx: Context) {
return (await ctx.get("messages")) ?? [];
},
},
{
type: "VIRTUAL_OBJECT",
handlerTypes: { send: "EXCLUSIVE", active: "SHARED", messages: "SHARED" },
},
);
```
In the browser: `cairnChatTransport({ baseUrl: "/cairn", service: "Support" })`.
### What `chatObject` does that this example does not
[Section titled “What chatObject does that this example does not”](#what-chatobject-does-that-this-example-does-not)
If you write your own object, decide whether you need these; `chatObject` has them built in.
* **Regenerate.** On `trigger: "regenerate-message"` it cuts the saved history at `messageId` before the turn.
* **Stale history.** It compares `after` (the ID of the message before the new one on the page) with the saved history, and refuses the turn when the page is behind.
* **History during a turn.** It keeps the turn’s input in state as soon as the turn starts, so `messages` includes the user message while the answer is still being generated.
* **Pending approvals after a reload.** `cairnTools` keeps each pending request in the object’s state under a key starting with `pending-approval/` until it is answered. `chatObject`’s `messages` turns those into an assistant message with tool parts in state `approval-requested`. Without that, a page opened during a long wait shows no approval buttons.
* **Approval decisions in history.** The history that `toUIMessageStream` builds shows a rejected tool as an ordinary result (`{ denied: true }`). `chatObject` marks such parts `output-denied` and records the decision on each approved or rejected part, so a reloaded chat matches what the live page showed.
## Rules that still apply
[Section titled “Rules that still apply”](#rules-that-still-apply)
* Model calls go through `cairnMiddleware`, side effects through `cairnTools` or `ctx.run`. An unwrapped call runs again on every replay.
* No `Date.now()`, `Math.random()` or generated IDs outside `ctx.run`; use `ctx.invocationId` where you need a stable ID.
* Ignore `Suspend` in any `onError` you write (`cairnOnError(ctx)` does); it is not an error of your code.
* Do not change state in a `catch` for errors that are not `TerminalError`.
## Next
[Section titled “Next”](#next)
* [Vercel AI SDK](/docs/agents/vercel-ai-sdk)
* [Durable steps](/docs/develop/durable-steps)
* [Services, objects and workflows](/docs/develop/services)
# Streaming to the browser
> How tokens reach the page over SSE, what happens on reload, stop() and failures, and the limits of temporary streams.
An agent turn writes UI chunks to a stream of its invocation while it runs. The browser reads that stream over Server-Sent Events. `cairnMiddleware` and `cairnTools` do the writing and `cairnChatTransport` does the reading, so with `chatObject` and `useChat` you write no streaming code. This page explains what happens underneath, so you can reason about reloads, stops and failures.
## The path of a message
[Section titled “The path of a message”](#the-path-of-a-message)
1. `sendMessage` posts the last message to `POST /invoke/Chat/send/send?key=`. The answer comes as soon as the invocation is durable and carries its ID. The transport attaches an `Idempotency-Key`, so a resend after a network error points at the same invocation instead of starting a second turn.
2. The transport opens `GET /invocations/{id}/streams/ui` with `accept: text/event-stream`.
3. In the handler, the middleware runs the model call inside `ctx.run`. Each part of the model stream is translated into a UI chunk (`start-step`, `text-delta`, `tool-input-available`, …) and appended to the `ui` stream as it arrives. In streaming mode the page sees tokens while the step is still running; in request-response mode it sees them when the step finishes (see below).
4. Tool calls append their input, approval request, output or error the same way.
5. When the turn ends, the stream is sealed; the SSE connection receives `end`, and the transport emits `finish`.
Chunks are appended only inside the step that produces them. When a handler replays, the model and tool results come from the journal and nothing is sent to the stream a second time.
Live tokens need the streaming transport
Chunks reach the page as they are generated only when your environment calls the service in streaming mode (`BIDI_STREAM`). On Cairnflow Cloud an `https://` endpoint is called in request-response mode unless you register it with `"transport": "declared"`, which works only when HTTP/2 reaches your app. In request-response mode the chunks of a step travel with the step’s result and reach the page together when the step finishes; the chat still works, without the typing effect. See [Deployments](/docs/cloud/deployments#transport) and the comparison in [Vercel AI SDK](/docs/agents/vercel-ai-sdk#streaming-versus-request-response).
## Reload and reconnect
[Section titled “Reload and reconnect”](#reload-and-reconnect)
With `resume: true`, `useChat` calls the transport’s `reconnectToStream` when the page loads. The transport asks the object’s `active` handler whether a turn is running; if so, it reads that invocation’s stream from the beginning, and the first chunk resets the message being shown.
```tsx
// `initial` comes from `await transport.messages(chatId)` when the page is rendered.
const { messages } = useChat({
id: chatId,
transport,
messages: initial,
resume: true,
});
```
`messages` already includes the user message of the running turn, so the page shows the question and the answer streams in under it. The same works in a second tab or on another device.
The reader also reconnects by itself when an SSE connection ends: a connection lives at most ten minutes, and the node serving the stream can change. If the stream turns out to be a new one (the step is being generated again), the transport sends a `reset-step` chunk first: the UI drops the partial step and shows it again from the start.
Note
In request-response mode the running turn becomes visible to `active` only after its first durable step. A reload during the very first model call finds nothing to reconnect to; the answer appears in `messages` when the turn ends.
## Stop
[Section titled “Stop”](#stop)
`stop()` in `useChat` stops reading and sends `POST /invocations/{id}/cancel?mode=signal`, a **cooperative** cancel. An Invoke only key may send it.
* In streaming mode (`BIDI_STREAM`) the cancel reaches the running turn at once. The model or tool call in progress receives an `AbortSignal`, so the provider request is cut and stops spending tokens. No later model or tool step runs.
* The model call that was cut returns **the text generated so far** as its result. The turn ends `completed`, and the saved history holds exactly what the user saw, like a “Stop” button in a hosted chat app.
* In request-response mode there is no channel into a running step: the step finishes, and the cancel takes effect from the next step.
A tool that should stop mid-way reads the signal from the AI SDK’s `execute` options:
```ts
const tools = {
research: tool({
description: "Search the web",
inputSchema: z.object({ query: z.string() }),
execute: async ({ query }, { abortSignal }) => search(query, { signal: abortSignal }),
}),
};
```
See [Cancellation](/docs/develop/cancellation) for the hard cancel used from the console.
## When something dies mid-step
[Section titled “When something dies mid-step”](#when-something-dies-mid-step)
| What dies | What the page sees |
| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Your service process (deploy, crash, out of memory) | Cairnflow retries the turn. The old attempt is marked superseded on the stream, the UI receives `reset-step`, and the step streams again from the start. The model call of that step **is** made again: it had no journaled result yet |
| The node leading the chat’s range | The temporary stream is lost with it. The UI receives `reset-step` and the new leader runs the unfinished step again. Completed steps do not run again |
| A step completed just before the failure | The new run has nothing left to stream for it. The transport closes cleanly, the UI keeps what it received, and the full history is in `messages` |
## Temporary streams: what to expect
[Section titled “Temporary streams: what to expect”](#temporary-streams-what-to-expect)
The `ui` stream is a **temporary** stream: it lives in the memory of the node that leads the chat’s range, and writing to it costs no storage requests. That is what makes token streaming cheap, and it comes with limits:
* **It holds the running step, not the whole history.** Each stream keeps up to 1 MiB; older records are overwritten, and a reader that falls that far behind sees a gap.
* **It disappears after the turn.** A sealed stream can be read for about 60 seconds, then it is gone. Read finished turns from `messages`.
* **A long wait releases it.** A turn suspended on an approval that streams nothing for about a minute releases its records. See [Human approval](/docs/agents/approvals) for how pending requests are recovered from `messages`.
* **Only the leader serves it.** Another node answers `503` and names the leader; the transport follows it once.
* **Each invocation has at most 16 streams.** An invocation never fails because of a stream: records over a limit are dropped.
* **The console does not show temporary streams.** Its **Streams** tab lists durable streams only. The model and tool results are in the **Journal** tab.
* **Open connections are capped** per environment and node; see [Limits](/docs/cloud/limits). A reader over the cap receives `429` and retries.
If you need records that survive a node failure, write them to a durable stream (`ctx.stream(name, { durable: true })`) in your own code; see [Streams and logs](/docs/develop/streams-logs).
## SSE events
[Section titled “SSE events”](#sse-events)
You only need these if you read streams without the transport, for example with `readStream` from the SDK client.
| Event | Data |
| ------------ | ------------------------------------------------------------------------------------------------------------------------ |
| `record` | `{offset, durable, step, attempt, k, data}`; the SSE `id` is the offset, `data` is the JSON the handler appended |
| `gap` | `{offset, dropped}`: records dropped over a cap, or overwritten because the reader fell too far behind |
| `superseded` | `{offset, step, attempt}`: that attempt of that step was replaced; its earlier records belong to an abandoned branch |
| `end` | `{next}`: the stream is sealed and fully read; the server closes the connection |
| `moved` | `{leader}`: the node stopped leading the range; ask the new leader |
| `reset` | `{}`: follows `moved` for a temporary stream; what was shown is gone, and a new attempt will stream again from the start |
Resume after a dropped connection with `?from=` or the `Last-Event-ID` header. The server sends a keep-alive comment every 15 seconds.
## Proxies
[Section titled “Proxies”](#proxies)
If a proxy sits between the browser and cairnflow, it must not buffer or compress `text/event-stream` responses, and it must pass `Last-Event-ID` through. See the proxy sketch in [Vercel AI SDK](/docs/agents/vercel-ai-sdk#keep-the-api-key-on-the-server).
# Vercel AI SDK
> Durable chat agents with streamText, useChat, tools and human approval.
Write the agent with `streamText` and `useChat` as usual; cairnflow makes each model call and each tool call a durable step. If the process dies mid-run, the run continues from the unfinished step without calling the model again for steps that already answered. A run can wait for a human approval as long as it takes without holding a process, and its output streams to the browser: token by token in streaming mode, a step at a time in request-response mode, the default on Cairnflow Cloud (see [Streaming versus request-response](#streaming-versus-request-response)). A page reload reconnects to the same run.
The adapter ships in `@cairnflow/sdk` and targets **AI SDK v7** (`ai@7`). The SDK does not depend on `ai`: install `ai`, `@ai-sdk/react` and your provider package in your app.
## What you get
[Section titled “What you get”](#what-you-get)
| You write | Cairnflow does |
| ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `wrapLanguageModel({ model, middleware: cairnMiddleware(ctx) })` | Each model call is a `ctx.run`: the result is journaled and replayed from the journal. A span `llm ` records input and output tokens |
| `cairnTools(ctx, tools)` | Each tool `execute` is a `ctx.run` with a span `tool `; input, result and error reach the UI |
| `cairnTools(ctx, tools, { approve: ["refund"] })` | The tool waits on a durable promise until someone approves; if rejected, it never runs |
| `chatObject("Chat", run)` | A virtual object keyed by chat ID: history in state, one turn at a time per chat |
| `useChat({ transport: cairnChatTransport(…) })` | Messages go through cairnflow, UI chunks come back over SSE; reload resumes; `stop()` cancels |
| `onError: turn.onError` | Errors from `streamText` go to the invocation’s log |
## Server
[Section titled “Server”](#server)
agent.ts
```ts
import { convertToModelMessages, stepCountIs, streamText, tool, wrapLanguageModel } from "ai";
import { anthropic } from "@ai-sdk/anthropic";
import { z } from "zod";
import { cairnMiddleware, cairnTools, chatObject, serve } from "@cairnflow/sdk";
const tools = {
lookupOrder: tool({
description: "Look up an order",
inputSchema: z.object({ id: z.number() }),
execute: async ({ id }) => db.orders.get(id),
}),
refund: tool({
description: "Refund an order (needs approval)",
inputSchema: z.object({ id: z.number(), amount: z.number() }),
execute: async ({ id, amount }) => payments.refund(id, amount),
}),
};
const chat = chatObject("Chat", async (ctx, turn) =>
streamText({
model: wrapLanguageModel({
model: anthropic("claude-sonnet-5-5"),
middleware: cairnMiddleware(ctx),
}),
system: "You are the support assistant of a shop.",
tools: cairnTools(ctx, tools, { approve: ["refund"] }),
messages: await convertToModelMessages(turn.messages),
stopWhen: stepCountIs(8),
onError: turn.onError,
}),
);
await serve({
services: [chat],
port: Number(process.env.PORT ?? 9080),
hostname: "0.0.0.0", // the default, 127.0.0.1, is unreachable from outside a container
identityKeys: [""],
});
```
Then register the deployment (`POST /deployments`, see [Deployments](/docs/cloud/deployments)).
In request-response mode, a model call that takes longer than the [turn time limit](/docs/cloud/limits#turn-time-limit) is cut and made again on the next attempt. For long generations, declare a longer `inactivityTimeout` in `opts.options` (below) and set a retry policy.
### What `chatObject` builds
[Section titled “What chatObject builds”](#what-chatobject-builds)
`chatObject(name, run, opts?)` returns a virtual object with three handlers. The browser transport talks to exactly these three.
| Handler | Type | What it does |
| ---------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `send` | exclusive | Records itself as the active turn, builds the history from state plus the new message (or cuts it at the message to regenerate), calls `run`, drains `toUIMessageStream` (the assistant message ID is the invocation ID), saves the new history, clears the active turn. Returns `{ id }` |
| `active` | shared | The invocation ID of the running `send`, or `null` |
| `messages` | shared | The saved history (`UIMessage[]`). During a turn: the history of that turn, including the message just sent, plus pending approval requests |
Because `send` is exclusive, two messages to the same chat never run at the same time; the second waits in the object’s queue. The shared handlers answer while `send` runs.
The `turn` argument of `run` carries:
* `messages` — the UI history to pass to `convertToModelMessages`;
* `onError` — pass it to `streamText({ onError })`;
* `chatId`, `trigger` (`"submit-message"` or `"regenerate-message"`), `messageId`;
* `body` — the `body` option the browser passed to `sendMessage`, if any.
`opts.options` takes the handler options shared by every cairnflow handler, such as `retryPolicy`. When it sets no `retryPolicy.maxAttempts`, `chatObject` uses 5 (`CHAT_MAX_ATTEMPTS`). `opts.stream` renames the stream the UI chunks go to (default `ui`).
### The three rules
[Section titled “The three rules”](#the-three-rules)
These apply to every cairnflow handler, and they matter more in an agent loop:
1. **Every side effect goes through `cairnTools` or `ctx.run`.** The handler body runs again on every replay. A tool `execute` that is not wrapped calls the outside API again each time.
2. **No `Date.now()`, `Math.random()` or `generateId()` outside `ctx.run`.**
3. **Do not catch and swallow errors around `ctx` commands.** A failed turn is still retried, whatever your `catch` does.
## Browser
[Section titled “Browser”](#browser)
The transport implements the AI SDK `ChatTransport` interface. `useChat` uses it for sending, reconnecting and stopping; you call two extra methods yourself.
chat.tsx
```tsx
import { useChat } from "@ai-sdk/react";
import type { UIMessage } from "ai";
import { cairnChatTransport } from "@cairnflow/sdk";
const transport = cairnChatTransport({ baseUrl: "/cairn", service: "Chat" });
function ChatPage({ chatId, initial }: { chatId: string; initial: UIMessage[] }) {
const { messages, sendMessage, stop, status } = useChat({
id: chatId,
transport,
messages: initial, // await transport.messages(chatId) when rendering the page
resume: true, // reload mid-generation: reconnect to the running turn
});
const approve = (approvalId: string, approved: boolean) =>
transport.approve(chatId, approvalId, { approved });
// …render messages; tool parts waiting for approval have state "approval-requested"
}
```
| Option | Meaning |
| ------------- | ------------------------------------------------------------------------------ |
| `baseUrl` | Where cairnflow is reached. In a browser, a same-origin proxy path (see below) |
| `service` | The virtual object, usually your `chatObject` name |
| `handler` | The handler that receives messages (default `send`) |
| `scope` | Scope of the object, if you use scopes |
| `headers` | Extra headers, for example `authorization` when running server-side |
| `stream` | The stream to read (default `ui`) |
| `sendHistory` | Send the whole history instead of only the last message (default `false`) |
| Method | Use |
| -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `transport.messages(chatId)` | The saved history, to initialise `useChat` after a page load |
| `transport.approve(chatId, approvalId, { approved, reason? })` | Answer a tool approval request — see [Human approval](/docs/agents/approvals). Throws if the request was already answered with a different decision |
By default the transport sends only the **last** message; the object keeps the history in its state. `sendHistory: true` makes the object use the client’s history instead, and adds a second copy of it to every turn’s journal.
### Stale history
[Section titled “Stale history”](#stale-history)
With each message the transport sends the ID of the message right before it. If the page holds an older history than the object (another tab sent a message, or the page never loaded `messages`), `send` does not run the turn and does not change the history: the UI receives an `error` chunk and `useChat` reports an error. Reload the history with `transport.messages(chatId)` and send again. Initialising `useChat` with `messages: await transport.messages(chatId)` avoids it.
### Keep the API key on the server
[Section titled “Keep the API key on the server”](#keep-the-api-key-on-the-server)
Cairnflow does not send CORS headers, and an API key must never reach the browser: anyone holding it can call every handler, read every chat and approve every request of the environment. Put a proxy on your app’s origin that checks your user and adds the key.
app/cairn/\[...path]/route.ts
```ts
// Sketch of a Next.js route handler. `auth` and `allowed` are your code.
async function handler(req: Request, { params }: { params: Promise<{ path: string[] }> }) {
const { path } = await params;
const user = await auth(req);
if (!(await allowed(user, req.method, path, new URL(req.url)))) {
return new Response("forbidden", { status: 403 });
}
const target = `/${path.join("/")}${new URL(req.url).search}`;
const headers: Record = {
"content-type": "application/json",
authorization: `Bearer ${process.env.CAIRN_INVOKE_KEY}`,
// Run the request at the node that leads this chat's range.
"x-cairn-forward": "leader",
};
// The transport sends Idempotency-Key with each message, Last-Event-ID when it reconnects.
for (const h of ["idempotency-key", "accept", "last-event-id"]) {
const v = req.headers.get(h);
if (v !== null) headers[h] = v;
}
return fetch(`${process.env.CAIRN_URL}${target}`, {
method: req.method,
headers,
body: req.method === "GET" ? undefined : await req.text(),
}); // the SSE body streams straight through
}
export { handler as GET, handler as POST };
```
An **Invoke only** key is enough. `allowed` should let through exactly these routes, and check that the user may use that chat:
| Route | Chat ID is in |
| --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `POST /invoke/Chat/send/send`, `POST /invoke/Chat/active`, `POST /invoke/Chat/messages` | `?key=` |
| `POST /promises/Chat/{chatId}/{approvalId}/resolve` | the path |
| `GET /invocations/{id}/streams/ui`, `POST /invocations/{id}/cancel` | the invocation ID: the proxy sees it in the answers of `send/send` (`{ id }`) and `active`, so it can keep an `id → chatId` map |
Do not buffer or compress `text/event-stream` responses in the proxy (with nginx: `X-Accel-Buffering: no`).
On a server that talks to cairnflow directly, give the key to the transport instead: `cairnChatTransport({ baseUrl, service, headers: { authorization: "Bearer …" } })`.
## Retries and errors
[Section titled “Retries and errors”](#retries-and-errors)
| What fails | What happens |
| ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| A transient error in a model or tool call (provider 429 or 5xx, timeout, a tool throwing a normal `Error`) | The turn fails and cairnflow retries it under the handler’s retry policy. Completed steps replay from the journal; only the failed step runs again |
| A provider error marked not retryable (`isRetryable: false`, such as 400 prompt too long or 401 bad key) | Journaled as the step’s failed result. The UI receives an `error`, the turn ends, no retry |
| A tool throws `TerminalError` | Journaled, so a replay does not run the tool again. The model sees the tool error (`tool-output-error` in the UI, `errorText` in history) and carries on |
Because retries happen at the turn level, the AI SDK’s own `maxRetries` has no effect on calls that go through `cairnMiddleware`.
So that a provider that keeps refusing does not retry forever, `chatObject` stops after 5 attempts unless you set your own policy:
```ts
const chat = chatObject("Chat", run, {
options: { retryPolicy: { maxAttempts: 3, onMaxAttempts: "PAUSE" } },
});
```
After the last attempt the invocation is paused; fix the cause, then resume it from the [console](/docs/cloud/console). See [Errors and retries](/docs/develop/errors-retries).
### `turn.onError` and `Suspend`
[Section titled “turn.onError and Suspend”](#turnonerror-and-suspend)
`streamText` reports every error to `onError`, and its default is `console.error`. `turn.onError` writes errors to the invocation’s log instead, where the console’s **Log** tab shows them.
When a turn waits (for an acknowledgement, a promise or an approval), nothing is thrown through your code: the waiting promise stays pending until the turn ends. The SDK throws `Suspend` only for a `ctx` command made after the turn has already suspended. That is not an error of your code, so `turn.onError` ignores it. If you write your own `onError`, ignore it too:
```ts
import { Suspend } from "@cairnflow/sdk";
const onError = ({ error }: { error: unknown }) => {
if (error instanceof Suspend) return;
report(error);
};
```
`cairnOnError(ctx)` is the same function `turn.onError` uses, for agents built without `chatObject`.
## Streaming versus request-response
[Section titled “Streaming versus request-response”](#streaming-versus-request-response)
How your environment calls the service decides what the chat can do. See [Deployments](/docs/cloud/deployments) for how the mode is chosen.
| | `BIDI_STREAM` | `REQUEST_RESPONSE` |
| ------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ |
| Tokens in the browser | As they are generated | All the text of a step at once, when the step completes |
| `stop()` during a model or tool call | The call receives an `AbortSignal` and stops; the partial answer is kept | The running step finishes; cancellation takes effect from the next step |
| Reload during the first model call | Reconnects at once | `active` is visible only after the first durable step, so there is nothing to reconnect to yet |
| A long model call | The SDK keeps the connection alive while it runs | It must finish within the [turn time limit](/docs/cloud/limits#turn-time-limit), or it is cut and made again |
| Needs | HTTP/2 all the way to your service | Any HTTPS host, serverless functions included |
On Cairnflow Cloud an `https://` endpoint is registered in request-response mode unless you ask for the declared mode (`"transport": "declared"`); streaming has not been verified on Fly.io yet. More in [Streaming to the browser](/docs/agents/streaming).
## Size and cost
[Section titled “Size and cost”](#size-and-cost)
* **Each model step’s journal entry** keeps every part of the model stream (text, tool calls, usage). The middleware drops the request body sent to the provider and the raw response body.
* **History lives in state.** Each turn reads it once and writes it back. Above 256 KiB the history is stored as immutable segments: the journal keeps references plus the open tail, so journal bytes per turn stay about the same as the conversation grows. In our tests a turn journals about 218 KB whether the history is 1, 3 or 6 MiB.
* **No need to trim for the payload limit.** A history larger than the [payload limit](/docs/cloud/limits#payload) (1 MiB during the Beta) is stored as segments instead of failing the turn. `transport.messages` returns the whole history in one response, capped at 64 MiB. Trim or summarise when the model’s context window needs it, not the runtime.
* **The SDK caches segments.** A long-running `serve()` keeps the segments it has read in memory (`valueCacheBytes`, 64 MiB by default), so a turn downloads only segments it has not seen.
* **Each approval** adds a journal entry and a durable wait.
## Observe a chat
[Section titled “Observe a chat”](#observe-a-chat)
| To see | Ask |
| --------------------------------------- | ------------------------------------------------------------- |
| The running turn of a chat | `POST /invoke/Chat/active?key=` |
| Spans and tokens of a turn | `GET /invocations/{id}/spans`, or the console’s **Trace** tab |
| `streamText` errors and `ctx.log` lines | `GET /invocations/{id}/logs`, or the **Log** tab |
| Each model step, tool call and approval | `GET /invocations/{id}/journal`, or the **Journal** tab |
| Whether an approval was answered | `GET /promises/Chat/{chatId}/{approvalId}` |
## Known limitations
[Section titled “Known limitations”](#known-limitations)
* **AI SDK v7 only.** Earlier major versions declare middleware and usage differently.
* **Providers.** The adapter is provider-agnostic and its tests use the AI SDK mock model. It has been run against a real model through `@ai-sdk/openai-compatible`; not every provider package has been tried yet.
* **A provider that refuses permanently with a transient status code** (for example a quota exhausted reported as `429`) is retried with backoff; the UI just waits. The error shows in the invocation’s status and log. Set `retryPolicy.maxAttempts`.
## Next
[Section titled “Next”](#next)
* [Human approval](/docs/agents/approvals)
* [Streaming to the browser](/docs/agents/streaming)
* [Agents without chatObject](/docs/agents/custom-agents)
# Cairnflow Cloud
> The hosted service — organizations, environments, region, and what the Beta includes.
Early-access waitlist
Cairnflow Cloud is not open yet — [join the waitlist](/#pricing) to hear when early access opens. This page describes the hosted service as it is built for its Beta, and details may change before it opens. To run cairnflow today, [host it yourself](/docs/self-hosting).
Cairnflow Cloud runs cairnflow for you. You write and host your service; Cloud keeps the journals, state and timers, calls your service when a handler has work to do, and gives you a console for each environment.
Cloud is planned to start as a **private Beta**: invite-only, free during the Beta, and with no SLA. Only invited email addresses will be able to create organizations and environments, and invitations have not started. How many organizations, environments and keys an account can create is in [Account limits](/docs/cloud/limits#account-limits).
## Organizations
[Section titled “Organizations”](#organizations)
Everything in Cloud belongs to an **organization**: usually your company or team. You create one the first time you sign in, and invite teammates by email (an invitation link is shown once and expires after 7 days).
Each member has a role in the organization:
| Role | Can |
| ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Owner | Everything an admin can, plus inviting, promoting, demoting and removing owners. An organization always keeps at least one owner. Deleting an organization is not in the web app yet: ask support |
| Admin | Manage environments, API keys and members |
| Member | Create and revoke API keys; cannot manage members |
| Viewer | Read-only access |
| Billing | Billing only; no access to environments |
The same roles decide what you can do in an environment’s console: owners, admins and members open it with full rights, viewers read only, and billing members cannot open it.
## Environments
[Section titled “Environments”](#environments)
An **environment** is where your invocations run: for example `prod` and `staging`. Each one has its own:
* **endpoint**: the URL your service and scripts talk to, such as `https://e0123456789a.iad.cairnflow.cloud`;
* **API keys**: see [API keys](/docs/cloud/api-keys);
* **identity key**: the public key your service uses to check that requests really come from this environment;
* **data**: journals, state, schedules, streams, archives and audit log;
* **console**.
An environment is an **isolated tenant on a shared cell**. A cell is a group of cairnflow nodes and its storage bucket, shared by many environments. Isolation between environments is enforced by the runtime: every request, query and stored object is scoped to its environment, and one environment cannot read, call or list another’s data. An environment is not a dedicated cell, and you cannot bring your own bucket.
A new environment usually becomes **Active** within a few seconds; the endpoint, identity key and API keys appear then. If it is still pending after a couple of minutes, write to .
## Region
[Section titled “Region”](#region)
Cloud runs in one region: **iad (US East, Virginia)**. Every resume of a handler is a round trip between the cell and your service, so host your service close to it.
## How Cloud calls your service
[Section titled “How Cloud calls your service”](#how-cloud-calls-your-service)
* Only **`https://`** endpoints on the public internet. Private and internal addresses are refused.
* Your service must check the **identity key**: `identityKeys` in `serve()` or `fetchHandler()`. Registering an endpoint that does not is refused.
* `https://` endpoints are called in **request-response** mode unless you register them with `"transport": "declared"`. Each turn is then one HTTP request and must finish within the [turn time limit](/docs/cloud/limits#turn-time-limit); tokens reach the browser when a step finishes, not as they are generated. Streaming mode needs HTTP/2 all the way to your app.
Details in [Deployments](/docs/cloud/deployments).
## What the Beta includes
[Section titled “What the Beta includes”](#what-the-beta-includes)
* Every environment has the same plan. See [Limits](/docs/cloud/limits) for the numbers.
* No billing page: the Beta is free.
* One region, no SLA, no uptime credit.
* Backups of each cell to a second storage provider, kept for about 45 days. See [Data and deletion](/docs/cloud/data-and-deletion).
What is not there yet is listed in [Known limitations](/docs/cloud/known-limitations).
## Self-hosting
[Section titled “Self-hosting”](#self-hosting)
Cloud runs the same runtime you can run yourself. Most of this section (deployments, the console, the query API) applies to a self-hosted cluster too; the plan limits, organizations and the shared-cell rules are specific to Cloud. See [Self-hosting](/docs/self-hosting).
## Support
[Section titled “Support”](#support)
Write to . Include your organization name and, for a problem with an invocation, its ID (shown in the console).
To report a security issue, write to .
## Next
[Section titled “Next”](#next)
* [Quickstart](/docs/quickstart)
* [API keys](/docs/cloud/api-keys)
* [Deployments](/docs/cloud/deployments)
# API keys and identity
> The environment endpoint, API keys and their roles, console sign-in, and the identity key your service checks.
Early-access waitlist
Cairnflow Cloud is not open yet — [join the waitlist](/#pricing) to hear when early access opens. This page describes the hosted service as it is built for its Beta, and details may change before it opens. To run cairnflow today, [host it yourself](/docs/self-hosting).
Three values connect your code to an environment. All three are on the environment page once the environment is **Active**.
| Value | Looks like | Used by |
| ------------ | ------------------------------------------ | ------------------------------------------------------------------------------------- |
| Endpoint | `https://e0123456789a.iad.cairnflow.cloud` | Everything that calls cairnflow: scripts, your backend, the chat proxy |
| API key | `cf_…` | Sent as `Authorization: Bearer ` on every request to the endpoint |
| Identity key | `publickeyv1_…` | Your service, in `identityKeys`, to check requests that come **from** the environment |
API keys authenticate you to the environment. The identity key works the other way round: it lets your service check that a request comes from your environment and not from someone who found its URL.
## API keys
[Section titled “API keys”](#api-keys)
Create a key on the environment page. Name it after where it will be used (`ci`, `laptop`, `billing-worker`) so you know what breaks when you revoke it.
The secret is shown **once**, when the key is created. Cloud keeps only a hash and the key’s metadata; if you lose a secret, revoke the key and create a new one.
```sh
curl -X POST "$CAIRN_URL/invoke/Greeter/greet" \
-H "authorization: Bearer $CAIRN_KEY" \
-H "content-type: application/json" \
-d '"world"'
```
A missing or wrong key gets `401`; a key whose role does not allow the route gets `403`.
### Roles
[Section titled “Roles”](#roles)
| Role | For | Can |
| ----------------------------- | ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Admin** (deploy and invoke) | CI, operators, your own scripts | Everything an Invoke key can, plus: register and remove deployments, move service revisions, read journals, logs, spans, usage, audit and archives, run SQL queries, hard-cancel, purge, resume, restart and migrate invocations. Signs in to the console |
| **Invoke only** | Clients that call your services: your backend, a chat proxy | Invoke handlers (`/invoke`, `/send`, workflows), read an invocation’s status and wait for it, resolve and reject durable promises and awakeables, send signals, cancel cooperatively, manage schedules, read the invocation’s own streams and artifacts |
An Invoke only key cannot read journals or state, and cannot register deployments. Give each client the smallest role that works: a browser-facing proxy needs Invoke only.
### Revoking
[Section titled “Revoking”](#revoking)
Revoking a key refuses requests that use it within seconds, on every node. An event stream already open with the key is closed within about 30 seconds. It cannot be undone.
Keys do not belong to the person who created them: when a member leaves the organization, the keys they created keep working until someone revokes them.
## Console sign-in
[Section titled “Console sign-in”](#console-sign-in)
**Open console** on the environment page signs you in with your Cairnflow Cloud account; no key to paste. Your organization role decides what you can do there (see [Cairnflow Cloud](/docs/cloud#organizations)).
The console’s own sign-in page also accepts an Admin API key. The key is exchanged for a session cookie and is not stored in the browser. Signing out revokes the session on the server, so a copy of the cookie stops working too.
## Identity key
[Section titled “Identity key”](#identity-key)
Every request Cloud sends to your service carries a signed token. Pass the environment’s identity key to the SDK and it rejects anything not signed by your environment: wrong signature, wrong path, expired, or replayed for another request. The handler does not run.
service.ts
```ts
await serve({
services: [greeter],
port: Number(process.env.PORT ?? 9080),
hostname: "0.0.0.0",
identityKeys: ["publickeyv1_…"],
});
```
route.ts
```ts
const handler = fetchHandler({
services: [greeter],
identityKeys: ["publickeyv1_…"],
});
```
Cloud refuses to register an endpoint that does not check identity keys, because a function URL is public: without the check, anyone who knows the URL could call your handlers.
`identityKeys` is a list so that a key can be rotated without downtime: the new key is added to the list before it starts signing, and the old one is removed after. You can also read the current keys with an Admin key:
```sh
curl "$CAIRN_URL/identity" -H "authorization: Bearer $CAIRN_KEY"
```
The answer is `{tenant, signing, keys: [{generation, kid, active}]}`; each `kid` is a `publickeyv1_…` value for `identityKeys`.
Caution
The identity key is public: it only verifies signatures. API keys are secrets. Never put an API key in a browser, a mobile app or a public repository.
## Next
[Section titled “Next”](#next)
* [Deployments](/docs/cloud/deployments)
* [Vercel AI SDK: keep the API key on the server](/docs/agents/vercel-ai-sdk#keep-the-api-key-on-the-server)
# The console
> Follow invocations step by step, see why one is waiting, act on it, query with SQL, and read usage and the audit log.
Early-access waitlist
Cairnflow Cloud is not open yet — [join the waitlist](/#pricing) to hear when early access opens. This page describes the hosted service as it is built for its Beta, and details may change before it opens. To run cairnflow today, [host it yourself](/docs/self-hosting).
Each environment has a web console. **Open console** on the environment page signs you in with your Cairnflow Cloud account. Owners, admins and members get full rights; viewers can read but not act. You can also sign in on the console’s own page with an Admin API key.
The console uses the same HTTP API you can call yourself: anything it shows, you can read with the [query API](/docs/query) or the [HTTP API](/docs/reference/http-api).
## Overview
[Section titled “Overview”](#overview)
Invocations by service and state, the ones that need attention (failed, paused), the busiest handlers, and completed and failed invocations over the last 24 hours. Hourly summaries are written about once a minute, so a new environment shows history after a short while.
## Invocations
[Section titled “Invocations”](#invocations)
The list shows invocations newest first, across the whole environment. Filter by service, handler, key, tag (`k=v`), idempotency key, parent invocation, creation time, roots only, or an ID prefix.
Select several invocations, or every invocation matching the filter, to run a **bulk action**: cancel, purge, resume or restart. Each invocation gets exactly the single-invocation action, in pages of up to 1,000; one failure does not stop the rest, and the errors can be downloaded as CSV.
## One invocation
[Section titled “One invocation”](#one-invocation)
The header shows the status, service, handler, key, deployment, creation and end time, tags, and the schedule that started it, if any.
### Why it is in this state
[Section titled “Why it is in this state”](#why-it-is-in-this-state)
A plain-language answer to “why is this not done?”, for example:
* sleeping until a given time;
* waiting for a call to another handler, a promise, a step, or another invocation;
* waiting in the queue of a virtual object, with its position and the invocation holding the lock;
* paused after running out of attempts, with the last failure;
* failed, with the code, message and stack trace;
* the last failed attempt and when the next attempt is due.
### Tabs
[Section titled “Tabs”](#tabs)
| Tab | Shows |
| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Journal** | Every entry in order: commands and their results, paired. Open an entry to see its decoded body (cut at 64 KiB). Entries still waiting for a result are highlighted |
| **Log** | `ctx.log` lines and errors reported through `turn.onError`. Live while the invocation runs (including lines not yet durable), filterable by level |
| **Trace** | A timeline per attempt (failed attempts in red, the retry wait between them) and the spans of `ctx.trace.span` as a waterfall, with token totals. Handlers declared with `trace: "runtime"` get a span per turn and per `ctx.run` |
| **Streams** | Durable streams (`ctx.stream(name, { durable: true })`), live while the invocation runs. Temporary streams, such as the `ui` stream of a chat, are not shown |
| **Tree** | Calls from and to other invocations, up to the root |
| **State** | The state of the virtual object or workflow, and its promises |
| **Artifacts** | Files stored with `ctx.artifact`, with preview and download |
### Actions
[Section titled “Actions”](#actions)
| Action | What it does | Needs |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ |
| **Resume** | Runs a paused invocation again | Admin |
| **Cancel (cooperative)** | Sends a cancel signal: the handler’s own cleanup runs and the invocation ends with its own failure. Needs your service to be running | Invoke |
| **Cancel now** | Ends the invocation as failed (code 572) without waiting for your service. Side effects of a turn already in flight still happen | Admin |
| **Restart from step…** | Starts a new invocation that reuses the journal before the chosen step (results of steps there are kept) and runs again from that step. Also available on each journal entry as **Restart from here** | Admin |
| **Replay check** | Runs the existing journal against a deployment without committing anything, to see whether new code would take the same path | Admin |
| **Migrate…** | Moves an unfinished invocation to another deployment; a replay check must match first unless you force it | Admin |
| **Send signal…** | Delivers a named signal (what `ctx.signal(name)` waits for). Sending the same name again does nothing | Invoke |
| **Purge** | Deletes the journal, status and idempotency key of an ended invocation (for a workflow run, also the workflow’s state and promises). It is archived first. Cannot be undone | Admin |
Destructive actions ask you to type a confirmation. The console reports success only after the server has answered.
## Services, workflows, objects
[Section titled “Services, workflows, objects”](#services-workflows-objects)
* **Services**: every service and handler of the current deployments, with statistics.
* **Workflows**: one run per workflow ID; pick a run or type an ID to open it.
* **Objects & state**: the keys of each virtual object, with their state and the invocations each one holds.
## Deployments
[Section titled “Deployments”](#deployments)
Every deployment, its transport, the services it is current for, and how many unfinished invocations are pinned to it. **Deploy safely** registers a new version without moving traffic, compares handlers, replay-checks unfinished invocations, moves services, drains and removes the old version. See [Deployments](/docs/cloud/deployments#ship-a-new-version).
## Schedules
[Section titled “Schedules”](#schedules)
Create, edit, pause, resume, run now and delete server-side schedules: cron (five fields, with an IANA time zone) or every N seconds. See [Schedules](/docs/develop/schedules).
## Query
[Section titled “Query”](#query)
A SQL editor over the environment’s `sys_*` tables, with sample queries and the table list on the side. Run with Ctrl/Cmd + Enter, switch between a table and a chart (a time column and numbers, or a text column and a number), and **Download CSV**. See [Query with SQL](/docs/query).
## Usage
[Section titled “Usage”](#usage)
Per hour, for a chosen time range: invocations, durable steps, SDK turns, completed and failed, compute units, billing units, run time, and input and output tokens per model (from spans that carry token counts, which `cairnMiddleware` records). Costs are shown only when token prices are set for the cell.
## Slow runs and archive
[Section titled “Slow runs and archive”](#slow-runs-and-archive)
* **Slow runs**: runs that took longer than the slow threshold, newest first, with where the time went (your code, the SDK, durable waits, engine wait, quota wait). Kept in each node’s memory only.
* **Archive**: purged invocations read back from the archive (final status, output and journal), by day.
## Audit log
[Section titled “Audit log”](#audit-log)
Who did what to the environment through its API and console: deployments, invocations, keys, sign-ins, refused requests. Filter by time range (up to 31 days), actor and action. The organization’s own audit log (members, invitations, environments, keys) is in the Cloud web app.
## Not available on Cloud
[Section titled “Not available on Cloud”](#not-available-on-cloud)
Cell-wide pages (**Cluster**, **Flow control**, **Settings**) need operator access to the cell and are not available to environments.
# Data and deletion
> What Cairnflow Cloud stores for an environment, how long it keeps it, and what deleting an environment does.
Early-access waitlist
Cairnflow Cloud is not open yet — [join the waitlist](/#pricing) to hear when early access opens. This page describes the hosted service as it is built for its Beta, and details may change before it opens. To run cairnflow today, [host it yourself](/docs/self-hosting).
This is the Beta data policy.
## What is stored
[Section titled “What is stored”](#what-is-stored)
For each environment:
* the journal of every invocation: inputs, step results, outputs, errors;
* the state of virtual objects and workflows, and their durable promises;
* schedules;
* durable streams, logs and trace spans of invocations;
* artifacts stored with `ctx.artifact`;
* archives of finished invocations;
* an audit log of who did what.
API keys are stored as hashes: a secret cannot be shown again.
Everything an environment stores sits on the cell’s object storage, scoped to that environment. You cannot bring your own bucket during the Beta.
Caution
Step results and state are kept in the journal, and the journal is visible in the console to anyone with access to the environment. Do not return secrets (tokens, API keys) from `ctx.run` or store them in state: keep them in your service’s environment variables or secret manager.
## How long it stays
[Section titled “How long it stays”](#how-long-it-stays)
* **Finished invocations** are removed 7 days after they end. Before removal, each one is written to the archive; the console’s **Archive** page reads it back. Archives do not expire yet.
* **Purging an invocation** yourself (console or `POST /invocations/{id}/purge`) removes its journal, status and idempotency key at once, after archiving it; purging a workflow run also removes that workflow’s state and promises. Only ended invocations can be purged.
* **Deleted items** sit in the cell’s trash for 7 days before they are removed for good, so a mistake can be undone.
* **Backups** copy each cell to a second storage provider on a schedule. Each copy expires about 45 days after it is made.
Retention is also the window of idempotency keys: once an invocation is removed, the same key starts a new invocation.
## Deleting an environment
[Section titled “Deleting an environment”](#deleting-an-environment)
When you delete an environment:
1. It is suspended at once: new invocations are refused and scheduled work stops.
2. Every API key is revoked and console sessions end.
3. The environment disappears from the web app.
Its data is then removed **permanently within 60 days**. The delay covers the trash (7 days) and the last backup that still holds it (about 45 days).
Caution
Deleting an environment cannot be undone from the web app. Export what you need from the console first: SQL query results download as CSV.
## Deleting an organization
[Section titled “Deleting an organization”](#deleting-an-organization)
There is no self-service way to delete an organization yet. Write to .
## Questions
[Section titled “Questions”](#questions)
For anything about your data, write to with your organization name.
# Deployments
> Register your service's URL, choose the transport, and ship new versions without breaking runs in flight.
Early-access waitlist
Cairnflow Cloud is not open yet — [join the waitlist](/#pricing) to hear when early access opens. This page describes the hosted service as it is built for its Beta, and details may change before it opens. To run cairnflow today, [host it yourself](/docs/self-hosting).
A **deployment** is one registered endpoint of your service: a URL where cairnflow can reach the handlers of one version of your code. Registering reads the endpoint’s list of services and handlers and makes it the current version of each service it contains.
The same API applies to a self-hosted cluster; the rules about `https://`, identity keys and the default transport are those of Cairnflow Cloud.
## Register
[Section titled “Register”](#register)
```sh
curl -X POST "$CAIRN_URL/deployments" \
-H "authorization: Bearer $CAIRN_KEY" \
-H "content-type: application/json" \
-d '{"uri":"https://your-service.example.com"}'
```
You need an **Admin** key. The answer describes the new deployment: its ID (`dp_…`) and `protocolMode`, which says how the environment will call your service.
Each registration creates a new, immutable deployment, even for the same URL. Handler options such as the retry policy and timeouts are read at registration, so changing them in code means registering again.
### What Cloud checks
[Section titled “What Cloud checks”](#what-cloud-checks)
| Requirement | If not met |
| ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| The URI is `https://` on the public internet | Refused: private and internal addresses are not allowed |
| The service checks identity keys (`identityKeys` in `serve()` or `fetchHandler()`) | `400` with code `identity_required` |
| The SDK compresses request-response bodies (the TypeScript SDK does by default; do not set `compression: false`) | `400` with code `compression_required` |
| The SDK and the runtime share a protocol version | Refused at registration |
| At most 10 registrations per minute | `429` with code `deploy_rate_limited` and a `Retry-After` header |
## Transport
[Section titled “Transport”](#transport)
Cairnflow calls your service in one of two modes:
* **`REQUEST_RESPONSE`.** Each turn of a handler is one HTTP request. When the handler waits (a sleep, a call, a promise) the request ends, and the next turn sends the journal recorded so far. A turn must finish within the [turn time limit](/docs/cloud/limits#turn-time-limit), and tokens and stream records of a step reach readers when the step finishes. Works behind every host and on serverless functions.
* **`BIDI_STREAM`.** One HTTP/2 stream stays open for the whole invocation, and the SDK keeps it alive while a step runs. Needed for live token streaming and for cancelling a running step through its `AbortSignal`. `serve()` declares this mode.
On Cloud, an `https://` endpoint is registered as **`REQUEST_RESPONSE`** by default, even if your service declares `BIDI_STREAM`. Most hosts end TLS at their edge and talk HTTP/1.1 to your app, or buffer the request body, and a streaming invocation would hang there.
If your host forwards HTTP/2 all the way to your app (Fly.io with `h2_backend` and Cloud Run with `--use-http2` are meant to; streaming has not been verified on Fly.io yet), keep the mode your service declares:
```sh
curl -X POST "$CAIRN_URL/deployments" \
-H "authorization: Bearer $CAIRN_KEY" \
-H "content-type: application/json" \
-d '{"uri":"https://your-service.example.com","transport":"declared"}'
```
Check `protocolMode` in the answer. If streaming does not reach your app, invocations fail with a message starting with `bidi_no_response_headers` (in the invocation’s last failure) and are retried. Register the endpoint again without `transport`.
`fetchHandler` always declares `REQUEST_RESPONSE`: a Fetch API handler cannot hold a bidirectional stream.
### Keeping request-response cheap
[Section titled “Keeping request-response cheap”](#keeping-request-response-cheap)
In `REQUEST_RESPONSE` the journal travels to your service on every turn, so bytes grow with the number of steps. Two SDK features reduce that:
* **Compression.** Request and response bodies are gzipped (on by default). Each journal entry is compressed on its own, so bytes of one entry are never compressed together with another.
* **Replay cache.** `serve()` keeps the journal it has already received for each running invocation in memory (64 MiB, 15 minutes by default), and the runtime then sends only the new entries plus a digest of the rest. If the cache misses, your service answers `409` and the turn is sent again in full at once, so it is always safe. `serve({ replayCache: false })` turns it off; `fetchHandler` has it off by default, because Lambda, Workers and edge functions do not keep a process between turns.
With several replicas behind a load balancer, the cache only hits when turns of one invocation reach the same replica. Cairnflow sends back cookies that your previous response set for the same invocation, so sticky-session cookies work; on Fly.io the SDK asks for the same machine by itself.
Keep step results small either way: large values belong in [artifacts](/docs/develop/artifacts), not in the journal, and the [payload limit](/docs/cloud/limits) applies.
## Platforms
[Section titled “Platforms”](#platforms)
| Platform | Serve with | Notes |
| ------------------------------------------------------------- | ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| Container, VM (Node.js 22.6 or newer) | `serve()` | Long-running process; replay cache on. Listen on `hostname: "0.0.0.0"` and the port your host gives you |
| Vercel (Next.js App Router) | `fetchHandler` in `app/api/cairn/[...path]/route.ts`, exported as `GET` and `POST` | Node.js runtime. Register a production or named domain: preview Deployment Protection answers with a login page |
| Cloudflare Workers | `export default { fetch: handler }` | Set `compatibility_flags = ["nodejs_compat"]` |
| AWS Lambda (Function URL or API Gateway HTTP API, payload v2) | `export const handler = lambdaHandler(fetchHandler({ … }))` | `identityKeys` is what keeps strangers out, so a Function URL with auth type `NONE` is fine |
| Deno, Bun | `Deno.serve(handler)`, `Bun.serve({ fetch: handler })` | |
The Fetch adapter is tested on Node.js, not yet on these platforms themselves.
Register the **base URL** where the handler is mounted, for example `https://your-app.vercel.app/api/cairn`. With a function, one turn must finish within the platform’s time limit: split long work into several short `ctx.run` steps. See [Serverless](/docs/workflows/serverless).
## Ship a new version
[Section titled “Ship a new version”](#ship-a-new-version)
Every invocation stays on the deployment it started on, for its whole life, even after you register a new version. New invocations go to the current version. So:
1. **Keep the old endpoint running** until nothing is left on it.
2. Register the new version. It becomes current for the services it contains.
3. Watch the old deployment drain: `GET /deployments/{id}` reports `pinnedInvocations`, the number of unfinished invocations still on it.
4. Remove it when it is empty: `DELETE /deployments/{id}`. It answers `409` while the deployment is still a current version or still has invocations on it. While it is being removed, moving a service to it, migrating to it or restarting on it answers `409` too.
For a careful rollout, register without moving anything with `POST /deployments?activate=false`, then move each service yourself:
```sh
curl -X PUT "$CAIRN_URL/services/Chat/revision" \
-H "authorization: Bearer $CAIRN_KEY" \
-H "content-type: application/json" \
-d '{"deployment":"dp_new…","expect":"dp_old…"}'
```
`expect` makes the move happen only if the service still points at that deployment: when two people roll back at once, exactly one wins. The same call with an older deployment is a rollback.
The console’s **Deployments → Deploy safely** page walks through these steps: register without moving, compare handlers, replay-check up to 20 unfinished invocations per service on the new version (read-only, nothing is committed), move, drain, migrate the invocations that replay cleanly, roll back, and remove the old version. See [Versioning](/docs/develop/versioning) for what makes a code change safe for invocations in flight.
## List and inspect
[Section titled “List and inspect”](#list-and-inspect)
| Request | Returns |
| ----------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `GET /deployments` | Every deployment: `id`, `endpoint`, `createdAtMs`, `protocolMode`, `currentFor` (services it is the current version of) |
| `GET /deployments/{id}` | The same, plus `pinnedInvocations` and the manifest: services, handlers and their options as registered |
| `GET /services` | Services and handlers you can call, with the deployment that serves each |
`protocolMode` is the first thing to check when every invocation of a deployment fails in transport.
## Next
[Section titled “Next”](#next)
* [Limits](/docs/cloud/limits)
* [The console](/docs/cloud/console)
* [HTTP API reference](/docs/reference/http-api)
# Known limitations
> What Cairnflow Cloud and the SDK do not do yet during the Beta.
Early-access waitlist
Cairnflow Cloud is not open yet — [join the waitlist](/#pricing) to hear when early access opens. This page describes the hosted service as it is built for its Beta, and details may change before it opens. To run cairnflow today, [host it yourself](/docs/self-hosting).
What the Beta does not do yet. None of these items changes the code you write today.
## Availability
[Section titled “Availability”](#availability)
* **Not open yet.** The Beta will be invite-only: only invited email addresses can create organizations and environments, and invitations have not started.
* **The SDKs are not on the public npm and PyPI registries yet**, and the Go module has no tagged release. Self-hosting binaries are not released either: the runtime is built [from source](/docs/self-hosting#build-from-source).
* **No SLA** and no uptime credit. Plan for interruptions.
* **No public status page yet.** Write to if something looks wrong.
## SDKs
[Section titled “SDKs”](#sdks)
Three SDKs exist: **TypeScript** (`@cairnflow/sdk`), **Python** (`cairnflow`, Python 3.11 or newer) and **Go** (package `cairn`, Go 1.25 or newer). The TypeScript `serve()` runs on Node.js 22.6 or newer. The Fetch adapter (`@cairnflow/sdk/fetch`, `fetchHandler`) targets Vercel (Node.js runtime), Cloudflare Workers (with `nodejs_compat`), AWS Lambda, Deno (`Deno.serve(handler)`) and Bun (`Bun.serve({ fetch: handler })`). It is tested on Node.js, against the standard Fetch API and Lambda payload v2 events, but not yet on those platforms themselves; report anything that behaves differently on one of them. The Python SDK serves with its built-in server, as an ASGI app, or on AWS Lambda. The [Go SDK](/docs/develop/go) serves with its built-in server, as an `http.Handler`, or on AWS Lambda. Neither has a Vercel AI SDK integration.
## Account
[Section titled “Account”](#account)
* Invite-only, with caps on organizations, environments and API keys: see [Account limits](/docs/cloud/limits#account-limits).
* No organization settings page yet: you cannot rename or delete an organization from the web app. Ask support.
* No billing page: the Beta is free.
## Transport
[Section titled “Transport”](#transport)
Endpoints on `https://` are called in request-response mode unless you register them with `"transport": "declared"` ([Deployments](/docs/cloud/deployments#transport)). In request-response mode:
* every resume of a handler sends the invocation’s journal again (compression and the replay cache reduce the bytes, not the round trips);
* each turn is one HTTP request and must finish within the [turn time limit](/docs/cloud/limits#turn-time-limit); a longer step is cut and retried;
* tokens of an AI step reach the browser all at once when the step completes, not as they are generated;
* `stop()` and cooperative cancel cannot interrupt the step that is running; they take effect from the next step.
Streaming mode needs HTTP/2 all the way to your app; it has not been verified on Fly.io yet. Detecting hosts that carry HTTP/2 to your app, so streaming is chosen for you, is planned.
## AI SDK adapter
[Section titled “AI SDK adapter”](#ai-sdk-adapter)
* **Vercel AI SDK v7 only.**
* Not every provider package has been tried. The adapter does not depend on the provider, and it has been run with a real model through `@ai-sdk/openai-compatible`.
* A provider that refuses permanently but answers with a transient status code (such as a used-up quota reported as `429`) is retried with backoff until the retry policy gives up. Set `retryPolicy.maxAttempts`.
## Streams
[Section titled “Streams”](#streams)
Temporary streams (the `ui` stream of a chat) live in the memory of the node leading the invocation’s range. A node failure or a change of leader loses them, and the console does not show them. The chat recovers from `messages`; see [Streaming to the browser](/docs/agents/streaming#temporary-streams-what-to-expect).
## Observability
[Section titled “Observability”](#observability)
* Spans and logs stay in the console and the API; exporting them to your own OpenTelemetry collector is turned off on shared cells.
* Slow runs are kept in each node’s memory only.
## Region
[Section titled “Region”](#region)
One region: **iad (US East, Virginia)**. Pick hosting close to it: every resume of a handler is a round trip between the cell and your service.
## Backups and recovery
[Section titled “Backups and recovery”](#backups-and-recovery)
Cells are backed up on a schedule to a second storage provider, and each copy expires after about 45 days. A restore brings an environment back to the last backup: work done after it can be lost, and an invocation that was waiting on another one at that moment may have to be restarted.
# Beta limits
> What every Cairnflow Cloud environment is allowed during the Beta, and what happens at each limit.
Early-access waitlist
Cairnflow Cloud is not open yet — [join the waitlist](/#pricing) to hear when early access opens. This page describes the hosted service as it is built for its Beta, and details may change before it opens. To run cairnflow today, [host it yourself](/docs/self-hosting).
Every environment has the same Beta plan. Your environment page shows it under **Plan & limits**, and `GET /tenant` with an Admin key returns your environment’s limits and current usage.
## Plan limits
[Section titled “Plan limits”](#plan-limits)
| Limit | Beta | At the limit |
| --------------------------------------------------------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Finished invocations kept | 7 days | Removed after that (archived first; see [Data and deletion](/docs/cloud/data-and-deletion)) |
| Largest payload | 1 MiB | A request body over it gets `413` with code `payload_too_large`. Larger state values, step results, inputs and outputs inside an invocation are stored as segments instead (see [Payload](#payload)) |
| Journal entries per invocation | 10,000 | The invocation fails with code `578` (`journal_too_long`) |
| Live invocations, whole environment | 1,000 | A new invocation gets `429` with code `live_invocations_limit`, and nothing is created. Schedules skip the runs that come due meanwhile. Invocations already running carry on, and so do the calls and sends they make |
| Deployments | 20 | Registering one more gets `409` with code `deployments_limit`. Remove a deployment that is no longer current to free a slot (see [Deployments](/docs/cloud/deployments#ship-a-new-version)) |
| Deployment registrations | 10 per minute | `429` with code `deploy_rate_limited` and a `Retry-After` header |
| Schedules | 50 | Creating one more gets `409` with code `schedules_limit`. Changing an existing schedule still works |
| Pending timers per invocation | 1,000 | The invocation fails with code `579`; the message starts with `timers_limit` |
| State keys per virtual object or workflow | 10,000 | Writing a new key fails the invocation with code `579`; the message starts with `state_keys_limit` |
| Artifact storage, whole environment | 1 GiB | Storing another artifact fails the invocation with code `579`; the message starts with `artifacts_limit` |
| Sustained throughput | 200 compute units per second | New work waits and runs as capacity frees up |
| Burst | 400 compute units | |
| Open streams and attached waits, per environment and node | 256 | `429` with code `too_many_open_streams` |
### Live invocations and artifact storage
[Section titled “Live invocations and artifact storage”](#live-invocations-and-artifact-storage)
Both are counted every few seconds, so an environment can go a little over either one before new work is refused. An invocation is live while it runs, waits or is paused; it stops counting when it ends. Artifacts stop counting when the invocation that stored them is purged, by you or at the end of retention.
### Compute units
[Section titled “Compute units”](#compute-units)
A compute unit (CU) is one per durable step, one per invocation created, and one per started 100 ms that each turn is open. A turn is open while your service works on it, and that includes time your handler waits inside `ctx.run`, for example for a model to answer. Time an invocation spends suspended is not counted: after a `ctx.sleep`, or while it waits on a promise, an awakeable, a signal or another invocation, the SDK ends the turn and nothing is counted until the next one starts. A handler that sleeps for a week costs nothing while it sleeps.
At 200 CU per second, about 20 turns can be open at once in an environment; further turns wait for capacity. The console’s **Usage** page shows compute units per hour and per handler.
### Payload
[Section titled “Payload”](#payload)
The payload limit applies to each request body sent to your environment. Inside an invocation, values larger than 256 KiB (state values, `ctx.run` results, invocation inputs and outputs, promise values) are stored as immutable segments in your environment’s storage. The journal keeps references, and a turn sends only the open tail of a value and what changed. Your code sees the whole value as before; nothing in the SDK API changes.
A conversation history in `chatObject` therefore grows past the payload limit without trimming. We test histories up to 8 MiB. One value read back in a single response, such as the history from `transport.messages` or an output from the HTTP API, is capped at 64 MiB. See [Vercel AI SDK](/docs/agents/vercel-ai-sdk#size-and-cost).
Files and images still belong in [artifacts](/docs/develop/artifacts): they are bytes your code stores and passes by reference, not values it reads back on every turn.
### Journal length
[Section titled “Journal length”](#journal-length)
Each step, sleep, call, state read or write and promise is a journal entry. An invocation that loops for a very long time should hand over to a fresh invocation (`ctx.continueAsNew`) rather than grow one journal without end.
### Open streams
[Section titled “Open streams”](#open-streams)
Each SSE stream reader (a chat page following a turn, for example) and each request waiting for an invocation’s result holds a connection. The cap is per environment on each node of the cell. The chat transport retries a refused connection with backoff.
## Turn time limit
[Section titled “Turn time limit”](#turn-time-limit)
In request-response mode, each turn of a handler is one HTTP request, and it must finish within the handler’s `inactivityTimeout`: **60 seconds** unless the service or the handler declares a longer one, up to one hour (see [Handler options](/docs/develop/services#handler-options)). Like every handler option, it is read when you register the deployment.
A turn that takes longer is cut and retried. The step it was running starts again from the beginning on the next attempt (a model call is made, and paid for, again), and without a retry policy the retries do not stop. Keep each `ctx.run` well under the limit, declare a longer `inactivityTimeout` for the handlers that need one, and set a [retry policy](/docs/develop/errors-retries#retry-policy) with `maxAttempts`.
Request-response is how Cloud calls an `https://` endpoint unless you register it with `"transport": "declared"`, and the only mode of `fetchHandler`. Only the streaming transport (`BIDI_STREAM`) keeps the connection alive while a closure runs, so a long step is not cut there. On a serverless platform a turn must also finish within the platform’s own time limit, and a proxy or tunnel in front of your service may have its own.
## Runtime limits
[Section titled “Runtime limits”](#runtime-limits)
These come from the runtime and apply to every environment:
| Limit | Value |
| ----------------------------------------------- | ----------------------------------------------------------------------------------------- |
| Streams per invocation | 16 |
| Temporary stream buffer, per stream | 1 MiB (older records are overwritten) |
| Temporary stream kept after the invocation ends | about 60 seconds |
| `ctx.log` per invocation | 1 MiB |
| Trace spans per invocation | 1 MiB |
| Durable streams per invocation, together | 8 MiB |
| One SSE connection | at most 10 minutes; clients reconnect |
| SQL query | 200,000 read units, 128 MiB, 10 seconds (up to 30 seconds with `timeout_ms`), 10,000 rows |
| SQL queries at once | 4 per node, 2 of them per environment |
Records over a stream or log cap are dropped and replaced by a `gap` marker; an invocation never fails because of a stream.
## Account limits
[Section titled “Account limits”](#account-limits)
Cloud is invite-only during the Beta: only an invited email address can create an organization, and environments can be created only in an organization whose owner was invited. People you invite into your organization do not need an invitation of their own. Invitations have not started.
| Limit | Beta | At the limit |
| ------------------------------------------------- | ---- | --------------------------- |
| Organizations one person can create | 2 | `409` with code `org_limit` |
| Environments per organization | 3 | `409` with code `env_limit` |
| API keys per environment, active or being revoked | 20 | `409` with code `key_limit` |
A deleted environment or a revoked API key frees its place once the deletion or revocation has finished. Changes made through the Cloud web app and its API are rate limited per person: over the limit they get `429` with code `rate_limited` and a `Retry-After` header.
## How Cloud calls your service
[Section titled “How Cloud calls your service”](#how-cloud-calls-your-service)
* **HTTPS only.** Deployments must be `https://` URLs on the public internet. Private and internal addresses are refused.
* **Identity keys are required.** Your service must check the environment’s identity key (`identityKeys` in `serve()` or `fetchHandler()`).
* **Request-response by default.** Each time a handler resumes is a new request. On serverless platforms the runtime sends the journal recorded so far with every resume; a long-running `serve()` keeps recent journals in memory, so a resume usually carries only what is new. Long journals and large step results still cost bytes: keep step results small. Each turn must finish within the [turn time limit](#turn-time-limit). Streaming needs `"transport": "declared"` and HTTP/2 all the way to your app; see [Deployments](/docs/cloud/deployments#transport).
* **No telemetry export from your handlers.** Spans and logs stay in the console; exporting them to your own OpenTelemetry collector is turned off on shared cells.
## No SLA
[Section titled “No SLA”](#no-sla)
The Beta has no service level agreement and no uptime credit. Plan for interruptions.
# Query with SQL
> Ask questions about invocations, journals, state and usage with read-only SQL over POST /query.
Everything cairnflow knows about your environment can be read with SQL: invocations and their state, journals, timers, promises, streams, deployments, schedules and usage. Queries are read-only, run across every node of the cell, and see only your environment’s data.
Use it from the console’s **Query** page, or over HTTP:
```sh
curl -X POST "$CAIRN_URL/query" \
-H "authorization: Bearer $CAIRN_KEY" \
-H "content-type: application/json" \
-d '{"sql": "SELECT service, class, sum(count) AS n FROM sys_invocation_counts GROUP BY service, class"}'
```
You need a key or console role that can read the environment: an **Admin** key, or a console session of an owner, admin, member or viewer. An Invoke only key cannot query.
## Request and response
[Section titled “Request and response”](#request-and-response)
| Field | Meaning |
| --------------- | ----------------------------------------------------------- |
| `sql` | One read-only statement |
| `params` | Values for `$1 … $n`: strings, integers, booleans or `null` |
| `allow_partial` | Default `true`. `false` turns a partial answer into a `503` |
| `timeout_ms` | Default 10,000; at most 30,000 |
```json
{
"columns": [{ "name": "service", "type": "…" }, { "name": "n", "type": "…" }],
"rows": [["Chat", 42], ["Greeter", 7]],
"partial": false,
"warnings": [],
"read": 12,
"ms": 3
}
```
Times come back as ISO-8601 strings; numbers and booleans keep their type. `read` is the number of read units the query used.
### Parameters
[Section titled “Parameters”](#parameters)
Pass values separately instead of writing them into the SQL text. They are bound before the query is planned and never become SQL:
```json
{
"sql": "SELECT id, class, created_at FROM sys_invocation WHERE service = $1 AND key = $2",
"params": ["Chat", "chat-42"]
}
```
Parameters are positional and consecutive (`$1`, `$2`, …), with exactly one value each. Named parameters, floats, arrays and objects are refused.
## The tables
[Section titled “The tables”](#the-tables)
| Group | Tables |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| Invocations | `sys_invocation` (one row per invocation), `sys_invocation_counts` (counts per service, handler and state) |
| Inside one invocation | `sys_journal`, `sys_timer`, `sys_attachment`, `sys_log`, `sys_span`, `sys_stream`, `sys_stream_record`, `sys_artifact`, `sys_outbox` |
| Objects and workflows | `sys_state`, `sys_value`, `sys_promise`, `sys_promise_waiter`, `sys_object`, `sys_vqueue_entry` |
| Scheduled work | `sys_schedule`, `sys_delayed` |
| Code | `sys_deployment`, `sys_service`, `sys_handler` |
| Usage and performance | `sys_metering`, `sys_artifact_bytes`, `sys_handler_stats`, `sys_handler_history`, `sys_slow_run` |
| History | `sys_archive`, `sys_audit` |
Columns and meanings are in the [table reference](/docs/query/tables).
**Some tables need a key.** Tables that read inside one invocation or one object require an equality filter on their key, so a query never scans everything: `id = …` for `sys_journal`, `sys_log`, `sys_artifact` and the other per-invocation tables; `service = … AND key = …` for `sys_state`, `sys_value`, `sys_promise` and `sys_promise_waiter`. Without it the query is refused with `400`.
## Questions operators ask
[Section titled “Questions operators ask”](#questions-operators-ask)
### What is stuck?
[Section titled “What is stuck?”](#what-is-stuck)
Invocations still running or waiting after an hour:
```sql
SELECT id, service, handler, status, created_at
FROM sys_invocation
WHERE class = 'active' AND created_at < now() - INTERVAL '1 hour'
ORDER BY created_at
LIMIT 50
```
Paused invocations (out of attempts, or stopped by an error that needs a person), with the last error:
```sql
SELECT id, service, handler, last_failure_message, transitioned_at
FROM sys_invocation
WHERE class = 'paused'
ORDER BY transitioned_at DESC, id
LIMIT 50
```
Invocations waiting for a retry, and why the last attempt failed:
```sql
SELECT id, service, handler, attempt, retry_at, last_failure_code, last_failure_message
FROM sys_invocation
WHERE retry_at IS NOT NULL
ORDER BY retry_at
LIMIT 50
```
### What is one invocation waiting for?
[Section titled “What is one invocation waiting for?”](#what-is-one-invocation-waiting-for)
```sql
SELECT index, name, entry_lite
FROM sys_journal
WHERE id = $1
ORDER BY index
```
In `entry_lite`, a command with `"completed": false` is still waiting for its result: a call, a promise, a sleep. Pending sleeps are also in `sys_timer`:
```sql
SELECT completion_id, due_at_ms FROM sys_timer WHERE id = $1
```
The console’s **Why it is in this state** panel answers the same question in words.
### What is failing?
[Section titled “What is failing?”](#what-is-failing)
```sql
SELECT id, service, handler, failure_code, failure_message, transitioned_at
FROM sys_invocation
WHERE class = 'failed'
ORDER BY transitioned_at DESC, id
LIMIT 50
```
Failed invocations per handler, from in-memory counters (reads nothing from storage):
```sql
SELECT service, handler, sum(count) AS n
FROM sys_invocation_counts
WHERE class = 'failed'
GROUP BY service, handler
ORDER BY n DESC
LIMIT 10
```
Common failure codes: `572` cancelled, `575` out of attempts, `578` journal too long. See [Errors](/docs/reference/errors).
### What is slow?
[Section titled “What is slow?”](#what-is-slow)
Handlers by turn latency over the recent window:
```sql
SELECT service, handler, sum(turns) AS turns, sum(failed) AS failed, max(p99_ms) AS p99_ms
FROM sys_handler_stats
GROUP BY service, handler
ORDER BY p99_ms DESC
LIMIT 10
```
Invocations that took longer than ten seconds end to end:
```sql
SELECT id, service, handler, duration_ms
FROM sys_invocation
WHERE duration_ms >= 10000
ORDER BY created_at DESC, id
LIMIT 50
```
Long journals, which cost more on every resume in request-response mode:
```sql
SELECT id, service, handler, journal_len
FROM sys_invocation
WHERE journal_len >= 100
ORDER BY created_at DESC, id
LIMIT 50
```
### How much is used?
[Section titled “How much is used?”](#how-much-is-used)
The current hour:
```sql
SELECT hour, invocations, steps, run_ms, input_tokens, output_tokens, units
FROM sys_metering
```
Completed, failed and compute units per hour, from a start time in milliseconds:
```sql
SELECT hour_ms, sum(completed) AS completed, sum(failed) AS failed, sum(cu) AS cu
FROM sys_handler_history
WHERE hour_ms >= $1
GROUP BY hour_ms
ORDER BY hour_ms
```
Tokens of one agent turn, per model call:
```sql
SELECT name, input_tokens, output_tokens
FROM sys_span
WHERE id = $1 AND input_tokens IS NOT NULL
```
### Find an invocation
[Section titled “Find an invocation”](#find-an-invocation)
By object key, idempotency key, tag, parent or whole call tree:
```sql
SELECT id, handler, class, created_at FROM sys_invocation
WHERE service = 'Chat' AND key = 'chat-42'
ORDER BY created_at DESC, id LIMIT 50;
SELECT id, service, handler, class FROM sys_invocation
WHERE idempotency_key = 'order-42' LIMIT 10;
SELECT id, parent_id, service, handler, class FROM sys_invocation
WHERE root_id = $1 ORDER BY id;
```
Send one statement per request; the block above shows three.
## Consistency
[Section titled “Consistency”](#consistency)
* **Only durable data.** A query sees rows that are committed to storage. It never waits for, or slows down, the invocations it reads. When the node ships the query worker, each statement runs in a separate worker process, apart from the engine.
* **Counts are exact** as of the last commit of each key range: `sys_invocation_counts` is kept in memory and updated with each commit.
* **Partial answers are flagged.** If part of the data cannot be read (a node does not answer, or an index is still being built after a change), the answer has `partial: true` and a `warnings` entry per affected range (`reason` such as `indexing`). It never silently drops rows. Send `allow_partial: false` to get a `503` instead.
* **Live tables come from the API.** Deployments, services, schedules, statistics, usage, archive and audit tables are read through the same API the console uses, with your key’s permissions.
## Limits and errors
[Section titled “Limits and errors”](#limits-and-errors)
| Answer | Cause |
| -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400` | SQL syntax error, unknown table or column, a statement that is not read-only (DDL, DML, `COPY`, `SET`), table functions, recursive CTEs, file reads, a keyed table without its key, or a statement too large to plan: over 64 KiB of text, more than 500 operators, more than 64 joined tables or more than 64 query blocks (`SELECT`, `UNION`, …) |
| `422`, `error` starting with `query_budget:` | The query would read more than 200,000 read units, use more than 128 MiB, run longer than its timeout, or return more than 10,000 rows. Add a `LIMIT` or filter on an indexed column (`service`, `class`, `created_at`, `id`) |
| `429` | More than 4 queries at once on a node or 2 of your environment’s, or your environment used up its read units for now (`error` starting with `query_budget:`). Retry shortly |
A query either completes or fails: an error never comes back as a truncated `200`.
`sys_invocation` is stored in `created_at DESC, id` order, so “newest first” lists with a `LIMIT` are cheap. Filters on `id`, `service`, `handler`, `key`, `kind`, `class`, `root`, `parent_id`, `root_id`, `schedule`, `deployment`, `restarted_from`, `created_at`, `transitioned_at` and `duration_ms` are applied during the scan; filters on other columns are applied after reading, so combine them with one of these.
## Next
[Section titled “Next”](#next)
* [Table reference](/docs/query/tables)
* [The console](/docs/cloud/console)
# CLI
> Reference for the cairn command-line client, plus a summary of the cairn-ctl recovery tool.
`cairn` is a thin client of the [HTTP API](/docs/reference/http-api): each command is one request (or two, when it follows a `503` to the leader). It prints a readable table by default and the raw JSON with `--json`.
## Global options
[Section titled “Global options”](#global-options)
```sh
cairn [--server URL] [--token KEY] [--json] ...
```
| Option | Environment | Default | Meaning |
| -------------- | ------------------ | ----------------------- | ----------------------------------------- |
| `--server URL` | `CAIRNFLOW_SERVER` | `http://127.0.0.1:8080` | Node or endpoint to talk to. |
| `--token KEY` | `CAIRNFLOW_TOKEN` | none | API key, sent as `Authorization: Bearer`. |
| `--json` | | off | Print the API’s JSON instead of a table. |
| `--version` | | | Print the version line. |
```sh
export CAIRNFLOW_SERVER=https://cairn.example.com
export CAIRNFLOW_TOKEN=
```
When a node answers `503` with a `leader`, `cairn` resends the request there once.
Exit codes: `0` success; `1` the request failed (the CLI prints the HTTP status and the error message); `2` wrong usage (the CLI prints the usage text); `3` `replay --bundle` found a mismatch.
## Deployments and services
[Section titled “Deployments and services”](#deployments-and-services)
| Command | Does |
| -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `cairn register ` | Register the service at `` (`POST /deployments`). Prints the deployment id and its services. |
| `cairn deployments` | List deployments and which services they are the current revision for. |
| `cairn deployments rm ` | Remove a deployment that is no longer a revision and has no bound invocations. |
| `cairn revision [--expect ID]` | Point a service at another deployment (rollback, pinning). With `--expect`, only if the current revision is `ID`. |
| `cairn services` | Services and handlers you can call. |
The URL you register must be reachable from the cairnflow nodes.
## Invoking
[Section titled “Invoking”](#invoking)
```sh
cairn invoke [--key K] [--input DATA] [--scope S] [--limit-key L]
```
| Option | Meaning |
| --------------- | ---------------------------------------------------- |
| `--key K` | Object key (virtual object) or workflow id. |
| `--input DATA` | Request body. `-` reads it from stdin. |
| `--scope S` | Run in a flow-control scope (`/scope/S/invoke/...`). |
| `--limit-key L` | Limit key inside the scope. Requires `--scope`. |
```sh
cairn invoke Greeter greet --input '"world"'
cairn invoke Cart add --key user-1 --input '{"sku":"tea"}'
echo '{"amount": 100}' | cairn invoke Orders submit --key order-42 --input -
```
The command waits like `POST /invoke`: it prints the result, or the invocation id when the result is not ready within the node’s wait time.
## Workflows
[Section titled “Workflows”](#workflows)
```sh
cairn workflow [--attach] [--scope S]
```
Prints the result of a workflow’s run, found by its workflow id. Without `--attach` it does not wait (`GET /workflow/.../output`); with it, it waits (`POST /workflow/.../attach`).
## Inspecting invocations
[Section titled “Inspecting invocations”](#inspecting-invocations)
| Command | Does |
| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------ |
| `cairn status ` | State of one invocation, with its output or error. |
| `cairn journal ` | The journal, entry by entry. |
| `cairn invocations [--status S] [--limit N] [--all-nodes]` | Invocations of the ranges led by the node you ask; `--all-nodes` asks the whole cluster. |
| `cairn invocations --cursor '' [--tag k=v] [--class C] [--service S] [--root] [--limit N]` | Paged listing across the cluster, newest first. Any of these options selects it; pass the printed cursor to get the next page. |
| `cairn sql ""` | Run a read-only SQL query (`POST /query`). |
| `cairn stats [--window 5m\|15m\|1h] [--tenant T] [--all-nodes]` | Per-handler summary: turns, outcomes, failed attempts, p50, p99, max. |
```sh
cairn invocations --status suspended
cairn sql "SELECT class, sum(count) FROM sys_invocation_counts GROUP BY class"
```
## Acting on invocations
[Section titled “Acting on invocations”](#acting-on-invocations)
| Command | Does |
| ------------------------------------------------- | ---------------------------------------------- |
| `cairn cancel ` | Hard cancel (`failed`, code 572). |
| `cairn purge ` | Delete a finished invocation now. |
| `cairn resume ` | Take an invocation out of `paused` and run it. |
| `cairn signal [--value JSON]` | Send a signal to a waiting invocation. |
## Promises
[Section titled “Promises”](#promises)
| Command | Does |
| ----------------------------------------------------- | ---------------------------------------- |
| `cairn resolve [--value JSON]` | Resolve a durable promise. |
| `cairn reject ` | Reject it; waiters get a terminal error. |
| `cairn promise ` | Show whether the promise has a result. |
```sh
cairn signal approve --value '{"by":"alice"}'
cairn resolve Orders order-42 approved --value '"ok"'
```
## API keys
[Section titled “API keys”](#api-keys)
| Command | Does |
| ----------------------------------- | -------------------------------------------------------- |
| `cairn keys` | List stored keys (never secrets). |
| `cairn keys create ` | Create a key. The secret is printed **once**. |
| `cairn keys rm ` | Revoke a key. Reports nodes that have not confirmed yet. |
| `cairn keys check ` | Whether the key is still accepted by any live node. |
Roles accepted by the API are `invoke`, `view`, `admin`, `provision` and `cluster-admin`. See [Security](/docs/self-hosting/security#roles).
```sh
cairn keys create default invoke
```
## Flow control
[Section titled “Flow control”](#flow-control)
| Command | Does |
| ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
| `cairn rules` | The rule book. |
| `cairn rules set [--concurrency N\|unlimited] [--description TXT] [--disabled\|--enabled]` | Add or update a concurrency rule (merge). |
| `cairn rules rm ` | Remove a rule. |
| `cairn limits` | Usage, limit and availability of each active counter. |
| `cairn vqueues` | Queues that have work, and what blocks them. |
| `cairn scheduler` | Queue depth, slots in use, locks held, rule book version in effect. |
Rate limits (`rate`, `burst`) and per-tenant rows are set through `POST /rules`; see [Flow control](/docs/reference/flow-control).
## Cluster
[Section titled “Cluster”](#cluster)
| Command | Does |
| -------------------------------------- | ------------------------------------------------------------------------- |
| `cairn cluster` | Who leads each range. |
| `cairn ranges` | The range table: version, key bounds, generation, pending split or merge. |
| `cairn ranges split [--at HEX16]` | Split a range (default: the middle of its keys). |
| `cairn ranges merge ` | Merge two adjacent ranges. |
## Capturing runs for debugging
[Section titled “Capturing runs for debugging”](#capturing-runs-for-debugging)
| Command | Does |
| --------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `cairn capture [--tenant T] [--deployment D] [--count N] [--ttl SECONDS]` | Capture the next matching invocations (journal and final state) when they finish or pause. |
| `cairn capture ls [--tenant T]` | Pending capture requests and captured bundles. |
| `cairn capture get [--out FILE]` | Download a bundle (default `.bundle`). |
| `cairn replay --bundle FILE [--endpoint URL]` | Replay a bundle against a service, read-only, without a cluster. `--endpoint` points at a local build you are fixing. Exits `3` on a mismatch. |
Capture commands need a `cluster-admin` key.
## cairn-ctl
[Section titled “cairn-ctl”](#cairn-ctl)
`cairn-ctl` is a separate tool that works on the bucket directly, without a running node. It takes the store like a node does (`--main-store URI` or `--data-dir DIR`, optional `--wal-store` and `--prefix`) and the bucket credentials from the environment.
| Command | Does |
| ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `verify [--deep] [--wal-logs] [--no-restore-checks]` | Check the bucket’s invariants; exit code `1` on findings. `--deep` also checks that every data file a range’s manifest names is present (one listing per range). By default it also looks for cross-range calls that lost a message; `--no-restore-checks` turns that off. |
| `table show`, `owners`, `ranges retired`, `wal floors`, `range dump ` | Read-only views of the range table, ownership records and data. |
| `cluster status` | Cluster version, gates and live sessions. |
| `cluster enable- --apply` | Turn on a one-way feature gate after every node is upgraded. |
| `table restore [--force] --apply` | Rebuild a lost range table from its newest saved version, only when the rest of the bucket proves it is the last one. Every node must be stopped. |
| `keys create --apply` | Create an API key directly in the bucket. |
| `identity publish\|activate\|retire --apply` | Rotate a tenant’s request-signing key. |
| `pricing`, `pricing set