Metadata-Version: 2.4
Name: agenttrafficcop
Version: 1.6.0
Summary: Python SDK for AgentTrafficCop — local and hosted deterministic checks for agent workflows.
Author: AgentTrafficCop
License-Expression: MIT
Project-URL: Homepage, https://github.com/belalshafeq/AgentTrafficCop-sdk
Project-URL: Repository, https://github.com/belalshafeq/AgentTrafficCop-sdk
Project-URL: Issues, https://github.com/belalshafeq/AgentTrafficCop-sdk/issues
Project-URL: Changelog, https://github.com/belalshafeq/AgentTrafficCop-sdk/blob/main/CHANGELOG.md
Keywords: ai,agents,multi-agent,llm,governance,orchestration,circuit-breaker,langgraph,observability
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Distributed Computing
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx<0.29.0,>=0.27.0
Provides-Extra: autogen
Requires-Dist: pyautogen==0.2.35; extra == "autogen"
Provides-Extra: crewai
Requires-Dist: crewai==1.15.45; extra == "crewai"
Provides-Extra: autogen-agentchat
Requires-Dist: autogen-agentchat==0.7.5; extra == "autogen-agentchat"
Provides-Extra: mcp
Requires-Dist: mcp==1.30.0; extra == "mcp"
Provides-Extra: langgraph
Requires-Dist: langgraph<1.3.0,>=1.2.24; extra == "langgraph"
Provides-Extra: dev
Requires-Dist: pytest<9,>=8.2; extra == "dev"
Requires-Dist: pytest-asyncio<0.25,>=0.24; extra == "dev"
Dynamic: license-file

# AgentTrafficCop Python SDK

