Arcezia
Arcezia · Developer Guide

Check an agent’s action before it runs.

Your agent describes the tool call it is about to make. Arcezia answers ALLOW, REVIEW or BLOCK, with a signed receipt. The same input always gets the same answer. Under heavy load a call may instead be answered ‘not decided, try again’; it is never given a different verdict. This guide takes a new key to all three answers, then covers everything an integration needs.

S

Setup recipes

Three ways to connect, one recipe each. Copy a recipe, set your key, run it top to bottom. Change nothing else. Every step says what it prints, so you know at once if a step went wrong. Quickstart below explains each step in more detail.

Before any recipe

  1. Python 3.10 or newer. Install: pip install -U arcezia cryptography requests
  2. Get a key: sign in at app.arcezia.com, Keys page, issue a key. It has the owner role, which setup needs.
  3. Put it in your shell: export ARCEZIA_API_KEY="<YOUR_KEY>"
  4. A key starting with ar_test_: also run export ARCEZIA_ENV=production. Without it, more calls come back ALLOW than the recipes show.
  5. Work in an empty folder. The recipes write principal_key.pem there: your private signing key. Keep it, and never put it where the agent can read it.

Recipe 1: Python SDK

Save as arcezia_setup.py, then run python arcezia_setup.py. Safe to run again.

import os

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey

import arcezia

# 1. Your signing key (made once, then reused).
PATH = "principal_key.pem"
if not os.path.exists(PATH):
    with open(PATH, "wb") as f:
        f.write(Ed25519PrivateKey.generate().private_bytes(
            serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
            serialization.NoEncryption()))
private_key = serialization.load_pem_private_key(open(PATH, "rb").read(), password=None)

az = arcezia.Arcezia(task="look up orders", signing_key=private_key)
az.register_token_key(private_key.public_key())
print("1 key registered:", az.token_key_status()["registered"])

# 2. A contract for your SQL tool (template: SQL reads).
for c in az.contracts():
    if c["name"] == "setup":
        az.delete_contract("setup")
contract = az.register_contract({"tools": {"execute_sql": {
    "pack": "database_ops",
    "not_present": ["outbound", "trust_boundary_crossing", "sensitive_data"],
}}}, name="setup")
SQL = contract["domains"]["execute_sql"]
print("2 contract domain:", SQL)

# 3. A signed session: what this run may touch.
az.start_session(capability_envelope={
    "allowed_domains": [SQL],
    "allowed_action_types": ["execute_sql"],
    "resource_scope": ["orders", "42"],
})
print("3 session:", az.session_id)


def check(sql, domain=SQL):
    cert = az.verify(action_type="execute_sql", action_description=sql, domain=domain)
    return cert.verdict, cert.release or cert.reason


# 4. The three answers.
print("4a", check("SELECT status FROM orders WHERE id = 42"))
print("4b", check("SELECT * FROM orders"))
print("4c", check("SELECT COUNT(*) FROM orders", domain="database_ops"))

It prints (the ids differ):

1 key registered: True
2 contract domain: <a domain id>
3 session: <a session id>
4a ('ALLOW', [])
4b ('REVIEW', ['approval:user'])
4c ('BLOCK', ['contract:tool_pairing'])

Next: in your agent, call az.verify(...) before each tool call and run the tool only when cert.allow is true. To take a held call to ALLOW with a person's approval, see Quickstart step 7.

Recipe 2: Claude Code hook

Run these in your own terminal, not from Claude Code.

pip install -U arcezia
arcezia-hook install

Prints Arcezia PreToolUse hook installed → ~/.claude/settings.json, after a warning that the key has the owner or admin role (expected: see Framework hookups). Then save this as arcezia_hook_setup.py and run python arcezia_hook_setup.py:

import json, os

import arcezia

NEVER = ["outbound", "trust_boundary_crossing", "sensitive_data", "mass_scope", "persistent_mutation",
         "irreversible", "recursive", "force_push", "privilege_escalation", "permission_change"]

az = arcezia.Arcezia(task="hook setup")
for c in az.contracts():
    if c["name"] == "hook":
        az.delete_contract("hook")
contract = az.register_contract({"tools": {
    "git_status":   {"pack": "filesystem_ops", "command_line": True, "commands": {"git status": NEVER}},
    "git_log":      {"pack": "filesystem_ops", "command_line": True, "commands": {"git log": NEVER}},
    "shell_search": {"pack": "filesystem_ops", "command_line": True, "commands": {"ls": NEVER}},
}}, name="hook")

path = os.path.expanduser("~/.claude/arcezia.json")
os.makedirs(os.path.dirname(path), exist_ok=True)
json.dump({"capability_envelope": {
    "allowed_domains": sorted(set(contract["domains"].values())) + ["filesystem_ops", "agent_action"],
    "allowed_action_types": ["git_status", "git_log", "shell_search", "shell_read"],
}}, open(path, "w"), indent=1)
print("hook envelope written:", path)

It prints hook envelope written: <your home>/.claude/arcezia.json. Test the hook from a git repository folder, without starting Claude Code. Each line is one real check:

for c in "git status" "cat README.md" "git push origin main"; do
  printf '{"session_id":"setup","cwd":"%s","hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"%s"}}' "$PWD" "$c" | arcezia-hook hook
  echo
done

Each answer is one JSON line. Look at permissionDecision:

CommandpermissionDecisionWhy
git statusallow (ALLOW)Your contract says it never changes or sends anything.
cat README.mdask (REVIEW)A file read can expose a secret. The reason names what would release it.
git push origin maindeny (BLOCK)git_push is not in your envelope's allowed_action_types.

Then make a missing or crashed hook block calls instead of letting them through. In ~/.claude/settings.json, add "onFailure": "block" to the Arcezia PreToolUse entry (Claude Code 2.1.295 or later). Without it, a hook that is missing or crashes lets every call run. Check that its "command" starts with a full path to arcezia-hook, not a bare name: install writes the one it finds on your PATH.

{"type": "command", "command": "/home/you/.venv/bin/arcezia-hook hook", "timeout": 60, "onFailure": "block"}

Start Claude Code in the same shell (it needs ARCEZIA_API_KEY, and ARCEZIA_ENV for a test key). Add each tool you want to run without a question to the contract and to allowed_action_types; Framework hookups lists the tool names.

Recipe 3: raw HTTP

Any language can call the API. Only the signing needs code; this recipe uses a small Python signer for it. Save the signer as arcezia_sign.py:

import base64, json, os, secrets, sys, time

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey

PATH = "principal_key.pem"
if not os.path.exists(PATH):
    with open(PATH, "wb") as f:
        f.write(Ed25519PrivateKey.generate().private_bytes(
            serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()))
key = serialization.load_pem_private_key(open(PATH, "rb").read(), password=None)
b64 = lambda b: base64.urlsafe_b64encode(b).decode().rstrip("=")

if sys.argv[1] == "pubkey":          # python arcezia_sign.py pubkey
    print(b64(key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)))
elif sys.argv[1] == "envelope":      # python arcezia_sign.py envelope <account id> '<envelope JSON>'
    claims = {"acct": int(sys.argv[2]), "sid": None, "typ": "envelope", "jti": secrets.token_urlsafe(16),
              "exp": int(time.time()) + 300, "env": json.loads(sys.argv[3])}
    payload = b64(json.dumps(claims, separators=(",", ":")).encode())
    print(payload + "." + b64(key.sign(payload.encode("ascii"))))

Then save this as arcezia_setup.sh in the same folder and run sh arcezia_setup.sh:

set -e
API="${ARCEZIA_API_URL:-https://api.arcezia.com}"
AUTH="Authorization: Bearer $ARCEZIA_API_KEY"
J="Content-Type: application/json"

# 1. Register your public key (safe to repeat with the same key).
curl -s -X POST "$API/v1/account/token_key" -H "$AUTH" -H "$J" \
  -d "{\"public_key\": \"$(python3 arcezia_sign.py pubkey)\"}"; echo
ACCOUNT=$(curl -s "$API/v1/account/token_key" -H "$AUTH" | python3 -c 'import json,sys; print(json.load(sys.stdin)["api_key_id"])')
echo "account: $ACCOUNT"

# 2. A contract for your SQL tool (template: SQL reads).
curl -s -X DELETE "$API/v1/contracts/setup" -H "$AUTH" > /dev/null
SQL=$(curl -s -X POST "$API/v1/contracts" -H "$AUTH" -H "$J" \
  -d '{"name": "setup", "contract": {"tools": {"execute_sql": {"pack": "database_ops", "not_present": ["outbound", "trust_boundary_crossing", "sensitive_data"]}}}}' \
  | python3 -c 'import json,sys; print(json.load(sys.stdin)["domains"]["execute_sql"])')
echo "domain: $SQL"

# 3. A signed session.
TOKEN=$(python3 arcezia_sign.py envelope "$ACCOUNT" "{\"allowed_domains\": [\"$SQL\"], \"allowed_action_types\": [\"execute_sql\"], \"resource_scope\": [\"orders\", \"42\"]}")
SID=$(curl -s -X POST "$API/v1/session" -H "$AUTH" -H "$J" \
  -d "{\"task\": \"look up orders\", \"capability_envelope_token\": \"$TOKEN\"}" \
  | python3 -c 'import json,sys; print(json.load(sys.stdin)["session_id"])')
echo "session: $SID"

# 4. The three answers.
check() {
  curl -s -X POST "$API/v1/verify" -H "$AUTH" -H "$J" \
    -d "{\"task\": \"look up orders\", \"session_id\": \"$SID\", \"action_type\": \"execute_sql\", \"domain\": \"$2\", \"action_description\": \"$1\"}" \
    | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d["verdict"], d.get("release") or d.get("reason") or [])'
}
check "SELECT status FROM orders WHERE id = 42" "$SQL"
check "SELECT * FROM orders" "$SQL"
check "SELECT COUNT(*) FROM orders" "database_ops"

It prints (the ids differ):

{"ok":true,"token_verification_required":true}
account: <a number>
domain: <a domain id>
session: <a session id>
ALLOW []
REVIEW ['approval:user']
BLOCK ['contract:tool_pairing']

Raw HTTP checks always give live answers, whatever the key's prefix. A signed envelope token opens one session and is valid for 5 minutes: sign a new one for each session.

Contract templates

Replace only what is in <ANGLE_BRACKETS>. Upload with az.register_contract(template, name="<NAME>") (or POST /v1/contracts with {"name", "contract"}), then use contract["domains"]["<TOOL>"] as the domain for that tool and put it in your session's allowed_domains.

SQL reads (Free plan)

{"tools": {"<YOUR_SQL_TOOL>": {
    "pack": "database_ops",
    "not_present": ["outbound", "trust_boundary_crossing", "sensitive_data"]}}}

