Approvals and policies
Make a risky agent call wait for a person's yes, route every call with policies, and let your team or the end user decide, with each decision recorded.
An approval holds one call until a person decides. A policy is a rule, evaluated on every call, that says whether the call runs, waits for a person, or is refused. Your team decides in the console, in Slack or through the API. For a call your agent makes for one of your users, the user can decide inside your own app.
Why a person should say yes before some calls
An agent that can act can also act wrongly: send the email to the wrong list, refund the same order twice, or follow an instruction injected into a document it read. Once the request reaches the provider, it has happened.
An approval moves the decision before the request leaves:
- Risk. A gated call is not sent until a person approves it. Anlyon holds the request, so your agent has nothing to send early. The credential that asked can never approve its own request.
- Effort. You do not build a queue, an expiry timer, notifications, a quorum, or an audit trail. You add a policy, and show the decision where your team or your users already are.
- Cost of a mistake. What the person approves is the frozen request, so what runs is exactly what they saw. For a governed action, the yes is bound to a digest of that request.
How an approval works
- Your code invokes an action with its API key, and with
Anlyon-End-Userwhen the call is for one of your users. - Anlyon evaluates the environment’s policies in order, and the action’s own
requiresApprovalflag. - If the call needs a decision, Anlyon records the invocation as
pending_approval, creates an approval, and answers202withpendingApproval: trueand theapprovalId. Nothing has been sent. The request is frozen as it was asked. - The decider is either your team (the console inbox, Slack, or the API with
approvals:decide) or the end user the call was made for (your app, through/api/v2/end-users/{endUserId}/approvals). - Approve: Anlyon runs the frozen request with the credential it holds, and the approve response carries the finished invocation. Deny: the invocation becomes
deniedand is never sent. No answer in time: the approval and the invocation becomeexpired, and nothing is sent. - The request, every vote and the decision are written as audit records, and emitted as
approval.requested,approval.approved,approval.deniedandapproval.expiredevents.
Require approval for an action
There are two ways to make an action wait for a person, and they combine:
- Set
requiresApproval: trueon the action. That is a floor: only a policy that names this action can lower it. - Add a policy whose
effectisrequire_approval. A policy can also apply to a subset of calls with a condition, such asinput.amount >= 50000.
Policies are written with an operator key that holds policies:write. That scope is never in the default set, so the agent a policy governs cannot change it. Your agent’s own key invokes the action.
import { Client } from '@anlyonhq/sdk';
// Deployment code. This key holds policies:write.
const operator = new Client({ apiKey: process.env.ANLYON_OPERATOR_KEY! });
await operator.approvalPolicies.create({
name: 'Large refunds need a person',
matchKind: 'action',
matchActionName: 'refund-order',
condition: 'input.amount >= 50000',
effect: 'require_approval',
});
// The agent. This key holds the default scopes.
const anlyon = new Client({ apiKey: process.env.ANLYON_API_KEY! });
const { data: invocation } = await anlyon.actions.invoke('refund-order', {
charge: 'ch_3P9x',
amount: 75000,
});
if (invocation!.pendingApproval) {
// 202. Nothing has been sent to the provider yet.
console.log('Waiting for a decision:', invocation!.approvalId);
}import os
from anlyon import Client
# Deployment code. This key holds policies:write.
operator = Client(api_key=os.environ["ANLYON_OPERATOR_KEY"])
operator.approval_policies.create(
name="Large refunds need a person",
match_kind="action",
match_action_name="refund-order",
condition="input.amount >= 50000",
effect="require_approval",
)
# The agent. This key holds the default scopes.
anlyon = Client(api_key=os.environ["ANLYON_API_KEY"])
invocation = anlyon.actions.invoke("refund-order", {"charge": "ch_3P9x", "amount": 75000}).data
if invocation["pendingApproval"]:
print("Waiting for a decision:", invocation["approvalId"])curl -X POST https://api.anlyon.com/api/v2/actions/refund-order/invoke \
-H "Authorization: Bearer $ANLYON_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "input": { "charge": "ch_3P9x", "amount": 75000 } }'The response is 202 Accepted. Abridged:
{
"success": true,
"data": {
"id": "inv_01JABCDEF",
"actionName": "refund-order",
"status": "pending_approval",
"pendingApproval": true,
"approvalId": "apr_01JABCDEF",
"responseStatus": null,
"body": null,
"endUserId": null
}
}
See Invoke an action and Create an approval policy for every field.
Wait for the decision in your code
approvals.waitForDecision() long-polls until the approval leaves pending or your timeout passes. A timeout is not an error: you get the approval back still pending, so always branch on status. Reading an approval needs approvals:read, which is in the default set.
import { Client } from '@anlyonhq/sdk';
const anlyon = new Client({ apiKey: process.env.ANLYON_API_KEY! });
const approval = await anlyon.approvals.waitForDecision('apr_01JABCDEF', { timeoutMs: 10 * 60_000 });
if (approval.status === 'approved') {
const { data: result } = await anlyon.actions.invocation('inv_01JABCDEF');
console.log(result!.status, result!.responseStatus);
} else if (approval.status === 'pending') {
console.log('Still waiting. Ask again later, or listen for approval.approved.');
} else {
console.log(`Not sent: the approval was ${approval.status}.`); // denied or expired
}import os
from anlyon import Client
anlyon = Client(api_key=os.environ["ANLYON_API_KEY"])
approval = anlyon.approvals.wait_for_decision("apr_01JABCDEF", timeout_seconds=600)
if approval["status"] == "approved":
result = anlyon.actions.invocation("inv_01JABCDEF").data
print(result["status"], result["responseStatus"])
elif approval["status"] == "pending":
print("Still waiting.")
else:
print(f"Not sent: the approval was {approval['status']}.")# Holds the request open for up to 55 seconds, then answers with the approval as it is.
curl "https://api.anlyon.com/api/v2/approvals/apr_01JABCDEF?waitSeconds=55" \
-H "Authorization: Bearer $ANLYON_API_KEY"waitSeconds is clamped to 0 to 55. The SDK helpers repeat the wait until your timeout, which defaults to 5 minutes. A server that should not hold a connection open can subscribe to the approval.* events instead. See Get an approval.
Decide as your team
An approval your team decides appears in the console’s Approvals inbox in real time. A member decides there, with the buttons on a Slack request, or through the API.
Deciding through the API needs a key with approvals:decide. That scope is privileged: no key gets it by default, and it should live on a separate operator key, never on the agent’s. The body takes an optional note of up to 1,000 characters.
import { Client } from '@anlyonhq/sdk';
// A separate key that holds approvals:decide.
const approver = new Client({ apiKey: process.env.ANLYON_APPROVER_KEY! });
const { data } = await approver.approvals.approve('apr_01JABCDEF', { note: 'Checked the order. OK.' });
console.log(data!.approval.status); // "approved", or "pending" while a quorum is incomplete
console.log(data!.invocation?.status); // the finished call, once the approval is final
await approver.approvals.deny('apr_01JABCDEF', { note: 'Duplicate request.' });import os
from anlyon import Client
approver = Client(api_key=os.environ["ANLYON_APPROVER_KEY"])
result = approver.approvals.approve("apr_01JABCDEF", note="Checked the order. OK.").data
print(result["approval"]["status"])
approver.approvals.deny("apr_01JABCDEF", note="Duplicate request.")curl -X POST https://api.anlyon.com/api/v2/approvals/apr_01JABCDEF/approve \
-H "Authorization: Bearer $ANLYON_APPROVER_KEY" \
-H "Content-Type: application/json" \
-d '{ "note": "Checked the order. OK." }'The answer is { approval, selfApproved, invocation }. invocation is present when the approval finalized an action call, and holds its outcome. See Approve a request and Deny a request. To list what is waiting, call GET /api/v2/approvals?status=pending (List approvals).
Let the end user decide in your app
When your agent acts in one of your users’ own accounts, the right person to approve “send this email from my Gmail” is often that user. Give the policy decidedBy: "end_user":
await operator.approvalPolicies.create({
name: 'Users approve their own sends',
matchKind: 'action',
matchActionName: 'gmail-send',
effect: 'require_approval',
decidedBy: 'end_user',
});
What changes for such an approval:
- It needs an end user.
decidedBy: "end_user"applies to calls made with theAnlyon-End-Userheader. A call made for nobody is always decided by your team. - One yes is enough. The end user decides alone, so a
requiredApprovalson the policy does not apply to them. - Your team does not see it to decide. It is not in the console inbox, not posted to Slack, and not reviewed by Anlyon Vigil. The team’s
/approveand/denyroutes answer404for it. Your team can list it read-only withGET /api/v2/approvals?decider=end_user, which needsend-users:approvalsas well asapprovals:read. - Your app shows it. Your server lists the user’s pending approvals and relays their answer. Both routes need a key with
end-users:approvals, a privileged scope.
When no policy matches a call made for a user, the workspace default decides who answers. Unless you change it, that is your team.
import { Client } from '@anlyonhq/sdk';
// Your server. This key holds end-users:approvals.
const anlyon = new Client({ apiKey: process.env.ANLYON_API_KEY! });
// What the signed-in user still has to decide.
const { data: pending } = await anlyon.endUsers.approvals.list(session.user.id, { status: 'pending' });
// The user clicked Approve in your UI.
const { data } = await anlyon.endUsers.approvals.decide(session.user.id, pending![0].id, {
decision: 'approve',
});
console.log(data!.approval.status, data!.invocation?.status);import os
from anlyon import Client
anlyon = Client(api_key=os.environ["ANLYON_API_KEY"])
pending = anlyon.end_users.approvals.list(user_id, status="pending").data
result = anlyon.end_users.approvals.decide(user_id, pending[0]["id"], decision="deny", reason="Not this one")
print(result.data["approval"]["status"])curl "https://api.anlyon.com/api/v2/end-users/user_42/approvals?status=pending" \
-H "Authorization: Bearer $ANLYON_API_KEY" \
-H "Anlyon-End-User: user_42"
curl -X POST https://api.anlyon.com/api/v2/end-users/user_42/approvals/apr_01JABCDEF/decide \
-H "Authorization: Bearer $ANLYON_API_KEY" \
-H "Anlyon-End-User: user_42" \
-H "Content-Type: application/json" \
-d '{ "decision": "approve" }'decision is approve or deny. reason, up to 1,000 characters, is recorded as the decision note. Approving runs the parked call, and the answer carries { approval, invocation }. Always take the user id from your own session, never from the request, so one user cannot decide another’s approval. An approval of a different end user answers 404.
To skip building these screens, the prebuilt React components list and decide a user’s approvals from the browser with a short-lived session token. The Act for your users guide builds the same screen by hand. See List an end user’s approvals and Decide an end user’s approval.
Ask for a decision that is not an action call
Some decisions are not one HTTP request: “ship the release?”, “send the contract?”. Create a custom approval and wait for it. It needs approvals:write, which is in the default set, and answers 201.
import { Client } from '@anlyonhq/sdk';
const anlyon = new Client({ apiKey: process.env.ANLYON_API_KEY! });
const { data } = await anlyon.approvals.request({
title: 'Send the contract to Acme?',
description: 'The draft is ready. Sending cannot be undone.',
payload: { draftId: 'doc_9' },
expiresInSeconds: 3600,
});
const decided = await anlyon.approvals.waitForDecision(data!.id);
if (decided.status === 'approved') {
// Your code does the work.
}import os
from anlyon import Client
anlyon = Client(api_key=os.environ["ANLYON_API_KEY"])
approval = anlyon.approvals.request(
title="Send the contract to Acme?",
description="The draft is ready. Sending cannot be undone.",
payload={"draftId": "doc_9"},
expires_in_seconds=3600,
).data
decided = anlyon.approvals.wait_for_decision(approval["id"])curl -X POST https://api.anlyon.com/api/v2/approvals \
-H "Authorization: Bearer $ANLYON_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "title": "Send the contract to Acme?", "payload": { "draftId": "doc_9" }, "expiresInSeconds": 3600 }'title is required (up to 200 characters), description takes up to 2,000, and expiresInSeconds takes 60 to 2,592,000 (30 days). Without it, the workspace’s approval window applies. Pass runId to put the wait and the decision on that run’s trace. See Request an approval.
Gate your own function
approvals.gate() wraps a function: each call creates an approval, waits, and calls through only on approve.
const guardedRefund = anlyon.approvals.gate(
{ title: 'Refund a customer?', timeoutMs: 10 * 60_000 },
refund,
);
await guardedRefund('ord_42', 129.99); // runs only after a person approves
A denied or expired request throws ApprovalDeniedError. A wait that runs out throws ApprovalPendingError and leaves the approval open. In Python, @client.approvals.gate(title=..., timeout_seconds=600) decorates the function and raises the same errors.
Be precise about what this gives you. The wrapper waits for a decision before calling your function, and it depends on your code going through the wrapper. Your credential stays in your process, so Anlyon cannot attest what your function did. You get the decision and the record, not credential isolation. See Local approval gates.
Route calls with policies
A policy turns “does this need a person?” into a rule that runs on every call in its environment:
effect |
What happens |
|---|---|
auto_approve |
The call runs with no person involved. To clear an action’s own requiresApproval flag, the policy must name that action with matchActionName. A catch-all auto_approve cannot disarm every gated action at once. |
require_approval |
The call waits for requiredApprovals distinct approvers (1 to 20), or for the end user with decidedBy: "end_user". |
auto_deny |
The call is refused and never sent. An auto_deny for every action or every request needs acknowledgeBroadScope: true. |
- Order is deterministic. Policies are evaluated by ascending
priority, then creation time, then id. The first match governs. - No match means no gate, unless the action has
requiresApproval. An unflagged action that no policy matches runs inline. - Every policy says what it applies to.
matchKindisaction(one action withmatchActionName, or every action),customorany. Nothing is inferred from the name. - A condition that cannot be evaluated requires approval. It never skips a policy and never auto-denies on an error.
- The decision is recorded. Each approval keeps
matchedPolicyId,matchedPolicyVersionand apolicyExplanation. An automatic denial is written onto the invocation as adecision, so the invocation explains itself even after the policy is edited.
Manage policies in the console under Approval Policies, or from code: see Policy as code for conditions, policy files, testing and version history.
Know who can decide, and the self-approval rule
These rules are enforced by the server on every decision:
- A credential never decides what it requested. The API key that requested an approval cannot decide it. An OAuth app cannot decide what it requested for the same person. No scope and no policy relaxes this. Automation that should not need a person is an
auto_approvepolicy. - A person never decides what their own agent asked for. That covers a request they made in the console, one an app made for them, and one made with an API key they created. The answer is
403 SELF_APPROVAL_NOT_ALLOWED. A second approver, or a separate approver key, must decide. - One exception for a team of one. When the requester is the only member who can decide approvals in that environment, they may decide directly, in the console or with a Slack button, never through an app or a key. The vote is marked
selfApproved: trueand shown as Self-approved (only approver in this environment) in the console, in Slack and in the audit record. Once a second member can decide there, the exception ends. - A person needs a deciding role in the approval’s environment: admin, member or approver. A viewer cannot decide. A per-environment role can grant or withhold it in one environment.
Each approval records who decided in decisionOrigin: human, policy, system (it expired), assistant (an Anlyon Vigil approval), or unknown for old decisions whose evidence does not settle it. GET /api/v2/approvals?decisionOrigin=automated lists the decisions nobody had to make. In the console, Approver history and Automated decisions are separate views from the inbox.
Set how long a request waits
- An action’s approval waits for the workspace’s approval window: 24 hours unless an admin changes it in Workspace defaults, from 1 to 168 hours. A governed action’s approval never outlives its bound preview.
- A custom approval waits
expiresInSecondswhen you pass it, and the window otherwise.
When nobody answers in time, the approval becomes expired with decisionOrigin: "system", its parked invocation becomes expired, and nothing is sent. Anlyon emits approval.expired, and your team gets an approval_expired alert when the workspace default says so.
Hear about requests without polling
A new workspace’s approval alerts go to the in-app inbox with no setup. Email alerts are included during Early Beta Access, up to 500 emails per workspace per UTC month. Once connected, alerts also go to Slack, Discord and a notification webhook. Each links to the approval. These alerts only notify: replying to one decides nothing. To decide from Slack, set up Slack approvals. Configure channels in Settings → Notifications; see Notifications.
Approvals for end users are not sent to your team’s channels. Your app hears about them from the approval.requested event, which carries endUserId and decider: "end_user".
Fix the errors you will meet
| Status and code | When | What to do |
|---|---|---|
202, pendingApproval: true |
The call needs a decision. Not an error. | Wait for the decision, or show it to the user. |
403 AUTHORIZATION_ERROR |
The key lacks the scope the route needs (approvals:decide, end-users:approvals, policies:write), a key decides its own request, or the person’s role cannot decide. The message names the reason. |
Use a separate key with the scope, or a member with a deciding role. |
403 SELF_APPROVAL_NOT_ALLOWED |
A person decides a request they, their app or their key made. | Have a second approver decide. |
404 APPROVAL_NOT_FOUND |
The id is wrong, belongs to another environment, is an end user’s approval sent to a team route, or belongs to another end user. | Check the key’s environment and which route the approval’s decider needs. |
409 APPROVAL_ALREADY_DECIDED |
The approval is already approved, denied or expired, or this decider already voted. | Read the approval again; do not retry the decision. |
402 QUOTA_EXCEEDED |
Creating an approval would pass the plan’s cap on pending approvals (200 during Early Beta Access). | Decide or let pending approvals expire. |
402 PAYMENT_REQUIRED |
The workspace has no plan, so an approval that would resume a parked call does not run it. | Choose a plan in Settings → Plan & billing. |
400 END_USER_HEADER_MISMATCH |
Anlyon-End-User names a different user than the path. |
Send the same id in both, or leave the header out. |
400 END_USER_REQUIRED |
A key created with Require an end user sent no Anlyon-End-User. |
Send the header. |
An approved call can still fail to run. If the environment is halted, the invocation is recorded as failed with the halt as its error. A governed action whose request no longer matches its bound preview is refused with 409 PREVIEW_MISMATCH. See When approval expires or changes.
Related
- Policy as code: conditions, policy files, evaluation without executing, version history.
- Slack approvals: decide with buttons in a Slack channel.
- Workspace defaults: who decides an unmatched user’s call, and the approval window.
- Anlyon Vigil: suggestions on the team’s queue, and auto-approve inside limits.
- Bound approvals: what an approval of a governed action is bound to.
- Workspace and end-user connections: acting in your users’ own accounts.
- Audit records: every request, vote and decision.
- Local approval gates: the hands-on guide for
gate().