[![PyPI version](https://img.shields.io/pypi/v/agenttrafficcop.svg)](https://pypi.org/project/agenttrafficcop/)
[![Python versions](https://img.shields.io/pypi/pyversions/agenttrafficcop.svg)](https://pypi.org/project/agenttrafficcop/)

**Check the next agent action before it runs.**

AgentTrafficCop provides deterministic checks for repeated actions, repeating
cycles, and approved-step limits. Choose local in-process checks or a hosted API
with shadow decisions, incident timelines, threshold comparison, and reported-cost
controls. Your application must honor every rejected or failed check.

Legacy checks do not execute actions, automatically intercept every model call,
understand semantic repetition with deterministic checks, or cancel in-flight work.
The new runtime execution helpers invoke only the callable explicitly passed to them.
The separate experimental SemanticMonitor uses your encoder for warnings only.

## Install

Python **3.11+**:

```bash
python -m pip install --upgrade 'agenttrafficcop==1.6.0'
python -c "from importlib.metadata import version; print(version('agenttrafficcop'))"
```

Base dependency: `httpx>=0.27.0,<0.29.0`. Use a virtual environment; optional
framework extras have their own requirements.

## New in 1.6.0

- GuardRuntime: one explicit sync/async facade, opt-in semantic blocking,
  root transport-metadata normalization and connection-only degraded fail-open.
- Registration-time hooks for a pinned LangGraph/CrewAI/current AutoGen set and
  an explicit MCP call_tool proxy; no global instrumentation or streaming support.
- Configured-price non-streaming OpenAI/Anthropic token-usage adapters and
  trusted signed reporting; check/reserve/execute/final-settlement helpers.
- Client-reported semantic evidence in compatible hosted timelines/replay;
  observations are not verified hosted approvals or re-evaluated semantic replay.
- Required-shared-state deployment gate and a durable Redis configuration;
  Redis must still be provisioned/configured by the operator.

See [RUNTIME_FEATURES.md](RUNTIME_FEATURES.md) for examples, supported versions,
privacy, failure/cancellation limits and infrastructure requirements. Existing
client defaults and detector thresholds remain unchanged. The new root metadata
preset is opt-in, not the previously reverted recursive field stripper.

## Included from 1.5.0

- **Explicit outage policy:** fail-closed hosted enforcement with optional safe
  connection-establishment retries and redacted events. No automatic local fallback.
- **Experimental semantic warnings:** opt-in `SemanticMonitor` with your own
  encoder, bounded embedding history, and no approvals or blocking authority.
- **Human review:** compatible hosted dashboards let account owners authorize one
  exact retry, without resetting history or bypassing quotas/spend controls.

See [FEATURES.md](FEATURES.md) for usage, privacy and failure-path limits.

## Included from 1.4.0

- **Optional payload normalization:** explicitly ignore selected object fields
  when computing action identity. Original action data is not mutated.
- **Threshold comparison:** compare repeat/cycle/step policies offline or against
  bounded hosted incident history, without executing actions or changing policy.
- **Shared run spending reservations:** reserve estimated cost before participating
  calls and settle through trusted signed actual-cost reporting. Pro/Team hosted
  creation; not a provider-side hard spending cap.

LocalGuard shipped in 1.3.0; hosted hash-only helpers shipped in 1.2.0. Defaults
remain unchanged in 1.5.0. New hosted helpers require a compatible backend.

## Local or hosted?

| Capability | `LocalGuard` | `Guard` / `GuardSync` |
|---|---|---|
| API key / network required | No | Yes |
| Exact repeats, cycles, step limits | Yes | Yes |
| Optional field exclusions | Yes | With `hash_only=True` |
| Shadow mode | No | Yes |
| Dashboard records and retained-run replay | No | Yes |
| Schema-change heuristic | No | Pro/Team |
| Reported run budgets / reservations | No | Pro/Team |
| State sharing | One guard instance | Depends on backend configuration |
| Automatic action interception | No | No |

## Local quick start

```python
from agenttrafficcop import LocalGuard

guard = LocalGuard(max_repeats=3, max_steps=50)
for _ in range(3):
    result = guard.check(
        session_id="example-run",
        payload={"tool": "search", "arguments": {"query": "refund policy"}},
    )
    if not result.approved:
        print("Not executed:", result.reason)
        break
    print("Approved step", result.step)
    # Execute your protected action here.
```

The first two checks approve; the third returns `REPEATED_PAYLOAD_LOOP`.
Reuse one guard instance and stable session ID throughout a run.

Local defaults:

```python
guard = LocalGuard(
    max_repeats=3, max_steps=50,
    max_cycle_length=2, max_cycle_repeats=3,
    max_sessions=1000, session_ttl=3600,
    ignore_paths=(),
)
```

`LocalResult` contains `approved`, `session_id`, `step`, `payload_hash`, and
`reason`. Policy rejection reasons are `REPEATED_PAYLOAD_LOOP`,
`CYCLIC_PAYLOAD_LOOP`, `STEP_LIMIT_EXCEEDED`, or `LOCAL_CAPACITY_EXCEEDED`.
Invalid inputs raise `ValueError`; do not execute after a failed check.

Checks and updates are thread-safe within one instance. History is in memory,
expires after inactivity, and is lost on restart or `guard.reset(session_id)`.
Separate processes/instances do not share history. At capacity, new unexpired
sessions are rejected rather than evicting active protection. Rejected checks
refresh existing activity time but do not advance approved history.

Local mode makes no network requests, uploads no decisions, and has no hosted
fallback, spending controls, or shadow mode. Approval counts checks, not verified
executions. A different action can be approved after a repeat rejection if no
other policy blocks it.

## Optional payload normalization

Changing timestamps or request IDs can hide exact repeats. Exclude only fields
you explicitly know are irrelevant:

```python
from agenttrafficcop import LocalGuard, normalize_payload

guard = LocalGuard(ignore_paths=["/timestamp", "/request/id"])
action = {"tool": "search", "arguments": {"query": "refund"}, "timestamp": 123}
result = guard.check(session_id="run-1", payload=action)
if result.approved:
    pass  # Execute the ORIGINAL action here.

normalized_copy = normalize_payload(action, ignore_paths=["/timestamp"])
```

Paths are JSON pointers through **objects only**, not arrays or wildcards.
`~1` escapes `/`; `~0` escapes `~`. Missing keys are ignored; root deletion is
unsupported. Up to 64 paths, 512 characters and 32 components per path are
accepted. Invalid paths/non-finite JSON inputs raise `ValueError`.

No fields are removed automatically. Keep exclusions stable throughout a run;
old hashes are not rewritten. Excluding meaningful arguments can make different
actions look identical. This is not semantic detection.

## Hosted quick start

Verify your email, create an account and generate an API key in the
[dashboard](https://agenttrafficcop.com/dashboard.html). Store it server-side:

```bash
export ATC_API_KEY="your-api-key"
```

```python
import asyncio
import os
import uuid
from agenttrafficcop import AgentTrafficCopError, Guard

async def main():
    run_id = uuid.uuid4().hex
    async with Guard(
        url="https://api.agenttrafficcop.com",
        api_key=os.environ["ATC_API_KEY"],
        dry_run=False,
    ) as guard:
        try:
            result = await guard.check(
                session_id=run_id, sender="planner", recipient="worker",
                payload={"tool": "search", "arguments": {"query": "refund"}},
            )
        except AgentTrafficCopError as exc:
            print("Not executed:", exc.error_code)
            return
        if result.approved:
            print("Approved at step", result.step)
            # Execute your protected action here.

if __name__ == "__main__":
    asyncio.run(main())
```

Use a stable ID throughout a run and a new ID for each independent run. Call at
all relevant execution boundaries. Client creation alone does not protect code.

`GuardSync` provides the same check without `await`:

```python
import os
from agenttrafficcop import AgentTrafficCopError, GuardSync

with GuardSync("https://api.agenttrafficcop.com", os.environ["ATC_API_KEY"], dry_run=False) as guard:
    try:
        result = guard.check(
            session_id="my-stable-run-id", sender="planner", recipient="worker",
            payload={"tool": "search", "arguments": {"query": "refund"}},
        )
    except AgentTrafficCopError as exc:
        print("Not executed:", exc.error_code)
    else:
        if result.approved:
            pass  # Execute your protected action here.
```

## Hosted hash-only checks

Within an open `Guard` context:

```python
result = await guard.check(
    session_id=run_id, sender="planner", recipient="worker",
    payload={"tool": "search", "query": "refund", "timestamp": 123},
    hash_only=True,
    ignore_paths=["/timestamp"],  # Optional; introduced in 1.4.0.
)
```

`GuardSync` uses the same arguments without `await`. Hosted field exclusions
require `hash_only=True`; otherwise they raise `ValueError` before a request.
The helper hashes a nonempty JSON object using sorted keys, compact separators,
unescaped Unicode, UTF-8 and SHA-256. Non-finite numbers are rejected. This is
not RFC 8785 canonicalization. A normalized empty object is rejected.

Raw transmission is the hosted default. Hash-only omits the raw payload, rejects
metadata, and never falls back to sending raw contents. Hashes and routing
identifiers still leave the application. Hashes reveal equality; predictable
inputs can be guessed. They are not encryption or guaranteed anonymization.
The backend cannot prove that the submitted hash matches the eventual action.

REST callers use `payload_mode="hash_only"` and a 64-character lowercase hex
`payload_hash`, omitting both `payload` and `metadata` entirely, including nulls.
Raw and hash-only checks share history when their hashes, key, session and
mode match. Required routing fields and ordinary policies still apply.

## Shadow mode

Within an open hosted client:

```python
result = await guard.check(
    session_id=run_id, sender="planner", recipient="worker",
    payload={"tool": "search"}, mode="shadow",
)
if result.would_block:
    print(result.shadow_decision["error"])
if result.approved:
    pass  # Application may execute in shadow mode.
```

Supported repeat/cycle/step and eligible schema detections become warnings.
Authentication, validation, rate limits, message/agent quotas, spending blocks,
exhausted budgets and coordination failures can still reject. Approved shadow
checks consume quota. Shadow and enforcement histories are separate. Switching
modes does not transfer history. Run spending retains its key/run scope.

Keep `dry_run=False`: legacy dry-run is not shadow mode. Do not let untrusted
callers change policy modes or reset history when enforcement is mandatory.

## Historical replay and threshold comparison

Offline, supply ordered SHA-256 hashes of observed attempted actions:

```python
from agenttrafficcop import compare_thresholds

comparison = compare_thresholds(
    payload_hashes,
    policies=[{"max_repeats": 3, "max_steps": 25},
              {"max_repeats": 4, "max_steps": 40}],
)
```

Up to 10,000 hashes and four policies are accepted. Supported settings are
`max_repeats`, `max_steps`, `max_cycle_length` and `max_cycle_repeats`. Offline
omitted settings follow LocalGuard defaults (50 steps). Each simulation starts
with empty history and stops at its first block. No actions run or alerts fire.

For retained hosted history, inside an open client:

```python
comparison = await guard.replay_run(
    session_id=run_id,
    policies=[{"max_repeats": 3, "max_steps": 25},
              {"max_repeats": 4, "max_steps": 40}],
    mode="shadow",
)
```

`GuardSync` omits `await`. Hosted omitted settings use 3 repeats, 25 steps,
cycle length 2 and 3 cycle repetitions. In the dashboard, use **Inspect run →
Compare detector thresholds**. Its reference is explicit—not the run's verified
original policy. Nothing changes live detector settings.

Results always set `full_history_verified=false`: timelines are bounded to 200
recorded checks per run, up to 10,000 per key within plan retention. Missing
hashes stop replay; discontinuous steps are flagged. Enforcement and shadow are
selected separately. Resets, expiry, historical policy changes, missing actions
and complete execution traces are not reconstructed. A different threshold
cannot invent actions the original workflow never attempted.

Comparison covers repeat/cycle/step rules—not schemas, semantic similarity,
quotas, spending or every custom hosted policy. Hashes cannot be re-normalized
without original payloads. Timeline records omit raw payloads and metadata;
raw-mode checks still transmit payloads for validation and hashing.

## Reported spending and run budgets — Pro/Team

```python
budget = await guard.set_run_budget(session_id=run_id, budget_usd="2.00")
# GuardSync: budget = guard.set_run_budget(...)
```

Setting a budget does not connect provider billing. An authorized backend must
report incremental costs through timestamp/HMAC-signed `POST /v1/ingest/usage`
requests. Use matching key/session attribution and stable unique event IDs;
never report cumulative run totals or duplicate spending across integrations.

Run budgets are **API key + session** scoped. Rolling thresholds cover a key's
reported costs over 60 seconds. Updating budgets preserves spending; a new run
needs a new session ID. Delayed reports, unguarded actions and in-flight work can
overshoot. These are not provider-side hard caps.

## Shared spending reservations — Pro/Team

Reserve estimated cost **before** participating calls start, after setting a run
budget. Admission atomically checks reported spending plus outstanding holds:

```python
hold = await guard.reserve_spend(
    session_id=run_id,
    reservation_id="operation-123",  # Stable, unique per logical operation.
    estimated_cost_usd="0.20",
)
if hold["duplicate"] or hold["status"] != "held":
    raise RuntimeError("Recover through your execution ledger; do not execute twice")
# Execute this operation once, only after all other required checks pass.
```

Sync clients omit `await`. Estimates are positive, at most $1 billion, with up
to 6 decimal places. Missing budgets return 409; insufficient available budget
returns 402. Same ID/estimate returns the existing reservation with
`duplicate=true`; changed estimates conflict. A duplicate is not permission to
execute again. Keep an execution ledger/provider idempotency key for recovery.

A trusted reporter submits one final incremental actual cost per reservation:

```json
{
  "api_key": "YOUR_ATC_KEY",
  "session_id": "run-1",
  "reservation_id": "operation-123",
  "event_id": "final-cost-123",
  "cost": "0.17"
}
```

Send this body to `/v1/ingest/usage` with `X-ATC-Timestamp` and
`X-ATC-Signature`. The signature is hexadecimal SHA-256 HMAC of
`timestamp + "." + exact_body`, using the server-side ingestion secret.
An ordinary API key does not grant access to that signing secret. Arrange an
authorized integration for the hosted service; never expose it in browser code.

Settlement records actual cost and clears its hold in one transaction. Retry the
same event with unchanged cost/attribution. Do not also report that operation
through another integration. Partial/streamed settlements of a single hold are
not supported; aggregate the final cost at the trusted reporter. CloudPulse
key-level reports do not settle individual run reservations.

There is **no automatic expiry or bearer-token cancellation**: a timed-out worker
may still be executing. A trusted reporter can settle at zero only after knowing
that no cost was incurred. Unknown outcomes remain held and require recovery.
There is a 10,000 unresolved-hold cap per run; active holds are not evicted.

The ledger is persistent and shared only by workers using the same database.
Separate SQLite files do not coordinate even when detector history uses Redis.
Reservations are key/run scoped, not account-wide or rolling-window allowances.
Unreserved calls are not prevented. Actual costs above estimates are still
recorded and can exceed the budget. `check()` does not reserve automatically.

Budget reads include `reserved_spend_usd` and `available_to_reserve_usd`.
`GET /v1/runs/{session_id}/reservations` supports `after` and `limit` pagination.

## Framework integrations

### LangGraph

```bash
python -m pip install 'agenttrafficcop[langgraph]==1.6.0'
```

```python
from agenttrafficcop.langgraph import guarded_node

# Existing graph, open hosted guard, and reviewer_fn:
graph.add_node("reviewer", guarded_node(
    reviewer_fn, guard=guard, sender="coder", recipient="reviewer",
    session_id=lambda state: state["run_id"],
    payload=lambda state: {"draft": state["draft"]},
    raise_on_trip=True,
))
```

Only wrapped nodes are protected. Keep exceptions propagating so failed checks
stop execution. Adapters do not automatically enable normalization, hash-only,
shadow mode or spending reservations. Use direct checks for unexposed options.

### Legacy AutoGen

```bash
python -m pip install 'agenttrafficcop[autogen]==1.6.0'
```

This legacy adapter supports only `pyautogen==0.2.35`, not AgentChat or AG2.
For current AgentChat 0.7.5 use the separate `guard_autogen_tools` hook documented
in RUNTIME_FEATURES.md. The legacy adapter does not support other
similarly named packages. `GuardedConversableAgent` checks supported
`generate_reply` / `a_generate_reply` pipelines, including registered handlers.
Direct sends, direct tool calls and work outside those methods are not
intercepted. One reply can execute multiple tools; costs are not automatically
reported or reserved. It is not an execution sandbox. Dry-run guards are rejected.
LocalGuard is not a drop-in replacement for hosted adapters.

## Failure handling and reliability

- Catch `AgentTrafficCopError` around hosted `check()` calls—not just loop errors.
- Budget, replay and reservation helpers expose HTTPX HTTP/transport exceptions.
- Local policy failures are results; invalid local input raises `ValueError`.
- Stop on every failed check, including timeouts and HTTP 503 coordination errors.
- A failed response does not prove that no history or quota update occurred.
- Policy-rejected checks do not consume approved-message quota. Ambiguous
  crash/storage failures can retain conservative charges without client approval.
- Memory-backed hosted detector history remains single-process and is lost on
  restart/expiry/reset. Redis coordination needs compatible participating workers.
  Persistent incident records do not restore active detector history.
- Webhook notifications are best effort, not a guaranteed-delivery incident queue.

Use a trusted execution boundary, stable session identity and a stable payload
policy. Different wording with different hashes is not detected semantically.
The SDK is Alpha software, not a compliance certification or a zero-error guarantee.

## Links

- [Website and plans](https://agenttrafficcop.com)
- [Dashboard](https://agenttrafficcop.com/dashboard.html)
- [PyPI](https://pypi.org/project/agenttrafficcop/)
- [Public SDK repository and issues](https://github.com/belalshafeq/AgentTrafficCop-sdk)

## License

The Python SDK is licensed under the [MIT License](https://github.com/belalshafeq/AgentTrafficCop-sdk/blob/main/LICENSE).
This does not license the hosted service or private backend.