Open the session with a signed resource_scope naming the tables and record ids the job reads. A keyed read of a named table: ALLOW. A read of a whole table or of a table not named: REVIEW. Writes: REVIEW until a person's approval and your backup check (Quickstart step 7).

Coding shell, read-only commands (Free plan; for the Claude Code hook)

NEVER = ["outbound", "trust_boundary_crossing", "sensitive_data", "mass_scope", "persistent_mutation",
         "irreversible", "recursive", "force_push", "privilege_escalation", "permission_change"]
{"tools": {
    "git_status":   {"pack": "filesystem_ops", "command_line": True, "commands": {"git status": NEVER}},
    "git_log":      {"pack": "filesystem_ops", "command_line": True, "commands": {"git log": NEVER}},
    "git_diff":     {"pack": "filesystem_ops", "command_line": True, "commands": {"git diff": NEVER}},
    "shell_search": {"pack": "filesystem_ops", "command_line": True, "commands": {"ls": NEVER}}}}

Each listed command: ALLOW. Put each tool name in the hook envelope's allowed_action_types. For commands that write or delete, use the Worked example: a coding agent's shell in Contracts.

Payments (Business plan)

{"approval_must_bind": True, "tools": {"<YOUR_PAYMENT_TOOL>": {
    "pack": "payment_ops",
    "not_present": ["mass_scope"],
    "present": ["moves_funds"],
    "arguments": {"amount": ["<AMOUNT_ARGUMENT>"], "recipient": ["<PAYEE_ARGUMENT>"]}}}}

Open the session with "max_amount": <LARGEST_AMOUNT> in the envelope and send the payment's arguments as action_parameters. A payment within the limit: REVIEW, naming your payment checks (check:aml_check_passed, check:sanctioned_entity_check_passed, ...) and approval:user. Above the limit: BLOCK scope:max_amount; no approval lifts it.

Common setup errors

You seeCauseFix
No API key provided. Pass api_key= or set ARCEZIA_API_KEY.The key is not in this shell.export ARCEZIA_API_KEY="<YOUR_KEY>" in the same shell, then run again.
ArceziaAuthError or HTTP 401The key is wrong or was deleted.Copy the key again from the Keys page.
ArceziaUpgradeRequired or HTTP 402 upgrade_requiredYour plan does not include that domain (for example payment_ops on Free).Use database_ops, filesystem_ops or agent_action, or change the plan.
BLOCK ['contract:tool_pairing']The tool was checked under a domain other than its contract's.Pass domain=contract["domains"]["<TOOL>"].
ContractRefused, tool_covered_by_another_contractAnother contract already names this tool.Delete it (az.delete_contract("<NAME>")), or upload under the same name.
SigningKeyConflictA different signing key is registered on this account.Run from the folder holding the first principal_key.pem, or pass replace=True on purpose.
REVIEW with release_without_person ['scope:resource_scope']The envelope was not signed, so its resource_scope does not count.Create the client with signing_key=private_key (raw HTTP: send capability_envelope_token).
ALLOW where a recipe shows REVIEWA test key in development mode.export ARCEZIA_ENV=production
HTTP 409 session_expired, or 409 on an envelopeThe session has ended, or already has an envelope.Open a new session.
HTTP 400 ... token rejected: ... or ... token has already been used. (an approval says Authorization token, a signed envelope says Capability envelope token)The token was signed by another key, has expired (an approval lasts 15 minutes at most), or was used before. A signed envelope opens one session only.Sign a new one with the registered key.
Hook answers deny: outside your capability envelopeThe tool name or the contract's domain is missing from ~/.claude/arcezia.json.Add the tool to allowed_action_types and contract["domains"][tool] to allowed_domains.
arcezia grant-workspace: no terminal to ask for a key fileIt was run from a script or by the agent.Run it yourself in a terminal, or use mint_workspace_grant (Framework hookups).
HTTP 400 invalid_probe: "This check cannot be registered."The name is not one a check can be registered for.Use the name exactly as it appears after check: in a release list, or a fact your own contract defines.
HTTP 429, ArceziaRateLimitErrorToo many calls in a short time.Wait retry_after seconds, then run again.

Setup, as data

The same steps for a coding assistant or script to follow. Also at /llms.txt.

{"arcezia_setup": {
  "install": "pip install -U arcezia cryptography requests",
  "env": {"ARCEZIA_API_KEY": "<YOUR_KEY> (owner role, from the Keys page)",
          "ARCEZIA_ENV": "production (only for ar_test_ keys)"},
  "steps": [
    {"do": "make an Ed25519 key pair; register the public half", "sdk": "az.register_token_key(public_key)",
     "http": "POST /v1/account/token_key {public_key}", "expect": "ok: true; GET /v1/account/token_key then shows registered: true"},
    {"do": "upload a contract per tool", "sdk": "az.register_contract(contract, name=...)",
     "http": "POST /v1/contracts {name, contract}", "expect": "domains[tool] = the domain to use"},
    {"do": "open a session with a signed envelope incl. resource_scope",
     "sdk": "Arcezia(signing_key=private_key).start_session(capability_envelope=...)",
     "http": "POST /v1/session {task, capability_envelope_token}", "expect": "session_id"},
    {"do": "check each tool call before it runs", "sdk": "az.verify(action_type, action_description, domain)",
     "http": "POST /v1/verify {task, session_id, action_type, domain, action_description}",
     "expect": "verdict ALLOW | REVIEW (release) | BLOCK (reason)"},
    {"do": "run the tool only on ALLOW", "expect": "REVIEW: send release to a person; BLOCK: stop"}],
  "hook": ["pip install -U arcezia", "arcezia-hook install",
           "in ~/.claude/settings.json add \"onFailure\": \"block\" to the PreToolUse entry; keep its command a full path",
           "write ~/.claude/arcezia.json {capability_envelope: {allowed_domains, allowed_action_types}}"],
  "first_answers": {"keyed read in the signed scope": "ALLOW",
                    "whole-table read": "REVIEW ['approval:user']",
                    "covered tool under another domain": "BLOCK ['contract:tool_pairing']"}}}
00

Quickstart

Install the package, get a key, and see all three answers on your own account: ALLOW, REVIEW and BLOCK. Then take one write all the way to ALLOW. Every answer shown here is what the service returns for exactly this code.

1. Install

Python 3.10 or newer. cryptography makes and uses your signing key; requests makes the few raw HTTP calls.

pip install -U arcezia cryptography requests
python -c "import arcezia; print(arcezia.__version__)"   # 1.0.7 or newer

2. Get a key

Sign in at app.arcezia.com and issue a key on the Keys page. It is shown once. It has the owner role, which steps 3, 4 and 7 need.

export ARCEZIA_API_KEY="ar_live_your_key_here"
Key starts withWhat it does
ar_live_Production. Every answer is the real answer. This guide shows these answers.
ar_test_For trying things out. By default the SDK runs a test key in development mode: checks that need your production systems are relaxed, and the session envelope does not have to grant each effect a call has. So more calls come back ALLOW than on a live key. Approval, fabrication and data-leak checks stay strict. To see what a live key would get, set ARCEZIA_ENV=production (or pass mode="production" to Arcezia(...)).

NEVER DECIDE PRODUCTION ACTIONS WITH A TEST KEY. A test key in development mode is more lenient on purpose. Use a live key, or a test key with ARCEZIA_ENV=production, before you trust an ALLOW.

3. Your signing key

You, the person or system in charge of the agent, hold an Ed25519 key pair. The public half is registered with Arcezia once. The private half signs two things the agent must never be able to forge: the limits of each session (step 5) and a person's approval (step 7). Keep the private half in your backend, never in the agent's process or anywhere the agent can read. This code makes it once and reuses it after.

import os
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey

PATH = "principal_key.pem"   # keep it in your backend, never where the agent can read it
if os.path.exists(PATH):
    private_key = serialization.load_pem_private_key(open(PATH, "rb").read(), password=None)
else:
    private_key = Ed25519PrivateKey.generate()
    with open(PATH, "wb") as f:
        f.write(private_key.private_bytes(serialization.Encoding.PEM,
                                          serialization.PrivateFormat.PKCS8,
                                          serialization.NoEncryption()))

import arcezia

az = arcezia.Arcezia(task="look up orders and mark order 42 as shipped",
                     signing_key=private_key)      # sessions this client opens are signed by you
az.register_token_key(private_key.public_key())     # once per account; safe to repeat with the same key
KEY_ID = az.token_key_status()["api_key_id"]        # your numeric account id, used in step 7

Registering a different key later raises SigningKeyConflict unless you pass replace=True. After a replacement, approvals signed with the old key no longer count.

4. Write a contract for your SQL tool

A contract says, per tool, which effects that tool never has. You write it once per key, and only for effects that are true of every call the tool can make. Anything the statement itself shows still counts, whatever the contract says.

# One contract per tool. Remove an earlier one that names the same tool.
for c in az.contracts():
    if c["name"] == "quickstart":
        az.delete_contract("quickstart")

contract = az.register_contract({
    "tools": {"execute_sql": {
        "pack": "database_ops",   # keep the built-in database rules for this tool
        "not_present": ["outbound", "trust_boundary_crossing", "sensitive_data"],
    }},
}, name="quickstart")

SQL = contract["domains"]["execute_sql"]   # the domain to use for execute_sql from now on

