# Human approval

> Make an agent wait for a person before a tool runs, and answer from the chat, an admin page or a webhook.

Source: https://cairnflow.dev/docs/agents/approvals

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

```ts title="agent.ts"

// 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

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

```tsx title="chat.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 (
    <>
      <button onClick={() => transport.approve(chatId, id, { approved: true })}>Approve</button>
      <button onClick={() => transport.approve(chatId, id, { approved: false, reason: "Not eligible" })}>
        Reject
      </button>
    </>
  );
}
```

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

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}'
```

```ts title="slack-webhook.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

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

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

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

- [Streaming to the browser](/docs/agents/streaming)
- [Durable promises and signals](/docs/develop/promises-signals)
