# AgentComply: a guardrail and audit trail for autonomous paying agents

AI agents now pay for APIs, data and services by themselves over **x402** (HTTP 402 + USDC), with nobody watching each payment. That's a compliance problem:
- Who did the agent pay?
- Was that address on the OFAC SDN list?
- Was the agent tricked by a prompt injection into approving unlimited USDC?
- Can the firm *prove* afterwards that it screened the payment?

**AgentComply is one call the agent makes before it pays.** It runs a set of live checks and returns **`ok`, `caution` or `block`**, together with a **signed, hash-chained compliance receipt**. That receipt is a tamper-evident record a compliance officer, auditor or lawyer can keep and independently verify.

**Live:** https://agentcomply.agentgate.workers.dev (try `GET /v1/screen?payTo=vitalik.eth&chain=ethereum&amount_usd=5`). **Source:** https://agentgate-source.pages.dev/agentcomply/

> Informational screening only. Not legal, compliance or financial advice. "ok" means none of the listed checks found a known risk signal at the listed time.

## How it works
```
agent ──POST /v1/screen──▶ AgentComply ──(parallel, read-only)──▶ CounterpartyCheck  (who is payTo? SDN/scam lists, wallet vs contract, ENS/Basename)
                                 │                                 PayGuard           (US Treasury OFAC SDN address match + list date)
                                 │                                 SignCheck          (pre-sign: unlimited approvals, permits, x402 overpay/wrong payTo)
                                 │                                 TokenVerdict       (honeypot / owner powers before buying a token)
                                 │                                 DomainCheck        (is the merchant domain real?)
                                 │                                 InjectScan         (prompt injection in the payment instructions)
                                 │                                 AgentGate          (is the paying agent registered + verified? Concordium registry)
                                 ▼
                  policy.json (firm-editable rules) ─▶ verdict ok / caution / block + action + reasons
                                 ▼
          receipt = canonical JSON ─▶ SHA-256 ─▶ Ed25519 signature, linked to the previous receipt (prev_hash)
```

### Fail-closed by design
- **An upstream failure can never produce `ok`.** Timeouts, network errors, 5xx, non-JSON responses, `sources_failed`, a `checks_incomplete` signal, or `ok` with less than `high` confidence all become `caution`, with `retryable: true`. Failed sources are listed in the receipt (`sources_failed`).
- **Paid CounterpartyCheck tiers** return `503 checks_incomplete` when a check couldn't finish; in that case the payment is not settled. AgentComply retries once, then uses the provisional verdict (`caution` or `block`, coerced to never be `ok`) and marks it `provisional: true, retryable: true`.
- **Names:** ENS (`*.eth`) and Basenames (`*.base.eth`) are accepted. An unknown name returns **400 `invalid_input`** and no receipt is issued. If name resolution fails, the result is `caution`, and the receipt records that the sanctions screen could not run.
- New upstream fields are ignored. Credentials are sent in a header and never written into receipts.

### Policy (policy.json)
These rules are editable by the compliance owner, and the policy's own SHA-256 is recorded in every receipt:
- SDN match → block
- counterparty `ok` requires `high` confidence
- degraded token data → caution
- malicious instructions → block
- **payments above $50 need a verified agent identity**, otherwise block
- above $10,000 → manual review
- a denylist
- allowed chains

### The receipt
Each receipt contains:
- `subject`: payTo, resolved address, chain, intent, amount, reference
- `request`: the input plus its hash. Free-text instructions are stored as a hash and a 280-character excerpt.
- `policy`: id, version, sha256
- every check: tool, engine version, endpoint, HTTP status, outcome, signals, `sources_failed`, upstream timestamp, SDN list date, and the SHA-256 of the raw upstream response
- `decision`
- `chain {seq, prev_hash}`
- `integrity {hash, kid, Ed25519 signature}`

`POST /v1/verify` checks a receipt, and `GET /v1/ledger/verify` checks the whole chain. Editing any field, swapping keys, or deleting a receipt from the chain is detected.

## API
| Route | |
|---|---|
| `POST /v1/screen` | body: `{payTo, chain?, intent? (pay\|approve\|interact), amount_usd?, token?, merchantDomain?, instructions?, agentId?, sign?:{to,data}, reference?}` |
| `GET /v1/screen?payTo=…` | same, query form |
| `POST /v1/verify` | body: a receipt → `{valid, reason?}` |
| `GET /v1/ledger/verify` | verify the receipt chain |
| `GET /v1/pubkey` | issuer public key (JWK, no private part) |
| `GET /v1/policy` | active policy |

## Run locally ($0, free preview routes)
```bash
npm run keygen      # writes the Ed25519 key to /home/box/crypto-vault/agentcomply-signing-key.json (chmod 600)
npm test            # 28 mocked tests (fail-closed paths, 503 retry, ENS, policy, tampering, chain)
npm run test:live   # 4 read-only live checks against api.youraitools.co preview routes
npm run demo        # 5 agent scenarios + verification + tamper detection (local server)
AGENTCOMPLY_URL=https://agentcomply.agentgate.workers.dev node demo/demo.mjs   # same demo against the live Worker
npm start           # http://localhost:8787
```
`MODE=paid CREDITS_KEY=…` switches to the paid lite tiers via a YourAITools Credits key. That isn't used in the demo: $0 spent.

## Chainlink CRE workflow
[`cre/`](cre/) has a CRE workflow ("screen before pay"): an HTTP or cron trigger sends the payment to `/v1/screen`, checks the receipt with `/v1/verify`, reaches DON consensus on the verdict and receipt hash, applies a fail-closed gate, and emits a DON-signed report of `{receiptHash, verdict, action, receiptId, seq, approved}` for an on-chain payment gate. It runs with `cre workflow simulate`; recorded runs are in `cre/sim/`.

## Tech stack
- JavaScript (ES modules), no runtime dependencies.
- WebCrypto Ed25519 and SHA-256, so the same code runs on the Cloudflare Workers runtime (`src/worker.js`) and Node 20 (`server.js`).
- Receipt ledger in a SQLite-backed Durable Object, which serializes appends and rejects a stale `prev_hash`.
- Upstream: YourAITools x402 tools (USDC on Base, Polygon, Arbitrum One, Solana), Concordium Agent Registry, US Treasury OFAC SDN data, ScamSniffer lists, OSV.

## What existed before vs. what's new
The checks (CounterpartyCheck, PayGuard, SignCheck, TokenVerdict, DomainCheck, InjectScan, AgentGate) existed before this hackathon as live paid APIs, and AgentComply calls them as-is. **New for this hackathon:**
- the orchestrator and fail-closed decision logic
- the policy engine
- signed, hash-chained compliance receipts and their verifier
- the HTTP API, test suite and demo

## Deploying
Deployed on Cloudflare Workers (free plan) as `agentcomply`, with the receipt ledger in a SQLite Durable Object (`LEDGER`, no KV writes):
1. `npx wrangler deploy`
2. `npx wrangler secret put AGENTCOMPLY_SIGNING_JWK < <path to your Ed25519 JWK file>` (the Worker returns 503 `not_configured` until this is set)

The live demo ledger is public and shared: anyone calling `/v1/screen` appends a receipt.

MIT licensed.
