Skip to content
Anlyon
Esc
↑↓navigate↵open⌘Jpreview
On this page

Local approval gates

Wrap one of your own functions so it runs only after a reviewer approves it, with the decision recorded, when the call cannot move into Anlyon.

Some calls cannot move into Anlyon: a native SDK with no HTTP equivalent, a database write, logic deep inside your own service. Your agent still should not run them unchecked. A local approval gate wraps that function. Each call creates an approval, waits for a decision, and runs the function only if it was approved. The decision, the decider, the note and the policy that routed it are recorded.

It takes one wrapper and no rewrite. You get a human checkpoint and an audit record for calls you could not otherwise put behind one.

How it works

  1. Your code calls the wrapped function.
  2. The SDK creates an approval (POST /api/v2/approvals) whose payload is the call’s arguments, unless you pass your own.
  3. Approval policies run on it. One may approve or deny it at once. Otherwise it waits in the console’s Approvals inbox, Slack if you connected it, and the API.
  4. The SDK long-polls for the decision. Approved: your function runs and its result is returned. Denied or expired: ApprovalDeniedError. Still pending when your wait runs out: ApprovalPendingError, and the function does not run.

1. Install the SDK

npm install @anlyonhq/sdk
pip install anlyon

2. Create a client

Create an API key in the console (Settings → API keys). The gate needs approvals:write to request and approvals:read to wait. Both are in the default set. Keys belong to one environment, so a staging key cannot create production approvals.

import { Client } from '@anlyonhq/sdk';

const client = new Client({ apiKey: process.env.ANLYON_API_KEY! });
export ANLYON_API_KEY=anlyon_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
import os
from anlyon import Client

client = Client(api_key=os.environ["ANLYON_API_KEY"])

3. Gate the function

import { ApprovalDeniedError, ApprovalPendingError } from '@anlyonhq/sdk';

// Any function: sync or async, any arguments.
async function refund(orderId: string, amount: number) {
  // ... your existing refund logic ...
}

const guardedRefund = client.approvals.gate(
  {
    title: 'Refund a customer?',
    description: 'Requested by the support agent. Refunds are irreversible.',
    timeoutMs: 10 * 60_000, // wait up to 10 minutes for a decision
  },
  refund,
);

try {
  // Blocks until a reviewer approves; then (and only then) refund() runs.
  await guardedRefund('ord_42', 129.99);
} catch (err) {
  if (err instanceof ApprovalDeniedError) {
    console.log('Denied:', err.approval.decisionNote);
  } else if (err instanceof ApprovalPendingError) {
    console.log('Nobody decided in time. The approval is still open:', err.approval.id);
  } else {
    throw err;
  }
}
# 1. Request the approval. Keep the id from data.id.
curl -X POST https://api.anlyon.com/api/v2/approvals \
  -H "Authorization: Bearer $ANLYON_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: refund-ord_42" \
  -d '{
    "title": "Refund a customer?",
    "description": "Requested by the support agent. Refunds are irreversible.",
    "payload": { "orderId": "ord_42", "amount": 129.99 }
  }'

# 2. Wait up to 55 seconds for a decision. Repeat while data.status is "pending".
curl "https://api.anlyon.com/api/v2/approvals/apr_01JABCDEF?waitSeconds=55" \
  -H "Authorization: Bearer $ANLYON_API_KEY"

# 3. Run your function only when data.status is "approved".
from anlyon import ApprovalDeniedError, ApprovalPendingError

@client.approvals.gate(
    title="Refund a customer?",
    description="Requested by the support agent. Refunds are irreversible.",
    timeout_seconds=600,  # wait up to 10 minutes for a decision
)
def refund(order_id: str, amount: float) -> None:
    ...  # your existing refund logic

try:
    # Blocks until a reviewer approves; then (and only then) refund() runs.
    refund("ord_42", 129.99)
except ApprovalDeniedError as err:
    print("Denied:", err.approval.get("decisionNote"))
except ApprovalPendingError as err:
    print("Nobody decided in time. The approval is still open:", err.approval["id"])

The gate defaults the approval’s payload to the call’s arguments, so the reviewer sees exactly what they are approving. Pass payload to show something friendlier, and to keep sensitive arguments out of the approval.

Options, in TypeScript and Python:

Option Default Meaning
title required in TypeScript; Approve <function name>? in Python Up to 200 characters. Shown in the inbox.
description none Up to 2,000 characters.
payload the call’s arguments What the reviewer sees.
timeoutMs / timeout_seconds 5 minutes How long your code waits before ApprovalPendingError. The approval itself stays open.
expiresInSeconds / expires_in_seconds the workspace’s approval window, 24 hours unless changed When the approval expires. From 60 seconds to 30 days.
runId / run_id none A run to receive the wait and decision spans.

The approval window is set in workspace defaults.

4. Decide

Decisions arrive in the console’s Approvals inbox in real time, in Slack when Slack approvals are on, or through the API from your own tooling:

// From a second, decision-scoped key. A key can never approve its own request.
const reviewer = new Client({ apiKey: process.env.ANLYON_REVIEWER_KEY! });

await reviewer.approvals.approve('apr_01JABCDEF', { note: 'Verified with the customer.' });
// or: await reviewer.approvals.deny('apr_01JABCDEF', { note: 'Amount too large.' });
curl -X POST https://api.anlyon.com/api/v2/approvals/apr_01JABCDEF/approve \
  -H "Authorization: Bearer $ANLYON_REVIEWER_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: decide-apr_01JABCDEF" \
  -d '{ "note": "Verified with the customer." }'
# From a second, decision-scoped key. A key can never approve its own request.
reviewer = Client(api_key=os.environ["ANLYON_REVIEWER_KEY"])

reviewer.approvals.approve("apr_01JABCDEF", note="Verified with the customer.")
# or: reviewer.approvals.deny("apr_01JABCDEF", note="Amount too large.")

Two rules are enforced server-side, always:

  • Deciding requires the separate approvals:decide scope, which is not granted by default. And the credential that requested an approval can never decide it, whatever scopes it holds and whatever any policy says. The person behind it does not decide it either while another member can decide approvals in that environment (see Workspaces). Owners, admins, members and approvers can decide in the console; a viewer cannot. If a decision should not need a reviewer at all, express that as an auto_approve policy. That decision is made in advance by an admin and recorded against a policy version. The requester does not vote on itself.
  • Every decision is recorded: decider, timestamp, note, and the policy (and its version) that governed the approval.

A local gate is decided by your team. An approval your end user decides, in your own app, belongs to a hosted action with a decidedBy: "end_user" policy. See Act for your users.

5. Let policies do the routine work

Approval policies evaluate at request time, per environment, in priority order, and the first match wins. A gate’s approval is a custom request, so a policy reaches it with matchKind: "custom" (or "any").

  • auto_approve the low-risk cases so reviewers only see what matters.
  • require_approval with N-of-M approvers for the big ones. N counts distinct deciders, and what a decider is depends on how they authenticate: an API-key decision counts per credential, a console or OAuth decision counts per user. Two keys held by the same person are two deciders, so require dashboard decisions when you mean two people.
  • auto_deny what should never happen.

Create them in the console under Controls → Policies, or from deployment code with a key holding policies:write. See Policy as code. Every governed approval records which policy version decided its routing and a readable explanation. The EU AI Act mapping says how these records relate to human-oversight obligations, and what they do not establish.

Handle errors and edge cases

What happens What you see What to do
The reviewer denies ApprovalDeniedError, with approval.status: "denied" and the note Tell the agent it was denied and why. Do not retry the same call.
The approval expires ApprovalDeniedError, with approval.status: "expired" Request again if the call is still wanted.
Your wait runs out first ApprovalPendingError. The function did not run, and the approval is still open Return to the agent and check later with approvals.get(id), or wait longer.
A policy denies it at once ApprovalDeniedError with no wait Read the decision’s policy name. Change the policy if it is wrong.
403 when requesting The key lacks approvals:write Add the scope.
403 when deciding The key lacks approvals:decide, or it requested this approval Decide with a different key, or in the console.
A retried decide Answered once Send an Idempotency-Key; the SDKs send one on every decide.

What comes with it

  • Tracing. Pass runId to the gate and the approval emits approval_wait and approval_decision spans into that run’s trace, so the wait is visible in the same timeline as the model and tool calls.
  • Events. approval.requested, approval.approved, approval.denied and approval.expired go to your webhook subscriptions.
  • The kill switch. Halting an environment blocks hosted action executions in it, including ones already approved. It does not stop a function your own process runs behind a local gate.

Next steps

Was this page helpful?