Audital developer docs
Audital is the control layer between your AI agent and the actions it takes: deterministic, fast, and recorded. Before an action runs it checks the proposed call against your policy; after, it reads back the actual system state, compares it with what was supposed to happen, and returns one of four verdicts — with an explainable diff and a signed, offline-verifiable receipt.
3-minute quickstart (observe mode)
Pick your entry point — every one calls the same API and gets the same four verdicts:
- Any agent or pipeline: curl, JS / TypeScript SDK, Python, LangChain / OpenAI Agents tool and MCP server, GitHub Action.
- Turnkey recipes: Stripe Refund Verification and GitHub PR / Deploy Verification — one click in the workspace, each with a restricted read-only key.
- Create an account. The workspace walks you through your first workflow (a template, a custom HTTP readback or a pre_action policy), mints an API key and adds a Slack alert. New workflows start in
observeand never block. - For readback workflows, add a restricted, read-only credential for the real system (see credentials).
- After your agent acts, send its claim. Set these once:
export AUDITAL_API_URL=https://api.audital.ai/api/v1
export AUDITAL_API_KEY=ak_… # from the workspace (shown once)curl
curl -s $AUDITAL_API_URL/runs \
-H "Authorization: Bearer $AUDITAL_API_KEY" -H "Content-Type: application/json" \
-H "Idempotency-Key: refund-re_123" \
-d '{"workflow":"stripe-refunds",
"expected_state":{"status":"succeeded","amount":4999,"currency":"gbp"},
"reported_outcome":{"status":"succeeded","message":"Refund issued"},
"readback_params":{"refund_id":"re_123"}}'In observe mode the API answers 202 straight away with a run_id. The run is stored before the response, verified in the background and sealed — see getting the verdict.
JavaScript / TypeScript
npm install @audital/sdk # zero dependencies · Node 18+ · ESM + CommonJS · TypeScript typesimport { createClient } from '@audital/sdk'; // CommonJS: const { createClient } = require('@audital/sdk');
const audital = createClient({
apiKey: process.env.AUDITAL_API_KEY,
baseUrl: process.env.AUDITAL_API_URL,
failurePolicy: 'fail_open', // 'fail_closed' for high-stakes gates
});
const r = await audital.check({
workflow: 'stripe-refunds',
expected_state: { status: 'succeeded', amount: 4999, currency: 'gbp' },
reported_outcome: agentResult,
readback_params: { refund_id: refund.id },
idempotencyKey: 'refund-' + refund.id,
});
if (!r.proceed) throw new Error('Audital blocked: ' + r.evaluation?.summary);ES modules support top-level await. In CommonJS, call check() inside an async function.
Python (honours fail_open / fail_closed)
import os, logging, requests
AUDITAL_API_URL = os.environ["AUDITAL_API_URL"]
FAILURE_POLICY = "fail_open" # "fail_closed" for high-stakes gates
class AuditalBlocked(Exception): pass
class AuditalUnavailable(Exception): pass
def audital_check(payload: dict, idempotency_key: str) -> dict:
"""Returns the run (verdict may still be pending in observe mode). Raises on BLOCKED."""
try:
r = requests.post(f"{AUDITAL_API_URL}/runs", json=payload, timeout=5,
headers={"Authorization": f"Bearer {os.environ['AUDITAL_API_KEY']}",
"Idempotency-Key": idempotency_key})
except requests.RequestException as e: # timeout, DNS, connection reset
return _unavailable(f"network error: {e}")
body = r.json() if r.headers.get("content-type", "").startswith("application/json") else {}
code = (body.get("error") or {}).get("code")
if r.status_code == 409 and code == "BLOCKED": # the gate fired: do not proceed
raise AuditalBlocked(body["error"]["message"])
if r.status_code == 409 and code == "IDEMPOTENCY_IN_PROGRESS":
return {"pending": True, **(body.get("error") or {})} # same key still verifying: poll later
if r.status_code in (402, 429) or r.status_code >= 500: # no credit, daily cap, Audital down
return _unavailable(f"HTTP {r.status_code} {code}")
r.raise_for_status() # 4xx = a bug in the request: fix it
return body["data"] # 200 allow/warn, 202 observe accepted
def _unavailable(reason: str) -> dict:
if FAILURE_POLICY == "fail_closed":
raise AuditalUnavailable(reason) # halt until Audital or a human resolves it
logging.warning("Audital unavailable (%s); proceeding under fail_open", reason)
return {"degraded": True, "reason": reason}
run = audital_check({"workflow": "stripe-refunds",
"expected_state": {"status": "succeeded", "amount": 4999, "currency": "gbp"},
"reported_outcome": agent_result, "readback_params": {"refund_id": refund_id}},
idempotency_key=f"refund-{refund_id}")Getting the verdict after a 202 (observe mode)
Observe never blocks, so the 202 carries run_id and status: "PENDING". Three ways to get the outcome:
- Poll the run — usually done within
settle_delay_msplus a few hundred milliseconds:
curl -s $AUDITAL_API_URL/runs/$RUN_ID -H "Authorization: Bearer $AUDITAL_API_KEY"
# -> {"data":{"status":"DONE","verdict":"DISCREPANCY_DETECTED","decision":{"action":"allow","would_block":true,…},
# "evaluation":{…diff…},"receipt_id":"rcpt_…"}}- Get alerted — set a Slack (or any https) webhook on the workflow. Every
DISCREPANCY_DETECTEDis posted, grouped per 5 minutes and signed, with the run ID, receipt ID and a link to the workspace:curl -X PUT $AUDITAL_API_URL/workflows/$WORKFLOW_ID/alert-webhook -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" -d '{"url":"https://hooks.slack.com/services/…"}' # the response includes signing_secret once — store it to verify alert signatures - Review in the workspace — the receipt timeline, the diff, and a would have blocked count that shows exactly what block mode would have stopped.
observe → warn → block (per workflow)
| enforcement_mode | HTTP | Behaviour |
|---|---|---|
observe | 202 | Durable async verification and receipt; never blocks. would_block tells you what block mode would have done. |
warn | 200 | Inline; a discrepancy returns warning + diff, the action proceeds. |
block | 409 | Inline gate: DISCREPANCY_DETECTED (or a pre_action override threshold, or NEEDS_VERIFICATION with strict_unverified) returns BLOCKED with the diff. |
Verdicts: VERIFIED (independent readback matched every expected field), DISCREPANCY_DETECTED, NEEDS_VERIFICATION (nothing independent observed — a pasted claim, a provider HTTP 200 on its own, or a 401/403/429/5xx readback is never proof; a 404 is covered below), SIMULATED (labelled demo fixtures only).
pre_action prevents · post_action stops what comes next
pre_action runs your deterministic policy on the proposed action before it executes, so a 409 really prevents it. A pass is NEEDS_VERIFICATION (a proposal is not an outcome) — follow it with a post_action check.
{ "rules": [
{ "field": "refund.amount", "op": "lte", "value": 50000, "label": "Refund cap £500" },
{ "field": "refund.currency", "op": "in", "value": ["gbp","eur"], "label": "Supported currency" } ],
"require_override_above": { "field": "refund.amount", "threshold": 25000 } }Ops: eq neq lt lte gt gte in not_in regex exists. No code execution, no LLM. Failed rules appear in diff[] with their label.
post_action reads the real system back after the agent claims completion. The action already happened, so a 409 stops downstream steps and cascading damage. Use settle_delay_ms (0–10000) and readback_retries (0–3, exponential backoff) for eventually-consistent providers.
failure_policy: when Audital is unreachable
fail_openis the default; setfail_closedfor high-stakes block gates. Underfail_open, timeouts, network errors, 5xx, 402 (no credit) and 429 (daily cap) let the agent proceed with a warning; the SDK queues the run for reconciliation (flushQueue()).- Under
fail_closed, the SDK throwsAuditalUnavailable; halt until Audital or an authorised human resolves it.
Readback, credentials & firewall allowlisting
- The readback host is fixed by your workflow admin; agents only fill URL-safe placeholders.
- Use restricted, read-only credentials: a Stripe restricted key with Refunds: Read only; a GitHub fine-grained token with Pull requests: Read / Deployments: Read on the specific repositories.
- Headers are stored with per-organisation envelope encryption (AES-256-GCM, data key wrapped by KMS), never logged, returned or written into receipts.
- Outbound requests are https-only, resolve DNS first and refuse private, loopback, link-local and metadata addresses, connect to the validated IP with TLS name pinning, and never follow redirects.
Egress IPs to allowlist (AUDITAL_EGRESS_STATIC_IPS): not yet published for this deployment — contact us before relying on IP allowlists.
Comparison options: 404s & numeric strings
Two per-workflow options (set with PATCH /workflows/:id). Both are recorded in every evaluation as comparison_options, so a sealed receipt shows which rules produced its verdict.
| option | default | what it does |
|---|---|---|
treat_404_as_discrepancy | true | After settle_delay_ms and all readback_retries, an authenticated readback that still returns HTTP 404 is DISCREPANCY_DETECTED: the resource the agent claims to have created or changed does not exist. Each expected field gets a resource_not_found diff entry with observed_http_status: 404. 401, 403, 429, 5xx and timeouts stay NEEDS_VERIFICATION. Set false for APIs that answer 404 for permission errors — GitHub does this for private repositories, so the GitHub packs ship with false. |
coerce_numeric_strings | false | For providers that return numbers as strings ("4999", "19.99"). true applies to every expected numeric field; a list such as ["refund.amount"] applies only to those fields. Only plain decimals are coerced (no exponents, spaces, + or leading zeros), compared exactly ("19.990" equals 19.99). The diff keeps the raw string and marks coerced: true. Expected values are never coerced. |
curl -X PATCH $AUDITAL_API_URL/workflows/$WORKFLOW_ID -H "Authorization: Bearer $JWT" \
-H "Content-Type: application/json" \
-d '{"coerce_numeric_strings":["refund.amount"],"treat_404_as_discrepancy":true}'Receipts, human overrides & erasure
Every run is sealed into your organisation’s append-only ledger: canonical JSON → SHA-256 → Ed25519 signature, hash-chained by prev_receipt_hash. The database rejects UPDATE/DELETE on receipts.
# Record an audited human override (never edits the original receipt)
curl -X POST https://api.audital.ai/api/v1/receipts/$RECEIPT_ID/override -H "Authorization: Bearer $JWT" \
-H "Content-Type: application/json" -d '{"reason":"Provider dashboard confirms the refund settled; readback lagged."}'
# Crypto-shred the private payload (the signed header stays verifiable)
curl -X DELETE https://api.audital.ai/api/v1/receipts/$RECEIPT_ID/payload -H "Authorization: Bearer $JWT"
# Archive a signed chain head externally to detect any later rewrite
curl https://api.audital.ai/api/v1/ledger/checkpoint -H "Authorization: Bearer $AUDITAL_API_KEY"Public seal pages (/r/<receipt_id>) show metadata only — verdict, mode, fingerprint, key and signature — never payloads or diffs.
Offline verify-seal (check our receipts yourself)
verify-seal.cjs is one file with zero dependencies and zero network calls (it uses only node:crypto and node:fs). It checks a receipt, a whole chain or a signed checkpoint against our published signing keys — tamper-evidence: it proves the record was not altered after Audital sealed it.
curl -s https://api.audital.ai/.well-known/audital-signing-key.json > keys.json
node verify-seal.cjs receipt.json --keys keys.json
node verify-seal.cjs --chain chain.json --checkpoint checkpoint.json --keys keys.json
# exit 0 = VERIFIED · 1 = REJECTED (e.g. one byte tampered) · 2 = usageSource: packages/verdict/bin/verify-seal.cjs in the Audital repository.
Agent frameworks & MCP
Drop-in Python tool for LangChain and the OpenAI Agents SDK (15 lines, only requests):
import os, requests
AUDITAL = os.environ["AUDITAL_API_URL"] # e.g. https://api.audital.ai/api/v1
def audital_check(workflow: str, expected_state: dict, reported_outcome: dict, readback_params: dict) -> str:
"""Verify an action with Audital before claiming success. Returns the verdict, whether to proceed, and the diff."""
r = requests.post(f"{AUDITAL}/runs", timeout=10,
headers={"Authorization": f"Bearer {os.environ['AUDITAL_API_KEY']}"},
json={"workflow": workflow, "expected_state": expected_state,
"reported_outcome": reported_outcome, "readback_params": readback_params})
data = r.json().get("data") or {}
return f"{data.get('verdict')} proceed={r.status_code != 409}: {(data.get('evaluation') or {}).get('summary', r.text[:200])}"
# LangChain: from langchain_core.tools import tool; audital_tool = tool(audital_check)
# OpenAI Agents SDK: from agents import function_tool; audital_tool = function_tool(audital_check)MCP (Claude Code, Cursor, any MCP client): a zero-dependency stdio server exposing one tool, audital_check.
claude mcp add audital -e AUDITAL_API_KEY=$AUDITAL_API_KEY -- npx -y @audital/mcp-server
# optional: -e AUDITAL_FAILURE_POLICY=fail_closed -e AUDITAL_API_URL=https://api.audital.ai/api/v1Cursor and other MCP clients (JSON config):
{
"mcpServers": {
"audital": {
"command": "npx",
"args": ["-y", "@audital/mcp-server"],
"env": { "AUDITAL_API_KEY": "ak_..." }
}
}
}The tool tells the agent to stop and report the diff when proceed is false, and to treat NEEDS_VERIFICATION as unverified.
CI/CD gate (GitHub Action)
- uses: abibismail/audital/.github/actions/audital-gate@<pinned-sha>
with:
api-key: ${{ secrets.AUDITAL_API_KEY }}
workflow: github-deploys
expected-state: '{"0":{"state":"success","environment":"production"}}'
readback-params: '{"owner":"acme","repo":"web","deployment_id":"${{ steps.deploy.outputs.id }}"}'
fail-on: block # or: discrepancy | unverified
failure-policy: fail_closedThe job fails on BLOCKED (and optionally on any discrepancy or unverified result), writes the diff to the step summary and exposes verdict, decision, run-id and receipt-id outputs. Re-runs reuse an idempotency key, so they are never double-charged.
Templates: Stripe & GitHub packs
- Stripe Refund Verification — reads
GET https://api.stripe.com/v1/refunds/{refund_id}; expected{"status":"succeeded","amount":4999,"currency":"gbp"}(amount in minor units); settle 2 s, 2 retries. Use a restricted key with Refunds: Read only. - GitHub PR Merge Verification — reads
/repos/{owner}/{repo}/pulls/{number}; expected{"merged":true,"merge_commit_sha":"…","base":{"ref":"main"}}. - GitHub Deploy Verification — reads the latest deployment status (
?per_page=1); expected{"0":{"state":"success","environment":"production"}}; settle 3 s, 3 retries.
Create one in a click from the workspace, or POST https://api.audital.ai/api/v1/workflows/from-template {"template_id":"stripe_refund","key":"stripe-refunds"}. Templates start in observe mode; add the read-only credential with PUT /workflows/:id/readback-headers. GitHub needs Accept: application/vnd.github+json and X-GitHub-Api-Version alongside the token.
Status codes & billing
202observe accepted ·200allow/warn ·409 BLOCKEDgate ·409 IDEMPOTENCY_IN_PROGRESS402 INSUFFICIENT_CREDIT·429 DAILY_CAP— enforced atomically in the database before a run is admitted422invalid input (never charged) ·503Audital could not seal the verdict (refunded; apply your failure_policy)- One unit per run, whatever the verdict. Retries with the same
Idempotency-Keyare never charged twice.