Metadata-Version: 2.4
Name: agentguard47
Version: 1.3.0
Summary: Zero-dependency runtime control for production Python agents - stop loops, retry storms, and budget burn
Author-email: BMD PAT LLC <pat@bmdpat.com>
License-Expression: MIT
Project-URL: Homepage, https://agentguard47.com
Project-URL: Documentation, https://github.com/bmdhodl/agent47#readme
Project-URL: Repository, https://github.com/bmdhodl/agent47
Project-URL: Issues, https://github.com/bmdhodl/agent47/issues
Project-URL: Changelog, https://github.com/bmdhodl/agent47/releases
Keywords: agents,coding-agents,ai-agents,multi-agent,llm,guardrails,runtime-guardrails,loop-detection,budget-guard,retry-guard,runtime-enforcement,runtime-control,production-agents,coding-agent-safety,local-first,retry-storms,budget-control,langchain,openai,anthropic
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Software Development :: Testing
Classifier: Topic :: System :: Monitoring
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: langchain
Requires-Dist: langchain-core>=1.6.3; extra == "langchain"
Provides-Extra: langgraph
Requires-Dist: langgraph>=1.2.11; extra == "langgraph"
Requires-Dist: langgraph-checkpoint>=4.2.0; extra == "langgraph"
Requires-Dist: langgraph-sdk>=0.4.4; extra == "langgraph"
Provides-Extra: crewai
Requires-Dist: crewai>=1.15.21; extra == "crewai"
Provides-Extra: otel
Requires-Dist: opentelemetry-api>=1.44.0; extra == "otel"
Requires-Dist: opentelemetry-sdk>=1.44.0; extra == "otel"
Dynamic: license-file

<!-- Generated by scripts/generate_pypi_readme.py. Edit README.md and CHANGELOG.md instead. -->

# AgentGuard

**Stop runaway agents before they burn money.**

Zero-dependency Python kill switch for AI agents. Hard budget caps. Loop detection. Local traces. MIT.