TWO THINGS THAT CATCH EVERYONE. Always verify the tool under SQL, the domain the contract returned. Verifying execute_sql under database_ops is refused with BLOCK, so a covered tool can never skip its contract. So is leaving domain out of az.verify(...): the SDK then sends agent_action. (Over raw HTTP, a request with no domain field at all is checked under the contract's domain.) A tool can be in only one contract. Registering a second contract that names execute_sql fails with ContractRefused; delete the old contract first with az.delete_contract(name). Uploading again under the same name replaces it.

5. Open a signed session and check some reads

A session is one agent run. Its envelope says what the run may do at most: which domains and tools, and, in resource_scope, exactly which tables, records, files, folders, addresses and hosts this job acts on. Because the client has your signing_key, the envelope is sent signed by you. Keep this client and this session for the rest of the quickstart.

session = az.start_session(capability_envelope={
    "allowed_domains": [SQL],
    "allowed_action_types": ["execute_sql"],
    "resource_scope": ["orders", "42"],    # what this job acts on: the orders table, record 42
})

def check(sql):
    cert = az.verify(action_type="execute_sql", action_description=sql, domain=SQL)
    print(cert.verdict, cert.release, "|", sql)
    return cert

check("SELECT COUNT(*) FROM orders")                   # ALLOW
check("SELECT status FROM orders WHERE id = 42")       # ALLOW
check("SELECT * FROM orders")                          # REVIEW ['approval:user']: every row
check("SELECT salary FROM payroll WHERE id = 7")       # REVIEW ['approval:user']: not in the scope

# A two-step plan, checked as a whole before any step runs:
plan = az.verify_chain({"steps": [
    {"id": "count",  "action_type": "execute_sql", "domain": SQL,
     "action_description": "SELECT COUNT(*) FROM orders"},
    {"id": "lookup", "action_type": "execute_sql", "domain": SQL,
     "action_description": "SELECT status FROM orders WHERE id = 42"},
]})
print(plan.overall_verdict, plan.safe)                 # SAFE True
ReadAnswerWhy
SELECT COUNT(*) FROM ordersALLOWA count returns no rows, and orders is in the signed scope.
SELECT status FROM orders WHERE id = 42ALLOWA keyed read of one record in the scope.
SELECT * FROM ordersREVIEWIt returns the whole table. It waits for a person.
SELECT salary FROM payroll WHERE id = 7REVIEWpayroll is not in the scope you signed. It waits for a person. release_without_person is empty: a signed scope is fixed for the session, so the only route without a person is a new session whose signed scope names payroll (and 7).

Why the scope matters. The task text is never what clears a call. "Look up orders" names the orders table in English, but the same task in Spanish or Hindi does not, and an answer must not depend on the language the task was written in. The scope you sign is the same in every language. It counts only when signed: the same envelope sent without your signature is held.

plain = arcezia.Arcezia(task="look up orders and mark order 42 as shipped")   # no signing_key
plain.start_session(capability_envelope={"allowed_domains": [SQL],
                                         "allowed_action_types": ["execute_sql"],
                                         "resource_scope": ["orders", "42"]})
cert = plain.verify(action_type="execute_sql", action_description="SELECT COUNT(*) FROM orders",
                    domain=SQL)
print(cert.verdict, cert.release, cert.release_without_person)
# REVIEW ['approval:user'] ['scope:resource_scope']

release_without_person names scope:resource_scope: sign the scope and the read clears without a person.

6. See a BLOCK

Two ways on a fresh key. The first is the mistake from step 4: the right tool under the wrong domain. The second is a limit you set yourself. Use a second client for it, so the session you opened in step 5 stays as it is.

cert = az.verify(action_type="execute_sql",
                 action_description="SELECT COUNT(*) FROM orders",
                 domain="database_ops")
print(cert.verdict, cert.reason)        # BLOCK ['contract:tool_pairing']: wrong domain for a covered tool

strict = arcezia.Arcezia(task="read-only reporting", signing_key=private_key)
strict.start_session(capability_envelope={
    "allowed_domains": [SQL],
    "allowed_action_types": ["execute_sql"],
    "structural_authority": {"irreversible": False},   # nothing permanent, ever
})
cert = strict.verify(action_type="execute_sql",
                     action_description="TRUNCATE orders", domain=SQL)
print(cert.verdict, cert.reason)        # BLOCK ['ceiling:irreversible']: your envelope forbids it

7. Take a write to ALLOW

A write changes stored data, so it needs two things only you can supply: a person's signed approval, bound to this exact call, and your own system confirming a recent backup.

7a. Connect your backup check. Your check is a small HTTPS endpoint of yours that answers one question: is there a recent, restorable backup? Register it on database_ops; it answers for your contract's domain too. Put the endpoint's public URL in webhook_url. The registration returns signing_key_v2 once: start your endpoint with it (its code is on Connect your own check). For a local test, expose it with a tunnel such as cloudflared. Until the check is registered and answering, the write below also lists check:verified_recent_backup: a registered check that times out, fails or answers that it cannot tell keeps the call held, just like no check at all.

import requests

API = os.environ.get("ARCEZIA_API_URL", "https://api.arcezia.com")
r = requests.post(
    f"{API}/v1/probes",
    headers={"Authorization": f"Bearer {os.environ['ARCEZIA_API_KEY']}"},
    json={"domain": "database_ops",
          "constraint_name": "verified_recent_backup",
          "webhook_url": "https://checks.example.com/arcezia",
          "secret": "at-least-16-random-characters"},
)
r.raise_for_status()
print(r.json()["signing_key_v2"])   # shown once: your endpoint verifies requests with it

7b. Ask, approve, ask again. The first check comes back REVIEW and says what would release it. Your backend signs both approvals for this exact call, and the same call is checked again in the same session.

from arcezia.signing import mint_token

sql = "UPDATE orders SET status = 'shipped' WHERE id = 42"
cert = check(sql)                        # REVIEW ['approval:production', 'approval:user']

# In your backend, after a person clicks Approve:
user_ok = mint_token(private_key, api_key_id=KEY_ID, token_type="user",
                     session_id=az.session_id, action=cert.action_binding)
prod_ok = mint_token(private_key, api_key_id=KEY_ID, token_type="production",
                     session_id=az.session_id, action=cert.action_binding)

az.authorize(user_ok).authorize_production(prod_ok)
cert = check(sql)                        # ALLOW
if cert.allow:
    run_sql(sql)                         # your own database call; cert.credential is its one-time pass

action=cert.action_binding ties each approval to this one call: same tool, same domain, same statement. A different statement needs a new approval, and so does running the same statement again: an approval covers one execution. An approval signed by any other key is refused when you attach it.

8. End the session

requests.delete(f"{API}/v1/session/{az.session_id}",
                headers={"Authorization": f"Bearer {os.environ['ARCEZIA_API_KEY']}"})

THAT IS THE WHOLE LOOP. Describe the real action, act only on ALLOW. A REVIEW tells you what would release it, in cert.release. A BLOCK tells you why, in cert.reason. Handling the answers covers every value.

01

Handling the answers

Every check returns ALLOW, REVIEW or BLOCK. Only ALLOW may reach the tool. A REVIEW names what would release it. A BLOCK names why.

cert = az.verify(action_type=tool, action_description=desc, domain=domain)

if cert.allow:
    run_tool(credential=cert.credential)
elif cert.review:
    for item in cert.release:            # e.g. "approval:user", "check:verified_recent_backup"
        handle(item)                     # see the table below, then check the same call again
else:  # BLOCK
    log.warning("refused: %s (%s)", cert.summary, cert.reason)
    if cert.fabrication_detected:
        alert_security(cert)

REVIEW: cert.release

A list of strings. Each item is one thing that would move the call forward. Supply what it names and check the same call again.

ItemWhat it meansWhat to do
approval:userA person's approval for this call.Have a person approve, then mint token_type="user" with action=cert.action_binding and attach it with az.authorize(token).
approval:productionAn approval to act on a production system.The same with token_type="production", attached with az.authorize_production(token).
approval:<role>Your contract requires a person in that role, for example approval:supervising_lawyer.That person approves; mint token_type="user" with role="<role>" and action=cert.action_binding. A generic approval, or another role's, does not release it. See Approvals.
check:<name>A fact about your own systems that only your check can answer, such as a recent backup or a secret scan.Register a check under that exact name (POST /v1/probes), or send its answer with the request if the check is in supplied mode. If a check is already registered, it gave no answer for this call: it timed out, failed, or answered that it cannot tell. Make it answer, then check the call again; cert.raw["probe_outcomes"] says what happened. See Connect your own check.
check:payment_destination_change_confirmedThe payee's bank details were changed earlier in this session.Have your check confirm the change through a channel the requester does not control, for example a call-back to a number already on file.
contract:tool_effectsState in your contract what this tool or command does.Settle it in the tool's contract with not_present, command_line, commands or arguments. See Contracts.
scope:workspace_rootsGrant the agent its workspace folder (a signed workspace).Open the session with start_session(workspace_roots=...) on a client that has your signing_key, or, for Claude Code, run arcezia grant-workspace. See Sessions and envelopes.
scope:resource_scopeThe call acts on a table, record, file, folder, address or host that the session's signed resource_scope does not name (or the session has no signed scope).If the job really should act on it, open a new session whose signed envelope's resource_scope names it. See Sessions and envelopes. A call whose target cannot be read from its arguments is held for a person’s approval instead: declare the argument as a resource in your contract (arguments: {name: [resource]}) so the target can be read.
contract:<fact>A fact from your own contract is not settled for this call.Give the call what the fact reads (for example its action_parameters), or change your contract.
scope:<field>The call is outside the session envelope field named.Open a new session whose envelope includes it, if a person agrees.
declare:<effect>An effect your contract does not rule out for this tool.If the tool never has that effect on any call, add it to the tool's not_present. Otherwise grant it in the envelope's structural_authority, as a person's decision.
personA person has to look at this call. It can appear next to approval:user, which is how a person says yes.Show it to a person. Do not retry automatically.

BLOCK: cert.reason

A list of strings, usually one. Each says which kind of limit refused the call.

ReasonWhat it meansWhat to do
fabricationThe agent stated something your own system contradicts, or something only your system can confirm (see system_only under Contracts). cert.fabrication_detected is True.Stop. Fix the agent. Never retry the same call.
contract:<rule>One of your contract rules refused it.Working as intended. Change the contract if the rule is wrong.
contract:deny_policyYour deny list refused it, or the deny list could not be read. See Your own deny list.Change the deny list if the entry is wrong. If it could not be read, retry shortly.
contract:kill_switchThe kill switch for this key is on. Every call is refused.Turn it off with POST /v1/killswitch and {"enabled": false}, when a person agrees.
contract:tool_pairingA tool your contract covers was checked under another domain, or a contract's domain was used for a tool it does not cover.Check it again under the domain listed in cert.raw["use_domain"] (a list; usually one entry).
check:<name>Your registered check answered, and its answer refuses the call. The summary reads "the answer from your check '<name>' refuses it".Working as intended when your check is right. If the fact changes (for example the recipient opts in), check the call again.
scope:<field>The session envelope does not allow it.A person may open a new session with a wider envelope.
ceiling:<effect>Your envelope set this effect to False and the call is known to have it. When it is unknown whether the call has it, the call is held instead.No approval lifts it. Only a new envelope can.
scope:max_amountThe call's amount is above the envelope's max_amount.No approval lifts it. Pay less, or a person opens a session with a higher ceiling.
safety:<effect> or safetyA built-in rule protecting that effect refused it.Do not run it. Change the action.
regulation:<law>.art_<n>A built-in rule that enforces that article of that law refused it, for example regulation:gdpr.art_9 or regulation:eu_ai_act.art_10.Do not run it. Your auditors can count refusals by article.

The six effects are outbound, trust_boundary_crossing, sensitive_data, mass_scope, persistent_mutation and irreversible. Contracts says what each one means.

Or, without a person: cert.release_without_person

When a REVIEW can be released only by a person's approval, cert.release_without_person may list a route through your own configuration instead: contract statements, checks or envelope fields, in the same item format. cert.next_steps adds them as one sentence beginning "Or, without a person (each only if it is true)".

ONLY IF IT IS TRUE. These items say what would clear the call, not what is true. A git push may list declare:outbound: stating that the tool never sends anything out would be false, so the push should wait for a person. Never add a statement to your contract because a release list offered it.

REPLACES THE OLD FIELDS. cert.release and cert.reason replace held_by, to_reach_allow and missing, which are no longer in responses. Code that read them should read release (REVIEW) and reason (BLOCK) instead.

Other fields you may use

GATE ON YES. if not cert.block: lets every REVIEW through. Always write if cert.allow:.

02

Approvals

A person's approval is a token your backend signs after the person clicks Approve. The agent cannot make one, and an approval the agent merely claims is refused.

Once per key: register your public key

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey

private_key = Ed25519PrivateKey.generate()      # keep it in your backend; reuse it
az.register_token_key(private_key.public_key())

print(az.token_key_status())   # {"registered": True, "fingerprint": "...", "api_key_id": 1234}

Owner or admin key. az.register_token_key is safe to run twice with the same key; a different key raises SigningKeyConflict unless you pass replace=True. Until a key is registered, approvals are not counted: the call stays REVIEW.

For each approval

from arcezia.signing import mint_token

cert = az.verify(action_type="execute_sql", action_description=sql, domain=SQL)
if cert.review and "approval:user" in cert.release:
    # show the person what the agent wants to do; on Approve, in your backend:
    token = mint_token(private_key,
                       api_key_id=KEY_ID,             # your numeric key id
                       token_type="user",             # or "production"
                       session_id=az.session_id,
                       action=cert.action_binding)    # this call and no other
    az.authorize(token)                               # authorize_production() for "production"
    cert = az.verify(action_type="execute_sql", action_description=sql, domain=SQL)

Token format, if you sign outside Python

base64url(payload_json) + "." + base64url(ed25519_signature_over_the_payload_segment)

{
  "acct": 1234,                          # your numeric key id
  "sid":  "<session id>",
  "typ":  "user",                        # or "production"
  "exp":  1790000000,                    # unix seconds, at most 15 minutes ahead (plus up to a minute for clock differences)
  "jti":  "<unique id>",                 # single use
  "act":  "<cert.action_binding>"        # optional: binds the approval to one call
}

Attach it over HTTP with POST /v1/authorize and {"session_id", "token_type", "token"}.

An approval from a named role

A contract rule can require a person in a particular role: "require": ["approval:supervising_lawyer"]. The role is your own word. The release list then names approval:<role>, and only a user approval carrying that role, bound to this exact call, releases it.

token = mint_token(private_key, api_key_id=KEY_ID, token_type="user",
                   session_id=az.session_id,
                   action=cert.action_binding,          # required with a role
                   role="supervising_lawyer")           # lower_snake_case, at most 32 characters
az.authorize(token)
03

Connect your own check

Some facts only your systems know, such as whether a recent backup exists. A check is an HTTPS endpoint of yours that answers one such fact. When a REVIEW lists check:<name>, register a check under that name.

Register

curl -X POST https://api.arcezia.com/v1/probes \
  -H "Authorization: Bearer $ARCEZIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"domain": "database_ops",
       "constraint_name": "verified_recent_backup",
       "webhook_url": "https://checks.example.com/arcezia",
       "secret": "at-least-16-random-characters"}'

