Metadata-Version: 2.4
Name: agenttrafficcop
Version: 1.2.0
Summary: Python SDK for AgentTrafficCop — a runtime circuit breaker and schema shield for multi-agent systems.
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: langgraph
Requires-Dist: langgraph<2.0.0,>=1.2.0; 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](https://img.shields.io/pypi/v/agenttrafficcop.svg)](https://pypi.org/project/agenttrafficcop/)

Check an agent action before executing it. AgentTrafficCop evaluates submitted
payloads for exact repetition, repeating cycles, step limits and applicable
usage/spending policies. Your application must honor rejections; the service does
not execute actions, intercept every model call or cancel in-flight work.

## Version 1.2.0

This release adds opt-in local payload hashing with `hash_only=True`. It requires
a backend supporting `payload_mode="hash_only"`. Earlier SDK versions do not
expose this option. Check PyPI for publication status; source version numbers
alone do not publish packages. Never install from the private backend repository.

## Hash-only payload checks

Inside an open `Guard` context (or `GuardSync`, without `await`):

```python
result = await guard.check(
    session_id=run_id,
    sender="planner",
    recipient="worker",
    payload={"task": "review", "private_content": "stays local"},
    hash_only=True,
)
```

The SDK hashes nonempty JSON objects locally using sorted keys, compact JSON,
unescaped Unicode and UTF-8 SHA-256. Non-finite numbers and unsupported JSON
values are rejected. No raw payload is sent, metadata is rejected, and there is
no fallback to raw transmission if a server rejects the format. Framework
adapters do not automatically opt in. Keep legacy `dry_run=False` for enforcement.

Routing identifiers still leave your app. Hashes reveal equality and predictable
inputs can be guessed; hashes are not anonymization or encryption. The server
cannot validate original payload contents or verify the hash represents the
executed action. Raw mode remains the default. Detectors, shadow mode, quotas,
and report-driven budgets still apply. Volatile fields are not stripped.

Python 3.11+:

```bash
python -m pip install 'agenttrafficcop==1.2.0'
```

Run the command after 1.2.0 is available on PyPI. Prefer an isolated virtual
environment. Base SDK compatibility is `httpx>=0.27,<0.29`, including 0.28.1; extras
have their own dependencies. No compatibility with every notebook package is implied.

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

Verify your email, create an account and generate a key in the
[dashboard](https://agenttrafficcop.com/dashboard.html).

## Async checks

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

async def main():
    run_id = uuid.uuid4().hex
    async with Guard("https://api.agenttrafficcop.com", os.environ["ATC_API_KEY"]) as guard:
        try:
            result = await guard.check(
                session_id=run_id, sender="planner", recipient="worker",
                payload={"task": "review patch"},
            )
        except AgentTrafficCopError as exc:
            print("Not executed:", exc.error_code)
            return
        if result.approved:
            # Execute the actual action here.
            print("Approved at step", result.step)

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

Use one stable session ID per run. Changing timestamps/random IDs in each payload
can defeat exact-repeat detection. Deterministic matching is not semantic detection.

## Sync checks

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

with GuardSync("https://api.agenttrafficcop.com", os.environ["ATC_API_KEY"]) as guard:
    try:
        result = guard.check(
            session_id=uuid.uuid4().hex, sender="planner", recipient="worker",
            payload={"task": "review patch"},
        )
    except AgentTrafficCopError as exc:
        print("Not executed:", exc.error_code)
    else:
        if result.approved:
            print("Execute action here")
```

## Shadow mode

Requires SDK 1.1.0 and a backend that supports `mode="shadow"`. Existing calls
default to enforcement; the SDK omits the new field in default requests for
compatibility with older backends.

```python
result = await guard.check(
    session_id=run_id, sender="planner", recipient="worker",
    payload={"task": "review patch"}, mode="shadow",
)
if result.would_block:
    print(result.shadow_decision["error"])
if result.approved:
    # Continue while evaluating loop policies.
    pass
```

`GuardSync.check` accepts the same arguments without `await`. A loop/step detection
returns an approved result with `would_block=True` and `shadow_decision` evidence.
Eligible schema-change checks also participate. Only the first matching rule is
reported. The dashboard timeline labels these as **[Shadow] Would block**.

Authentication, validation, rate limits, agent/message quotas, rolling spend
blocks and exhausted run budgets still reject requests. Approved shadow requests
consume quota. Shadow mode deliberately allows detected looping work to continue.
Shadow/enforcement loop histories are separate; switching modes does not migrate
history. Key/run spending policies remain shared regardless of mode.

Keep legacy `dry_run=False` (the default). Legacy dry-run suppresses additional
errors and is not shadow mode. Don't let untrusted callers select a mode when
blocking policies are mandatory. Existing framework adapters do not automatically
select shadow mode; use direct guard calls or explicit adapter wiring.

## Per-run budgets — Pro/Team

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

Requires a backend supporting run budgets. A trusted backend must separately
report incremental costs to `POST /v1/ingest/usage` with the same ATC key and
session ID, stable unique event IDs, and timestamped HMAC headers. The signing
secret belongs only on the trusted reporter, never in browser code. Setting a
budget does not connect billing or report costs automatically.

Reports use `api_key`, `event_id`, `cost` (decimal string), and `session_id`.
`X-ATC-Signature` is the hex SHA-256 HMAC of `timestamp + "." + exact_body`, using
the ingestion secret; `X-ATC-Timestamp` contains that timestamp. Do not report
running totals or duplicate the same spending across reporting integrations.

When reported spending reaches a budget, subsequent guarded actions are rejected
with `RUN_BUDGET_EXCEEDED`. Updates preserve accumulated spending; new runs need
new session IDs. Budgets are API-key + session scoped.

These are report-driven controls, not provider hard caps. Missing/delayed reports,
concurrency and in-flight calls can cause overshoot. Unguarded actions are outside
ATC's control. CloudPulse key-level reports do not attribute spending to runs.

## LangGraph

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

```python
from agenttrafficcop.langgraph import guarded_node

# With your existing graph, guard client and node function:
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 rejection exceptions propagating to stop
execution. The wrapper supports sync and async node functions. No other framework
is automatically intercepted by installing the SDK.

## Legacy AutoGen 0.2.35

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

Only `pyautogen==0.2.35` is supported, not AutoGen 0.4+/AgentChat or AG2.

```python
import os
import uuid
from autogen import ConversableAgent
from agenttrafficcop import GuardSync, AgentTrafficCopError
from agenttrafficcop.autogen import GuardedConversableAgent

with GuardSync("https://api.agenttrafficcop.com", os.environ["ATC_API_KEY"]) as guard:
    worker = GuardedConversableAgent(
        "worker", atc_guard=guard, atc_session_id=uuid.uuid4().hex,
        llm_config=False, human_input_mode="NEVER", code_execution_config=False,
        default_auto_reply="Acknowledged.",
    )
    caller = ConversableAgent("caller", llm_config=False, human_input_mode="NEVER",
                             code_execution_config=False)
    try:
        print(worker.generate_reply(
            messages=[{"role": "user", "content": "Review this task"}], sender=caller,
        ))
    except AgentTrafficCopError as exc:
        print("Not executed:", exc.error_code)
```

The adapter checks before `generate_reply` and `a_generate_reply` reply handlers.
The async path offloads the sync guard check to a thread. Keep GuardSync open for
the agent's lifetime. Direct sends/tool calls outside guarded reply methods are
not intercepted. One reply can contain multiple tools, not individual spending
reservations. No automatic cost reporting or execution sandbox is supplied.
Dry-run guards are rejected.

## Operational notes

- Normal route checks submit payloads for server-side hashing; timeline records
  omit raw payloads. Hash-only submission is not implemented yet.
- Timelines contain bounded evidence, not complete traces or historical replay.
- Without shared session storage, active loop history can be process-local and
  lost on restart; persistent timeline records do not restore it.
- Catch `AgentTrafficCopError` for check failures; rejections aren't all HTTP 422.
- Operator-only endpoints are not available to ordinary API keys.
- SDK reset helpers require administrator permission on the hosted service.

## Roadmap candidates

These are not available features or delivery commitments.

| Candidate | Goal |
|---|---|
| Hash-only payload mode | Reduce raw payload exposure |
| Historical replay | Compare settings against recorded event sequences |
| Local-first checks | Evaluate selected deterministic rules locally |
| Controlled resume | Human review and limited continuation |
| Spending reservations | Coordinate participating parallel agents |
| Semantic detection experiments | Evaluate rephrased repetition, initially warning-only |

## Links and license

[Website](https://agenttrafficcop.com) ·
[Public SDK repository](https://github.com/belalshafeq/AgentTrafficCop-sdk) ·
[Issues](https://github.com/belalshafeq/AgentTrafficCop-sdk/issues)

The SDK is MIT licensed. See [LICENSE](LICENSE).