[![PyPI](https://img.shields.io/pypi/v/agentguard47)](https://pypi.org/project/agentguard47/)
[![Downloads](https://img.shields.io/pypi/dm/agentguard47)](https://pypi.org/project/agentguard47/)
[![Python](https://img.shields.io/pypi/pyversions/agentguard47)](https://pypi.org/project/agentguard47/)
[![CI](https://github.com/bmdhodl/agent47/actions/workflows/ci.yml/badge.svg)](https://github.com/bmdhodl/agent47/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://github.com/bmdhodl/agent47/blob/v1.3.0/LICENSE)

```bash
pip install agentguard47
```

## Getting started

### 1. Install and verify

```bash
pip install agentguard47
agentguard doctor   # package ok?
agentguard demo     # offline proof (no API keys)
```

### 2. Guard an OpenAI client

```python
from agentguard import BudgetGuard, LoopGuard, Tracer, patch_openai

budget = BudgetGuard(max_cost_usd=5.00, warn_at_pct=0.8)
loop = LoopGuard(max_repeats=3)
tracer = Tracer(service="my-agent", guards=[loop])

patch_openai(tracer, budget_guard=budget)
# every OpenAI call is now traced + budget-enforced
```

When spend crosses the hard limit, `BudgetExceeded` is raised and the run stops.

### 3. Cap a single task

Session budget can still have headroom. One goal can still be killed:

```python
with budget.goal("refund", max_cost_usd=0.50, warn_at_pct=0.8) as g:
    g.attempt()
    budget.consume(cost_usd=0.12)
    # BudgetExceeded names the goal when it crosses
```

### 4. Read the local proof

```bash
agentguard report .agentguard/traces.jsonl
agentguard incident .agentguard/traces.jsonl
```

Or scaffold a starter file:

```bash
agentguard quickstart --framework raw --write
python agentguard_raw_quickstart.py
```

## What it stops

| Problem | Guard | Exception |
|---------|-------|-----------|
| Spend blowup | `BudgetGuard` | `BudgetExceeded` |
| Same tool forever | `LoopGuard` | `LoopDetected` |
| Fuzzy / A-B-A-B loops | `FuzzyLoopGuard` | `LoopDetected` |
| Retry storms | `RetryGuard` | `RetryLimitExceeded` |
| Hung runs | `TimeoutGuard` | `TimeoutExceeded` |
| Spam calls | `RateLimitGuard` | — |
| Wallet drain (x402/USDC) | `X402SpendGuard` | `BudgetExceeded` |

Not a dashboard. Not a model router. An **in-process exception** that kills the bad run mid-flight.

### Cap your agent's x402 wallet spend

Agents that pay per-call via x402 (USDC micropayments) can drain a wallet in a
silent loop. `X402SpendGuard` wraps the payment step and refuses before paying:

```python
from agentguard import X402SpendGuard

guard = X402SpendGuard(
    max_total_usd=5.00,        # wallet cap, add period="day" for a daily reset
    max_per_endpoint_usd=1.00, # cap per resource URL
    max_per_call_usd=0.10,     # refuse any single payment above this
)
guard.charge(0.001, "https://api.example.com/search", my_x402_pay_step)
```

AgentGuard meters and refuses; it never signs or settles. Amounts come from
your x402 client. No crypto dependencies.

## Features

- **Hard stops** — exceptions inside your process, not after-the-fact alerts
- **Task-level budgets** — `BudgetGuard.goal(...)` for sub-task caps + warn hooks
- **Local traces** — JSONL by default; no network unless you opt in
- **Zero deps** — stdlib only; Python 3.9+
- **Provider patches** — `patch_openai` / `patch_anthropic`
- **Framework hooks** — LangChain, LangGraph, CrewAI (optional extras)

## Local by default

- No API key required for local proof
- No network unless you configure `HttpSink`
- MIT licensed

The SDK is the free local proof path. Start local. Add hosted ingest later only if you want retained history, alerts, team visibility, spend trends, hosted decision history, or dashboard-managed remote kill signals. Local guards remain authoritative. `HttpSink` mirrors trace and decision events; it does not execute remote kill signals by itself.

## Integrations

OpenAI · Anthropic · LangChain · LangGraph · CrewAI · raw agent loops

```bash
pip install "agentguard47[langchain]"   # optional extras as needed
```

## Security

The base install declares zero runtime dependencies. `pip install agentguard47` pulls nothing, so a default install adds no third-party exposure.

Extras install third-party packages and need a separate audit. The LangChain and LangGraph extras now require Python 3.10+ and raise their minimum versions to the tested September 2026 releases. OpenTelemetry requires 1.44.0 or newer. The base SDK remains compatible with Python 3.9+.

The optional `[crewai]` extra requires CrewAI 1.15.21 or newer. Its current dependency tree still installs ChromaDB 1.1.1, with four distinct unresolved advisories: CVE-2026-45829, CVE-2026-45830, CVE-2026-45831, and CVE-2026-45833. The audit database provides no fixed version. Avoid this extra unless you have reviewed that upstream exposure. Installing AgentGuard alone does not install ChromaDB or start a server. See [the upstream advisory](https://osv.dev/vulnerability/PYSEC-2026-311) and [the release audit](https://github.com/bmdhodl/agent47/blob/v1.3.0/proof/audit-20260912/README.md).

`HttpSink` validates the address it actually connects to, retains TLS hostname verification, and refuses cross-origin redirects. It connects directly and does not use environment proxy settings. A local guard stops instrumented work in your Python process; it does not cancel an agent loop running on a provider's server. Cost estimates are not invoices; supply provider-reported cost or use strict cost resolution when an estimate is insufficient.

## Docs

- [Getting started guide](https://github.com/bmdhodl/agent47/blob/v1.3.0/docs/guides/getting-started.md)
- [Examples](https://github.com/bmdhodl/agent47/tree/v1.3.0/examples)
- [MCP server](https://github.com/bmdhodl/agent47/tree/v1.3.0/mcp-server) — `npx -y @agentguard47/mcp-server`

## Links

- PyPI: https://pypi.org/project/agentguard47/
- Issues: https://github.com/bmdhodl/agent47/issues
- AgentGuard on the web (hosted history, alerts, and MCP visibility for Claude Code, Cursor, and Codex): https://bmdpat.com/tools/agentguard?utm_source=agentguard47&utm_medium=readme&utm_campaign=touchpoints

The hosted page is an optional next step, not a requirement. The SDK stays free, local, and MIT, and the local guards stay authoritative. Nothing in this package phones home. The only network egress is a sink or exporter you configure yourself, such as `HttpSink` or an OpenTelemetry exporter.

---

MIT · Built for people who ship agents and hate surprise bills.

## Latest Release Notes (1.3.0)

(2026-09-12)

This release includes the accumulated, unpublished 1.2.14 candidate work below.

### Security and enforcement fixes
- LangChain now propagates guard exceptions through its real callback manager.
  A zero-call budget stops the tool before its body runs; previously LangChain
  could log the exception and continue. Sync and async dispatch run inline.
- Budget and timeout caps reject invalid, negative, boolean, and non-finite
  values. Corrupt stored budget counters fail closed without rewriting state.
  Warning callbacks run outside budget locks and zero limits do not divide by zero.
- Failed x402 payment callbacks refund only their original budget generation,
  so a reset or day rollover cannot reduce a later period's spending.
- HTTP trace delivery rejects credential-bearing URLs, cross-origin redirects,
  mapped private IPv6 addresses, and private/reserved DNS answers at connection
  time. Connections use the validated address while TLS retains hostname checks.
  This transport deliberately does not use environment proxies.
- Retry-After delays are finite, non-negative, and capped at 30 seconds.
- MCP dependency updates resolve the npm audit findings in the committed lockfile.

### Optional dependency compatibility
- LangChain requires 1.6.3+, LangGraph 1.2.11+ with checkpoint 4.2.0+ and SDK
  0.4.4+, OpenTelemetry 1.44.0+, and CrewAI 1.15.21+.
- LangChain and LangGraph extras require Python 3.10+. The dependency-free base
  package remains compatible with Python 3.9+.
- The optional CrewAI tree still installs ChromaDB with four distinct unresolved
  advisories (CVE-2026-45829, CVE-2026-45830, CVE-2026-45831, CVE-2026-45833).
  No fixed upstream version was available in the audit. Avoid this extra unless
  its exposure has been reviewed. Base installs do not include ChromaDB.
- Audit scope, regression results, dependency resolutions, and limitations:
  [September audit](https://github.com/bmdhodl/agent47/blob/v1.3.0/proof/audit-20260912/README.md).


### Reliability
- Added the file-backed `JsonFileStateStore` integration for
  `BudgetGuard(store=...)`, so configured budget usage can persist across
  processes and scheduled tasks. This is local persistence, not distributed
  coordination or a fairness guarantee.
- Hardened the cross-process state lock (`JsonFileStateStore`, used by
  `BudgetGuard(store=...)`) against two Windows races that crashed concurrent
  processes under contention: an exclusive lock create that fails with
  `PermissionError` instead of `FileExistsError` during a concurrent release
  ("delete pending"), and an `os.replace` that transiently fails with
  access-denied when an antivirus/indexer holds the destination. Both now retry
  safely, so cross-process budget enforcement holds on Windows scheduled tasks.

### Budget Goals
- Added `BudgetGuard.goal(...)` for scoped per-goal caps on tokens, calls, and
  cost, with an optional `warn_at_pct` threshold and `on_warning` callback.
  Goal warnings are emitted once per goal while hard caps still refuse excess
  spend.

### Payment Guardrails
- Added `X402SpendGuard` for local caps on total, per-endpoint, and per-call
  x402/USDC spend. It checks and reserves configured spend before payment and
  rolls the reservation back if the payment callback raises. It does not settle
  x402 payments or add a crypto dependency.

### Cost Accounting
- Added maximum-precision billable-cost resolution with explicit source labels
  for provider-reported values, caller prices, estimates, zero-cost tool/local
  work, and unknown cost. Unknown usage stays conservative or fails in strict
  mode; the result is not a provider invoice.

### Usage Accounting
- Anthropic usage normalization now preserves thinking/reasoning tokens and
  separates them from answer tokens when the provider payload exposes that
  detail, alongside cache-read and cache-write fields.

### Hardening
- Rejected NaN, infinite, and negative budget inputs before state mutation so
  non-finite values cannot bypass a cost ceiling.
- Made LoopGuard argument fingerprinting tolerate non-JSON-serializable tool
  arguments instead of crashing the guard while it checks for repeats.

### Public Docs
- Made the reader-facing surface fully model-agnostic to match the
  already-vendor-neutral code path: the README/PyPI "As a skill" heading now
  leads with Codex alongside Claude Code, and the budget-aware escalation
  example notes the escalate target can be any provider's model, not just
  Claude.

### Onboarding
- Bare `agentguard` now prints a friendly first-run welcome with the 60-second
  local path and the star call to action instead of an argparse help dump.
- Added `python -m agentguard` as an entry point so the CLI works even when the
  `agentguard` script is not on PATH.
- Added `agentguard welcome` and `agentguard badge`. `badge` prints a
  paste-able "Guarded by AgentGuard" README badge (markdown, rST, or HTML) so
  adopters can advertise the SDK and drive new installs.

### Distribution
- Added an opt-in bridge to the hosted AgentGuard page
  (`bmdpat.com/tools/agentguard`) from the README/PyPI page, the `agentguard
  --help` footer, and the first-run welcome. These are static links only: the
  SDK still makes no network calls unless you configure `HttpSink`, and nothing
  in the package phones home. The links carry UTM parameters so the site can
  measure click-through; no identifier is sent from your machine.

Full changelog: [CHANGELOG.md](https://github.com/bmdhodl/agent47/blob/v1.3.0/CHANGELOG.md)
