Metadata-Version: 2.4
Name: agentx-security-sdk
Version: 0.5.12
Summary: Runtime firewall for AI agents - watches every tool call, and once switched on blocks the catastrophic ones and tells the agent a safe path.
Home-page: https://agentx-core.com
Author: AgentX Core Team
Author-email: founders@agentx-core.com
License: MIT
Project-URL: Homepage, https://agentx-core.com
Project-URL: Get Started, https://agentx-core.com/gateway
Project-URL: Source, https://github.com/vdalal/agentx-security-sdk
Keywords: ai-agents,agent-security,llm-security,ai-firewall,prompt-injection,guardrails,llm-guardrails,agent-guardrails,tool-use,autonomous-agents,mcp,ai-safety,self-healing
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Information Technology
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: agentx_sdk/LICENSE
Requires-Dist: requests>=2.25.0
Requires-Dist: tzdata; python_version >= "3.9"
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: license
Dynamic: license-file
Dynamic: project-url
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# 🛡️ AgentX: The Action Firewall for AI Agents

[![PyPI](https://img.shields.io/pypi/v/agentx-security-sdk.svg)](https://pypi.org/project/agentx-security-sdk/)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://github.com/vdalal/agentx-security-sdk/blob/main/LICENSE)

*This package (`agentx-security-sdk`) is MIT licensed. The gateway and control plane are separate, closed-source products; see [Licensing](#-licensing) below.*

An agent that can act will eventually act badly: a `DROP TABLE` arriving through a prompt-injected field, a secret read, an SSRF to a cloud metadata endpoint, an installer piped straight into a shell. Most agent frameworks already give you a place to stop a tool call before it runs. What they don't give you is the decision about **which** calls are worth stopping.

**AgentX is that decision, and it starts with zero keys.** A deterministic floor runs inside your process, with no LLM call and no network hop. It knows the never-legitimate call (`DROP TABLE`, SSRF, secret reads, supply-chain RCE, destructive shell such as `rm -rf /` or wiping a disk) from the one that can be legitimate and needs a human (payments over a limit, external publishes, runaway spend), which the gateway holds for a person. Cloud teardown (`terraform destroy`, whole bucket and volume deletes) is checked by the gateway, not yet by the keyless floor.

**Out of the box it watches.** Every call your wrapped tools make is screened and written down, and **nothing is stopped**, so adding AgentX cannot break an agent that already works. When the catches look right, `AGENTX_POSTURE=enforce` makes the same floor hard-block that first list (for Claude Code, `agentx hook install --enforce`). No API key, no signup. Keyless, your calls never leave the machine; the only thing sent is an anonymous daily usage count, which `AGENTX_TELEMETRY=off` turns off (see [What leaves your machine](#-what-leaves-your-machine)).

A block is not a dead end. Every block hands your agent a **coaching message** naming a safe path to try instead, so the run continues rather than ending. Add a Gemini key and the gateway's **reasoning layer** writes that message to fit the specific task rather than from a template, catches what a keyword floor cannot see, and runs the retry for you.

**For your customer's security reviewer:** give each agent a [site allowlist](#step-5b-limit-each-agent-to-its-tools-and-sites), and [`agentx evidence`](#-local-telemetry--agent-health) writes a file for them: the rules, and the calls AgentX stopped or flagged. No key, and the file is written on your machine.

---

## ⚡ 1. Quickstart

AgentX needs **no changes** to your agent logic, your tools, or your payload schemas. It reads your function signatures at runtime and works out what to inspect on its own.

### Step 1: Install the SDK
```bash
pip install agentx-security-sdk
```

### Step 1b: See it work in 10 seconds (no key, no gateway)
```bash
agentx demo
```
Runs a canned agent twice against the in-process floor, offline and with no key: first in the default watching posture, where the `DROP TABLE` is recorded and still runs, then enforcing, where it is stopped. The fastest way to confirm the install works, and to see both postures, before you wire it into your own agent. (`agentx demo --audit` and `agentx demo --enforce` run one half each.)

Hit a block you're proud of? Turn it into a postable card:
```bash
agentx share
```
Renders your most recent catch as a clean, screenshot-able receipt + a ready-to-post draft and link. Privacy-safe by construction: it uses the policy class and your own tool name only, never the query or payload (the local ledger never stores one).

### Step 2: Decorate Sensitive Tool Operations
Attach the `@agentx_protect` decorator over any high-risk system tool. The SDK automatically serializes parameters and enforces the evaluation wedge:

```python
# ✅ MODERN REFLECTIVE IMPORTS (No boilerplate functions required)
from agentx_sdk.decorators import agentx_protect

@agentx_protect(agent_id="crm_worker")
def run_sql(query: str, db=None):
    """
    AgentX reads the argument NAMED for what it runs, ignores connection objects
    like 'db', and evaluates intents out-of-prompt natively in RAM.
    """
    return db.execute(query)
```

The shield reads SQL, shell, paths and URLs in an argument **named** for them. If no argument is, it
reads every text argument of a tool whose own name says what it runs. A free-text argument is not
read as a statement: a ticket note stays a ticket note however it is worded. Name the argument that
carries the command, or return it from `extract_query_func`, and the floor can see it.

**Trying it on a live agent?** Out of the box a keyless install watches: calls are screened and
recorded, none are blocked. Set `AGENTX_API_KEY`, or `AGENTX_POSTURE=enforce`, and the same floor
blocks. To hard-block one dangerous tool while the rest keep watching, pin it:

```python
@agentx_protect(agent_id="crm_worker", posture="enforce")
def run_sql(query: str, db=None):
    ...
```

Run `agentx audit` to see what your tools have really been doing, and set `AGENTX_POSTURE=enforce`
on a keyless run when you want every catch blocked. A per-tool `posture=` beats the variable, in
either direction.

**Using Claude Code?** You do not need to decorate anything. In your project folder run:

```bash
agentx hook install
```

It adds a hook to your project's Claude Code settings (merged into what is there) so Claude Code asks AgentX
before every shell command and MCP call, with the same rules. It watches: a call the rules would
stop still runs, and Claude Code shows you a line saying so. To block those calls in every
session, install it with `agentx hook install --enforce` (`--watch` switches back); the call is
refused and the agent is told why. Other tools (reading and editing files) are not checked yet,
and neither are commands you type yourself with `!`: Claude Code does not pass those to any
hook, so they are not recorded either.
`agentx hook uninstall` removes it again and leaves the rest of your settings, and your record,
as they were.

What it costs and where it writes: each checked call starts Python once, which took about 0.3
seconds per call on our Windows test machine (a slower or busier machine takes longer). The
record goes in your project folder, in `.agentx.db` (with `.agentx.db-wal` and `.agentx.db-shm`
beside it) and small per-session files under `.agentx/hook-sessions/`; install gives you the
`.gitignore` lines for them. The hook is tied to the Python you installed it with: if you move
or rebuild that environment, run `agentx hook install` again (`agentx status` tells you when).
Installed the hook before 0.5.6? Run `agentx hook install` again too: it now starts Python with
the project folder off its import path, so a file the agent writes there cannot switch the check
off (`agentx status` warns until you do).

**Correcting your agent about the same thing again?** Turn the correction into a team rule:

```bash
agentx rule add "run_suites.py" --why "the suites run once, at the end, with my go-ahead"
```

Before any shell command containing every phrase you gave, Claude Code asks you first, and shows
your reason. The rule is written to `.agentx/team-rules.json` with who added it (your git name)
and when; commit the file and teammates who use the AgentX hook get the same rule.
`agentx rule list` shows each rule and what it did; `agentx rule remove <id>` takes one out.
An SDK agent's call is checked by a gateway, which holds a matching call for you to answer with
`agentx holds`. If your gateway lists an admin key in `AGENTX_ADMIN_KEYS`, set it as
`AGENTX_ADMIN_KEY` in your own shell, not the agent's, so the agent cannot answer its own hold.
Where nobody can answer a hold, such as a gateway you share with other teams and no admin key for
your key, the gateway stops the call instead and says why. The hosted gateway holds it, and you
answer at agentx-core.com/app. The SDK on its own does not check team rules. Name the agent's tool in the rule (`--tool run_shell`), since `shell` means Claude
Code's and Codex's shell. A gateway you run from the project reads the file; for the hosted
gateway, or any other gateway your agent reaches with `AGENTX_API_KEY` (gateway 2026.10.26.2 or
later), send the rules with `agentx rule push`, and `agentx rule list` says whether the
gateway's copy matches the file. On the hosted gateway you can also add,
edit, switch off and remove them on the website (agentx-core.com/app, Rules tab). With
`AGENTX_API_KEY` set where Claude Code or Codex runs (its environment, or the project's `.env`),
each developer's hook also checks your gateway's rules and tells the gateway only about the calls
a rule matched; `agentx rule list` then shows what each rule did across the team. The gateway's
list wins: a rule changed on the website reaches every machine within 5 minutes, `agentx rule
push` refuses to undo a change made there, and `agentx rule pull` takes those changes into the
file for you to commit.
Nothing is written without a person at the
terminal (or `--yes` from a script you run yourself). In Claude Code's auto mode (and when
permission prompts are skipped) Claude Code does not stop to ask, so AgentX stops the call
instead and gives the command back to you to run yourself as `!<command>`, which the agent cannot
type. The same check runs in Codex once you add it there with `agentx hook install --codex`;
Codex cannot ask, so a team rule warns there and the call runs, unless you add the rule with
`--stop-where-cannot-ask`.

A rule can also hold a call by a number in it: 50 VMs may be fine on dev and not on production.

```bash
agentx rule add --tool provision_instances --argument count --hold-at prod=25 --hold-at dev=500 --why "more than a handful of VMs needs a second look"
```

A call to provision_instances waits for a person when its count is at or above the limit for
where the agent runs. That comes from `AGENTX_ENVIRONMENT` in the agent's process, such as
`AGENTX_ENVIRONMENT=prod`, named as in `--hold-at`; with none set, or one the rule doesn't list,
the lowest limit applies. A call whose count is missing or not a number waits too.

For money, add `--currency USD`, and `--unit cents` if the call's amount is in cents (an amount
of 2550 is 25.50); `--hold-at` stays in the currency. The gateway
already holds a payment at or above a set amount, $10 on the hosted gateway. A money rule
replaces that amount for its tool, higher or lower, unless a limit set on your own gateway is
lower. With `--currency-field` naming the argument that carries the call's currency, a call in
another currency waits for a person too.

With `--recipient customer_id` naming the argument that says who is paid, payments to the same
recipient add up. Without it, the gateway looks for one such as to, payee or customer, and adds up
the tool's payments together when it finds none.

A call counts as a payment when it has an argument named amount, or ending in _amount (not a min_,
max_, lower_ or upper_ bound; nested objects too), and something says it is money: a currency
argument beside it, a value marked as money such as "$250", or a tool or action name that moves
money, such as refund, pay or transfer. A call whose text says it moves money, such as "transfer $50
to the vendor", counts too, and a team money rule names its own argument. The gateway holds one
at or above the money limit for a person: $10 by default, or your money rule's number. A
payment under the money limit can wait for a person too: when payments to the same recipient in the
last 24 hours reach the limit; when the same call, with the same arguments, comes twice within 10
minutes, such as a retry after a timeout; or when an argument named order_id, invoice_id,
payment_id, charge_id or transaction_id (orderId counts too) has the same value as in another call
to the same tool in the last 24 hours, whatever else changed, such as a refund for order 4417
retried the next morning. A retry of the same payment (the same id and amount, or the same call
within 10 minutes) while it waits for a person takes its place, so one approval pays once; the
earlier call never runs. When a payment a person denied comes again (the same id within 24 hours, or the same call
within 10 minutes), the held call says so, in `agentx holds` and on agentx-core.com/app.

When a tool a team rule names changes, the SDK says so once on stderr, so you can check the rule
still fits. It reads the rules file in your project, so a rule kept only on the gateway is not
seen.

#### Decorator options

Everything `@agentx_protect` takes. Only `agent_id` is required.

| Option | What it does |
|---|---|
| `agent_id` | Required. Names the agent on every record, and picks its own site list in `.agentx/allowlist.json`. |
| `extract_query_func` | A function given the call's arguments that returns the text AgentX checks, for a command in an argument named something else, such as `q`. Default: the arguments named for what they carry (`sql`, `command`, `path`, `url` and the like); if none is, every text argument of a tool named for what it runs. |
| `extract_cot_func` | A function given the call's arguments that returns the agent's reasoning for it, sent to the gateway's judge when you have a key. Default: none. |
| `action` | With a key, tells the gateway what kind of action the tool takes, such as `"fetch_url"`. Default: a call whose text starts with a URL is read as one; otherwise the gateway decides. |
| `budget_pool_id` | With a key, tools that share one id share one spend budget. Default: the `AGENTX_BUDGET_POOL_ID` env var, else no pooling. |
| `enforcement` | The older name for `posture`. Still accepted, with a warning; if both disagree, blocking wins. |
| `posture` | `"audit"` watches: the call runs and what your rules would stop is recorded. `"enforce"` blocks. Beats `AGENTX_POSTURE` for this tool. Default: watching without a key, blocking with one. |
| `returns_sensitive` | New. `True` treats the prose this tool returns as sensitive (text of 20 characters or more, more than one word; not status words, dates or ids), for data only you know is private (notes, contracts). Default: `False`, and values are judged by their shape and field name. |
| `sends_out` | New. `True` treats this tool as sending data out of your company, for a tool whose name and arguments do not say so (a helpdesk or CRM client). Default: `False`, and calls are judged by where they go and by their name. |
| `verify` | New. `verify(args, result)` reads the change back after the tool returns. `args` is the call's arguments by name, with the defaults it left out filled in. `result` is what the tool returned. It runs only when the tool returned and the call was not stopped. Exactly `True` confirms. On an async tool it may be async. See Step 2d. Default: none. |

**Sensitive data leaving (Python).** Within one run, AgentX remembers the sensitive values your
protected tools returned: emails, phone numbers, US social security numbers, card numbers, AWS
keys, private keys and GitHub tokens; values under customer-data fields such as `address` or
`billing_address` and secret fields such as `password` (a field ending in key or token, such as
`api_key`, counts when its value looks like a key: 16 characters or more, no spaces, letters
mixed with digits or symbols); and the prose a tool marked `returns_sensitive=True` returns. A
later protected call that sends one
of them out is stopped, or recorded while you are watching, with or without a key. A call sends
out when it names a host or a recipient outside your company, when its name says so (send, post,
upload, email, publish, notify, transfer, push, export), or when it is marked `sends_out=True`. A
value that appears only where the call is addressed, such as `to=` or a URL's host, does not
count: emailing a customer at their own address is the job. The value itself in a call's content
is stopped wherever it goes, its owner included, so the stop tells the agent to leave it out or
refer to it without it (the last four digits of a card). Inside the company means a private or
local address (`localhost`, private IP ranges, names ending `.internal`, `.local`, `.corp`,
`.lan`, `.svc`); every public name counts as outside, your company's own domains included, so a
stop on one of them is a call to look at rather than a leak by itself. The values stay in your process's
memory for the run; the local record keeps the kind of value and the two tool names, never the
value. Not caught: data that is reworded, summarised or encoded before it leaves.

```python
@agentx_protect(agent_id="support")
def read_customer(customer_id):
    ...  # returns the customer's email, card and address

@agentx_protect(agent_id="support", sends_out=True)
def create_ticket(summary):
    ...  # files a ticket in an outside helpdesk

read_customer(42)
create_ticket("Card 4242 4242 4242 4242 was declined")
# watching: it runs, and the record notes it would have been stopped
# blocking: it is stopped, and the agent is told which tool returned the card
```

---

### Step 2b: Handle the Block

Decorating is half the job. Your code also has to *react* when AgentX blocks a call. You never parse the message text. Use `is_block()` and read the structured fields:

```python
from agentx_sdk import agentx_protect, is_block

result = run_sql(query=agent_query, db=session)

if is_block(result):
    print(f"Blocked by policy: {result.policy}")
    llm.send(str(result))             # the whole message: what was wrong AND the safe path to try instead
else:
    use(result)                        # not blocked — the real return value
```

`str(result)` is what your agent should see: it names what was wrong and the safe alternative, and tells the agent to retry. The parts are also there on their own: `result.challenge` is what was wrong, `result.safe_path` is what to do instead. Send `.challenge` alone and your agent never hears the safe path.

For **strictly-typed tools** (e.g. LangChain / Pydantic tools that validate a `-> dict` return), AgentX raises instead of returning, so the framework doesn't crash. Catch it and feed the same message back:

```python
from agentx_sdk import AgentXSecurityBlock

try:
    data = fetch_user(uid)             # -> dict
except AgentXSecurityBlock as block:
    llm.send(str(block))               # same message, same fields (.challenge, .safe_path)
```

> A **circuit-breaker trip** (runaway loop) is *not* a policy block. It raises `AgentXCircuitBreakerTripped` and `is_block()` returns `False` for it. Catch it separately to abort the run.

---

### Step 2c: Or protect an MCP server with zero code

Don't own the tool's Python? Running a non-Python agent? Wrap any **MCP server** with `agentx-mcp` and every `tools/call` is screened by the same keyless floor before it runs. No decorator, no key, no code change. Just one line in your `mcp.json` (Claude Code, Cursor, or any MCP client):

```json
{
  "mcpServers": {
    "filesystem": {
      "command": "agentx-mcp",
      "args": ["npx", "-y", "@modelcontextprotocol/server-filesystem", "/data"]
    }
  }
}
```

`agentx-mcp <real server command>` spawns the real server and relays the protocol untouched, intercepting only tool calls. Out of the box it watches, key or no key: a dangerous call is recorded, noted on the proxy's stderr, and forwarded, and `agentx-mcp --audit` shows what it would have stopped. Add `"env": { "AGENTX_POSTURE": "enforce" }` to that server's entry and a blocked call comes back to the agent as a coaching tool error it can self-correct on, so the run keeps going and the dangerous call never reaches the server.

Beyond the calls your agent makes, `agentx-mcp` also watches the **server's advertised tools** for a bait-and-switch: a malicious or compromised server can advertise a benign tool at install (you approve it once), then silently rewrite that tool's description or schema on a later run to steer your agent. The proxy fingerprints each tool the first time it sees it and warns you when an already-approved tool's definition later changes (the NSA's 2026 MCP guidance names this exact attack). It runs in advisory mode by default (a loud warning, never breaks a run); set `AGENTX_MCP_TOOL_PINNING=block` to also block calls to a changed tool, on every run, until you have checked the change and approved it with `agentx-mcp --approve-changes`; or `off` to disable. Block mode also holds a tool whose description, the first time it is listed, looks like it hides instructions for your agent. `uvx agentx-mcp --audit` lists what your servers changed and which tools are held, apart from the calls your agent made.

**No Python in your stack?** You don't need a persistent install. Run it on demand with [`uvx`](https://docs.astral.sh/uv/) (or `pipx run`), which fetches the package into a throwaway environment, so your `mcp.json` stays one line:

```json
{
  "mcpServers": {
    "filesystem": {
      "command": "uvx",
      "args": ["agentx-mcp", "npx", "-y", "@modelcontextprotocol/server-filesystem", "/data"]
    }
  }
}
```

(`pipx run agentx-mcp <real server command>` works the same way.)

---

### Step 2d: Check that a write really happened

Your agent moves a contact to "customer" in your CRM. The API answers `ok`, nothing changed, and the agent tells the sales team it's done. `verify` reads the record back after the tool has run:

```python
@agentx_protect(agent_id="crm",
    verify=lambda args, result: crm.get(args["contact_id"])["stage"] == args["stage"])
def update_contact(contact_id, stage):
    return crm.update(contact_id, stage)
```

Return `True` when the change is there. Anything else counts as not confirmed. `args` is the call's arguments by name, and `result` is what the tool returned.

When the tool returns an id, check by the id:

```python
@agentx_protect(agent_id="billing",
    verify=lambda args, result: stripe.Refund.retrieve(result["id"]).status in ("pending", "succeeded"))
def issue_refund(charge_id, amount):
    return stripe.Refund.create(charge=charge_id, amount=amount)
```

When it isn't confirmed, the agent gets this instead of the tool's result, and you get a line on stderr:

> ⚠️ [AgentX Unconfirmed] 'update_contact' ran, but reading it back did not show the change. Do not report this as done. Do not repeat the call until you have checked the current state. Tell the user it is unconfirmed.

`is_unconfirmed(result)` tells your code. `agentx status` and `agentx audit` count these by tool. `agentx audit` also says how many calls were read back and confirmed, and the evidence file counts both.

It needs no key. It also works while you're watching, so it's the one option that changes what a watched call returns. A tool with a strict return type, such as `-> dict`, raises `AgentXUnconfirmedError` instead.

When your own code calls the function, not a model, give it a return type like that, or check `is_unconfirmed(result)`: an untyped one hands your code the message in place of its result.

What it won't catch:

- An agent that says done without calling the tool.
- A tool that raises an error, including a timeout where the write did land.
- A slow write. It reads as not confirmed, so wait inside `verify`, and give your read a timeout, because `verify` has none of its own.

If `verify` itself raises an error, the agent is told the result is unknown. The TypeScript SDK has the same option on `agentxProtect`; its README shows it.

---

### Step 3: See your first block: no key, no gateway, no signup

This is the point of AgentX: the deterministic **floor** runs *inside the SDK*. The catastrophic call is caught in-process, with **zero keys and nothing else running**, no LLM, no gateway. (`agentx demo` shows a watching run first and then an enforcing one; the script below pins `posture="enforce"` so you can watch it stop something. Your own install watches by default and lets the call run.)

If you installed from PyPI, `agentx demo` (Step 1b) is this, and it needs nothing else. To read the same block with the source in front of you:

```bash
python examples/00_quickstart_pip.py     # from the repo (a pip install has no examples/)
```

The script wraps an ordinary SQL helper, then feeds it a prompt-injected `DROP TABLE users;`. The in-process keyword shield intercepts it *before it executes*, with no `.env`, no API key and no gateway required. You'll see the block and a clean session summary:

---

🕹️ Console Session Output Logs:

```text
================================================================
AgentX quickstart — watch a DROP TABLE get blocked, no key needed
================================================================

Agent tool call:
  run_sql(query='Update notes for client 99401; DROP TABLE users;')


🛡️ [AgentX SDK] Checking 'run_sql'...
🛑 [AgentX SDK] Stopped 'run_sql': Mass Destructive Intent (local check, no LLM).
📝 [AgentX SDK] Recorded locally (no key needed).
BLOCKED before execution (deterministic floor — no key, no LLM).
  policy:  Mass Destructive Intent
  receipt: local-1

The DROP TABLE never reached your database.
================================================================

════════════════════════════════════════════════════════════
 🛡️  AgentX Session Summary (Trace: b6a45c9f-7e5e-4f56-a5aa-62507625118c)
════════════════════════════════════════════════════════════
 ⏱️  Uptime:                0.01 seconds
 🛠️  Tool calls:            1   |  every call, blocked or not
────────────────────────────────────────────────────────────
 🛑 Intercepts:            1   |  On record: 1
 🚨 Human Escalations:     0   |  this run
 🔄 Self-Corrections:      0   |  On record: 0
 📈 Recovery:              0 of 1 challenges this run |  On record: 0 of 1 blocks
    ↳ of 1 challenge(s): 0 recovered · 0 continued · 1 abandoned · 0 looped
────────────────────────────────────────────────────────────
 💡 Not every call ran as asked this session. See what AgentX caught:
    ▶ agentx insights
════════════════════════════════════════════════════════════
```
---

### Step 3b: Customize the coaching (keyless, by name)

Every block above hands your agent a **coaching** message: what went wrong, plus a safe path to try instead. That wording is what drives whether the agent recovers, so you can override it for any built-in floor policy, **by name, keyless**. No UUID, no gateway.

List the policies you can customize and the coaching each one ships with:

```bash
agentx policies
```

Then override one by its name, inline or in your editor:

```bash
agentx customize "Mass Destructive Intent" --text "Our house rule: never DROP; snapshot then soft-delete first."
agentx customize "Network Sandbox (SSRF)" --edit          # opens $EDITOR seeded with the current coaching
```

Your customized coaching is saved to `./.agentx/overrides.json` (commit it to share with your team) and applies **keyless on both surfaces**: the `@agentx_protect` decorator and the `agentx-mcp` proxy. Add `--safe-path "..."` to set the concrete safe alternative distinctly from the coaching. Validate the store anytime, so a hand-edit typo is loud instead of a silent disable:

```bash
agentx policies --check
```

---

### Step 4: (Upgrade) Recover: turn hard blocks into recoverable challenges

Everything above is keyless **Watch**: the floor screens every call, records it, and (once you set `AGENTX_POSTURE=enforce`) blocks the blatant ones and coaches your agent to self-correct. The **reasoning axis** (orthogonal to `AGENTX_MODE`, and orthogonal to the posture) is **Recover**: the gateway judge catches what the keyword floor can't see, writes the **task-fitting challenge** when your policy carries none, and runs the coach-and-retry for you, plus Discovery for novel-intent classification. The quickest way is our hosted gateway with a free key from **[agentx-core.com/gateway](https://agentx-core.com/gateway)**: nothing to run and no Gemini key of your own. Put the key and the address it gives you in your project's `.env` and load it where the agent starts (`load_dotenv()` from `python-dotenv`, as in Step 5): the SDK reads them from the environment, not from the file. To run your own instead, it takes two things, and they go together:

**1. A `GEMINI_API_KEY`**, the cheap part. Copy `.env.example` to `.env` and set it:

```text
# Reasoning axis — OPTIONAL. Unset = floor-only (zero LLM, zero keys).
GEMINI_API_KEY=your_gemini_key_here       # from aistudio.google.com
# AGENTX_REASONING=off                     # force floor-only even when a key is present
```

**2. The gateway running with that key (Step 5)**, because the judge that *writes* the task-fitting challenge lives in the gateway, not the SDK. The gateway is closed-source, so you run a prebuilt private image. Drop your email at **[agentx-core.com/gateway](https://agentx-core.com/gateway)** and you get a one-paste `docker` command back, no wait. This is the wedge worth the two minutes.

The recovery demo **needs a `GEMINI_API_KEY`** (it makes a real LLM call to re-plan after a block) and the
`google-genai` client, and it lives in the repo's `examples/` folder, so it needs a checkout
(a pip install has no `examples/`). Run it without the key or the client and it declines with a
pointer to the keyless example 00 rather than failing:

```bash
pip install google-genai
python examples/01_self_healing_agent.py
```

> Run it with the key but **without the gateway** and it still completes, but *fail-open*: the in-process shield applies a **static** challenge and the deep semantic checks are skipped. The demo says so itself (`⚠️  RECOVERED, DEGRADED … start the gateway to verify`). The **verified, judge-written** recovery, the actual Recover tier, is the gateway path in Step 5.

---

### Step 5: (Upgrade) Run the gateway: the reasoning judge (Recover), telemetry, control plane, HITL

The SDK screens every call on its own (keyless **Watch**), and blocks on its own once you set the posture. The gateway is what unlocks **Recover** from Step 4: with a `GEMINI_API_KEY` set, the judge here writes the verified, task-fitting challenge (the keyless path only ever gets a static one). Run the gateway and the Next.js console to add the **data plane** (the reasoning judge, deep AST evaluation, the policy lifecycle) and the **control plane** (the ROI dashboard, Chain-of-Thought review, human-in-the-loop approvals). This is the `AGENTX_MODE` **data axis**, where data lives and whether it syncs:

```text
#   local   isolated; local SQLite store; no sync; no keys required
#   linked  local-authoritative; explicit pull/push; no auto-sync
#   cloud   control plane authoritative; continuous sync + upload + HITL/SOC
AGENTX_MODE=local
NEXT_PUBLIC_AGENTX_MODE=local   # the UI's build-time copy; keep it equal
# AGENTX_API_KEY=agentx_sk_your_key_here   # required for `cloud` (and remote `linked`)
```

**Connecting to the cloud is one variable.** You don't need to set all three. In the
gateway's own environment, `AGENTX_API_KEY` means cloud upload, so just setting it there (with
no `AGENTX_MODE`/`CONTROL_PLANE_URL`) puts the gateway in `cloud` mode against the
public plane, and it says so loudly at boot (`🔑 AGENTX_API_KEY detected → CLOUD
mode …`). Set `AGENTX_MODE=local` to override and stay isolated, or `linked` (with
a `CONTROL_PLANE_URL`) for explicit pull/push without auto-upload.

**Your agent needs a key too, or it never calls the gateway.** With no `AGENTX_API_KEY`, a Python
tool stays on the local checks and a TypeScript tool only records, whatever the gateway URL. Set
these where your agent runs:

```text
AGENTX_API_KEY=agentx_sk_local_sandbox
AGENTX_GATEWAY_URL=http://127.0.0.1:8000
```

Set them in your shell, or put them in your agent's own `.env`, not the gateway's, and load it:
`load_dotenv()` in Python, `node --env-file=.env` in TypeScript. If you set your own `AGENTX_API_KEY` in the gateway's `.env`,
use that one instead.

Boot the data-plane wedge and the dashboard:

```bash
docker compose up -d
```
OR
```bash
uvicorn --app-dir backend gateway:app --host "0.0.0.0" --port=8000
```

> Run it from the **project root** with `--app-dir backend`, not `cd backend && uvicorn …`.
> The gateway resolves its data home from the project root, and that is fully
> cwd-independent only where a `.git` anchor exists; in a checkout-less tree the fallback
> is the nearest `.agentx/` ancestor, so a server started inside `backend/` can resolve a
> different home than `agentx insights` does. `scripts/start_gateway.py` does this for you.

**Running the end-to-end suites?** Start the gateway with the launcher instead. Both
`backend/test_gateway.py` and `sdk_tests/test_agentx_sdk.py` drive a gateway that is
*already running*, so their incident writes happen in the server's process and no test
fixture can redirect them. The launcher points that process at a scratch incident and
policy store, so a full test run does not write the stores `agentx insights` reports on:

```bash
py scripts/start_gateway.py --e2e            # uvicorn, scratch store
py scripts/start_gateway.py --e2e --docker   # same, via docker compose
py scripts/start_gateway.py                  # normal dev gateway, real store
```

The gateway keeps its data in **one** place: `<project root>/.agentx/`
(`incidents.db`, `policies.db`, `policies.json`). That is resolved from the project
root, not the directory you start from, so starting the gateway from `backend/` no
longer creates a second store that `agentx insights` cannot see.

> **Both commands above build the gateway from source** (internal / source-access).
> The gateway is closed-source, so **you run a prebuilt private image instead**,
> `pip install agentx-security-sdk` does not ship it. Drop your email at
> [agentx-core.com/gateway](https://agentx-core.com/gateway) and you get a one-paste
> `docker` command back immediately. No sales form, no wait. The starter kit in
> [`deploy/partner/`](deploy/partner/) then runs the image (no source needed).

The reasoning engine then listens on http://localhost:8000 and the dashboard on http://localhost:3000. In `local`/`linked` mode the gateway owns the policy lifecycle from a local SQLite store (seeded on first boot, editable via the Policy & Discovery tabs); in `cloud` mode it mirrors policies from your Supabase-backed Control Plane.

**Fail-mode (optional).** This answers a different question from the posture below: what happens when the **gateway** is unreachable. By default AgentX **fails open** -- tool calls still execute, with a loud warning and a tally in the session summary, and the in-process floor still screens them. `AGENTX_FAIL_MODE=closed` refuses any call the engine could not verify until it recovers. ⚠️ It does nothing while you are watching, because a posture that refuses nothing cannot refuse an unverified call; set it together with `AGENTX_POSTURE=enforce`, and on its own the SDK says once that it is inert.

**Money limit (optional).** The gateway holds a payment at or above 10 for a person by default. On a gateway you run, `AGENTX_TRANSFER_ESCALATION_THRESHOLD=500` changes that default, and `AGENTX_TRANSFER_LIMITS={"support_agent:issue_refund": 500}` sets one for an agent and tool. A team money rule (`agentx rule add --currency USD`, under "Correcting your agent about the same thing again?" above) sets one for its tool on any gateway, the hosted one included, higher or lower, unless a limit set on your own gateway is lower.

**Posture: the free SDK watches, a gateway enforces, and you can say otherwise.** Out of the box the keyless SDK **watches**. It runs the full detection and records every call, and **nothing is blocked** -- so adding AgentX cannot break an agent that already works. `agentx audit` shows what your agent actually did; `agentx insights` shows what would have been blocked, per policy. When the catches look right, set `AGENTX_POSTURE=enforce` and they become real. ⚠️ **An install with an `AGENTX_API_KEY` set enforces by default instead**, and that is deliberate: a key is what reaches the gateway, so it is the rung you climbed to in order to block. Handing that install the watching posture would quietly turn off the protection you set up. `AGENTX_POSTURE` still wins on either rung -- set `audit` on a gateway install and it watches. The one exception is our hosted gateway: a key set to enforce there enforces the calls the gateway checks, whatever this setting says (Step 5c). You can also keep one dangerous tool hard-blocked while everything else watches, with a per-tool override: `@agentx_protect(..., posture="enforce")`. Posture is a separate setting from the fail-mode above, **and it wins**: while a tool is watching, nothing AgentX decides changes what that tool does -- including `AGENTX_FAIL_MODE=closed`, which cannot refuse a call in a posture that refuses nothing. Every kind of stop is written down and then let through: the built-in keyword shield, a policy block from the gateway, a pause for human approval, and the halt that fires when an agent keeps retrying. A tool you gave the per-tool override above still blocks, which is the point of the override. A test re-checks this against every rule in the gateway's list. (`AGENTX_ENFORCEMENT`, the old name, is no longer read.)

**With a key, the gateway decides.** A call the SDK's free check matches is sent to your gateway,
and the gateway's answer stands, its allow included (the console says the free check had matched
it). The free check decides alone without a key, and whenever the gateway cannot answer
(unreachable, an error, an answer it cannot read). `AGENTX_SHIELD_ASKS_GATEWAY=false` keeps the
older behaviour, where a match was refused in process and the gateway never asked. One shape the
free check stops, the gateway does not stop yet: a local script piped into a shell
(`cat setup.sh | sh`); with a key you get the gateway's answer on it.

### Step 5b: Limit each agent to its tools and sites

An agent you ship calls a fixed set of tools. Write that set down and your gateway stops anything
else, and your customer's reviewer gets the list itself:

```bash
agentx review            # proposes each agent's tools and sites from the calls it ran
agentx allowlist push    # sends .agentx/allowlist.json to your gateway, for it to enforce
agentx allowlist         # says whether your gateway holds the same list as the file
```

The list lives in `.agentx/allowlist.json`; commit it, and git records who changed it. An entry
named `*` covers every agent the file does not name, so an agent cannot leave its list by calling
itself something else (not the Claude Code hook or agentx-mcp, which are your own tools: name them
to limit them). The gateway's evidence (`/v1/evidence`; for a hosted key, the Rules tab
at [agentx-core.com/app](https://agentx-core.com/app)) lists each agent's tools and sites and when the list was pushed. Without a gateway the SDK checks the
sites in the file on its own (it flags a call to a site off the list, and stops it with
`AGENTX_POSTURE=enforce`); tool lists need the gateway, so review proposes a first tool list
only when `AGENTX_API_KEY` is set (`uvx agentx-mcp --review` proposes none). On a self-hosted
gateway that set `AGENTX_ADMIN_KEY` (or, on a box with `AGENTX_API_KEYS`, listed that customer in
`AGENTX_ADMIN_KEYS`), pushing needs that **admin key**, so the agent's own process,
which holds the agent key, cannot loosen its own list with a push: set it in your own shell, never in the
agent's environment or the project's `.env` (the CLI refuses one it finds there). On the hosted
gateway a push made with your key waits as a change until whoever reads the email address the key
was issued to approves it at [agentx-core.com/app](https://agentx-core.com/app), signed in with a code sent to
that address (`agentx allowlist push` and `agentx rule push` say "Nothing changed yet"), unless
that person let the key answer for itself (Step 5c): then a push with it applies at once. ⚠️ A
self-hosted gateway with no admin key still takes the API key for a push, so there any holder of
that key, the agent's own process included, can push a list. A tool list makes the file version 2, which SDK 0.5.5
and older refuse (they then stop every outbound call, naming the file), so upgrade every install
that shares it.

### Step 5c: Answer the calls your gateway holds

A rule can hold a call for a person instead of stopping it (a payment over the limit, a delete the
judge doubts). The agent waits, and you answer:

```bash
agentx holds                      # the calls waiting for your answer
agentx holds approve <receipt>    # let it run
agentx holds deny <receipt>       # stop it
agentx holds dismiss <receipt>    # clear it without approving (it does not run)
```

The dashboard's **Held Calls** tab lists the same calls. On a gateway that set an admin key,
answering needs it, for the same reason as pushing a list: an agent can never approve its own
held call, and its key can only say it stopped waiting. The dashboard does not hold that key, so
there you answer with `agentx holds` (from TypeScript, `npx @agentx-core/security-sdk holds`). On a
gateway with one key, that key answers, in either
place, so there a hold is a pause for you, not a lock against an agent that can reach the key.
On the hosted gateway your key cannot answer: we email the address that asked for it when a call
is held, the email carries a 10-character code, and whoever reads that address signs in with
it at [agentx-core.com/app](https://agentx-core.com/app). With no code to hand, press "No code?
Email me one" there: on the page opened with the key (under "Just want to look?") it sends a code
for that key; typed with the address alone it sends one for that address's newest key. The
sign-in lasts 8 hours on that browser, a refresh included.
That holds only while your agent cannot read that inbox: an agent with access to that email
account could read the code and sign in itself. Starting with one key? Signed in, you can let the
key answer its own held calls (and push rules that apply at once) on the Settings tab, under "Who
answers held calls": `agentx holds approve` then works with it again, and your agent can approve
what is held for it too, so a hold is a pause for you, not a lock.
Each waiting call shows why it was held and, where its call carried one, the command it asked to
run, with Approve and Deny. `agentx holds` still lists them. The same page sets whether the
key's calls are only watched or enforced: the key's first call that speaks for the whole install
set it (a tool's own `posture` does not). On a key set to enforce, a call your code sets to watch
only, a tool's own `posture` included, is enforced when the gateway checks it (SDK 0.5.12 and
later); set the key to watch only to let it watch. A match on this machine's own policy files,
decided before the gateway is asked, still only watches.
In cloud mode the held calls live in the control plane: answer them on the dashboard
(`agentx holds` sees none).

---

## 📊 Control Plane Telemetry

When your agent script finishes or exits, AgentX writes its telemetry to the local `.agentx.db`. In `cloud` mode that also syncs to your control plane; in `local` and `linked` mode it stays on the machine. With the dashboard running, open http://localhost:3000/dashboard to see the summary. **The numbers below are illustrative, not measured results:**

```text
+-----------------------------------------------------------------------------------+
|                        EXECUTIVE COMMAND CONSOLE                                   |
+-----------------------------------------------------------------------------------+
|  [Catastrophic Actions]   [Autonomous Recovery]  [Runs Protected]  [Time Saved]   |
|         92                      36.3%                  37             12.3 hrs     |
|  🛑 Irreversible/exfil   📈 Self-corrected ÷    🛡️ Runs that     ⏱️ ~20 min/run  |
|     stopped pre-exec        challenged loops       self-corrected     reclaimed    |
+-----------------------------------------------------------------------------------+

```

**Executive ROI Mappings** (all computed *per session*, grouped by `trace_id`):
* **Catastrophic Actions Blocked (hero):** A pure count of distinct sessions whose intercepted action fell in an irreversible / exfiltrative class, `failure_mode ∈ {DESTRUCTIVE_ACTION, PII_EXFILTRATION, NETWORK_TRAVERSAL, SECRETS_LEAK}`, with a policy-name keyword fallback. Every incident in the ledger is a *pre-execution* interception, so this is harm averted, not harm survived.
* **Autonomous Recovery Rate:** Of the sessions that entered the challenge loop, the share whose terminal status is `COMPLIED` (the agent self-corrected). Counted per session so `recovered ⊆ challenged`, **bounded ≤100% by construction**. HITL-approved sessions are excluded; only autonomous self-correction counts.
* **Agent Runs Protected:** Sessions the agent self-corrected after a block (terminal `COMPLIED`).
* **Engineering Time Saved:** ~20 min of manual triage credited per protected run, valued at $75/hr.

> Operator dashboard metrics are scoped to **production agents only**, demo, simulation, blind-eval, and test/probe traffic are excluded so benchmarks never inflate an operator's numbers (they showcase the engine on the public landing page instead).

---

## 🧠 The 5 Pillars of Agentic Security

AgentX is built on a "Reasoning Engine" architecture that treats AI agents as autonomous employees rather than static scripts:

1. **Cognitive Interception:** We intercept tool calls to compare the agent's stated intent (Chain of Thought) against its actual deterministic action.
2. **Socratic Nudging:** Instead of crashing the agent, we issue a Socratic Challenge to guide them to a safe, desired end-goal.
3. **Shared Immunity Network (roadmap):** Novel zero-day signatures discovered on one node are designed to graduate into the deterministic floor and propagate to other Edge nodes for O(1) interception. The local Discovery → Promote → live-in-3s loop works today; cross-node global distribution is a Day-100 capability and is **not yet active**, we don't claim it until it is.
4. **Circuit Breakers:** If an agent enters an infinite hallucination loop, AgentX hard-locks the runtime after 3 strikes to prevent massive LLM token billing overages.
5. **Human-in-the-Loop (HITL):** If an agent pulls the "Andon Cord" (requests help), the system suspends the execution thread (`202 Accepted`) and parks it in Held Calls for a person to approve (see Step 5c).

---

## 🚀 The 4 Shields (Defense-in-Depth)

1. The Inbound Shield (Prompt Injection): Sanitizes inbound user text to prevent cognitive hijacking ("Ignore previous instructions") before the agent reads it.

2. The Logic Shield (Database Guard): Uses AST parsing and Gemini to catch destructive queries (DROP, DELETE) and nudges the agent to write safer SQL.

3. The Network Shield (SSRF Guard): Prevents agents from acting as confused deputies to hit cloud metadata IPs (e.g., 169.254.169.254).

4. The Egress Shield (DLP/PII Scrubber): Dynamically masks PII and API keys on the wire, maintaining clean audit logs without triggering SOC alert fatigue.

---

## 📊 Local Telemetry & Agent Health

AgentX ships with a built-in, privacy-first SQLite time-series event log (`.agentx.db`). It records every interception locally, and never a raw query, argument value or payload. It also records one row per call that PASSED, whether blocking is on or off, so `agentx audit` can show you what your agent actually did: the tool's own name, its argument NAMES, a magnitude bucket, a coarse target class, and the site any web address in the call pointed at (the host alone, never the full address). Never the values. The one place values are kept is a second local file you turn on yourself: `agentx_sdk.task()` and `reply()`, and `AGENTX_KEEP_ARG_VALUES=1`, write the task, the agent's reply and the calls' values to `.agentx.db.runs.jsonl` for `agentx match` (see "From this SDK's own record" below). When your agent script finishes or crashes, AgentX prints a session summary:

```text
════════════════════════════════════════════════════════════
 🛡️  AgentX Session Summary (Trace: 74096ff7-37b0-4b69-a7a3-fe27d62d4000)
════════════════════════════════════════════════════════════
 ⏱️  Uptime:                0.01 seconds
 🛠️  Tool calls:            1   |  every call, blocked or not
────────────────────────────────────────────────────────────
 🛑 Intercepts:            1   |  On record: 6
 🚨 Human Escalations:     0   |  this run
 🔄 Self-Corrections:      0   |  On record: 0
 📈 Recovery:              0 of 1 challenges this run |  On record: 0 of 6 blocks
    ↳ of 1 challenge(s): 0 recovered · 0 continued · 1 abandoned · 0 looped
────────────────────────────────────────────────────────────
 💡 Not every call ran as asked this session. See what AgentX caught:
    ▶ agentx insights
────────────────────────────────────────────────────────────
 Most blocks in this ledger are one policy: 'Mass Destructive Intent'
════════════════════════════════════════════════════════════
```

To see what was blocked, grouped by policy, with recoveries beside each:

```bash
agentx insights
```

`agentx insights` answers *what got stopped*. **`agentx audit` answers the wider question: what
did my agent actually do**, including every call we let through. It is the screen to read before
you trust an agent with something, and the one to read after it surprises you.

```bash
agentx audit                # grouped by tool, one row per tool
agentx audit --calls        # one row per call instead
agentx audit --json         # the same content as data, for a program
agentx audit --share        # writes agentx-audit.json, with this machine's fingerprints removed
agentx audit --limit 100    # or --all. The human views page; --json is never capped
```

**`agentx evidence` writes the file a reviewer asks for**: the rules this machine checks calls
against (each in a reviewer's words, your team's rules included), the calls it stopped or held (a call stopped while watching
is listed as having run), the calls that did not run because no verdict could be had or that were
halted as a runaway loop, and the record's latest entry, which `agentx audit --record --head`
checks later to show the record was not rewritten. It never includes the calls' own text.

```bash
agentx evidence                       # writes agentx-evidence-<date>.json here
agentx evidence --out for-review.json  # or a name you choose
agentx evidence --json                 # the same document on stdout, for a program
```

With a key, `agentx evidence --gateway` writes your gateway's own file instead: the rules it
checked every call against and the calls it stopped or held, for every agent using that key, with
the gateway's notes on how to read each part. The gateway builds it (2026.10.30.2 or later), and
with a hosted key the same file comes from [agentx-core.com/app](https://agentx-core.com/app), on
the Security review tab.

```bash
agentx evidence --gateway                  # writes agentx-evidence-<date>.json here
agentx evidence --gateway --head <value>   # was the gateway's record rewritten since that file?
```

Two flags turn `agentx audit` into a CI gate, with the same exit codes as the TypeScript door:

```bash
agentx audit --require-calls        # exit 2 if the ledger holds no calls: the output says nothing about the agent
agentx audit --fail-on-rule-match   # exit 3 if a recorded call matched a rule you adopted
```

Both work with `--json`, which then carries the verdict in a `ci` block, alone on stdout.

`--calls` and `--json` are independent on purpose: `--calls` decides **what** you see, `--json`
decides **how** it prints, so all four combinations mean something. There is no way to ask for
the grouped view machine-readably if those are folded into one flag.

To show a single catch to someone else:

```bash
agentx share                                # your most recent block, as a postable receipt
agentx share --note "what my agent tried"   # add your own line to the draft
```

It renders a receipt card plus a ready-to-post draft. The card is built only from the abstract
ledger fields: policy class, your own tool name, the verdict, and when. **It cannot carry a raw
query or payload, because the ledger never stores one.**

### Check what your agent said it did against your records

`agentx match` reads three files you export and lists where they disagree: what the agent was
asked (the tasks), what it did and said (its log), and what your system shows changed (the
change history of your CRM, help desk or other system). It runs on your machine, makes no network
calls and needs no key.

For example: someone asks the agent to move Lea Brandt to Won. The agent calls
`update_contact(contact_id="C111", stage="Won")` and replies "Done, I've moved Lea Brandt to Won."
The CRM's history shows the agent's account moving her to Proposal. The report lists it, with the
call, the reply and the CRM row side by side.

```bash
agentx match --demo      # a practice week with 11 mistakes planted, to see the report first
agentx match --tasks tasks.csv --log agent_log.jsonl --records history.csv
agentx match --tasks tasks.csv --log agent_log.jsonl --records history.csv --out report   # also writes report.md and report.json
```

It lists five things: work the agent said it did that no record shows (and runs that made no
change at all, with the agent's reply, for you to read); work done twice (the same call again within
30 minutes of the one before, or `--window`, and the records showing the change twice: a reminder
sent at 09:00 and again at 15:00 is two pieces of work, not one done twice; or one call whose change
the records show twice within the window); records that differ from
what the agent's call asked for; changes the agent's account made with no call in the log behind
them; and tasks the agent never ran. Anything it cannot decide goes on an "unsure" list instead.

It compares the record with the agent's **call**, not with the task's words. An agent that reads
"move Lea Brandt to Won" as Proposal, calls for Proposal and gets Proposal is not caught: its call
and the record agree.

It reads CSV, JSON or JSON Lines, finds the columns by their usual names, and works out the
agent's account, the records' time zone and which call writes which field, then prints what it
assumed. When a guess is wrong or a column has another name, a mapping file sets it:

```json
{
  "records": {"time": "When", "entity_id": "Object ID", "entity_name": "Object", "tz": "+03:00"},
  "tasks": {"id": "ticket", "time": "opened_at", "text": "body"},
  "log": {"run_id": "session", "task_id": "ticket", "reply": "output"},
  "agent_account": "integration:my-agent",
  "window_minutes": 30
}
```

```bash
agentx match --tasks tickets.json --log agent_log.csv --records history.json --map mapping.json
```

Each part names a column by its header. `records`: `id`, `time`, `entity_id` (the record's id),
`entity_name`, `field`, `old`, `new`, `actor` (who made the change). `tasks`: `id`, `time`,
`text`. `log`: `run_id`, `task_id`, `time`, `calls` (a run's list of calls), `tool`, `args`,
`reply`. Any part may add `tz` for times written without a zone (`UTC`, `-05:00`); a time that
states its own zone keeps it.

**From this SDK's own record.** Instead of exporting the tasks and the log, let the SDK keep them.
Your code tells it where each task starts and what the agent replied, around the agent (the agent
itself never calls these):

```python
import agentx_sdk

def handle_message(text, conversation_id):
    agentx_sdk.task(text, id=conversation_id)  # the request, as it came in
    answer = run_agent(text)                   # your agent; its protected tools are recorded under this task
    agentx_sdk.reply(answer)                   # what it told the person
    return answer
```

To match a call to a record, the check needs the values the call was made with. The SDK keeps only
argument names unless you set `AGENTX_KEEP_ARG_VALUES=1` where the agent runs. Then:

```bash
agentx match --from-sdk --records crm_history.csv
```

`--records` is what your system shows changed: a CRM's change history, a calendar export (`.ics`)
or a Twilio message log. To check bookings against a calendar, say once, on the tool, that it books:

```python
@agentx_protect(agent_id="front-desk", effect="books")
def book_appointment(customer_email, start): ...
```

Three failures people building agents have told us about, and what `agentx match` prints for each.

The agent said it booked, and the slot is not on the calendar (`--records bookings.ics`, the
calendar's export):

```text
1. Said it was done, but no record shows it (1)

- task call-101, run call-101/a1b2c3d4e5f0,
  book_appointment(customer_email=ana@example.com,
  start=2026-11-24T15:00:00-05:00): No booking for ana@example.com at
  2026-11-24T15:00:00-05:00 is on the calendar, and none was made within 30
  minutes of the call.
  - Asked: "Can I come in Tuesday at 3pm? I'm ana@example.com"
  - The agent said: "You're booked for Tuesday at 3pm."
```

Two triggers fired on one webhook, and the lead was routed twice. Each run did it once, so neither
run shows it; the CRM's change history does:

```text
2. Done twice (1)

- task lead-L77-wh-1, run lead-L77-wh-1/a1b2c3d4e5f0,
  assign_lead(lead_id=L77, owner=maya): 2 runs made the same call for the
  same request, 0 minutes apart (lead-L77-wh-1, lead-L77-wh-2), and the
  records show the change 2 times.
```

The booking landed on another slot: the one made right after the call is at 4pm, not 3pm.

```text
3. The record differs from what the agent's call asked for (1)

- task call-101, run call-101/a1b2c3d4e5f0,
  book_appointment(customer_email=ana@example.com,
  start=2026-11-24T15:00:00-05:00): The call asked for start =
  '2026-11-24T15:00:00-05:00'; the booking for ana@example.com made then
  starts at '2026-11-24T16:00:00-05:00'.
```

Against a calendar, the calls checked are those of a tool marked `effect="books"`, each naming one
person by email and one start time. `effect="cancels"` marks a tool that removes a booking, so its
missing booking is never reported. A tool's name is never read: every other call is named in a note
as not checked, with the line to add, and so is a booking known only by phone number. For a log
written by anything else, name the tools in a mapping file passed with `--map`:
`{"book_tools": ["book_appointment"], "undo_tools": ["cancel_appointment"]}` (and `"read_tools"`
for tools that only read, to leave them out of that note). What the files cannot settle (a start with no time
zone, a booking rescheduled or cancelled since, an event that does not say when it was made) is
listed as unsure, not as a finding. An event counts as a person's booking when it lists them as a
guest; one made at that time without them (a system that invites only the stylist or the room, or
writes the customer only in the title) makes a missing booking unsure. A call that carries the
person and time of a booking made earlier (a reminder) is not reported as a missing booking. A
missing booking dated before the file's first event or after its last (an export of a date range
that leaves that day out), in a file with no events, or in one with an event whose start time this
tool cannot read (the report names how many), is unsure.

All of it goes in one file, `.agentx.db.runs.jsonl`, beside the SDK's ledger (`.agentx.db`), on your
machine. Nothing in it is sent anywhere. The SDK says what it keeps the first time it writes there. An
argument named like a secret (`password`, `api_key`, `token`, `database_url`, `key`, `session`,
`pin`, `ssn` and the like, inside dataclass, pydantic and other structured arguments too) is kept as
`[withheld]`, and so is an argument whose fields cannot be read. An id under such a name, like
`contact_key` or `session_id`, is withheld too and cannot be matched, so pass it as `contact_id`. A
long value is cut at 1,000 characters. `crm_history.csv` here is the same change history as above. Keep the file out of git: a
`.agentx.db*` line in `.gitignore` covers it and the ledger, and the SDK names that line when git
would commit the file. `reply()` ends the task, so calls after it are not filed under it; call it in
the same thread or async task as `task()`. A task belongs to the thread or async task that started it, so an agent
serving several people at once keeps each conversation's calls apart; `id=` is optional. A call made
in another thread is filed under the task when that thread carries the caller's context
(`asyncio.to_thread`, `contextvars.copy_context().run`); a thread started without it is not. With no task
started and the setting off, the file is never made. In a notebook or an async agent, a line reaches
the file a moment after its call returns. To check a run straight after it ends, call
`agentx_sdk.runs.flush()` in the agent's own code first (in a notebook, in the cell before `!agentx
match`). A task
with a call recorded before the setting was on is left out of the report and counted, because its
calls cannot be matched. The TypeScript SDK does not have `task()` or `reply()` yet.

**A calendar on its own.** Export the calendar your booking agent writes to (Google Calendar,
Outlook and Apple Calendar all export `.ics`; Cal.com and Calendly bookings land in that calendar)
and run:

```bash
agentx match --records bookings.ics
```

It lists two things the agent may have done: a slot booked twice (two events that overlap on the
calendar) and one person booked twice (two bookings for the same person, made within 30
minutes of each other and starting within a day). Two events made together on purpose for the
same people (a game and the party after it, a meeting and its extension) show as booked twice too:
the file cannot say which was intended. The report gives the dates the file covers and how many
events no check reads. A cancelled event or a time marked free never
counts; an all-day event never holds a slot; a repeating event's moved instance is not compared with
its own series, and a first occurrence that was deleted or moved holds nothing; a person who
declined, and a room, are not counted as people (a room is what the export marks as one, and any
Google Workspace room by its address); nor is a Google shared calendar added as a guest. A repeating
event is checked at its first date only: a clash with a later week of it is not found. One export
is one calendar, read as its owner's time: the owner is the
address a mapping file names (`{"owner": "dr@clinic.com"}`), else the calendar's name when that is
an address, else the address on nearly every event that names an organizer. When two addresses are
equally likely (an agent's account that books every event and the owner it invites), the report
says so and asks for the mapping file. The owner is never one of the people booked, and an
invitation the owner declined holds no time (one not answered yet still does, as on the calendar
itself). For a shared calendar of several people, export each person's. "Booked twice" needs each
event's creation time; the report says how many events had none. An event in a time zone that
cannot be read (Outlook writes a few names this tool does not know; on Python 3.8, every named zone)
is compared only with events in the same zone: the report names the zone and the reason, and the
run exits 1, not 0, since those events were not checked against the rest.

**Text messages on their own.** On Twilio's console, open Monitor, then Logs, then Messaging, set
the dates and press Export CSV. Then:

```bash
agentx match --records sms-log.csv
```

It lists three things: texts that did not arrive (Twilio marks them failed or undelivered, named
with the error in plain words), one person texted the same thing twice, and texts the agent started
outside permitted hours. A text still at "sent" has no delivery receipt from the carrier, which is
not a failure: it is counted, not listed. Twice means: a text the agent started (`outbound-api`)
repeated to the same person within an hour, or a reply sent twice to one incoming text (a reply to
each new message repeats on purpose). A copy that failed or was undelivered never reached the person
and is not counted, so a retry is not a second text. An `outbound-api` text sent within 5 minutes
after the person's own text is the agent answering it, and counts as a reply. Permitted hours are
08:00 to 21:00 in the time zone the export writes; a reply to the person's own text may go out at
any hour. A mapping file
sets other hours: `{"hours": {"start": "08:00", "end": "20:00", "tz": "-06:00"}}`. SMS and
WhatsApp to one number count as one person. Twilio's voice-call log, and pages from Twilio's API,
are not read: the tool says so and how to export the message log instead.

The exit code is 0 when nothing is listed, 1 when something is listed or on the "unsure" list
(what it could not decide), a check could
not finish or some events could not be compared with the rest, and 2 when a
file could not be read or nothing could be checked (a change history alone checks nothing; a
calendar or a message export alone runs its own checks), so a scheduled run can tell them apart. Readers for other
systems' exports, and checks of your own, plug in as Python packages (entry-point groups
`agentx.adapters` and `agentx.checks`).

### The rest of the commands

Two more you will want early, and neither has appeared above:

```bash
agentx status     # what is armed right now, and your local protection stats
agentx review     # one key per pending block: adopt a safe path, or label the block
```

`agentx review` is the loop that turns a pile of blocks into rules you keep. `--stats` summarises
every incident's outcome rather than only what is still pending.

The rules you adopt live in **`.agentx/rules.json`**, a plain file in your project: commit it,
review a change to it in a pull request, and a gateway reads it at boot and on every policy
refresh, so a change reaches a running gateway within minutes.
Name a rule yourself with `agentx adopt <#> --name "..."`; without a name, a rule proposed from
your own calls is named after the tool and its argument names. `agentx review --undo` takes one
back. Over the MCP door, name your project in the server's env block
(`AGENTX_PROJECT_DIR`; `${CLAUDE_PROJECT_DIR}` on Claude Code) and the proxy reads the same file.

The rest live behind `agentx help --advanced`: adopting learned safe-paths, recording
verdicts, customising a floor policy's coaching by name, and org sync. **`agentx help` is the
list that is always current** — this page is a walkthrough, not a reference, and the CLI is the
thing that ships.

**Every number on these CLI screens is one the SDK measured.** There is no "tokens saved" or
"time saved" line, because nothing on this path can observe what a call we stopped would
have spent — those figures used to be a constant multiplied by a block count, and they are
gone rather than estimated. The operator dashboard's "Engineering Time Saved" (Control Plane
Telemetry, above) is still that kind of estimate, 20 minutes per protected run, and is labelled
as one there.

---

## 📦 Try the other Developer Demos

These live in the `examples/` folder of the repo, so they need a checkout rather than the pip install:

* **01_self_healing_agent.py:** Watch AgentX catch a hallucination and coach the agent to self-correct (Saving tokens and uptime).
* **02_cognitive_intent_block.py:** Watch AgentX catch malicious intent even when the raw syntax is perfectly safe.
* **04_circuit_breaker_demo.py:** AgentX catches and prevents an infinite apology loop, saving time and tokens.
* **06_hitl_escalation.py:** See how an agent safely pauses execution and waits for a person to approve it, using a 202 Accepted queue.
* **09_budget_ceiling_demo.py:** Watch AgentX meter a runaway agent's cumulative spend and halt the session the moment it crosses your budget ceiling, a deterministic, gateway-side escalation (no LLM judge). Needs the gateway running + a key.
* **10_self_correction_coaching.py:** The Recover tier, where the gateway judge does the coaching for you. AgentX blocks a dangerous action and returns a task-fitting challenge that names a safe path, so your agent finishes the job instead of dead-ending. Puts the AgentX challenge side by side with a bare refusal, then watches the agent recover on it. Needs the gateway running + your Gemini key (the keyless Shield already coaches in-band; Recover's judge catches more and runs the retry for you).
* **12_audit_what_your_agent_did.py:** The one demo where nothing is blocked, including the poisoned call at the end. A support agent works a refund ticket end to end, and AgentX records every wrapped tool call, whether blocking is on or off: the argument names, the surface, the size of any amount passed, the site any web address pointed at, never the values. Run `agentx audit` afterwards for the table. The poisoned call is not on it, because a call that tripped a policy shows in `agentx insights` instead. Keyless, no gateway.
* **And many more...**

---

## 🕹️ Human-in-the-Loop (HITL) & Control Plane
Sometimes, an agent needs to drop a table for a valid business reason.

AgentX ships a Next.js Control Plane dashboard. If an agent requests an escalation, the SDK pauses local execution and polls the gateway. A human reviewer clicks "Approve" or "Deny" in the UI, and the Python execution loop resumes on its own.

Running the dashboard needs the repo, not the pip install:

```bash
cd ui
npm install
npm run dev
```

---

## 🏗️ The Architecture (Split-Plane)

Three pieces. Only the first one is required, and it is the only one that ships in the pip package.

* **The Edge SDK (`agentx_sdk`):** The Python package that instruments your tools and carries the keyless deterministic floor. Runs in your process. This is what `pip install` gives you.
* **The Data Plane (Reasoning Engine):** A FastAPI service that evaluates what the floor waves through, via a three-stage funnel: the deterministic floor first, then AST evaluation, then the LLM judge. Closed source, run as a prebuilt image.
* **The Control Plane (Dashboard):** A Next.js app where a human reviews intercepted traffic, reads chains of thought, and approves or denies parked requests.
* **Where state lives:** Mode-dependent. In `cloud`, Supabase is authoritative and both planes sync through it. In `local` and `linked`, the gateway's own SQLite stores (`.agentx/incidents.db`, `.agentx/policies.db`) are authoritative and nothing syncs. See [What leaves your machine](#-what-leaves-your-machine).
* **The Evaluator:** Google Gemini 2.5 Flash or Pro, configurable by environment variable. It reads the agent's stated intent and evaluates it against your policies. Only used on the gateway path; the keyless floor never calls it.

---

## ✨ Key Features & Built-in Policies

* **Automated Socratic Self-Healing:** Intercepts dangerous tool calls and challenges the agent to revise its strategy.
* **Fast Pass Heuristic Traps:** Instantly intercepts structurally dangerous queries (e.g., `DROP TABLE`, or an unscoped / `WHERE 1=1` mass `DELETE`/`UPDATE`) with minimal latency.
  **What the SQL checks do not promise:** they catch the common destructive and bulk-read
  shapes, not every spelling. Known ways past them: a `WHERE` hidden behind a comment (`--` or
  `#`), a statement written with no spaces, two statements on one line, a `LIMIT` with a
  fraction, `COPY ... TO` or `INTO OUTFILE`, `SUM` or `AVG` over one-row groups, and a statement
  the parser cannot read; and on the free SDK, an unlimited `MERGE` (a gateway stops it). To limit what an agent can reach whatever the spelling, give
  it only the tools it needs ([Step 5b](#step-5b-limit-each-agent-to-its-tools-and-sites)).
* **Zero-Knowledge Intent Extraction:** Prevents malicious prompt injection by translating raw agent logic into a strict schema before policy evaluation.
* **Dynamic Policies:** In `cloud`, enforces isolation rules via a Supabase-backed Control Plane that syncs to edge caches in ~3 seconds. In `local`/`linked`, the gateway owns the policy lifecycle locally, create/edit/toggle/delete and AI-drafted promotions from the Policy & Discovery tabs are armed live (re-embedded into the in-RAM vector index) with no restart.

---

## 🔒 What leaves your machine

Keyless, in `local` mode, the answer is almost nothing. Your queries, payloads and agent chain-of-thought stay on the machine and are never uploaded unless you explicitly push them. One thing does leave, and it is narrow and named:

* **An anonymous daily usage pulse.** Version, OS and block **counts**. Never your code, queries, chain-of-thought or identity. It is **on by default**, prints a one-time notice before the first pulse, and turns off with `AGENTX_TELEMETRY=off`. See `.env.example`.

With the gateway, its dependency-reputation check also sends *package names only* to the public npm and PyPI registries, to catch slopsquats. The keyless SDK has no such check.

Contributing to the shared corpus is separate and **off by default**. It happens only when you push it (`agentx push`, or `agentx sync` which pulls policies and pushes in one step), and only after you opt in with `AGENTX_CONTRIBUTE`. Left unset on a terminal, it asks once and saves your answer; left unset in CI or a script, it stays off and never blocks. What it sends is abstract: which policy fired and when, never a query, payload, chain-of-thought or identifier. It also needs the gateway, because the gateway is what reduces your local records to abstract signal before anything leaves the machine.

---

## 🔒 Licensing

**This package is MIT.** The `agentx_sdk/` edge client, published to PyPI as `agentx-security-sdk`, is licensed under the [MIT License](https://github.com/vdalal/agentx-security-sdk/blob/main/LICENSE). The `agentx-mcp` launcher is MIT as well. Use them freely, including commercially.

**The gateway and control plane are not.** The Reasoning Engine and Control Plane are closed source and proprietary, all rights reserved. No public open-source or source-available license is granted for them. Source access for evaluation is available to qualified customers and partners under written agreement.

---

## 🚀 Roadmap & Milestones

✅ Trust Boundary Shift: Moved neuro-symbolic evaluation entirely into the Data Plane container to eliminate agent runtime bypasses. (Completed)

✅ Hard Split-Plane: Telemetry is stripped of payload and chain-of-thought content at the edge, so what crosses the plane boundary is counts and classes rather than your data. (Completed)

✅ Zero-Config Reflection Engine: Eliminated manual query and CoT boilerplate writing using dynamic signature parameters compilation hooks. (Completed)

✅ Local Keyword Shield: Deterministic, dependency-free keyword/intent pre-filter in the SDK that intercepts obvious threats offline, in-process, with zero gateway/LLM calls. Scans the action payload only; chain-of-thought intent is deferred to the gateway's LLM judge. (Completed)

✅ Judge Verdict Memoization: Bounded in-memory cache on the Data Plane that reuses prior LLM verdicts for identical (payload + reasoning + policy set), eliminating repeat Gemini calls during agent retry loops. (Completed)

✅ Catastrophic-Action Hero Metric: Reframed the Executive ROI strip to lead with severity-filtered "Catastrophic Actions Blocked" (irreversible / exfiltration intents stopped pre-execution), with per-session metric accounting that bounds Recovery Rate ≤100% by construction across the dashboard, the Supabase summary view, and the SDK. (Completed)

✅ Detection-vs-Recovery Eval Harness (`eval/`): Independent instruments that measure the engine honestly, `blind_agent_eval.py` (end-to-end detection recall via a blind LLM agent + independent oracle), `probe_judge.py` (isolates the reasoning layer's *marginal* recall over the deterministic floor), and `recovery_eval.py` (A/B marginal-recovery lift of the Socratic challenge vs a bare 403). (Completed)

✅ Incident-Persistence Hardening & Fail-Mode Switch: Restored the CHALLENGED→COMPLIED persistence pipeline (gateway-pinned UUID receipts, `/v1/incident` Layer-0 registration, COMPLIED PATCH gated on a real `200`) and added `AGENTX_FAIL_MODE=open|closed`. (Completed)

✅ Deterministic Floor, Hard-Block + HITL-Escalation + Loop-Abort Tiers: The gateway's zero-LLM core, which runs before (and without) the judge. The keyless SDK runs part of it in your process; cloud teardown and the approval holds below are the gateway's only. **Hard-block** tier DENIES never-legitimate actions (destructive DDL/DML incl. `ALTER … DROP COLUMN`, cluster/cloud teardown, SSRF, secret reads + egress exfiltration, filesystem whole-scope deletes + path-boundary escapes, remote-pipe-to-shell installs, and bidi-override / Unicode-Tags carrier payloads, Trojan-Source / invisible-instruction smuggling). **HITL-escalation** tier returns `202 ESCALATED` → human SOC for *consequence-gated* actions that can be legitimate: **High-Value Transfer Approval** (`AGENTX_TRANSFER_ESCALATION_THRESHOLD`), **External Publication Approval**, **Comms Bulk-Deletion Approval**, and **Budget Ceiling Approval** (cumulative session token/$ spend vs `AGENTX_SESSION_TOKEN_CEILING` / `AGENTX_SESSION_COST_CEILING_USD`; report real usage with `agentx.record_spend(...)` or rely on the built-in volume estimate). **Loop-abort** tier terminates runaway loops (strike-count breaker + the `detect_no_progress_loop` no-progress repeat breaker, `AGENTX_LOOP_REPEAT_CEILING`). Every detector has a fires-in-anger test asserting attribution + zero LLM calls. See `AGENT_FAILURE_CATALOG.md` for the per-incident coverage state. (Completed)

⬜ Containerized Multi-Region Edge Cluster: Standardize container blueprints for automated high-availability deployments onto AWS ECS and Render clusters. (Future)


## 🤝 Support & design partners

* **Docs:** [agentx-core.com/docs](https://agentx-core.com/docs)
* **Community and support:** the Discord invite is on [agentx-core.com](https://agentx-core.com), which always has the current link.
* **Issues in the SDK:** the MIT client is mirrored at [github.com/vdalal/agentx-security-sdk](https://github.com/vdalal/agentx-security-sdk), which is where SDK issues belong. This monorepo is private, so an issue opened here will not reach anyone.
* **Contact:** founders@agentx-core.com

If you are running agents that write to systems you care about and want to compare notes on what they try, we are actively looking for design partners.


