agenttrafficcop 2.1.0__tar.gz → 2.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/CHANGELOG.md +17 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/PKG-INFO +43 -6
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/QUICKSTARTS.md +1 -1
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/README.md +42 -5
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop/__init__.py +1 -1
- agenttrafficcop-2.2.0/agenttrafficcop/cli.py +251 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop/client.py +80 -0
- agenttrafficcop-2.2.0/agenttrafficcop/langgraph.py +316 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop.egg-info/PKG-INFO +43 -6
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop.egg-info/SOURCES.txt +3 -0
- agenttrafficcop-2.2.0/agenttrafficcop.egg-info/entry_points.txt +2 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/pyproject.toml +4 -1
- agenttrafficcop-2.1.0/agenttrafficcop/langgraph.py +0 -159
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/FEATURES.md +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/LICENSE +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/MANIFEST.in +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/RUNTIME_FEATURES.md +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop/accounting.py +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop/autogen.py +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop/embeddings.py +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop/exceptions.py +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop/frameworks.py +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop/local.py +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop/models.py +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop/normalization.py +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop/openai_gateway.py +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop/outage.py +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop/py.typed +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop/recipes.py +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop/recovery.py +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop/replay.py +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop/runtime.py +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop/security.py +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop/semantic.py +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop/tracing.py +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop.egg-info/dependency_links.txt +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop.egg-info/requires.txt +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop.egg-info/top_level.txt +0 -0
- {agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/setup.cfg +0 -0
|
@@ -1,3 +1,20 @@
|
|
|
1
|
+
## 2.2.0
|
|
2
|
+
|
|
3
|
+
- Publish the SDK LangGraph checkpointed-review adapter with a built-in,
|
|
4
|
+
read-only verifier for owner-scoped ATC approval status. Resume input must
|
|
5
|
+
carry the exact review ID; the action is rechecked by ATC immediately before
|
|
6
|
+
execution and the one-action grant is consumed by the server.
|
|
7
|
+
- Add a LangGraph-native first-run and deployment walkthrough with a supported
|
|
8
|
+
versioned container image and Helm defaults.
|
|
9
|
+
|
|
10
|
+
## Unreleased
|
|
11
|
+
|
|
12
|
+
- Add Anthropic model-aware gateway input-token preflight with a clearly labeled
|
|
13
|
+
buffered-estimate fallback; estimates remain admission buffers, not invoice caps.
|
|
14
|
+
- Add a starter Kubernetes Helm chart and `atc doctor` deployment preflight.
|
|
15
|
+
- Add LangGraph checkpointed review interrupts with safe reasons, exact-action
|
|
16
|
+
approval verification and a fresh ATC check before resumed node execution.
|
|
17
|
+
|
|
1
18
|
## 2.1.0
|
|
2
19
|
|
|
3
20
|
- Add optional OpenAI SDK helpers that route BYOK Chat Completions through the
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: agenttrafficcop
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.2.0
|
|
4
4
|
Summary: Python SDK for AgentTrafficCop — local and hosted deterministic checks for agent workflows.
|
|
5
5
|
Author: AgentTrafficCop
|
|
6
6
|
License-Expression: MIT
|
|
@@ -82,7 +82,7 @@ change. Unknown-cost exceptions retain holds; they are never settled as zero.
|
|
|
82
82
|
Python **3.11+**:
|
|
83
83
|
|
|
84
84
|
```bash
|
|
85
|
-
python -m pip install --upgrade 'agenttrafficcop==2.
|
|
85
|
+
python -m pip install --upgrade 'agenttrafficcop==2.2.0'
|
|
86
86
|
python -c "from importlib.metadata import version; print(version('agenttrafficcop'))"
|
|
87
87
|
```
|
|
88
88
|
|
|
@@ -671,8 +671,10 @@ sync/async helper. No PyPI version change is required for the HTTP endpoint.
|
|
|
671
671
|
|
|
672
672
|
### LangGraph
|
|
673
673
|
|
|
674
|
+
Install the versioned SDK and the optional LangGraph extra:
|
|
675
|
+
|
|
674
676
|
```bash
|
|
675
|
-
python -m pip install 'agenttrafficcop[langgraph]==2.
|
|
677
|
+
python -m pip install 'agenttrafficcop[langgraph]==2.2.0'
|
|
676
678
|
```
|
|
677
679
|
|
|
678
680
|
```python
|
|
@@ -688,13 +690,48 @@ graph.add_node("reviewer", guarded_node(
|
|
|
688
690
|
```
|
|
689
691
|
|
|
690
692
|
Only wrapped nodes are protected. Keep exceptions propagating so failed checks
|
|
691
|
-
stop execution.
|
|
692
|
-
|
|
693
|
+
stop execution. To pause a circuit-breaker trip for a dashboard review, compile
|
|
694
|
+
with a **durable LangGraph checkpointer** (for example, a production
|
|
695
|
+
database-backed saver) and enable the built-in ATC verifier:
|
|
696
|
+
|
|
697
|
+
```python
|
|
698
|
+
builder.add_node("reviewer", guarded_node(
|
|
699
|
+
reviewer_fn, guard=guard, sender="coder", recipient="reviewer",
|
|
700
|
+
session_id=lambda state: state["run_id"],
|
|
701
|
+
payload=lambda state: {"draft": state["draft"]},
|
|
702
|
+
review_on_trip=True,
|
|
703
|
+
))
|
|
704
|
+
# durable_saver is your database-backed LangGraph checkpointer.
|
|
705
|
+
graph = builder.compile(checkpointer=durable_saver)
|
|
706
|
+
```
|
|
707
|
+
|
|
708
|
+
When paused, show `__interrupt__[0].value` to the authorized operator and use
|
|
709
|
+
the dashboard's run-review flow to approve/reject the exact action. Resume with
|
|
710
|
+
`Command(resume={"review_id": event["review_id"]})`; the resume payload itself
|
|
711
|
+
is never authorization. The SDK queries ATC's owner-scoped review status, the
|
|
712
|
+
adapter checks that the state/action and review ID did not change, and ATC then
|
|
713
|
+
rechecks policy and consumes the one-action approval before the node runs. The
|
|
714
|
+
status API is read-only; only an authenticated dashboard owner can decide a
|
|
715
|
+
review. A custom `review_approval` callback is optional and must fail closed.
|
|
716
|
+
|
|
717
|
+
Run `python -I examples/langgraph_checkpointed_review.py` from the repository
|
|
718
|
+
after installing `./sdk[langgraph]` for an offline walkthrough; it uses fake ATC
|
|
719
|
+
and review services and an in-memory saver, so it is **not** a production setup.
|
|
720
|
+
|
|
721
|
+
A trip creates a checkpoint with only a generic review event, session ID,
|
|
722
|
+
opaque review ID and safe detector error code—never state, prompts, results or
|
|
723
|
+
exception text. On resume the verifier must approve that exact unchanged action;
|
|
724
|
+
only then does the node perform a fresh ATC check immediately before running. A
|
|
725
|
+
resume value by itself is never approval. Do not use an in-memory saver for
|
|
726
|
+
restart durability.
|
|
727
|
+
Approval does not bypass ATC spend/quota/policy controls. Adapters do not
|
|
728
|
+
automatically enable normalization, hash-only, shadow mode or spending
|
|
729
|
+
reservations. Use direct checks for unexposed options.
|
|
693
730
|
|
|
694
731
|
### Legacy AutoGen
|
|
695
732
|
|
|
696
733
|
```bash
|
|
697
|
-
python -m pip install 'agenttrafficcop[autogen]==2.
|
|
734
|
+
python -m pip install 'agenttrafficcop[autogen]==2.2.0'
|
|
698
735
|
```
|
|
699
736
|
|
|
700
737
|
This legacy adapter supports only `pyautogen==0.2.35`, not AgentChat or AG2.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# Short integration recipes — SDK 2.1
|
|
2
2
|
|
|
3
3
|
Install the SDK and the optional OpenAI adapter with
|
|
4
|
-
`python -m pip install 'agenttrafficcop[openai]==2.
|
|
4
|
+
`python -m pip install 'agenttrafficcop[openai]==2.2.0'`. For editable
|
|
5
5
|
development, clone this repository and run
|
|
6
6
|
`python -m pip install -e './sdk[openai]'`
|
|
7
7
|
from its root.
|
|
@@ -33,7 +33,7 @@ change. Unknown-cost exceptions retain holds; they are never settled as zero.
|
|
|
33
33
|
Python **3.11+**:
|
|
34
34
|
|
|
35
35
|
```bash
|
|
36
|
-
python -m pip install --upgrade 'agenttrafficcop==2.
|
|
36
|
+
python -m pip install --upgrade 'agenttrafficcop==2.2.0'
|
|
37
37
|
python -c "from importlib.metadata import version; print(version('agenttrafficcop'))"
|
|
38
38
|
```
|
|
39
39
|
|
|
@@ -622,8 +622,10 @@ sync/async helper. No PyPI version change is required for the HTTP endpoint.
|
|
|
622
622
|
|
|
623
623
|
### LangGraph
|
|
624
624
|
|
|
625
|
+
Install the versioned SDK and the optional LangGraph extra:
|
|
626
|
+
|
|
625
627
|
```bash
|
|
626
|
-
python -m pip install 'agenttrafficcop[langgraph]==2.
|
|
628
|
+
python -m pip install 'agenttrafficcop[langgraph]==2.2.0'
|
|
627
629
|
```
|
|
628
630
|
|
|
629
631
|
```python
|
|
@@ -639,13 +641,48 @@ graph.add_node("reviewer", guarded_node(
|
|
|
639
641
|
```
|
|
640
642
|
|
|
641
643
|
Only wrapped nodes are protected. Keep exceptions propagating so failed checks
|
|
642
|
-
stop execution.
|
|
643
|
-
|
|
644
|
+
stop execution. To pause a circuit-breaker trip for a dashboard review, compile
|
|
645
|
+
with a **durable LangGraph checkpointer** (for example, a production
|
|
646
|
+
database-backed saver) and enable the built-in ATC verifier:
|
|
647
|
+
|
|
648
|
+
```python
|
|
649
|
+
builder.add_node("reviewer", guarded_node(
|
|
650
|
+
reviewer_fn, guard=guard, sender="coder", recipient="reviewer",
|
|
651
|
+
session_id=lambda state: state["run_id"],
|
|
652
|
+
payload=lambda state: {"draft": state["draft"]},
|
|
653
|
+
review_on_trip=True,
|
|
654
|
+
))
|
|
655
|
+
# durable_saver is your database-backed LangGraph checkpointer.
|
|
656
|
+
graph = builder.compile(checkpointer=durable_saver)
|
|
657
|
+
```
|
|
658
|
+
|
|
659
|
+
When paused, show `__interrupt__[0].value` to the authorized operator and use
|
|
660
|
+
the dashboard's run-review flow to approve/reject the exact action. Resume with
|
|
661
|
+
`Command(resume={"review_id": event["review_id"]})`; the resume payload itself
|
|
662
|
+
is never authorization. The SDK queries ATC's owner-scoped review status, the
|
|
663
|
+
adapter checks that the state/action and review ID did not change, and ATC then
|
|
664
|
+
rechecks policy and consumes the one-action approval before the node runs. The
|
|
665
|
+
status API is read-only; only an authenticated dashboard owner can decide a
|
|
666
|
+
review. A custom `review_approval` callback is optional and must fail closed.
|
|
667
|
+
|
|
668
|
+
Run `python -I examples/langgraph_checkpointed_review.py` from the repository
|
|
669
|
+
after installing `./sdk[langgraph]` for an offline walkthrough; it uses fake ATC
|
|
670
|
+
and review services and an in-memory saver, so it is **not** a production setup.
|
|
671
|
+
|
|
672
|
+
A trip creates a checkpoint with only a generic review event, session ID,
|
|
673
|
+
opaque review ID and safe detector error code—never state, prompts, results or
|
|
674
|
+
exception text. On resume the verifier must approve that exact unchanged action;
|
|
675
|
+
only then does the node perform a fresh ATC check immediately before running. A
|
|
676
|
+
resume value by itself is never approval. Do not use an in-memory saver for
|
|
677
|
+
restart durability.
|
|
678
|
+
Approval does not bypass ATC spend/quota/policy controls. Adapters do not
|
|
679
|
+
automatically enable normalization, hash-only, shadow mode or spending
|
|
680
|
+
reservations. Use direct checks for unexposed options.
|
|
644
681
|
|
|
645
682
|
### Legacy AutoGen
|
|
646
683
|
|
|
647
684
|
```bash
|
|
648
|
-
python -m pip install 'agenttrafficcop[autogen]==2.
|
|
685
|
+
python -m pip install 'agenttrafficcop[autogen]==2.2.0'
|
|
649
686
|
```
|
|
650
687
|
|
|
651
688
|
This legacy adapter supports only `pyautogen==0.2.35`, not AgentChat or AG2.
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""Command-line preflight tools for AgentTrafficCop deployments."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
import urllib.error
|
|
10
|
+
import urllib.request
|
|
11
|
+
import uuid
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _kubectl_json(*args: str) -> dict[str, Any]:
|
|
16
|
+
result = subprocess.run(
|
|
17
|
+
["kubectl", *args, "-o", "json"], check=True, capture_output=True,
|
|
18
|
+
text=True, timeout=20,
|
|
19
|
+
)
|
|
20
|
+
value = json.loads(result.stdout)
|
|
21
|
+
if not isinstance(value, dict):
|
|
22
|
+
raise ValueError("kubectl returned a non-object response")
|
|
23
|
+
return value
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _egress_policy_is_expected(
|
|
27
|
+
policy: dict[str, Any], atc_namespace: str, atc_port: int,
|
|
28
|
+
dns_namespace: str, dns_selector: dict[str, str]
|
|
29
|
+
) -> bool:
|
|
30
|
+
spec = policy.get("spec", {})
|
|
31
|
+
if spec.get("podSelector") != {} or "Egress" not in spec.get("policyTypes", []):
|
|
32
|
+
return False
|
|
33
|
+
rules = spec.get("egress", [])
|
|
34
|
+
if len(rules) != 2:
|
|
35
|
+
return False
|
|
36
|
+
|
|
37
|
+
def matches(rule: dict[str, Any], namespace: str, selector: dict[str, str],
|
|
38
|
+
ports: set[tuple[str, int]]) -> bool:
|
|
39
|
+
peers = rule.get("to", [])
|
|
40
|
+
rule_ports = rule.get("ports", [])
|
|
41
|
+
if len(peers) != 1 or len(rule_ports) != len(ports):
|
|
42
|
+
return False
|
|
43
|
+
peer = peers[0]
|
|
44
|
+
if peer.get("namespaceSelector", {}).get("matchLabels", {}).get(
|
|
45
|
+
"kubernetes.io/metadata.name") != namespace:
|
|
46
|
+
return False
|
|
47
|
+
if peer.get("podSelector", {}).get("matchLabels") != selector:
|
|
48
|
+
return False
|
|
49
|
+
actual = {(item.get("protocol", "TCP"), item.get("port")) for item in rule_ports}
|
|
50
|
+
return actual == ports
|
|
51
|
+
|
|
52
|
+
atc_target = {"app.kubernetes.io/name": "agenttrafficcop"}
|
|
53
|
+
return (
|
|
54
|
+
any(matches(rule, atc_namespace, atc_target, {("TCP", atc_port)}) for rule in rules)
|
|
55
|
+
and any(matches(rule, dns_namespace, dns_selector,
|
|
56
|
+
{("TCP", 53), ("UDP", 53)}) for rule in rules)
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _probe_agent_egress(
|
|
61
|
+
kubectl: str, namespace: str, health_url: str, image: str, timeout: int
|
|
62
|
+
) -> tuple[bool, str]:
|
|
63
|
+
"""Test allowed ATC access and blocked public egress from a disposable pod."""
|
|
64
|
+
pod = f"atc-doctor-{uuid.uuid4().hex[:8]}"
|
|
65
|
+
run = subprocess.run
|
|
66
|
+
try:
|
|
67
|
+
run(
|
|
68
|
+
[kubectl, "-n", namespace, "run", pod, f"--image={image}",
|
|
69
|
+
"--restart=Never", "--command", "--", "python", "-c", "import time; time.sleep(600)"],
|
|
70
|
+
check=True, capture_output=True, text=True, timeout=30,
|
|
71
|
+
)
|
|
72
|
+
run([kubectl, "-n", namespace, "wait", "--for=condition=Ready",
|
|
73
|
+
f"pod/{pod}", f"--timeout={timeout}s"],
|
|
74
|
+
check=True, capture_output=True, text=True, timeout=timeout + 10,
|
|
75
|
+
)
|
|
76
|
+
check_atc = (
|
|
77
|
+
"import urllib.request; r=urllib.request.urlopen(" + repr(health_url)
|
|
78
|
+
+ ", timeout=8); assert r.status == 200; print('ATC_OK')"
|
|
79
|
+
)
|
|
80
|
+
reachable = run(
|
|
81
|
+
[kubectl, "-n", namespace, "exec", pod, "--", "python", "-c", check_atc],
|
|
82
|
+
check=False, capture_output=True, text=True, timeout=20,
|
|
83
|
+
)
|
|
84
|
+
if reachable.returncode != 0 or "ATC_OK" not in reachable.stdout:
|
|
85
|
+
return False, "probe pod could not reach the ATC health URL"
|
|
86
|
+
|
|
87
|
+
check_public = (
|
|
88
|
+
"import socket,sys; s=socket.socket(); s.settimeout(5); "
|
|
89
|
+
"\ntry: s.connect(('1.1.1.1',443)); print('PUBLIC_REACHABLE')"
|
|
90
|
+
"\nexcept OSError: print('PUBLIC_BLOCKED')"
|
|
91
|
+
"\nfinally: s.close()"
|
|
92
|
+
)
|
|
93
|
+
public = run(
|
|
94
|
+
[kubectl, "-n", namespace, "exec", pod, "--", "python", "-c", check_public],
|
|
95
|
+
check=False, capture_output=True, text=True, timeout=20,
|
|
96
|
+
)
|
|
97
|
+
if public.returncode == 0 and "PUBLIC_BLOCKED" in public.stdout:
|
|
98
|
+
return True, "probe pod reached ATC and public TCP egress was blocked"
|
|
99
|
+
if public.returncode == 0 and "PUBLIC_REACHABLE" in public.stdout:
|
|
100
|
+
return False, "probe pod reached public TCP egress; review CNI and additive policies"
|
|
101
|
+
return False, "could not determine public-egress result from the probe pod"
|
|
102
|
+
except (subprocess.SubprocessError, OSError):
|
|
103
|
+
return False, "Kubernetes probe failed; check pod permissions, image access and CNI"
|
|
104
|
+
finally:
|
|
105
|
+
try:
|
|
106
|
+
run([kubectl, "-n", namespace, "delete", "pod", pod,
|
|
107
|
+
"--wait=true", "--timeout=60s"],
|
|
108
|
+
check=False, capture_output=True, text=True, timeout=70)
|
|
109
|
+
except (subprocess.SubprocessError, OSError):
|
|
110
|
+
pass
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _doctor(args: argparse.Namespace) -> int:
|
|
114
|
+
failures = 0
|
|
115
|
+
|
|
116
|
+
def report(name: str, ok: bool, detail: str) -> None:
|
|
117
|
+
nonlocal failures
|
|
118
|
+
print(f"{'PASS' if ok else 'FAIL'} {name}: {detail}")
|
|
119
|
+
failures += not ok
|
|
120
|
+
|
|
121
|
+
kubectl = shutil.which("kubectl")
|
|
122
|
+
if not kubectl:
|
|
123
|
+
report("kubectl", False, "not found in PATH")
|
|
124
|
+
return 1
|
|
125
|
+
report("kubectl", True, kubectl)
|
|
126
|
+
|
|
127
|
+
try:
|
|
128
|
+
context = subprocess.run(
|
|
129
|
+
[kubectl, "config", "current-context"], check=True,
|
|
130
|
+
capture_output=True, text=True, timeout=10,
|
|
131
|
+
).stdout.strip()
|
|
132
|
+
report("cluster-context", bool(context), context or "no current context")
|
|
133
|
+
except (subprocess.SubprocessError, OSError) as exc:
|
|
134
|
+
report("cluster-context", False, type(exc).__name__)
|
|
135
|
+
return 1
|
|
136
|
+
|
|
137
|
+
try:
|
|
138
|
+
ns = _kubectl_json("get", "namespace", args.namespace)
|
|
139
|
+
report("atc-namespace", ns.get("metadata", {}).get("name") == args.namespace,
|
|
140
|
+
args.namespace)
|
|
141
|
+
deployments = _kubectl_json("get", "deployments", "-n", args.namespace)
|
|
142
|
+
items = deployments.get("items", [])
|
|
143
|
+
ready = [d for d in items if d.get("metadata", {}).get("labels", {}).get(
|
|
144
|
+
"app.kubernetes.io/name") == "agenttrafficcop"]
|
|
145
|
+
healthy = bool(ready) and all(
|
|
146
|
+
d.get("status", {}).get("readyReplicas", 0) >= d.get("spec", {}).get("replicas", 1)
|
|
147
|
+
for d in ready
|
|
148
|
+
)
|
|
149
|
+
report("atc-deployment", healthy,
|
|
150
|
+
f"{len(ready)} matching deployment(s); " +
|
|
151
|
+
("all replicas ready" if healthy else "missing or replicas not ready"))
|
|
152
|
+
|
|
153
|
+
services = _kubectl_json("get", "services", "-n", args.namespace)
|
|
154
|
+
service = next((item for item in services.get("items", [])
|
|
155
|
+
if item.get("metadata", {}).get("name") == args.service), None)
|
|
156
|
+
ports = service.get("spec", {}).get("ports", []) if service else []
|
|
157
|
+
service_ok = any(p.get("port") == args.port for p in ports)
|
|
158
|
+
report("atc-service", service_ok,
|
|
159
|
+
f"{args.service} exposes TCP/{args.port}" if service_ok else
|
|
160
|
+
f"{args.service} missing or does not expose port {args.port}")
|
|
161
|
+
endpoints = _kubectl_json("get", "endpoints", args.service, "-n", args.namespace)
|
|
162
|
+
has_ready_endpoint = any(
|
|
163
|
+
subset.get("addresses") for subset in endpoints.get("subsets", [])
|
|
164
|
+
)
|
|
165
|
+
report("atc-endpoints", has_ready_endpoint,
|
|
166
|
+
f"{args.service} has ready pod addresses" if has_ready_endpoint else
|
|
167
|
+
f"{args.service} has no ready pod endpoints")
|
|
168
|
+
|
|
169
|
+
policies = _kubectl_json("get", "networkpolicies", "-n", args.agent_namespace)
|
|
170
|
+
if "=" not in args.dns_pod_label:
|
|
171
|
+
raise ValueError("--dns-pod-label must be key=value")
|
|
172
|
+
dns_key, dns_value = args.dns_pod_label.split("=", 1)
|
|
173
|
+
if not dns_key or not dns_value:
|
|
174
|
+
raise ValueError("--dns-pod-label must be key=value")
|
|
175
|
+
policy_ok = any(
|
|
176
|
+
p.get("metadata", {}).get("name") == args.egress_policy
|
|
177
|
+
and _egress_policy_is_expected(
|
|
178
|
+
p, args.namespace, args.port, args.dns_namespace, {dns_key: dns_value}
|
|
179
|
+
)
|
|
180
|
+
for p in policies.get("items", [])
|
|
181
|
+
)
|
|
182
|
+
report("agent-egress-policy", policy_ok,
|
|
183
|
+
f"{args.egress_policy} has the expected ATC-only and DNS egress rules"
|
|
184
|
+
if policy_ok else
|
|
185
|
+
f"{args.egress_policy} is missing or its rules differ from the expected restricted policy")
|
|
186
|
+
except (subprocess.SubprocessError, OSError, ValueError, KeyError) as exc:
|
|
187
|
+
report("kubernetes-resources", False, type(exc).__name__)
|
|
188
|
+
return 1
|
|
189
|
+
|
|
190
|
+
url = args.url or f"http://{args.service}.{args.namespace}.svc.cluster.local:{args.port}/health"
|
|
191
|
+
if args.url or not args.probe_egress:
|
|
192
|
+
try:
|
|
193
|
+
with urllib.request.urlopen(url, timeout=args.timeout) as response:
|
|
194
|
+
health_ok = response.status == 200
|
|
195
|
+
report("atc-health", health_ok, f"{url} returned HTTP 200" if health_ok else url)
|
|
196
|
+
except (urllib.error.URLError, TimeoutError, OSError) as exc:
|
|
197
|
+
report("atc-health", False, f"could not reach {url} ({type(exc).__name__})")
|
|
198
|
+
else:
|
|
199
|
+
print("INFO atc-health: skipped local URL check; the probe pod will test the cluster service")
|
|
200
|
+
|
|
201
|
+
if args.agent_url:
|
|
202
|
+
try:
|
|
203
|
+
with urllib.request.urlopen(args.agent_url, timeout=args.timeout) as response:
|
|
204
|
+
agent_ok = response.status == 200
|
|
205
|
+
report("agent-url-from-this-host", agent_ok,
|
|
206
|
+
f"{args.agent_url} returned HTTP 200" if agent_ok else args.agent_url)
|
|
207
|
+
except (urllib.error.URLError, TimeoutError, OSError) as exc:
|
|
208
|
+
report("agent-url-from-this-host", False,
|
|
209
|
+
f"could not reach {args.agent_url} ({type(exc).__name__})")
|
|
210
|
+
|
|
211
|
+
if args.probe_egress:
|
|
212
|
+
probe_ok, detail = _probe_agent_egress(
|
|
213
|
+
kubectl, args.agent_namespace, url, args.probe_image, args.probe_timeout
|
|
214
|
+
)
|
|
215
|
+
report("agent-egress-runtime", probe_ok, detail)
|
|
216
|
+
|
|
217
|
+
if not args.probe_egress:
|
|
218
|
+
print("INFO network-policy-cni: policy shape is checked, but enforcement requires "
|
|
219
|
+
"a CNI that supports NetworkPolicy. Add --probe-egress to test from a "
|
|
220
|
+
"temporary pod; this requires pod create/delete/exec permissions and an image pull.")
|
|
221
|
+
return 1 if failures else 0
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def main() -> None:
|
|
225
|
+
parser = argparse.ArgumentParser(prog="atc", description="AgentTrafficCop deployment utilities")
|
|
226
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
227
|
+
doctor = subparsers.add_parser("doctor", help="preflight a deployed Kubernetes setup")
|
|
228
|
+
doctor.add_argument("--namespace", default="atc-system", help="ATC namespace")
|
|
229
|
+
doctor.add_argument("--agent-namespace", default="atc-agents", help="dedicated agent namespace")
|
|
230
|
+
doctor.add_argument("--service", default="agenttrafficcop", help="ATC Service name")
|
|
231
|
+
doctor.add_argument("--port", type=int, default=8000, help="ATC Service port")
|
|
232
|
+
doctor.add_argument("--egress-policy", default="agenttrafficcop-egress-only")
|
|
233
|
+
doctor.add_argument("--dns-namespace", default="kube-system")
|
|
234
|
+
doctor.add_argument("--dns-pod-label", default="k8s-app=kube-dns",
|
|
235
|
+
help="DNS pod selector expected in the egress policy")
|
|
236
|
+
doctor.add_argument("--url", help="health URL reachable from this machine (defaults to cluster DNS)")
|
|
237
|
+
doctor.add_argument("--agent-url", help="optional URL to test from this machine, e.g. an agent pod")
|
|
238
|
+
doctor.add_argument("--probe-egress", action="store_true",
|
|
239
|
+
help="create a temporary pod to test ATC reachability and blocked public egress")
|
|
240
|
+
doctor.add_argument("--probe-image", default="python:3.12-alpine",
|
|
241
|
+
help="container image used by the temporary egress probe")
|
|
242
|
+
doctor.add_argument("--probe-timeout", type=int, default=180,
|
|
243
|
+
help="seconds to wait for the probe pod to become ready")
|
|
244
|
+
doctor.add_argument("--timeout", type=float, default=5.0)
|
|
245
|
+
args = parser.parse_args()
|
|
246
|
+
if args.command == "doctor":
|
|
247
|
+
raise SystemExit(_doctor(args))
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
if __name__ == "__main__":
|
|
251
|
+
main()
|
|
@@ -213,6 +213,86 @@ class Guard:
|
|
|
213
213
|
session_id=session_id,
|
|
214
214
|
)
|
|
215
215
|
|
|
216
|
+
async def verify_review_resume(self, resume_value: Any, **action: Any) -> bool:
|
|
217
|
+
"""Check an ATC review ID from LangGraph resume against its owner/run.
|
|
218
|
+
|
|
219
|
+
Only dashboard-authenticated reviewers can approve the ID. The read-only
|
|
220
|
+
verification POST binds it to the current server detector state and exact
|
|
221
|
+
action; ``check`` then re-runs policy and consumes the grant before execution.
|
|
222
|
+
"""
|
|
223
|
+
if not isinstance(resume_value, dict) or set(resume_value) != {"review_id"}:
|
|
224
|
+
return False
|
|
225
|
+
review_id = resume_value.get("review_id")
|
|
226
|
+
session_id = action.get("session_id")
|
|
227
|
+
if (not isinstance(session_id, str) or not isinstance(review_id, str)
|
|
228
|
+
or len(review_id) != 32
|
|
229
|
+
or any(char not in "0123456789abcdef" for char in review_id)):
|
|
230
|
+
return False
|
|
231
|
+
client = await self._ensure_client()
|
|
232
|
+
verification = {
|
|
233
|
+
"session_id": session_id,
|
|
234
|
+
"sender": action.get("sender"),
|
|
235
|
+
"recipient": action.get("recipient"),
|
|
236
|
+
"payload": action.get("payload"),
|
|
237
|
+
"intent": action.get("intent", "handoff"),
|
|
238
|
+
"mode": "enforce",
|
|
239
|
+
}
|
|
240
|
+
if action.get("metadata") is not None:
|
|
241
|
+
verification["metadata"] = action["metadata"]
|
|
242
|
+
try:
|
|
243
|
+
response = await client.post(
|
|
244
|
+
f"{self._base_url}/v1/run-reviews/verify",
|
|
245
|
+
headers={"authorization": f"Bearer {self._api_key}"},
|
|
246
|
+
json={"review_id": review_id, "action": verification},
|
|
247
|
+
)
|
|
248
|
+
except httpx.RequestError:
|
|
249
|
+
return False
|
|
250
|
+
try:
|
|
251
|
+
result = response.json()
|
|
252
|
+
except ValueError:
|
|
253
|
+
return False
|
|
254
|
+
return (
|
|
255
|
+
response.status_code == 200
|
|
256
|
+
and isinstance(result, dict)
|
|
257
|
+
and result.get("review_id") == review_id
|
|
258
|
+
and result.get("approved") is True
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
async def get_review_status(self, session_id: str, review_id: str) -> Dict[str, Any]:
|
|
262
|
+
"""Read one review's status for this API key and run; cannot approve it."""
|
|
263
|
+
if not isinstance(session_id, str) or not session_id or len(session_id) > 128:
|
|
264
|
+
raise ValueError("session_id must be a non-empty string of at most 128 characters")
|
|
265
|
+
if (not isinstance(review_id, str) or len(review_id) != 32
|
|
266
|
+
or any(char not in "0123456789abcdef" for char in review_id)):
|
|
267
|
+
raise ValueError("review_id must be a 32-character lowercase hexadecimal ID")
|
|
268
|
+
client = await self._ensure_client()
|
|
269
|
+
try:
|
|
270
|
+
response = await client.get(
|
|
271
|
+
f"{self._base_url}/v1/run-reviews/status",
|
|
272
|
+
headers={"authorization": f"Bearer {self._api_key}"},
|
|
273
|
+
params={"session_id": session_id, "review_id": review_id},
|
|
274
|
+
)
|
|
275
|
+
except httpx.RequestError as exc:
|
|
276
|
+
raise AtcConnectionError(
|
|
277
|
+
f"Could not reach AgentTrafficCop at {self._base_url}: {exc}",
|
|
278
|
+
error_code="CONNECTION_FAILED", session_id=session_id,
|
|
279
|
+
) from exc
|
|
280
|
+
try:
|
|
281
|
+
result = response.json()
|
|
282
|
+
except ValueError as exc:
|
|
283
|
+
raise AgentTrafficCopError(
|
|
284
|
+
"Server returned a non-JSON review status response.",
|
|
285
|
+
error_code="MALFORMED_RESPONSE", session_id=session_id,
|
|
286
|
+
) from exc
|
|
287
|
+
if response.status_code != 200:
|
|
288
|
+
raise exception_from_response(result if isinstance(result, dict) else {})
|
|
289
|
+
if not isinstance(result, dict):
|
|
290
|
+
raise AgentTrafficCopError(
|
|
291
|
+
"Server returned an invalid review status response.",
|
|
292
|
+
error_code="MALFORMED_RESPONSE", session_id=session_id,
|
|
293
|
+
)
|
|
294
|
+
return result
|
|
295
|
+
|
|
216
296
|
def span(self, session_id: str, name: str, *, kind: str = "tool",
|
|
217
297
|
parent_span_id: str | None = None, span_id: str | None = None):
|
|
218
298
|
"""Trace a completed operation as metadata in the dashboard run timeline.
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
"""LangGraph integration for AgentTrafficCop.
|
|
2
|
+
|
|
3
|
+
Wraps a LangGraph node function so that every invocation first asks
|
|
4
|
+
AgentTrafficCop whether the current handoff is allowed. Optional human review
|
|
5
|
+
uses LangGraph's configured durable checkpointer and always requires an
|
|
6
|
+
application-supplied verifier for the exact, unchanged action.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import concurrent.futures # <-- ADDED: Required to fix the async loop crash
|
|
13
|
+
import copy
|
|
14
|
+
import inspect
|
|
15
|
+
import logging
|
|
16
|
+
import re
|
|
17
|
+
from typing import Any, Awaitable, Callable, Dict, Optional, Union
|
|
18
|
+
|
|
19
|
+
from .client import Guard
|
|
20
|
+
from .exceptions import AgentTrafficCopError, SecurityPolicyError
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger("agenttrafficcop.langgraph")
|
|
23
|
+
|
|
24
|
+
StateT = Dict[str, Any]
|
|
25
|
+
NodeFn = Callable[[StateT], Union[Optional[StateT], Awaitable[Optional[StateT]]]]
|
|
26
|
+
ValueOrExtractor = Union[str, Callable[[StateT], Any]]
|
|
27
|
+
|
|
28
|
+
_AUTO_PAYLOAD_EXCLUDE = frozenset(
|
|
29
|
+
{"messages", "history", "trace", "logs"}
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _safe_error_code(value: Any) -> str:
|
|
34
|
+
if isinstance(value, str) and re.fullmatch(r"[A-Z0-9_]{1,64}", value):
|
|
35
|
+
return value
|
|
36
|
+
return "AGENTTRAFFICCOP_REJECTED"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _resolve(value: ValueOrExtractor, state: StateT, *, name: str) -> Any:
|
|
40
|
+
if callable(value):
|
|
41
|
+
try:
|
|
42
|
+
return value(state)
|
|
43
|
+
except Exception as e:
|
|
44
|
+
raise RuntimeError(
|
|
45
|
+
f"AgentTrafficCop: {name} extractor raised on state: {e}"
|
|
46
|
+
) from e
|
|
47
|
+
return value
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _default_payload(state: StateT) -> Dict[str, Any]:
|
|
51
|
+
return {k: v for k, v in state.items() if k not in _AUTO_PAYLOAD_EXCLUDE}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def guarded_node(
|
|
55
|
+
node_fn: NodeFn,
|
|
56
|
+
*,
|
|
57
|
+
guard: Guard,
|
|
58
|
+
sender: str,
|
|
59
|
+
recipient: str,
|
|
60
|
+
session_id: Optional[ValueOrExtractor] = None,
|
|
61
|
+
payload: Optional[ValueOrExtractor] = None,
|
|
62
|
+
intent: str = "handoff",
|
|
63
|
+
metadata: Optional[ValueOrExtractor] = None,
|
|
64
|
+
raise_on_trip: bool = True,
|
|
65
|
+
review_on_trip: bool = False,
|
|
66
|
+
review_approval: Optional[Callable[..., Any]] = None,
|
|
67
|
+
trace_batch=None,
|
|
68
|
+
) -> NodeFn:
|
|
69
|
+
if not callable(node_fn):
|
|
70
|
+
raise TypeError("node_fn must be callable")
|
|
71
|
+
if session_id is None:
|
|
72
|
+
raise ValueError(
|
|
73
|
+
"guarded_node: session_id is required. Pass a string or an "
|
|
74
|
+
"extractor callable, e.g. session_id=lambda s: s['run_id']. "
|
|
75
|
+
"The old default ('session_id') shared one global session "
|
|
76
|
+
"across all callers, so it's now a hard error."
|
|
77
|
+
)
|
|
78
|
+
if type(review_on_trip) is not bool:
|
|
79
|
+
raise TypeError("review_on_trip must be a bool")
|
|
80
|
+
if review_on_trip and not raise_on_trip:
|
|
81
|
+
raise ValueError("review_on_trip requires raise_on_trip=True")
|
|
82
|
+
if review_approval is not None and not callable(review_approval):
|
|
83
|
+
raise TypeError("review_approval must be callable")
|
|
84
|
+
if review_on_trip and review_approval is None:
|
|
85
|
+
# The built-in Guard verifier is read-only and bound to the opaque review
|
|
86
|
+
# ID issued for the exact blocked action. Custom verifiers remain optional.
|
|
87
|
+
review_approval = guard.verify_review_resume
|
|
88
|
+
|
|
89
|
+
def _is_resuming() -> bool:
|
|
90
|
+
try:
|
|
91
|
+
from langgraph.config import get_config
|
|
92
|
+
return bool(get_config().get("configurable", {}).get("__pregel_resuming"))
|
|
93
|
+
except (ImportError, RuntimeError):
|
|
94
|
+
return False
|
|
95
|
+
|
|
96
|
+
def _resume_pending_review(session: str) -> Any:
|
|
97
|
+
try:
|
|
98
|
+
from langgraph.types import interrupt
|
|
99
|
+
except ImportError as exc:
|
|
100
|
+
raise RuntimeError(
|
|
101
|
+
"review_on_trip requires the optional 'langgraph' dependency"
|
|
102
|
+
) from exc
|
|
103
|
+
# On replay this is interrupt index zero, matching the saved review
|
|
104
|
+
# interrupt. LangGraph returns its resume input before any new ATC check.
|
|
105
|
+
return interrupt({
|
|
106
|
+
"type": "agenttrafficcop_review_resume",
|
|
107
|
+
"session_id": session,
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
def _interrupt_for_review(session: str, error: AgentTrafficCopError) -> Any:
|
|
111
|
+
try:
|
|
112
|
+
from langgraph.types import interrupt
|
|
113
|
+
except ImportError as exc:
|
|
114
|
+
raise RuntimeError(
|
|
115
|
+
"review_on_trip requires the optional 'langgraph' dependency"
|
|
116
|
+
) from exc
|
|
117
|
+
# Keep the checkpoint payload deliberately minimal: never include state,
|
|
118
|
+
# prompts, exception text, or model/tool results. The resumed execution
|
|
119
|
+
# must pass guard.check again; the interrupt resume value is not authority.
|
|
120
|
+
error_code = _safe_error_code(error.error_code)
|
|
121
|
+
review_id = error.diagnostics.get("review_request_id")
|
|
122
|
+
if not isinstance(review_id, str) or not re.fullmatch(r"[a-f0-9]{32}", review_id):
|
|
123
|
+
raise SecurityPolicyError(
|
|
124
|
+
"AgentTrafficCop did not issue a review ID for this action",
|
|
125
|
+
error_code="HUMAN_REVIEW_REQUIRED", session_id=session,
|
|
126
|
+
)
|
|
127
|
+
return interrupt({
|
|
128
|
+
"type": "agenttrafficcop_review_required",
|
|
129
|
+
"session_id": session,
|
|
130
|
+
"review_id": review_id,
|
|
131
|
+
"error_code": error_code,
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
def _resolve_action(state: StateT) -> dict[str, Any]:
|
|
135
|
+
sid = _resolve(session_id, state, name="session_id")
|
|
136
|
+
pld = _default_payload(state) if payload is None else _resolve(payload, state, name="payload")
|
|
137
|
+
md = _resolve(metadata, state, name="metadata") if metadata is not None else None
|
|
138
|
+
if not isinstance(sid, str) or not sid or not isinstance(pld, dict):
|
|
139
|
+
raise SecurityPolicyError("Review action is invalid or changed")
|
|
140
|
+
return {
|
|
141
|
+
"session_id": sid, "sender": sender, "recipient": recipient,
|
|
142
|
+
"payload": pld, "intent": intent, "metadata": md,
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async def _approve_resume(
|
|
146
|
+
state: StateT, resume_value: Any, expected_action: dict[str, Any],
|
|
147
|
+
expected_review_id: str,
|
|
148
|
+
) -> None:
|
|
149
|
+
"""Require reviewer backend approval for the unchanged exact action."""
|
|
150
|
+
action = _resolve_action(state)
|
|
151
|
+
if (not isinstance(resume_value, dict)
|
|
152
|
+
or resume_value.get("review_id") != expected_review_id):
|
|
153
|
+
raise SecurityPolicyError(
|
|
154
|
+
"LangGraph resume input is not authorization for this review",
|
|
155
|
+
error_code="HUMAN_REVIEW_REQUIRED",
|
|
156
|
+
session_id=action["session_id"],
|
|
157
|
+
)
|
|
158
|
+
if action != expected_action:
|
|
159
|
+
raise SecurityPolicyError(
|
|
160
|
+
"The action changed while human review was pending",
|
|
161
|
+
error_code="HUMAN_REVIEW_ACTION_CHANGED",
|
|
162
|
+
session_id=action["session_id"],
|
|
163
|
+
)
|
|
164
|
+
if not callable(review_approval): # type narrowing for type checkers
|
|
165
|
+
raise SecurityPolicyError("No review approval verifier is configured")
|
|
166
|
+
approved = review_approval(
|
|
167
|
+
resume_value,
|
|
168
|
+
**action,
|
|
169
|
+
)
|
|
170
|
+
if inspect.isawaitable(approved):
|
|
171
|
+
approved = await approved
|
|
172
|
+
if approved is not True:
|
|
173
|
+
raise SecurityPolicyError(
|
|
174
|
+
"Human review is missing, expired, or does not match this action",
|
|
175
|
+
error_code="HUMAN_REVIEW_REQUIRED",
|
|
176
|
+
session_id=action["session_id"],
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
is_async = inspect.iscoroutinefunction(node_fn)
|
|
180
|
+
if isinstance(trace_batch, dict):
|
|
181
|
+
trace_batch = trace_batch.get('async' if is_async else 'sync')
|
|
182
|
+
if trace_batch is not None:
|
|
183
|
+
required = '__aenter__' if is_async else '__enter__'
|
|
184
|
+
if not callable(getattr(trace_batch, 'span', None)) or not callable(getattr(trace_batch, required, None)):
|
|
185
|
+
raise ValueError(f'guarded_node tracing requires a matching {"async" if is_async else "sync"} trace_batch')
|
|
186
|
+
trace_name = getattr(node_fn, '__name__', 'langgraph_node')
|
|
187
|
+
|
|
188
|
+
async def _check(state: StateT) -> bool:
|
|
189
|
+
sid = _resolve(session_id, state, name="session_id")
|
|
190
|
+
if payload is None:
|
|
191
|
+
pld = _default_payload(state)
|
|
192
|
+
else:
|
|
193
|
+
pld = _resolve(payload, state, name="payload")
|
|
194
|
+
md = _resolve(metadata, state, name="metadata") if metadata is not None else None
|
|
195
|
+
|
|
196
|
+
if not isinstance(sid, str) or not sid:
|
|
197
|
+
raise ValueError(
|
|
198
|
+
"AgentTrafficCop: session_id resolved to an empty/invalid value"
|
|
199
|
+
)
|
|
200
|
+
if not isinstance(pld, dict):
|
|
201
|
+
raise ValueError(
|
|
202
|
+
"AgentTrafficCop: payload must resolve to a dict, got "
|
|
203
|
+
f"{type(pld).__name__}"
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
try:
|
|
207
|
+
await guard.check(
|
|
208
|
+
session_id=sid,
|
|
209
|
+
sender=sender,
|
|
210
|
+
recipient=recipient,
|
|
211
|
+
payload=pld,
|
|
212
|
+
intent=intent,
|
|
213
|
+
metadata=md,
|
|
214
|
+
)
|
|
215
|
+
return True
|
|
216
|
+
except AgentTrafficCopError as e:
|
|
217
|
+
if raise_on_trip:
|
|
218
|
+
logger.warning(
|
|
219
|
+
"langgraph_node_tripped node=%s session=%s error_code=%s",
|
|
220
|
+
getattr(node_fn, "__name__", repr(node_fn)),
|
|
221
|
+
sid,
|
|
222
|
+
_safe_error_code(e.error_code),
|
|
223
|
+
)
|
|
224
|
+
raise
|
|
225
|
+
logger.info(
|
|
226
|
+
"langgraph_node_skipped node=%s session=%s error_code=%s",
|
|
227
|
+
getattr(node_fn, "__name__", repr(node_fn)),
|
|
228
|
+
sid,
|
|
229
|
+
_safe_error_code(e.error_code),
|
|
230
|
+
)
|
|
231
|
+
return False
|
|
232
|
+
|
|
233
|
+
def _check_sync(state: StateT) -> bool:
|
|
234
|
+
try:
|
|
235
|
+
loop = asyncio.get_running_loop()
|
|
236
|
+
except RuntimeError:
|
|
237
|
+
loop = None
|
|
238
|
+
|
|
239
|
+
if loop and loop.is_running():
|
|
240
|
+
# Avoid blocking an active event loop while preserving the current
|
|
241
|
+
# LangGraph task context for interrupt() in the wrapper thread.
|
|
242
|
+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
|
|
243
|
+
return pool.submit(asyncio.run, _check(state)).result()
|
|
244
|
+
return asyncio.run(_check(state))
|
|
245
|
+
|
|
246
|
+
if is_async:
|
|
247
|
+
async def _wrapped_async(state: StateT) -> Any:
|
|
248
|
+
if review_on_trip and _is_resuming():
|
|
249
|
+
action = copy.deepcopy(_resolve_action(state))
|
|
250
|
+
resume_value = _resume_pending_review(action["session_id"])
|
|
251
|
+
resume_id = resume_value.get("review_id", "") if isinstance(resume_value, dict) else ""
|
|
252
|
+
await _approve_resume(state, resume_value, action, resume_id)
|
|
253
|
+
# Verify before checking: if state changed and the new action
|
|
254
|
+
# would otherwise pass ATC, the old review must not authorize it.
|
|
255
|
+
should_run = await _check(state)
|
|
256
|
+
else:
|
|
257
|
+
try:
|
|
258
|
+
should_run = await _check(state)
|
|
259
|
+
except AgentTrafficCopError as error:
|
|
260
|
+
if not review_on_trip:
|
|
261
|
+
raise
|
|
262
|
+
action = copy.deepcopy(_resolve_action(state))
|
|
263
|
+
resume_value = _interrupt_for_review(action["session_id"], error)
|
|
264
|
+
await _approve_resume(
|
|
265
|
+
state, resume_value, action,
|
|
266
|
+
error.diagnostics.get("review_request_id", ""),
|
|
267
|
+
)
|
|
268
|
+
# Approval is necessary but not sufficient: re-run current ATC
|
|
269
|
+
# spend/quota/policy checks immediately before invoking the node.
|
|
270
|
+
should_run = await _check(state)
|
|
271
|
+
if not should_run:
|
|
272
|
+
return None
|
|
273
|
+
if trace_batch is None:
|
|
274
|
+
return await node_fn(state)
|
|
275
|
+
async with trace_batch.span(trace_name, kind='agent'):
|
|
276
|
+
return await node_fn(state)
|
|
277
|
+
|
|
278
|
+
_wrapped_async.__name__ = getattr(node_fn, "__name__", "guarded_node")
|
|
279
|
+
_wrapped_async.__doc__ = node_fn.__doc__ or ""
|
|
280
|
+
return _wrapped_async
|
|
281
|
+
|
|
282
|
+
def _wrapped_sync(state: StateT) -> Any:
|
|
283
|
+
if review_on_trip and _is_resuming():
|
|
284
|
+
action = copy.deepcopy(_resolve_action(state))
|
|
285
|
+
resume_value = _resume_pending_review(action["session_id"])
|
|
286
|
+
resume_id = resume_value.get("review_id", "") if isinstance(resume_value, dict) else ""
|
|
287
|
+
asyncio.run(_approve_resume(state, resume_value, action, resume_id))
|
|
288
|
+
# Verify before checking: a changed action that would otherwise
|
|
289
|
+
# pass ATC must not inherit the pending review's resume.
|
|
290
|
+
should_run = _check_sync(state)
|
|
291
|
+
else:
|
|
292
|
+
try:
|
|
293
|
+
should_run = _check_sync(state)
|
|
294
|
+
except AgentTrafficCopError as error:
|
|
295
|
+
if not review_on_trip:
|
|
296
|
+
raise
|
|
297
|
+
action = copy.deepcopy(_resolve_action(state))
|
|
298
|
+
resume_value = _interrupt_for_review(action["session_id"], error)
|
|
299
|
+
asyncio.run(_approve_resume(
|
|
300
|
+
state, resume_value, action,
|
|
301
|
+
error.diagnostics.get("review_request_id", ""),
|
|
302
|
+
))
|
|
303
|
+
# Approval is necessary but not sufficient: re-run current ATC
|
|
304
|
+
# spend/quota/policy checks immediately before invoking the node.
|
|
305
|
+
should_run = _check_sync(state)
|
|
306
|
+
|
|
307
|
+
if not should_run:
|
|
308
|
+
return None
|
|
309
|
+
if trace_batch is None:
|
|
310
|
+
return node_fn(state)
|
|
311
|
+
with trace_batch.span(trace_name, kind='agent'):
|
|
312
|
+
return node_fn(state)
|
|
313
|
+
|
|
314
|
+
_wrapped_sync.__name__ = getattr(node_fn, "__name__", "guarded_node")
|
|
315
|
+
_wrapped_sync.__doc__ = node_fn.__doc__ or ""
|
|
316
|
+
return _wrapped_sync
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: agenttrafficcop
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.2.0
|
|
4
4
|
Summary: Python SDK for AgentTrafficCop — local and hosted deterministic checks for agent workflows.
|
|
5
5
|
Author: AgentTrafficCop
|
|
6
6
|
License-Expression: MIT
|
|
@@ -82,7 +82,7 @@ change. Unknown-cost exceptions retain holds; they are never settled as zero.
|
|
|
82
82
|
Python **3.11+**:
|
|
83
83
|
|
|
84
84
|
```bash
|
|
85
|
-
python -m pip install --upgrade 'agenttrafficcop==2.
|
|
85
|
+
python -m pip install --upgrade 'agenttrafficcop==2.2.0'
|
|
86
86
|
python -c "from importlib.metadata import version; print(version('agenttrafficcop'))"
|
|
87
87
|
```
|
|
88
88
|
|
|
@@ -671,8 +671,10 @@ sync/async helper. No PyPI version change is required for the HTTP endpoint.
|
|
|
671
671
|
|
|
672
672
|
### LangGraph
|
|
673
673
|
|
|
674
|
+
Install the versioned SDK and the optional LangGraph extra:
|
|
675
|
+
|
|
674
676
|
```bash
|
|
675
|
-
python -m pip install 'agenttrafficcop[langgraph]==2.
|
|
677
|
+
python -m pip install 'agenttrafficcop[langgraph]==2.2.0'
|
|
676
678
|
```
|
|
677
679
|
|
|
678
680
|
```python
|
|
@@ -688,13 +690,48 @@ graph.add_node("reviewer", guarded_node(
|
|
|
688
690
|
```
|
|
689
691
|
|
|
690
692
|
Only wrapped nodes are protected. Keep exceptions propagating so failed checks
|
|
691
|
-
stop execution.
|
|
692
|
-
|
|
693
|
+
stop execution. To pause a circuit-breaker trip for a dashboard review, compile
|
|
694
|
+
with a **durable LangGraph checkpointer** (for example, a production
|
|
695
|
+
database-backed saver) and enable the built-in ATC verifier:
|
|
696
|
+
|
|
697
|
+
```python
|
|
698
|
+
builder.add_node("reviewer", guarded_node(
|
|
699
|
+
reviewer_fn, guard=guard, sender="coder", recipient="reviewer",
|
|
700
|
+
session_id=lambda state: state["run_id"],
|
|
701
|
+
payload=lambda state: {"draft": state["draft"]},
|
|
702
|
+
review_on_trip=True,
|
|
703
|
+
))
|
|
704
|
+
# durable_saver is your database-backed LangGraph checkpointer.
|
|
705
|
+
graph = builder.compile(checkpointer=durable_saver)
|
|
706
|
+
```
|
|
707
|
+
|
|
708
|
+
When paused, show `__interrupt__[0].value` to the authorized operator and use
|
|
709
|
+
the dashboard's run-review flow to approve/reject the exact action. Resume with
|
|
710
|
+
`Command(resume={"review_id": event["review_id"]})`; the resume payload itself
|
|
711
|
+
is never authorization. The SDK queries ATC's owner-scoped review status, the
|
|
712
|
+
adapter checks that the state/action and review ID did not change, and ATC then
|
|
713
|
+
rechecks policy and consumes the one-action approval before the node runs. The
|
|
714
|
+
status API is read-only; only an authenticated dashboard owner can decide a
|
|
715
|
+
review. A custom `review_approval` callback is optional and must fail closed.
|
|
716
|
+
|
|
717
|
+
Run `python -I examples/langgraph_checkpointed_review.py` from the repository
|
|
718
|
+
after installing `./sdk[langgraph]` for an offline walkthrough; it uses fake ATC
|
|
719
|
+
and review services and an in-memory saver, so it is **not** a production setup.
|
|
720
|
+
|
|
721
|
+
A trip creates a checkpoint with only a generic review event, session ID,
|
|
722
|
+
opaque review ID and safe detector error code—never state, prompts, results or
|
|
723
|
+
exception text. On resume the verifier must approve that exact unchanged action;
|
|
724
|
+
only then does the node perform a fresh ATC check immediately before running. A
|
|
725
|
+
resume value by itself is never approval. Do not use an in-memory saver for
|
|
726
|
+
restart durability.
|
|
727
|
+
Approval does not bypass ATC spend/quota/policy controls. Adapters do not
|
|
728
|
+
automatically enable normalization, hash-only, shadow mode or spending
|
|
729
|
+
reservations. Use direct checks for unexposed options.
|
|
693
730
|
|
|
694
731
|
### Legacy AutoGen
|
|
695
732
|
|
|
696
733
|
```bash
|
|
697
|
-
python -m pip install 'agenttrafficcop[autogen]==2.
|
|
734
|
+
python -m pip install 'agenttrafficcop[autogen]==2.2.0'
|
|
698
735
|
```
|
|
699
736
|
|
|
700
737
|
This legacy adapter supports only `pyautogen==0.2.35`, not AgentChat or AG2.
|
|
@@ -9,6 +9,7 @@ pyproject.toml
|
|
|
9
9
|
./agenttrafficcop/__init__.py
|
|
10
10
|
./agenttrafficcop/accounting.py
|
|
11
11
|
./agenttrafficcop/autogen.py
|
|
12
|
+
./agenttrafficcop/cli.py
|
|
12
13
|
./agenttrafficcop/client.py
|
|
13
14
|
./agenttrafficcop/embeddings.py
|
|
14
15
|
./agenttrafficcop/exceptions.py
|
|
@@ -30,6 +31,7 @@ pyproject.toml
|
|
|
30
31
|
agenttrafficcop/__init__.py
|
|
31
32
|
agenttrafficcop/accounting.py
|
|
32
33
|
agenttrafficcop/autogen.py
|
|
34
|
+
agenttrafficcop/cli.py
|
|
33
35
|
agenttrafficcop/client.py
|
|
34
36
|
agenttrafficcop/embeddings.py
|
|
35
37
|
agenttrafficcop/exceptions.py
|
|
@@ -51,5 +53,6 @@ agenttrafficcop/tracing.py
|
|
|
51
53
|
agenttrafficcop.egg-info/PKG-INFO
|
|
52
54
|
agenttrafficcop.egg-info/SOURCES.txt
|
|
53
55
|
agenttrafficcop.egg-info/dependency_links.txt
|
|
56
|
+
agenttrafficcop.egg-info/entry_points.txt
|
|
54
57
|
agenttrafficcop.egg-info/requires.txt
|
|
55
58
|
agenttrafficcop.egg-info/top_level.txt
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "agenttrafficcop"
|
|
7
|
-
version = "2.
|
|
7
|
+
version = "2.2.0"
|
|
8
8
|
description = "Python SDK for AgentTrafficCop — local and hosted deterministic checks for agent workflows."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
@@ -41,6 +41,9 @@ dependencies = [
|
|
|
41
41
|
"httpx>=0.27.0,<0.30.0",
|
|
42
42
|
]
|
|
43
43
|
|
|
44
|
+
[project.scripts]
|
|
45
|
+
atc = "agenttrafficcop.cli:main"
|
|
46
|
+
|
|
44
47
|
[project.optional-dependencies]
|
|
45
48
|
openai = ["openai>=1.109.1,<3.0"]
|
|
46
49
|
autogen = ["pyautogen==0.2.35"]
|
|
@@ -1,159 +0,0 @@
|
|
|
1
|
-
"""LangGraph integration for AgentTrafficCop.
|
|
2
|
-
|
|
3
|
-
Wraps a LangGraph node function so that every invocation first asks
|
|
4
|
-
AgentTrafficCop whether the current handoff is allowed.
|
|
5
|
-
"""
|
|
6
|
-
|
|
7
|
-
from __future__ import annotations
|
|
8
|
-
|
|
9
|
-
import asyncio
|
|
10
|
-
import concurrent.futures # <-- ADDED: Required to fix the async loop crash
|
|
11
|
-
import inspect
|
|
12
|
-
import logging
|
|
13
|
-
from typing import Any, Awaitable, Callable, Dict, Optional, Union
|
|
14
|
-
|
|
15
|
-
from .client import Guard
|
|
16
|
-
from .exceptions import AgentTrafficCopError
|
|
17
|
-
|
|
18
|
-
logger = logging.getLogger("agenttrafficcop.langgraph")
|
|
19
|
-
|
|
20
|
-
StateT = Dict[str, Any]
|
|
21
|
-
NodeFn = Callable[[StateT], Union[Optional[StateT], Awaitable[Optional[StateT]]]]
|
|
22
|
-
ValueOrExtractor = Union[str, Callable[[StateT], Any]]
|
|
23
|
-
|
|
24
|
-
_AUTO_PAYLOAD_EXCLUDE = frozenset(
|
|
25
|
-
{"messages", "history", "trace", "logs"}
|
|
26
|
-
)
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
def _resolve(value: ValueOrExtractor, state: StateT, *, name: str) -> Any:
|
|
30
|
-
if callable(value):
|
|
31
|
-
try:
|
|
32
|
-
return value(state)
|
|
33
|
-
except Exception as e:
|
|
34
|
-
raise RuntimeError(
|
|
35
|
-
f"AgentTrafficCop: {name} extractor raised on state: {e}"
|
|
36
|
-
) from e
|
|
37
|
-
return value
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
def _default_payload(state: StateT) -> Dict[str, Any]:
|
|
41
|
-
return {k: v for k, v in state.items() if k not in _AUTO_PAYLOAD_EXCLUDE}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
def guarded_node(
|
|
45
|
-
node_fn: NodeFn,
|
|
46
|
-
*,
|
|
47
|
-
guard: Guard,
|
|
48
|
-
sender: str,
|
|
49
|
-
recipient: str,
|
|
50
|
-
session_id: Optional[ValueOrExtractor] = None,
|
|
51
|
-
payload: Optional[ValueOrExtractor] = None,
|
|
52
|
-
intent: str = "handoff",
|
|
53
|
-
metadata: Optional[ValueOrExtractor] = None,
|
|
54
|
-
raise_on_trip: bool = True,
|
|
55
|
-
trace_batch=None,
|
|
56
|
-
) -> NodeFn:
|
|
57
|
-
if not callable(node_fn):
|
|
58
|
-
raise TypeError("node_fn must be callable")
|
|
59
|
-
if session_id is None:
|
|
60
|
-
raise ValueError(
|
|
61
|
-
"guarded_node: session_id is required. Pass a string or an "
|
|
62
|
-
"extractor callable, e.g. session_id=lambda s: s['run_id']. "
|
|
63
|
-
"The old default ('session_id') shared one global session "
|
|
64
|
-
"across all callers, so it's now a hard error."
|
|
65
|
-
)
|
|
66
|
-
|
|
67
|
-
is_async = inspect.iscoroutinefunction(node_fn)
|
|
68
|
-
if isinstance(trace_batch, dict):
|
|
69
|
-
trace_batch = trace_batch.get('async' if is_async else 'sync')
|
|
70
|
-
if trace_batch is not None:
|
|
71
|
-
required = '__aenter__' if is_async else '__enter__'
|
|
72
|
-
if not callable(getattr(trace_batch, 'span', None)) or not callable(getattr(trace_batch, required, None)):
|
|
73
|
-
raise ValueError(f'guarded_node tracing requires a matching {"async" if is_async else "sync"} trace_batch')
|
|
74
|
-
trace_name = getattr(node_fn, '__name__', 'langgraph_node')
|
|
75
|
-
|
|
76
|
-
async def _check(state: StateT) -> bool:
|
|
77
|
-
sid = _resolve(session_id, state, name="session_id")
|
|
78
|
-
if payload is None:
|
|
79
|
-
pld = _default_payload(state)
|
|
80
|
-
else:
|
|
81
|
-
pld = _resolve(payload, state, name="payload")
|
|
82
|
-
md = _resolve(metadata, state, name="metadata") if metadata is not None else None
|
|
83
|
-
|
|
84
|
-
if not isinstance(sid, str) or not sid:
|
|
85
|
-
raise ValueError(
|
|
86
|
-
"AgentTrafficCop: session_id resolved to an empty/invalid value"
|
|
87
|
-
)
|
|
88
|
-
if not isinstance(pld, dict):
|
|
89
|
-
raise ValueError(
|
|
90
|
-
"AgentTrafficCop: payload must resolve to a dict, got "
|
|
91
|
-
f"{type(pld).__name__}"
|
|
92
|
-
)
|
|
93
|
-
|
|
94
|
-
try:
|
|
95
|
-
await guard.check(
|
|
96
|
-
session_id=sid,
|
|
97
|
-
sender=sender,
|
|
98
|
-
recipient=recipient,
|
|
99
|
-
payload=pld,
|
|
100
|
-
intent=intent,
|
|
101
|
-
metadata=md,
|
|
102
|
-
)
|
|
103
|
-
return True
|
|
104
|
-
except AgentTrafficCopError as e:
|
|
105
|
-
if raise_on_trip:
|
|
106
|
-
logger.warning(
|
|
107
|
-
"langgraph_node_tripped node=%s session=%s error_code=%s",
|
|
108
|
-
getattr(node_fn, "__name__", repr(node_fn)),
|
|
109
|
-
sid,
|
|
110
|
-
e.error_code,
|
|
111
|
-
)
|
|
112
|
-
raise
|
|
113
|
-
logger.info(
|
|
114
|
-
"langgraph_node_skipped node=%s session=%s error_code=%s",
|
|
115
|
-
getattr(node_fn, "__name__", repr(node_fn)),
|
|
116
|
-
sid,
|
|
117
|
-
e.error_code,
|
|
118
|
-
)
|
|
119
|
-
return False
|
|
120
|
-
|
|
121
|
-
if is_async:
|
|
122
|
-
async def _wrapped_async(state: StateT) -> Any:
|
|
123
|
-
should_run = await _check(state)
|
|
124
|
-
if not should_run:
|
|
125
|
-
return None
|
|
126
|
-
if trace_batch is None:
|
|
127
|
-
return await node_fn(state)
|
|
128
|
-
async with trace_batch.span(trace_name, kind='agent'):
|
|
129
|
-
return await node_fn(state)
|
|
130
|
-
|
|
131
|
-
_wrapped_async.__name__ = getattr(node_fn, "__name__", "guarded_node")
|
|
132
|
-
_wrapped_async.__doc__ = node_fn.__doc__ or ""
|
|
133
|
-
return _wrapped_async
|
|
134
|
-
|
|
135
|
-
def _wrapped_sync(state: StateT) -> Any:
|
|
136
|
-
try:
|
|
137
|
-
loop = asyncio.get_running_loop()
|
|
138
|
-
except RuntimeError:
|
|
139
|
-
loop = None
|
|
140
|
-
|
|
141
|
-
if loop and loop.is_running():
|
|
142
|
-
# FIX (Priority 1): We are inside an async event loop (e.g. LangGraph .ainvoke()).
|
|
143
|
-
# We cannot use asyncio.run() because the loop is already running.
|
|
144
|
-
# We run the async check in a separate thread so we don't block the loop.
|
|
145
|
-
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
|
|
146
|
-
should_run = pool.submit(asyncio.run, _check(state)).result()
|
|
147
|
-
else:
|
|
148
|
-
should_run = asyncio.run(_check(state))
|
|
149
|
-
|
|
150
|
-
if not should_run:
|
|
151
|
-
return None
|
|
152
|
-
if trace_batch is None:
|
|
153
|
-
return node_fn(state)
|
|
154
|
-
with trace_batch.span(trace_name, kind='agent'):
|
|
155
|
-
return node_fn(state)
|
|
156
|
-
|
|
157
|
-
_wrapped_sync.__name__ = getattr(node_fn, "__name__", "guarded_node")
|
|
158
|
-
_wrapped_sync.__doc__ = node_fn.__doc__ or ""
|
|
159
|
-
return _wrapped_sync
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{agenttrafficcop-2.1.0 → agenttrafficcop-2.2.0}/agenttrafficcop.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|