Owner or admin key. A new registration answers 201. constraint_name is the name after check: in the release list. The response carries signing_key_v2 once: store it, your endpoint needs it. Registering the same domain and name again replaces the registration. A check registered on a built-in domain also answers for a contract domain built on it.

What your endpoint receives

FieldMeaning
constraintWhich check is being asked, for example verified_recent_backup.
domainThe domain the check was registered on.
action_typeThe tool being checked.
parametersThe call's action_parameters (record ids, table names). Use these for lookups.
targetsThe places on disk the call names, as absolute paths, resolved against its working folder (parameters.cwd; send it as a real path, os.path.realpath). The list can name more than the call touches: keep the paths that exist.
targets_completefalse when some word of the call could not be resolved (~, $VAR, a folder change the line does not spell out), so targets may not be every place the call touches.
action_descriptionWritten by the agent. Display only: never run it or feed it to a model.
nonceA fresh value for this request (also in the X-Arcezia-Nonce header). Sign your reply with it (below).
call_domainThe domain the call itself was checked under (for a contract tool, the contract's domain).
session_idThe session the call belongs to, when it has one.
taskThe task text of the session. Written by your integration, but it may repeat what a user or agent typed: display only.
untrusted_fieldsThe names of the fields above that the agent wrote and that must never be used as an answer.

What it answers

{"value": true,  "grounded": true,  "detail": "snapshot 40 minutes old"}   # your records say yes
{"value": false, "grounded": true,  "detail": "no snapshot today"}         # your records say no
{"value": false, "grounded": false, "detail": "cannot tell"}              # you do not know

grounded: true means your records answered. When you cannot tell, say so: the call waits for a person rather than being cleared.

A check that does not answer holds the call. If your registered check answers that it cannot tell, returns an error, takes longer than 5 seconds, or sends a reply whose signature is wrong, the call comes back REVIEW with check:<name> in release and the summary "have your check '<name>' answer". It is never allowed because the check was silent. probe_outcomes says which of these happened (see Handling the answers).

A check answering no can refuse. When your check's answer is what makes the call unacceptable, the call is BLOCK with reason check:<name> and the summary "the answer from your check '<name>' refuses it". Measured on an email contract: recipient_is_opted_in answering no gives BLOCK ['check:recipient_is_opted_in'].

Sign your reply. Put X-Arcezia-Answer-Signature: sha256=<hex> on the reply, where <hex> is HMAC-SHA256 with your signing_key_v2 over the bytes arcezia-check-answer-v1, a newline, the request's nonce, a newline, and the exact reply body. A reply whose signature is present and wrong is never counted. arcezia.signing.sign_check_reply(signing_key_v2, nonce, body) makes the value.

A complete endpoint

A minimal Flask app (pip install flask). Run it behind HTTPS on a public address; for a local test, a tunnel such as cloudflared works.

import hmac, hashlib, json, os
from flask import Flask, request, abort, Response

app = Flask(__name__)
SIGNING_KEY_V2 = os.environ["ARCEZIA_SIGNING_KEY_V2"]   # from the registration response

@app.post("/arcezia")
def answer():
    raw = request.get_data()                             # check the raw bytes, before parsing
    sent = request.headers.get("X-Arcezia-Signature-V2", "")
    good = "sha256=" + hmac.new(SIGNING_KEY_V2.encode(), raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(sent, good):
        abort(401)

    ask = json.loads(raw)
    if ask.get("constraint") == "verified_recent_backup":
        ok, age = latest_backup_is_recent()             # your own lookup
        reply = {"value": ok, "grounded": True, "detail": f"latest backup {age} old"}
    else:
        reply = {"value": False, "grounded": False, "detail": "not handled"}

    body = json.dumps(reply).encode()
    mac = hmac.new(SIGNING_KEY_V2.encode(),
                   b"arcezia-check-answer-v1\n" + ask.get("nonce", "").encode() + b"\n" + body,
                   hashlib.sha256).hexdigest()
    return Response(body, content_type="application/json",
                    headers={"X-Arcezia-Answer-Signature": "sha256=" + mac})

Or send the answer with the request (supplied mode)

Each check above costs a round trip from Arcezia to your endpoint. If your integration already knows the answer at the moment of the call, it can send it with the request instead, signed. Three things set this up, once:

from arcezia.signing import SuppliedFactSigner

session = az.start_session(capability_envelope={...})            # as in the Quickstart
signer = SuppliedFactSigner(fact_key, session["session_binding_id"])   # fact_key: your fact signing key

sql = "UPDATE orders SET status = 'shipped' WHERE id = 42"
cert = az.verify(action_type="execute_sql", action_description=sql, domain=SQL)
answer = signer.sign(cert.action_binding, "verified_recent_backup",
                     {"grounded": True, "value": True})      # what your endpoint would have answered
cert = az.verify(action_type="execute_sql", action_description=sql, domain=SQL,
                 supplied_facts=[answer])
print(cert.release)        # check:verified_recent_backup is gone; approvals are still needed

What a check can and cannot do

A check answer, asked or supplied, only fills in a fact about your own systems that the call itself cannot show. It never approves a call and never lifts a limit, whatever the check is called: approvals come only from a token signed with your approval key, and limits only from your envelope. Supplied mode is refused for the built-in approval and limit facts (422 invalid_probe). A check registered for a person's approval can only refuse: its "no" refuses the call even when signed approvals are attached, and its "yes" is ignored, so the call still needs the signed approval. A check registered for a person's approval can only refuse: its "no" refuses the call even when signed approvals are attached, and its "yes" is ignored, so the call still needs the signed approval. A check registered for a person's approval can only refuse: its "no" refuses the call even when signed approvals are attached, and its "yes" is ignored, so the call still needs the signed approval. An answer never overrules what the call itself shows: an answer that a DROP TABLE is not destructive changes nothing. And nothing the agent writes (its description, its parameters, its evidence) is ever read as an answer. The trust boundary is your keys: whoever holds your fact signing key can answer facts for your account, within those limits, so keep it where the agent cannot read it.

04

Contracts

A contract states, per tool, which effects that tool never has. It lets ordinary calls clear without a person. It can only rule effects out for the calls where they are genuinely absent: what a call itself shows always counts.

contract = az.register_contract({
    "tools": {
        "execute_sql": {"pack": "database_ops",
                        "not_present": ["outbound", "trust_boundary_crossing", "sensitive_data"]},
        "read_job_stats": {"pack": "agent_action",
                           "not_present": ["outbound", "trust_boundary_crossing", "sensitive_data",
                                           "mass_scope", "persistent_mutation", "irreversible"]},
    },
}, name="my-tools")

DOMAINS = contract["domains"]     # {"execute_sql": "...", "read_job_stats": "..."}
FieldMeaning
packThe built-in domain whose rules the tool keeps.
not_presentEffects the tool never has, from: outbound, trust_boundary_crossing, sensitive_data, mass_scope, persistent_mutation, irreversible. List one only if it is true of every call.
approval_must_bindOptional, true: only an approval bound to the exact call counts for this tool.
command_lineOptional, true: every call of this tool is a shell command line.
commandsOptional, needs command_line. Per command, named by its leading words, the effects that command never has (the same names as not_present).
mayOptional. Effects this tool is allowed to have. They become the tool's grants in the reply's session_grants, and count only in a session whose envelope you sign. An effect cannot be in both may and not_present.
presentOptional. Effects the tool has on every call, for example ["outbound"] for a tool that always sends. It can only add requirements, and it may not repeat an entry of not_present.
per_callOptional. Effects that depend on the call. Define each one in effect_when (below).
argumentsOptional. Which of the tool's arguments hold its statement (the SQL or command it runs), an amount, a recipient, a payee's destination, or a path (a file or folder).
rules, factsOptional. Your own requirements (below).

The six effects

Every call is described by six effects. A contract says which ones a tool never has (not_present), always has (present) or has on some calls (per_call). An envelope grants or forbids them for a session (structural_authority).

EffectWhat it meansExample
outboundData leaves your own systems.Emailing a report; posting to an outside address.
trust_boundary_crossingThe call goes to or through a system outside your own, whichever way the data moves.Calling a payment provider's API; fetching a page from an outside site.
sensitive_dataThe call reads, writes or sends credentials, personal data or financial data.Reading customers' email addresses; opening a .env file.
mass_scopeThe call acts on many records or files at once.UPDATE orders SET status = 'x' with no WHERE.
persistent_mutationThe call leaves a lasting change.An INSERT; writing a file; a commit.
irreversibleThe call cannot be undone by a later call.DROP TABLE; a wire transfer; a sent email.

Five more names describe what a call does. Use them wherever an effect name is accepted (not_present, present, commands):

NameWhat it meansExample
force_pushRewrites the history of a shared branch.git push --force
recursiveActs on a folder and everything inside it.rm -r build
privilege_escalationRuns with more rights than the agent has, or changes who may do what.GRANT ALL ON orders TO app
permission_changeChanges a file's permissions or owner.chmod 777 deploy.sh
moves_fundsThis tool moves money.A payment tool: "present": ["moves_funds"].

Rules that always apply

Command lines and argument roles

ALL = ["outbound", "trust_boundary_crossing", "sensitive_data",
       "mass_scope", "persistent_mutation", "irreversible"]

contract = az.register_contract({
    "tools": {
        "run_command": {"pack": "filesystem_ops",
                        "command_line": True,
                        "commands": {"git status": ALL, "git diff": ALL, "git log": ALL}},
        "run_report": {"pack": "database_ops",
                       "arguments": {"statement": ["sql"], "path": ["output_file"]}},
        "send_invoice": {"pack": "agent_action",
                         "arguments": {"amount": ["total"], "recipient": ["bill_to"]}},
    },
}, name="agent-tools")

Per-call answers: per_call and effect_when

Some effects depend on the call: a git reset --hard loses work only when the tree has unsaved changes. List such effects in per_call and define each in effect_when as an expression over fields your own system answers for that call. The call's own arguments are readable as call_<name>.

"per_call": ["irreversible", "mass_scope"],
"effect_when": {"irreversible": "loses_unrecoverable_state",
                "mass_scope": "files_changed > 1"},

Your own rules and role approvals

contract = az.register_contract({
    "facts": {"is_court_filing": {"means": "the call files a document with a court",
                                  "from": "len(call_matter) > 0"}},
    "tools": {"efile": {
        "not_present": ["outbound", "trust_boundary_crossing", "sensitive_data",
                        "mass_scope", "persistent_mutation", "irreversible"],
        "rules": [{"when": ["is_court_filing"], "require": ["approval:supervising_lawyer"]}],
    }},
}, name="legal")

Claims only your system can confirm: system_only

Some things an agent might say about a call are not the agent's to know: that a manager approved it, that a bank confirmed it. List such fields under system_only. If the agent states one in agent_evidence and your system does not confirm the same value, the call is refused as a fabrication.

contract = az.register_contract({
    "system_only": ["manager_approved"],
    "tools": {"issue_refund": {"pack": "agent_action",
                               "not_present": ["outbound", "trust_boundary_crossing", "sensitive_data",
                                               "mass_scope", "irreversible"]}},
}, name="refunds")
REFUND = contract["domains"]["issue_refund"]

cert = az.verify(action_type="issue_refund", action_description="refund order 42", domain=REFUND,
                 agent_evidence={"manager_approved": True})     # the agent's own claim
print(cert.verdict, cert.reason, cert.fabrication_detected)   # BLOCK ['fabrication'] True

Worked example: a coding agent's shell

A contract for every routine command, your own system answering per call, a signed workspace and the session's grants. Routine work then runs without a person, and what cannot be undone still waits for one.

LOCAL = ["outbound", "trust_boundary_crossing", "force_push", "privilege_escalation", "permission_change"]
READ_ONLY = LOCAL + ["sensitive_data", "mass_scope", "persistent_mutation", "irreversible", "recursive"]

contract = az.register_contract({"tools": {"Bash": {
    "pack": "filesystem_ops",
    "command_line": True,
    "arguments": {"statement": ["command"]},
    "commands": {                       # what each command never does, on ANY call
        "git status": READ_ONLY, "ls": READ_ONLY,
        "git add": LOCAL + ["irreversible"],
        "git commit": LOCAL + ["irreversible", "recursive"],
        "git reset": LOCAL, "git clean": LOCAL, "git stash": LOCAL, "rm": LOCAL + ["sensitive_data"],
    },
    "per_call": ["irreversible", "mass_scope"],
    "effect_when": {"irreversible": "loses_unrecoverable_state", "mass_scope": "files_changed > 1"},
}}}, name="coding-shell")
BASH = contract["domains"]["Bash"]

agent = arcezia.Arcezia(task=f"Coding agent working on the project in {ws}",
                        signing_key=private_key, account_id=KEY_ID)
agent.start_session(capability_envelope={
    "allowed_domains": [BASH], "allowed_action_types": ["Bash"],
    "structural_authority": {"persistent_mutation": True, "sensitive_data": True, "mass_scope": True,
                             "outbound": True, "trust_boundary_crossing": True},
}, workspace_roots=[ws])

cert = agent.verify(action_type="Bash", action_description="git status", domain=BASH,
                    action_parameters={"command": "git status", "cwd": ws})   # ALLOW once the checks below answer
CommandClean treeUnsaved changes
git status, ls, git add -A, git commit -m ...ALLOWALLOW
git stashALLOW: the dry run answers that nothing is lostALLOW: the changes are saved, not lost
git reset --hard, git clean -fd, rm notes.txt, rm -rf src/legacy (a folder inside the workspace)ALLOW: the dry run answers that nothing is lostREVIEW: work would be lost
rm -rf .gitREVIEW: the dry run answers that it loses stateREVIEW
git stash dropALLOW when the dry run answers there is no saved entry to lose; REVIEW otherwise
git push origin mainREVIEWREVIEW

Payments: a changed payee, and a ceiling

contract = az.register_contract({"approval_must_bind": True, "tools": {
    "update_beneficiary": {"pack": "payment_ops",
                           "not_present": ["outbound", "trust_boundary_crossing", "mass_scope", "irreversible",
                                           "moves_funds"],
                           "arguments": {"recipient": ["beneficiary_id"], "destination": ["account_number"]},
                           "rules": [{"when": [], "require": ["approval"]}]},
    "send_payment": {"pack": "payment_ops", "not_present": ["mass_scope"], "present": ["moves_funds"],
                     "arguments": {"amount": ["amount"], "recipient": ["beneficiary_id"]}},
}}, name="payments")

# the session's envelope adds a ceiling on any one amount:
#   {..., "max_amount": 25000}

Over HTTP: POST /v1/contracts with {"name", "contract"}, GET /v1/contracts, DELETE /v1/contracts/{name}.

Moving from declarations

Contracts replace declarations (/v1/declarations). A tool's not_present now says what it never does.

moved = az.declarations_as_contract()     # GET /v1/declarations/as-contract
print(moved["contract"])                  # your declarations, written as a contract
print(moved["pack_candidates"])           # built-in domains your recent calls used, per tool

# add a "pack" to each tool yourself, then upload it:
az.register_contract(moved["contract"], name="from-declarations")
05

Sessions and envelopes

A session is one agent run: one task, one envelope, and the record of what earlier steps did. The envelope is set by a person and says what the run may do at most.

az = arcezia.Arcezia(task="mark shipped orders",          # be specific: the task is the boundary
                     signing_key=private_key)               # signed: resource_scope and workspace_roots count

session = az.start_session(capability_envelope={
    "allowed_domains": [SQL],
    "allowed_action_types": ["execute_sql"],
    "denied_action_types": ["drop_table"],
    "resource_scope": ["orders", "order_notes", "42", "43"],
    "max_scope": "batch",                          # single_record | batch | limited | mass
    "structural_authority": {"irreversible": False, "outbound": False},
    "session_limits": {"max_calls": 50},
})
print(session["session_id"], session["api_key_id"], session["revocation_epoch"])
Envelope fieldMeaning
allowed_domainsDomains the session may use. Include contract domains by their returned id.
allowed_action_typesTools the session may call. An empty list allows nothing.
denied_action_typesTools always refused in this session.
max_scopeThe largest scope one call may touch.
max_amountThe largest amount one call may carry, read from the argument your contract names as amount. A larger amount is refused (scope:max_amount); no approval lifts it.
workspace_rootsThe folders the agent works in. Counts only when the envelope is signed (below).
resource_scopeExactly what this job acts on: table names, record ids, file or folder paths, email addresses, @domain for every address at that domain, and hosts. Each entry is one name, never a pattern (at most 512). A location in a call that cannot be placed exactly (it contains $, *, ?, [, {, a backquote or ~, or is a relative path with no known folder) is never read as inside the scope: the call is held and the hold names it. Send the resolved path. A call on something not named is held for a person. Counts only when the envelope is signed (below).
structural_authorityThe six effects. True grants the effect for this session; False forbids it outright and no approval lifts it; leaving it out means it needs an approval or a contract. recursive, force_push, privilege_escalation and permission_change are not grants: the SDK refuses them here. You do not need to forbid them: the built-in rules already hold or refuse them (a forced push, for example, is refused as irreversible). To refuse a tool outright, list it in denied_action_types. To let one through, settle it per call (a command's entry, your per-call answer) or attach a person's approval.
tool_authorityEffects granted to one tool by name, for example {"issue_refund": ["persistent_mutation"]}.
session_limitsmax_calls and max_calls_per_tool. The call past a limit is refused.
expires_atISO-8601. After it, the envelope's grants lapse and its denials stay. The session goes on: a call that needed a grant comes back REVIEW with scope:expires_at in cert.release. Open a new session to grant again.

Signed envelopes and the agent's workspace

Give the client your private signing key (the one registered on Approvals) and every envelope it opens a session with is sent signed by you. Do this in your backend, never in the agent's process. Two grants count only when signed: resource_scope (what the job acts on) and workspace_roots (the folders the agent works in).

az = arcezia.Arcezia(task="clean the build folder of the app in /home/dev/app",
                     signing_key=private_key,      # yours, never the agent's
                     account_id=KEY_ID)            # optional: looked up once when left out
session = az.start_session(capability_envelope={"allowed_domains": ["filesystem_ops"],
                                                "allowed_action_types": ["run_shell"]},
                           workspace_roots=["/home/dev/app"])
print(session["workspace_grant"])   # {'applied': True, 'roots': ['/home/dev/app'], ...}

cert = az.verify(action_type="run_shell", action_description="rm -r build",
                 domain="filesystem_ops", action_parameters={"cwd": "/home/dev/app"})
print(cert.verdict, cert.release)   # REVIEW: inside the workspace, held for what cert.release names

cert = az.verify(action_type="run_shell", action_description="rm -r /home/other/build",
                 domain="filesystem_ops", action_parameters={"cwd": "/home/dev/app"})
print(cert.verdict, cert.reason)    # BLOCK ['safety:irreversible']: outside the workspace

The user's own words

Pass what the user typed as principal_request= on verify(). It decides nothing and is not stored. When the call is held, cert.raw.get("unrequested_arguments") names the arguments the user never gave, the usual sign that the call is not what was asked.

06

Several steps at once

Check a whole plan before any step runs. Each step is judged with what the earlier steps did, so a sequence that is harmful together is caught even when every step is fine alone.

result = az.verify_chain({"steps": [
    {"id": "count",  "action_type": "execute_sql", "domain": SQL,
     "action_description": "SELECT COUNT(*) FROM orders"},
    {"id": "lookup", "action_type": "execute_sql", "domain": SQL,
     "action_description": "SELECT status FROM orders WHERE id = 42"},
]}, stop_on_block=True)

if result.safe:                          # overall_verdict == "SAFE"
    run_the_plan()
else:
    print(result.overall_verdict, result.blocked_at, result.human_summary)
    if not result.steps:                 # refused before any step ran
        print(result["reason"])          # e.g. ['contract:tool_pairing'], ['contract:kill_switch']
    for step in result.steps:
        print(step["id"], step["verdict"])
overall_verdictMeaning
SAFEEvery step may run.
BLOCKEDA step was refused. blocked_at is its id. When the whole plan was refused before any step ran (kill switch, deny list, a tool under the wrong domain, a claim your system contradicts), steps is empty and result["reason"] says why, in the same labels as a single check.
SEMANTIC_BLOCKEach step clears on its own, but the sequence is not allowed. It needs every step to clear first, so in practice most risky sequences come back REVIEW_REQUIRED or BLOCKED at a step instead.
REVIEW_REQUIREDA step needs a person. blocked_at is None; find the step in result.steps.
07

Framework hookups

Ready-made hookups for common agent frameworks. Each one checks a tool call before it runs. Make one client, open the session, and hand the client to the hookup. SQL below is the contract domain from the Quickstart.

from arcezia import Arcezia

az = Arcezia(task="look up orders", on_error="review", signing_key=private_key)
az.start_session(capability_envelope={
    "allowed_domains": [SQL],
    "allowed_action_types": ["execute_sql"],
    "resource_scope": ["orders"],
})

LangChain and LangGraph

from arcezia.integrations.langchain import ArceziaToolkit

safe = ArceziaToolkit(az).wrap([execute_sql], domain_overrides={"execute_sql": SQL})
safe[0].run({"query": "SELECT COUNT(*) FROM orders"})   # raises ToolException on REVIEW or BLOCK

graph_tools = ArceziaToolkit(az).wrap_for_langgraph([execute_sql],
                                                    domain_overrides={"execute_sql": SQL})

OpenAI function calling

from arcezia.integrations.openai import ArceziaGuard

r = ArceziaGuard(az).execute_tool_call(
    {"name": "execute_sql", "arguments": '{"query": "SELECT COUNT(*) FROM orders"}'},
    {"execute_sql": lambda query: db.execute(query)},   # called with the arguments by name
    {"execute_sql": SQL},
)
if r["needs_review"]:  ask_a_person(r["cert"].summary)
elif r["blocked"]:     raise RuntimeError(r["cert"].summary)
else:                  use(r["result"])

CHECK needs_review FIRST. A hold comes back with both blocked and needs_review set. Read needs_review first.

Anthropic tool use

from arcezia.integrations.anthropic import ArceziaAnthropicGuard

g = ArceziaAnthropicGuard(az, domain_map={"execute_sql": SQL})
cert = g.verify_tool_use("execute_sql", {"query": "SELECT COUNT(*) FROM orders"})

CrewAI

from arcezia.integrations.openai import ArceziaCrewTool

class SafeDBTool(ArceziaCrewTool):
    az = az
    domain = SQL
    name = "execute_sql"
    description = "Run SQL"
    def _run(self, query: str) -> str:
        return db.execute(query)          # never reached on REVIEW or BLOCK

AutoGen, LlamaIndex, your own loop

from arcezia.integrations.autogen import ArceziaAutoGenGuard
safe_sql = ArceziaAutoGenGuard(az).wrap("execute_sql", db.execute, domain=SQL)   # wrap_async for 0.4

from arcezia.integrations.llamaindex import ArceziaLlamaToolkit
safe = ArceziaLlamaToolkit(az).wrap([sql_tool], domain_overrides={"execute_sql": SQL})

from arcezia.integrations.openclaw import DispatchGuard
DispatchGuard(az, domain=SQL).dispatch("execute_sql", {"query": "..."},
                                       fn=lambda **kw: db.execute(kw["query"]))

Any Python function

from arcezia import guard

@guard(az, domain=SQL, action_type="execute_sql")
def execute_sql(query: str) -> str:
    return db.execute(query)
# Raises ArceziaReviewError on REVIEW, ArceziaBlockError on BLOCK.
# Works for Pydantic AI, smolagents, the OpenAI Agents SDK, Google ADK, Strands.

Claude Code hook

pip install -U arcezia
export ARCEZIA_API_KEY="ar_live_..."
arcezia-hook install        # adds the hook to ~/.claude/settings.json
export TASK="refactor the auth module"   # optional

The hook's tool names

The hook does not send Bash or Write. It sends one tool name per command, so each can have its own contract entry and its own place in your envelope:

What the agent runsTool name the hook sends
git status, git log, git diff, git show, git branch, git tag, git remote, git add, git commit, git stash, git switch, git fetch, git pull, git pushgit_status, git_log, git_diff, git_show, git_branch, git_tag, git_remote, git_add, git_commit, git_stash, git_switch, git_fetch, git_pull, git_push
cat, head, tail, less, wcshell_read
ls, grep, findshell_search
curl, wgethttp_request (domain agent_action), when the download goes to the screen. A download saved to a file (wget's default, curl -o) writes a file, so it is sent as run_shell.
pip install, pip3 install, uv add, uv pip, poetry addpip_install
npm install / i / ci / add, yarn add / install, pnpm add / install / inpm_install
npm test, yarn test, pnpm test, pytest, go test, cargo test, make testrun_tests
npm runnpm_run
go build, cargo buildbuild
alembic upgrade / downgrade / revisiondb_migrate, db_downgrade, db_migration_file
psql, mysql, sqlite3database_query (domain database_ops)
terraform plan / init / validate / apply / destroyterraform_plan, terraform_init, terraform_validate, terraform_apply, terraform_destroy
aws <service> <operation>, gcloud <a> <b>, az <a> <b>, kubectl <verb>aws_<service>_<operation> (for example aws_s3_cp), gcloud_<a>_<b>, az_<a>_<b>, kubectl_<verb>
Any other command; a line joined with &&, ; or | is checked one command at a time; a command with a redirection (>), a substitution ($(...)), a path before the program (./x), an option before the subcommand (git -C dir status) or an option that writes a file (git log --output=f) is checked wholerun_shell
The Read tool (a file outside the working directory), Grep, Glob (outside it)shell_read, shell_search (inside the working directory: not checked)
The Write tool; Edit, MultiEdit, NotebookEditwrite_file; edit_file
WebFetch, WebSearchfetch_url, web_search (domain agent_action)
An MCP or any other toolits name in lower case (a database MCP server uses database_ops)

Every name uses filesystem_ops unless the table says otherwise (ARCEZIA_DEFAULT_DOMAIN changes that default). If your envelope's allowed_action_types names run_shell but not a finer name, that command is sent as run_shell.

Contracts for the hook's tools

A contract can name the hook's tool names. The hook's domain is only a default: when your contract covers the tool, the call is checked under the contract's domain. Three things make it work:

ALL = ["outbound", "trust_boundary_crossing", "sensitive_data",
       "mass_scope", "persistent_mutation", "irreversible"]
NEVER = ALL + ["recursive", "force_push", "privilege_escalation", "permission_change"]
NEVER_BUT_READS = [e for e in NEVER if e != "sensitive_data"]     # cat can read a secret

contract = az.register_contract({"tools": {
    "git_status":   {"pack": "filesystem_ops", "command_line": True, "commands": {"git status": NEVER}},
    "shell_search": {"pack": "filesystem_ops", "command_line": True, "commands": {"ls": NEVER}},
    "shell_read":   {"pack": "filesystem_ops", "command_line": True, "commands": {"cat": NEVER_BUT_READS}},
}}, name="hook")

import json, os
json.dump({"capability_envelope": {
    "allowed_domains": sorted(set(contract["domains"].values())) + ["filesystem_ops", "agent_action"],
    "allowed_action_types": ["git_status", "shell_search", "shell_read", "run_shell"],
    "structural_authority": {"sensitive_data": True},     # needed for cat, together with the check
}}, open(os.path.expanduser("~/.claude/arcezia.json"), "w"))
The agent runsAnswer
git status, lsALLOW
cat a.txt, your secret_scan_passed check answering yes for itALLOW
cat a.txt, no check registeredREVIEW: names check:secret_scan_passed
cat a.txt, check yes, no sensitive_data in the envelopeREVIEW: a person's approval
cat a.txt, secret_scan_passed no, your file_contains_secrets check answering noALLOW
cat a.txt, secret_scan_passed no, file_contains_secrets yesBLOCK check:secret_scan_passed
cat a.txt, secret_scan_passed no, file_contains_secrets cannot tellREVIEW
the same, with the contract's domains missing from allowed_domainsBLOCK: outside your envelope

The hook's envelope file is not signed. Grants in it are applied but reported in the answer's unverified_approvals, and anyone who can edit the file can change them, so keep it where the agent cannot write. A resource_scope in that file never counts, because a scope counts only when signed. To give the hook a signed grant, use the workspace grant below.

Grant the agent its workspace

Tell Arcezia which folders the agent works in, signed by you, for a limited time. Run this yourself in your own terminal, never from the agent. Locations inside the folders are then judged as the agent's own work area. This applies to calls whose locations can be read: a typed path argument, or a tool your contract declares as command_line (the hook's shell tools need such an entry, see Contracts for the hook's tools). For a shell tool with no contract entry, the command text is not read, so its locations stay unknown and the call still asks; its release then names contract:tool_effects, not the workspace.

arcezia grant-workspace ~/code/my-app --for 8h    # at most 24h; grant again when it ends
arcezia grant-workspace --revoke                  # end it early

n8n

from arcezia.integrations.n8n import build_verify_body

body = build_verify_body(task="...", action_type="execute_sql",
                         action_description="...", domain=SQL)
# POST https://api.arcezia.com/v1/verify with Authorization: Bearer <key>

SAME ANSWERS EVERYWHERE. Every hookup calls the same service with the same rules. Switching frameworks does not change a verdict.

08

Python SDK

Every method an integration uses, with its arguments.

arcezia.Arcezia(
    api_key: str | None = None,        # or the ARCEZIA_API_KEY environment variable
    task: str = "",                    # what the agent was asked to do
    api_url: str | None = None,        # or ARCEZIA_API_URL; defaults to https://api.arcezia.com
    on_error: str = "fail_closed",     # or "review": when the service is unreachable
    signing_key=None,                  # your Ed25519 private key: every envelope is sent signed
    account_id: int | None = None,     # your numeric account id; looked up once when left out
    mode: str | None = None,           # test keys only: "development" (default) or "production"
)

Checking

az.verify(action_type, action_description, domain="agent_action",
          action_parameters=None,      # flat dict of the call's arguments (max 32)
          principal_request=None,      # what the user typed
          agent_evidence=None,         # what the agent says; it can never clear a call
          supplied_facts=None,         # signed answers of supplied-mode checks
          capability_envelope=None, capability_envelope_token=None)   -> ArceziaCertificate
az.verify_chain({"steps": [...]}, stop_on_block=True)                -> ArceziaChainResult
az.verify_outcome(action_type, action_description, outcome, expected=None)
az.validate_credential(cert)         # your tool confirms the pass before it acts
require_pass(credential, action_type, domain, description, parameters,
             resource_id=..., mode="online" | "offline" | "both")
                                     # from arcezia.actuator: the service refuses to act
                                     # without a valid pass for exactly this call
@az.gate(domain=..., action_type=...)  # decorator: raises on BLOCK and REVIEW

verify_outcome compares what a cleared action actually did (outcome) with what was intended (expected). For your highest-stakes actions you can also register a dry run of your own with POST /v1/simulate/register (owner or admin); an action whose dry run goes beyond what was allowed does not run.

Sessions and approvals

az.start_session(capability_envelope=None, principal_rules=...,
                 workspace_roots=None)   -> dict (session_id, api_key_id, session_binding_id,
                                                   revocation_epoch, workspace_grant, task_manifest)
az.set_workspace_grant(grant) / az.revoke_workspace_grant(grant_id)
az.session_id / az.attach_session(session_id)
az.authorize(token) / az.authorize_production(token)             # chainable
az.register_token_key(public_key, replace=False) / az.token_key_status()

from arcezia.signing import (mint_token, mint_envelope_token, action_binding,
                             public_key_b64, SuppliedFactSigner, sign_supplied_fact,
                             sign_check_reply, mint_workspace_grant)
mint_workspace_grant(private_key, roots, *, api_key_id, expires_at, not_before=None)   # at most 24 hours
mint_token(private_key, *, api_key_id, token_type, session_id=None,
           ttl_seconds=300, action=None, role=None)

Contracts

az.register_contract(contract, name=...)   -> dict with "domains"
az.contracts() / az.delete_contract(name)
az.declarations_as_contract()              # older keys: declarations written as a contract

Every counted call (verify, verify_chain, verify_outcome) carries an Idempotency-Key header the SDK makes per call, so a retry after a dropped connection is answered once and counted once. See API reference.

ArceziaCertificate

cert.allow / cert.review / cert.block    # bool: gate on cert.allow
cert.verdict                             # "ALLOW" | "REVIEW" | "BLOCK"
cert.summary                             # one sentence for a person
cert.release                             # REVIEW: list of what would release it
cert.reason                              # BLOCK: list of why it was refused
cert.release_without_person              # REVIEW: a route without a person, each item only if true
cert.next_steps                          # one plain sentence per item
cert.credential                          # ALLOW: the one-time pass
cert.action_binding                      # for an approval's act claim
cert.fabrication_detected                # True / False / None
cert.is_clean()                          # True only when nothing was flagged and it was reported
cert.degraded                            # stand-in answer (service unreachable)
cert.signature, cert.log_id, cert.session_id
cert.raw                                 # the full response
09

API reference

The routes an integration needs, on https://api.arcezia.com. The SDK covers all of them.

Send Authorization: Bearer ar_live_… and JSON bodies. Set a User-Agent: the edge refuses Python's default urllib one with 403 (requests, curl and the SDK are fine). Required fields are in bold. Errors usually come as {"detail": {"error": "<code>", "message": "…"}}. Some come as {"detail": "<text>"} (for example a refused approval token), a request whose fields do not fit, or that sends a value in a field the service does not read, comes as {"detail": [ … ]} (422, naming the field; a field sent as null is ignored), and idempotency_key_reused comes as {"error", "message"} with no detail. Read the status code first.

Idempotency-Key. On POST /v1/verify, /v1/verify_chain and /v1/verify_outcome, send a header Idempotency-Key: <any unique string, at most 255 printable characters> per logical call. A retry with the same key and the same body gets the first answer back and is counted once. The same key with a different body is refused (422 idempotency_key_reused); a retry that arrives while the first is still running gets 409 with Retry-After. A key is remembered for 10 minutes. The SDK does this for you.

Checking

RouteBodyReturns
POST /v1/verifytask, action_type, action_description, domain (a request with no domain field: the contract's domain for a tool a contract covers, otherwise agent_action; the SDK always sends one), session_id, action_parameters, principal_request, agent_evidence, supplied_facts, capability_envelope or capability_envelope_token (first call only), audience (the one service that will perform the action; the pass is then valid there only, and can be checked there offline)verdict, summary, release (REVIEW), release_without_person (REVIEW, when there is one), reason (BLOCK), credential (ALLOW), action_binding, fabrication_detected, contract_coverage, credential_withheld (no pass issued), reduced_mode (only when true), use_domain (on contract:tool_pairing), session_id, revocation_epoch, fact_sources, probe_outcomes, evidence_channel_failures (when a check failed or timed out), log_id
POST /v1/verify_chaintask, chain_manifest {"steps": [{"id", "action_type", "domain", "action_description", "action_parameters", "evidence"}]}, stop_on_block (default true), session_id, step_approvals (a list in step order: a signed user approval bound to that step's call, or null)overall_verdict, blocked_at, steps (the steps that ran), human_summary, reason (when the plan was refused), steps_not_run (when some did not run), fact_sources, probe_outcomes, log_id
POST /v1/validate_credentialtoken, action_type, action_digest, action_binding (compute the last two from the call your service is about to perform, not from the agent's certificate), resource_id (required when the pass names an audience)ok, action_bound, call_bound; a refusal is 403 with error (action_binding_mismatch, credential_already_used, audience_mismatch, …)
GET /v1/account/pass_keys—the public keys that check a pass offline, each with kid and fingerprint_sha256; pin the fingerprint at your service out of band. When keys is empty, passes cannot be checked offline on this account yet: check them online with POST /v1/validate_credential

Sessions and approvals

RouteBodyReturns
POST /v1/sessiontask, capability_envelope or capability_envelope_token, principal_rules, workspace_grantsession_id, api_key_id, session_binding_id (for supplied answers), revocation_epoch, task_manifest (its capability_envelope is the envelope in force, signed or not), workspace_grant: applied, roots, from (the signed envelope, a grant, or both), reason and not_applied when a route did not apply, grant_id and expires_at for a grant; null when no route named a folder
DELETE /v1/session/{session_id}none204
POST /v1/authorizesession_id, token_type (user or production), tokenok, counts_toward_verdicts
GET /v1/account/token_keynone (owner or admin)registered, fingerprint, api_key_id
POST /v1/account/token_keypublic_key (base64url, 32 bytes), replace (default false) (owner or admin)ok
GET /v1/account/fact_keynone (owner or admin)registered, fingerprint, api_key_id
POST /v1/account/fact_keypublic_key (base64url, 32 bytes; not your approval key), replace (default false) (owner or admin)ok, fingerprint

Contracts and checks

RouteBodyReturns
POST /v1/contractsname, contract (owner or admin)domains
GET /v1/contractsnonecontracts
DELETE /v1/contracts/{name}none (owner or admin)ok
GET /v1/declarations/as-contractnonecontract, pack_candidates, declarations_deprecated
POST /v1/probesdomain, constraint_name, webhook_url, secret (16+ characters), fact_mode (probe, the default, or supplied), spot_check_every (owner or admin)201: signing_key_v2 (once), created, fact_mode. A name that cannot be registered: 400 invalid_probe
GET /v1/probesnoneprobes: each with domain, constraint_name, webhook_url, active, fact_mode; retired and retired_reason on a check whose name is no longer accepted
DELETE /v1/probes/{domain}/{constraint_name}none (owner or admin)ok

Stopping and deleting

RouteBodyReturns
POST /v1/killswitchenabled (true or false) (admin or owner)status, killswitch_enabled
POST /v1/account/workspace_grants/revokegrant_id, expires_at (owner or admin)ok
GET /v1/account/exportnone (owner or admin, every plan); after_id, limit (at most 1000) to pageNDJSON. The first line is a signed header (record_count, next_after_id, page, header_signature, signature, checkpoints, purge_attestations, ...); each following line is one decision record. To page, send after_id=<next_after_id> until next_after_id is null.
GET /v1/account/deletionnone (owner or admin)what deleting does: confirm_phrase, export_first, deleted_now, kept, requires
POST /v1/account/deleteconfirm (the exact confirm_phrase), export_offered (true), request_ref (optional: a reference id only, 3 to 64 letters, digits and . _ : - with at least one digit; no names or email addresses, it is kept in the signed erasure statements) (owner or admin)deleted, what was erased and kept, and erasure_receipt (keep it: it cannot be shown again or recovered). The key stops working first, so a second call with it gets 401.
GET /v1/erasure/statementsno API key: header X-Arcezia-Erasure-Receipt: <erasure_receipt>account, statements (the signed erasure statements of the deleted account; each names its ledger: decision_record, approval_record or credential_record). An unknown receipt gets 404.
GET /v1/account/record_keysnone (owner, admin or analyst)the keys that verify your records: key_id, fingerprint_sha256, public_key, and keys (each with key_id, fingerprint_sha256, valid_from, valid_to)

GATE ON ALLOW. Run the tool only when verdict is ALLOW, never on "not BLOCK". Keep one session per agent run.

10

Errors

A refusal is an answer, not an outage: every 4xx raises under every on_error setting.

ExceptionWhenDo
ArceziaBlockError@az.gate, guard and the hookups, on BLOCK. Has .cert.Stop. Read e.cert.reason.
ArceziaReviewErrorThe same, on REVIEW. Has .cert.Send e.cert.release to a person.
ArceziaUpgradeRequiredHTTP 402 upgrade_required: this account cannot use that domain or feature.Use a domain this account can use, or change the account.
ArceziaAuthErrorHTTP 401: missing or invalid key.Check ARCEZIA_API_KEY.
ArceziaRateLimitErrorHTTP 429: too many calls. Has .retry_after.Slow down: wait .retry_after seconds, then retry.
ContractRefusedregister_contract() was refused. Has .error and .problems.Fix what .problems names; for a tool already in another contract, delete that contract first.
SigningKeyConflictA different signing key is already registered.Use the registered key, or pass replace=True on purpose.
DeclarationsRetiredHTTP 410 from a retired method. Has .contract.Upload .contract with register_contract().
ArceziaUnavailableErrorThe service could not be reached, under on_error="fail_closed".Do not run the action.
ArceziaAPIErrorAny other non-2xx. Has .status_code.Read the message; see below.

Status codes

Status · errorMeaning
404 domain_not_foundNo domain by that name. For a contract tool use contract["domains"][tool].
409 session_expiredThe session has ended (you deleted it, or the service no longer keeps it). Open a new session. An envelope's expires_at does not cause this; it only ends the grants.
409 tool_covered_by_two_contractsThe tool is in two contracts. Keep it in one.
409 tool_covered_by_another_contract, 422 invalid_contract, 422 contract_rule_never_firesA contract upload was refused (ContractRefused).
warnings firing_not_decided, clearable_not_decidedThe contract was stored. Whether a rule can ever hold or refuse a call (or whether a tool can ever be allowed) was not decided within the upload check’s fixed work limit; nothing was proved either way.
409 on an envelopeThe session already has an envelope. Open a new session.
422 invalid_capability_envelopeAn envelope field could not be read.
400 workspace_grant_rejectedA workspace grant was refused: not signed by this account's registered key, or longer than 24 hours. The SDK opens the session without it and warns.
402 upgrade_requiredThis account cannot use that domain or feature. Nothing was checked.
429Too many calls in a short time. The limit depends on the account. Wait the seconds in Retry-After (ArceziaRateLimitError.retry_after in the SDK), then retry, and look for a runaway loop.
503 custom_domain_unresolvableYour contract's domain could not be loaded. Nothing was checked. Upload the contract again.
400 confirmation_mismatch, 409 export_not_offeredAn account deletion was refused; nothing was deleted. Type the exact confirm_phrase, and send export_offered: true after you downloaded your records.
409 key_reusedThe key you tried to register as the fact signing key is your approval key. Use two different keys.
400 invalid_probeA check registration was refused: the name is not one a check can be registered for. Use a name from a check:<name> item, or one your contract defines.
422 invalid_probeA check registration was refused: supplied mode for an approval, a ceiling or a limit.
422 idempotency_key_reusedThis Idempotency-Key was already used for a different request. Use a new key for a new call.
409 with Retry-After on a counted callThe first request with this Idempotency-Key is still running. Wait and retry with the same key.
400 invalid_idempotency_keyThe Idempotency-Key is longer than 255 characters or not printable.
409 fact_key_already_registeredA different fact signing key is registered. Send replace: true to replace it.

When the service is unreachable

on_errorWhat happens
"fail_closed" (default)Raises ArceziaUnavailableError; the action does not run.
"review"Returns a stand-in REVIEW (cert.degraded is True).
"fail_open"Removed in SDK 1.0.8: it returned an ALLOW nobody computed. Passing it raises ValueError. For a tool that is not critical, do not gate it, and say so in your own code.
11

Domains

Pass one of these as domain, or the domain a contract returned for your tool. Every domain runs the same kind of check. A domain this account cannot use is refused with 402 before anything is checked.

DomainFor
agent_actionGeneric tool calls. The SDK default.
database_opsSQL.
filesystem_opsFiles and directories.
api_opsOutbound HTTP and webhooks.
email_opsEmail.
messaging_opsSlack, Teams, Discord, SMS, WhatsApp.
browser_opsBrowser actions.
payment_opsPayments, transfers, refunds.
deployment_opsCI/CD and releases.
cloud_opsCloud resources and IAM.
crm_opsCRM records.
customer_supportActions taken on a customer's behalf.
data_warehouse_opsWarehouse queries and exports.
pii_opsPersonal data.
healthcare_opsHealth records.
financial_complianceAML, KYC, sanctions, filings.
government_opsGovernment systems.
eu_ai_actEU AI Act high-risk systems.
legal_opsLegal practice.
insurance_opsInsurance.
12

Stop, revoke, delete

How to stop an agent at once, take back what you granted, and delete the account. Each of these takes effect at the next call the service sees.

The kill switch

curl -X POST https://api.arcezia.com/v1/killswitch \
  -H "Authorization: Bearer $ARCEZIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"enabled": true}'        # every call for this key is now BLOCK

Revoking what you granted

The revocation counter

Your account has a counter, revocation_epoch, that only ever goes up, sometimes by more than one for a single change, whenever one of these happens: the kill switch is turned on, a workspace grant is revoked, the deny list is changed, the fact signing key is replaced or cleared, or the account is deleted. Opening a session returns it, and every answer carries the counter it was decided under (cert.raw["revocation_epoch"]). If you keep answers anywhere to reuse them, drop every answer whose counter is lower than the newest one you have seen.

Delete your account

An owner or admin can delete the account. Download your records first: after deletion only their hashes remain and nothing can be exported. GET /v1/account/export (owner or admin key, every plan) returns them as NDJSON. The first line is a signed header that says how many records follow (record_count) and where the next page starts (next_after_id); its signature (header_signature, made with the key that signs your records) covers the account, the period, the page, the record count, the first and last record of the page and the hash of each, the next page and the time of the export. Each following line is one record. Ask again with after_id=<next_after_id> (and limit, at most 1000) until next_after_id is null.

13

Receipts and compliance

Every answer comes with a signed record of the decision and its reason. It is not a certification.

Check the records yourself

An auditor can check an export without asking us: pip install "arcezia[verify]", then arcezia-verify-records export.ndjson --fingerprint <fingerprint> --use-export-keys (pass every page). It checks each record's signature, the order and links of the records, the signed header of each page, the signed checkpoints and removal statements, and with --erasure the signed erasure statements of a deleted account. Each record is PASS, FAIL or UNVERIFIED.

Records in your export come in three forms:

Any disagreement (an edited view, attestation, hash or column, a record missing from the chain, or a stored signature or chain hash that no longer matches) is FAIL. Exports taken before this change rewrote older signed records and are reported FAIL; take a new export. tools/verify_arcezia_export.py is deprecated; use arcezia-verify-records.

Check every page of the export together. A withheld record's place is proved by the chain from the first record: checked from one page alone, it is UNVERIFIED, not PASS-ATTESTED (--partial does not change that). GET /v1/audit/record/{log_id} returns one record in the same three forms.

The key decides everything, so it must not come only from the file being checked, nor only from us. You, the account holder, are the source: read the fingerprint on the dashboard's API Keys page ("Record-signing key fingerprint") or from GET /v1/account/record_keys, and give it to your auditor yourself, outside the export (for example in your own signed letter). A key whose fingerprint does not match is not used, and the records it would check are UNVERIFIED. An auditor can instead pass the key itself with --public-key, obtained the same way.

RequirementWhat the record gives you
EU AI Act Art. 9A per-action decision before the action runs; REVIEW surfaces residual risk.
EU AI Act Art. 11/12A signed record per decision.
EU AI Act Art. 13/14A plain reason per decision; REVIEW stops the action for a person.
EU AI Act Art. 15Accuracy measured on public benchmarks; made-up approvals refused.
NIST AI RMF Measure 2.6Evidence that the check ran before the action.
14

FAQ

The questions engineers ask first.

Is this an LLM judge?

No. There is no language model in the decision. The same input always gets the same answer. Under heavy load a call may instead be answered ‘not decided, try again’ (a REVIEW with reduced_mode); it is never given a different verdict.

Why did a harmless call come back REVIEW?

Something it needs has not been supplied yet. Read cert.release and cert.release_without_person: they name what would release the call. On a fresh key the usual answers are a contract for the tool and a signed resource_scope for the session.

Why is "Select the old orders and remove them" held?

Only a SQL statement is read as SQL. A sentence that starts with "select" is words: it clears nothing, so the call waits. Send the statement itself, or put it in the tool's statement argument.

What if the agent lies about an approval?

A claim never clears anything. Only a token signed with your registered key approves a call: az.authorize("approved") is refused, and a token signed with any other key is refused when it is attached. An approval the agent merely writes into its description, parameters or evidence is ignored, so the call stays held. When the agent states something your own system can check, and your system says otherwise (or it is a system_only field your system does not confirm), the call is BLOCK with reason fabrication. Contracts shows an example.

Does the language of the task change the answer?

No. The task's words are never what clears a call, so a task written in Spanish gets the same answer as the same task in English. What a job may act on comes from the resource_scope you sign, from your contract, and from your own checks.

What does the SDK send?

Only what you pass it. It is a thin HTTPS client, so you can read exactly what leaves your process.

Which languages? Can I self-host?

Python today; any language can call the HTTP API. Arcezia is hosted only.

15

Send records to your SIEM

Every refusal, and every time an agent claimed an approval it did not have, can be posted to an HTTPS address you own. Each record is signed. Delivery never slows a check or changes an answer.

curl -X POST https://api.arcezia.com/v1/siem \
  -H "Authorization: Bearer $ARCEZIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://siem.example.com/arcezia", "secret": "a-long-random-string"}'

One POST per record, signed in the X-Arcezia-Signature header:

{
  "event": "arcezia.verdict",
  "ts": "2026-09-07T11:02:14.331Z",
  "api_key_id": 1234,
  "verdict": "BLOCK",
  "domain": "database_ops",
  "action_type": "execute_sql",
  "fabrication_detected": true,
  "summary": "Blocked: ...",
  "request_id": "ef233dfcf2e4466597bc3687bd58663c"
}
import hmac, hashlib

def is_from_arcezia(raw_body: bytes, header: str, secret: str) -> bool:
    expected = "sha256=" + hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, header)      # check the raw bytes, before parsing
16

Your own deny list

A short list of things always refused for this key. It can only add refusals; it never turns a refusal or a hold into ALLOW.

curl -X POST https://api.arcezia.com/v1/policy \
  -H "Authorization: Bearer $ARCEZIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"deny_domains": ["payment_ops"],
       "deny_action_types": ["delete_user"],
       "deny_patterns": ["--force"]}'
FieldMatches
deny_domainsThe request’s domain, exactly.
deny_action_typesThe tool name, exactly.
deny_patternsA case-insensitive pattern searched in the first 2,000 characters of the description.