agent-action-gateway 0.2.0__py3-none-any.whl
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.
- agent_action_gateway/__init__.py +44 -0
- agent_action_gateway/__main__.py +7 -0
- agent_action_gateway/audit/__init__.py +1 -0
- agent_action_gateway/audit/failure_wall.py +215 -0
- agent_action_gateway/audit/promotions.py +196 -0
- agent_action_gateway/audit/receipts.py +143 -0
- agent_action_gateway/audit/wall.py +298 -0
- agent_action_gateway/cli.py +997 -0
- agent_action_gateway/credential/__init__.py +1 -0
- agent_action_gateway/credential/credentials.py +272 -0
- agent_action_gateway/credential/egress.py +216 -0
- agent_action_gateway/data/calibration/calibration-v1.json +47 -0
- agent_action_gateway/data/golden/golden-v1.json +35 -0
- agent_action_gateway/engine/__init__.py +1 -0
- agent_action_gateway/engine/enforcement.py +419 -0
- agent_action_gateway/eval/__init__.py +1 -0
- agent_action_gateway/eval/calibration.py +138 -0
- agent_action_gateway/eval/evaluator.py +166 -0
- agent_action_gateway/eval/gate.py +108 -0
- agent_action_gateway/eval/golden.py +135 -0
- agent_action_gateway/eval/judge.py +163 -0
- agent_action_gateway/eval/models.py +120 -0
- agent_action_gateway/eval/online.py +192 -0
- agent_action_gateway/eval/providers/__init__.py +1 -0
- agent_action_gateway/eval/providers/gemini.py +269 -0
- agent_action_gateway/eval/trajectory.py +231 -0
- agent_action_gateway/eval/verdict.py +53 -0
- agent_action_gateway/gate_cli.py +295 -0
- agent_action_gateway/guards/__init__.py +1 -0
- agent_action_gateway/guards/capture.py +58 -0
- agent_action_gateway/guards/redaction.py +124 -0
- agent_action_gateway/guards/sql.py +158 -0
- agent_action_gateway/guards/status.py +20 -0
- agent_action_gateway/integrations/__init__.py +1 -0
- agent_action_gateway/integrations/adapters/__init__.py +1 -0
- agent_action_gateway/integrations/adapters/base.py +59 -0
- agent_action_gateway/integrations/gateway.py +751 -0
- agent_action_gateway/integrations/mcp.py +153 -0
- agent_action_gateway/integrations/mcp_http.py +436 -0
- agent_action_gateway/integrations/mcp_proxy.py +2020 -0
- agent_action_gateway/integrations/mcp_server.py +101 -0
- agent_action_gateway/observability/__init__.py +1 -0
- agent_action_gateway/observability/dashboard.py +916 -0
- agent_action_gateway/observability/view.py +170 -0
- agent_action_gateway/observability/wiring.py +481 -0
- agent_action_gateway/policy/__init__.py +1 -0
- agent_action_gateway/policy/cross_check.py +47 -0
- agent_action_gateway/policy/fingerprint.py +111 -0
- agent_action_gateway/policy/fuses.py +291 -0
- agent_action_gateway/policy/locks.py +411 -0
- agent_action_gateway/policy/safety.py +37 -0
- agent_action_gateway/policy/stop_rules.py +219 -0
- agent_action_gateway/proofs/__init__.py +4 -0
- agent_action_gateway/proofs/approval_proof.py +76 -0
- agent_action_gateway/proofs/chaos.py +298 -0
- agent_action_gateway/proofs/chaos_manual.py +82 -0
- agent_action_gateway/proofs/evaluation_proof.py +99 -0
- agent_action_gateway/proofs/fakes.py +22 -0
- agent_action_gateway/proofs/proof.py +113 -0
- agent_action_gateway/runtime/__init__.py +4 -0
- agent_action_gateway/runtime/orchestrator.py +281 -0
- agent_action_gateway/runtime/records.py +49 -0
- agent_action_gateway/runtime/session.py +764 -0
- agent_action_gateway/storage/__init__.py +3 -0
- agent_action_gateway/storage/base.py +185 -0
- agent_action_gateway/storage/evaluations.py +224 -0
- agent_action_gateway/storage/postgres.py +190 -0
- agent_action_gateway/storage/traces.py +765 -0
- agent_action_gateway-0.2.0.dist-info/LICENSE +21 -0
- agent_action_gateway-0.2.0.dist-info/METADATA +374 -0
- agent_action_gateway-0.2.0.dist-info/RECORD +74 -0
- agent_action_gateway-0.2.0.dist-info/WHEEL +5 -0
- agent_action_gateway-0.2.0.dist-info/entry_points.txt +2 -0
- agent_action_gateway-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Agent Action Gateway: let AI agents change real systems safely.
|
|
2
|
+
|
|
3
|
+
You control what an agent can do, and you can prove what it did. The public
|
|
4
|
+
surface is intentionally small. A user wraps their own agent's tools (or puts the
|
|
5
|
+
MCP proxy between the agent and its MCP servers) and receives recorded evidence
|
|
6
|
+
and enforced policy; this package does not own the agent loop or the agent's
|
|
7
|
+
model calls.
|
|
8
|
+
|
|
9
|
+
Layout:
|
|
10
|
+
|
|
11
|
+
policy/ pure decisions: risk, approval, budgets, stop rules, hashes
|
|
12
|
+
engine/ the one enforcement pipeline
|
|
13
|
+
guards/ redaction, capture policy, honest status
|
|
14
|
+
runtime/ run orchestration
|
|
15
|
+
credential/ key custody and outbound host checks
|
|
16
|
+
integrations/ MCP proxy, HTTP gateway, in-process adapters
|
|
17
|
+
audit/ receipts, failure grouping, lifecycle stores
|
|
18
|
+
eval/ golden set, judges, verdict engine, regression gate
|
|
19
|
+
storage/ durable SQLite/Postgres persistence (leaf layer)
|
|
20
|
+
observability/ dashboard and wiring check
|
|
21
|
+
proofs/ verification scripts about this library, not in the CLI
|
|
22
|
+
|
|
23
|
+
Import from here rather than from submodules; the submodule layout is an
|
|
24
|
+
implementation detail.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from agent_action_gateway.audit.receipts import OutcomeUnknown
|
|
28
|
+
from agent_action_gateway.policy.fuses import (
|
|
29
|
+
FuseBudget,
|
|
30
|
+
FuseController,
|
|
31
|
+
FuseLimits,
|
|
32
|
+
FuseTrippedError,
|
|
33
|
+
)
|
|
34
|
+
from agent_action_gateway.runtime.session import DEFAULT_FUSE_LIMITS, SafetySession, session
|
|
35
|
+
|
|
36
|
+
# The names below are what a consumer needs. The remaining imports stay
|
|
37
|
+
# reachable so that existing `from agent_action_gateway import X` calls keep working,
|
|
38
|
+
# but they are not advertised as part of the public surface.
|
|
39
|
+
__all__ = [
|
|
40
|
+
"FuseLimits",
|
|
41
|
+
"OutcomeUnknown",
|
|
42
|
+
"SafetySession",
|
|
43
|
+
"session",
|
|
44
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""audit package."""
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""Deterministic Failure Wall grouping.
|
|
2
|
+
|
|
3
|
+
Failures group by error type, failing step and normalized configuration
|
|
4
|
+
fingerprint. Nothing here merges or splits on judgment: those are explicit human
|
|
5
|
+
operations, recorded separately.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
from collections.abc import Iterable, Mapping
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class FailureSignature:
|
|
17
|
+
"""Deterministic Failure Wall key."""
|
|
18
|
+
|
|
19
|
+
error_type: str
|
|
20
|
+
failing_step: str
|
|
21
|
+
config_fingerprint: str
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class FailureRecord:
|
|
26
|
+
"""Redacted trace evidence used by the Failure Wall."""
|
|
27
|
+
|
|
28
|
+
trace_id: int
|
|
29
|
+
run_id: str
|
|
30
|
+
step: int
|
|
31
|
+
event: str
|
|
32
|
+
status: str
|
|
33
|
+
error_type: str
|
|
34
|
+
failing_step: str
|
|
35
|
+
config_fingerprint: str
|
|
36
|
+
flags: tuple[str, ...] = ()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class FailureGroup:
|
|
41
|
+
"""Human-reviewable failure group. Ownership starts as unknown."""
|
|
42
|
+
|
|
43
|
+
group_id: str
|
|
44
|
+
signature: FailureSignature
|
|
45
|
+
records: list[FailureRecord]
|
|
46
|
+
ownership: str = "unknown"
|
|
47
|
+
state: str = "unconfirmed"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def config_fingerprint(config: Mapping[str, Any] | None) -> str:
|
|
51
|
+
"""Create a stable fingerprint for relevant configuration."""
|
|
52
|
+
|
|
53
|
+
payload = json.dumps(
|
|
54
|
+
dict(config or {}),
|
|
55
|
+
sort_keys=True,
|
|
56
|
+
separators=(",", ":"),
|
|
57
|
+
default=str,
|
|
58
|
+
).encode("utf-8")
|
|
59
|
+
return hashlib.sha256(payload).hexdigest()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _failure_error_type(trace: Mapping[str, Any]) -> str:
|
|
63
|
+
output = trace.get("output")
|
|
64
|
+
if isinstance(output, Mapping):
|
|
65
|
+
error = output.get("error")
|
|
66
|
+
if isinstance(error, Mapping):
|
|
67
|
+
name = error.get("type") or error.get("name")
|
|
68
|
+
if name:
|
|
69
|
+
return str(name)
|
|
70
|
+
if error:
|
|
71
|
+
return type(error).__name__ if not isinstance(error, str) else "tool-error"
|
|
72
|
+
|
|
73
|
+
status = str(trace.get("status", "")).lower()
|
|
74
|
+
if status in {"failed", "error"}:
|
|
75
|
+
return "runtime-error"
|
|
76
|
+
|
|
77
|
+
flags = tuple(str(flag) for flag in trace.get("flags", ()))
|
|
78
|
+
if flags:
|
|
79
|
+
return "silent-wrong:" + ",".join(sorted(flags))
|
|
80
|
+
return "unknown"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _failure_config(trace: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
84
|
+
metadata = trace.get("provider_metadata")
|
|
85
|
+
if not isinstance(metadata, Mapping):
|
|
86
|
+
return {}
|
|
87
|
+
config = metadata.get("config")
|
|
88
|
+
return config if isinstance(config, Mapping) else {}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def failure_record(trace: Mapping[str, Any]) -> FailureRecord | None:
|
|
92
|
+
"""Turn a persisted trace into a Failure Wall record.
|
|
93
|
+
|
|
94
|
+
Only explicit failures or suspicious observability traces enter the wall.
|
|
95
|
+
"""
|
|
96
|
+
status = str(trace.get("status", "")).lower()
|
|
97
|
+
flags = tuple(str(flag) for flag in trace.get("flags", ()))
|
|
98
|
+
if status not in {"failed", "error", "blocked"} and not flags:
|
|
99
|
+
return None
|
|
100
|
+
|
|
101
|
+
step = int(trace.get("step", 0))
|
|
102
|
+
event = str(trace.get("event", "unknown"))
|
|
103
|
+
return FailureRecord(
|
|
104
|
+
trace_id=int(trace.get("id", 0)),
|
|
105
|
+
run_id=str(trace.get("run_id", "")),
|
|
106
|
+
step=step,
|
|
107
|
+
event=event,
|
|
108
|
+
status=status,
|
|
109
|
+
error_type=_failure_error_type(trace),
|
|
110
|
+
failing_step=event or str(step),
|
|
111
|
+
config_fingerprint=config_fingerprint(_failure_config(trace)),
|
|
112
|
+
flags=flags,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def build_failure_wall(traces: Iterable[Mapping[str, Any]]) -> list[FailureGroup]:
|
|
117
|
+
"""Group by error type × failing step × config fingerprint only."""
|
|
118
|
+
|
|
119
|
+
groups: dict[FailureSignature, FailureGroup] = {}
|
|
120
|
+
for trace in traces:
|
|
121
|
+
record = failure_record(trace)
|
|
122
|
+
if record is None:
|
|
123
|
+
continue
|
|
124
|
+
signature = FailureSignature(
|
|
125
|
+
record.error_type,
|
|
126
|
+
record.failing_step,
|
|
127
|
+
record.config_fingerprint,
|
|
128
|
+
)
|
|
129
|
+
group = groups.get(signature)
|
|
130
|
+
if group is None:
|
|
131
|
+
payload = "|".join(
|
|
132
|
+
(
|
|
133
|
+
signature.error_type,
|
|
134
|
+
signature.failing_step,
|
|
135
|
+
signature.config_fingerprint,
|
|
136
|
+
)
|
|
137
|
+
)
|
|
138
|
+
group = FailureGroup(
|
|
139
|
+
group_id=hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16],
|
|
140
|
+
signature=signature,
|
|
141
|
+
records=[],
|
|
142
|
+
)
|
|
143
|
+
groups[signature] = group
|
|
144
|
+
group.records.append(record)
|
|
145
|
+
|
|
146
|
+
return sorted(groups.values(), key=lambda group: group.group_id)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def confirm_failure_group(group: FailureGroup) -> FailureGroup:
|
|
150
|
+
"""Human confirmation changes state only; it never assigns ownership."""
|
|
151
|
+
group.state = "confirmed"
|
|
152
|
+
group.ownership = "unknown"
|
|
153
|
+
return group
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def merge_failure_groups(groups: Iterable[FailureGroup]) -> FailureGroup:
|
|
157
|
+
"""Explicit human merge. The automatic grouper never performs this."""
|
|
158
|
+
selected = list(groups)
|
|
159
|
+
if len(selected) < 2:
|
|
160
|
+
raise ValueError("merge requires at least two groups")
|
|
161
|
+
|
|
162
|
+
payload = "|".join(sorted(group.group_id for group in selected))
|
|
163
|
+
records = [record for group in selected for record in group.records]
|
|
164
|
+
return FailureGroup(
|
|
165
|
+
group_id="merged-" + hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16],
|
|
166
|
+
signature=selected[0].signature,
|
|
167
|
+
records=records,
|
|
168
|
+
ownership="unknown",
|
|
169
|
+
state="confirmed" if all(g.state == "confirmed" for g in selected) else "unconfirmed",
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def split_failure_group(
|
|
174
|
+
group: FailureGroup,
|
|
175
|
+
signatures: Iterable[FailureSignature],
|
|
176
|
+
) -> list[FailureGroup]:
|
|
177
|
+
"""Explicit human split using signatures selected from the evidence."""
|
|
178
|
+
requested = list(signatures)
|
|
179
|
+
if not requested:
|
|
180
|
+
raise ValueError("split requires at least one target signature")
|
|
181
|
+
if len(requested) != len(set(requested)):
|
|
182
|
+
raise ValueError("split target signatures must be unique")
|
|
183
|
+
|
|
184
|
+
buckets: dict[FailureSignature, list[FailureRecord]] = {
|
|
185
|
+
signature: [] for signature in requested
|
|
186
|
+
}
|
|
187
|
+
for record in group.records:
|
|
188
|
+
key = FailureSignature(
|
|
189
|
+
record.error_type,
|
|
190
|
+
record.failing_step,
|
|
191
|
+
record.config_fingerprint,
|
|
192
|
+
)
|
|
193
|
+
if key not in buckets:
|
|
194
|
+
raise ValueError("split signature does not match group evidence")
|
|
195
|
+
buckets[key].append(record)
|
|
196
|
+
|
|
197
|
+
if any(not records for records in buckets.values()):
|
|
198
|
+
raise ValueError("split target must contain evidence")
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
result = []
|
|
202
|
+
for signature, records in buckets.items():
|
|
203
|
+
payload = "|".join(
|
|
204
|
+
(signature.error_type, signature.failing_step, signature.config_fingerprint)
|
|
205
|
+
)
|
|
206
|
+
result.append(
|
|
207
|
+
FailureGroup(
|
|
208
|
+
group_id=hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16],
|
|
209
|
+
signature=signature,
|
|
210
|
+
records=records,
|
|
211
|
+
ownership="unknown",
|
|
212
|
+
state="unconfirmed",
|
|
213
|
+
)
|
|
214
|
+
)
|
|
215
|
+
return result
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""Durable storage for promoted baseline versions."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import sqlite3
|
|
6
|
+
from collections.abc import Iterable
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from datetime import UTC, datetime
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from agent_action_gateway.audit.failure_wall import FailureGroup
|
|
13
|
+
from agent_action_gateway.audit.wall import FailureWallStore
|
|
14
|
+
from agent_action_gateway.eval.models import GoldenCase
|
|
15
|
+
from agent_action_gateway.storage.base import SqliteStore
|
|
16
|
+
|
|
17
|
+
_ALLOWED_CHECK_TYPES = frozenset({"exact", "field-equality", "regex", "rubric"})
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class GoldenCasePromotion:
|
|
22
|
+
"""An evaluation golden case promoted from confirmed observability evidence."""
|
|
23
|
+
|
|
24
|
+
case: GoldenCase
|
|
25
|
+
failure_group_id: str
|
|
26
|
+
source_trace_ids: tuple[int, ...]
|
|
27
|
+
promoted_at: str
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class GoldenCasePromotionStore(SqliteStore):
|
|
31
|
+
"""Durable store for human-promoted golden cases and their provenance."""
|
|
32
|
+
|
|
33
|
+
store_name = "golden_promotions"
|
|
34
|
+
|
|
35
|
+
def __init__(self, path: str | Path = "data/golden-promotions.db") -> None:
|
|
36
|
+
super().__init__(path)
|
|
37
|
+
|
|
38
|
+
def _migrations(self):
|
|
39
|
+
yield 1, [
|
|
40
|
+
"""
|
|
41
|
+
CREATE TABLE IF NOT EXISTS golden_case_promotions (
|
|
42
|
+
case_id TEXT PRIMARY KEY,
|
|
43
|
+
task_json TEXT NOT NULL,
|
|
44
|
+
expected_json TEXT NOT NULL,
|
|
45
|
+
check_type TEXT NOT NULL,
|
|
46
|
+
source TEXT NOT NULL,
|
|
47
|
+
catastrophic INTEGER NOT NULL,
|
|
48
|
+
rubric_json TEXT NOT NULL,
|
|
49
|
+
failure_group_id TEXT NOT NULL UNIQUE,
|
|
50
|
+
source_trace_ids_json TEXT NOT NULL,
|
|
51
|
+
promoted_at TEXT NOT NULL
|
|
52
|
+
);
|
|
53
|
+
""",
|
|
54
|
+
"""
|
|
55
|
+
CREATE INDEX IF NOT EXISTS idx_golden_promotions_group
|
|
56
|
+
ON golden_case_promotions(failure_group_id);
|
|
57
|
+
""",
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
def save(self, promotion: GoldenCasePromotion) -> None:
|
|
61
|
+
if not promotion.case.case_id:
|
|
62
|
+
raise ValueError('"case_id" must be a non-empty string')
|
|
63
|
+
if promotion.case.check_type not in _ALLOWED_CHECK_TYPES:
|
|
64
|
+
raise ValueError(
|
|
65
|
+
f"unsupported golden check type: {promotion.case.check_type!r}"
|
|
66
|
+
)
|
|
67
|
+
if not promotion.failure_group_id:
|
|
68
|
+
raise ValueError("failure_group_id must be non-empty")
|
|
69
|
+
if not promotion.source_trace_ids:
|
|
70
|
+
raise ValueError("at least one source trace is required")
|
|
71
|
+
|
|
72
|
+
with self.connection() as connection:
|
|
73
|
+
existing_case = connection.execute(
|
|
74
|
+
"SELECT 1 FROM golden_case_promotions WHERE case_id = ?",
|
|
75
|
+
(promotion.case.case_id,),
|
|
76
|
+
).fetchone()
|
|
77
|
+
if existing_case is not None:
|
|
78
|
+
raise ValueError(
|
|
79
|
+
f"golden case already promoted: {promotion.case.case_id}"
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
existing_group = connection.execute(
|
|
83
|
+
"SELECT 1 FROM golden_case_promotions WHERE failure_group_id = ?",
|
|
84
|
+
(promotion.failure_group_id,),
|
|
85
|
+
).fetchone()
|
|
86
|
+
if existing_group is not None:
|
|
87
|
+
raise ValueError(
|
|
88
|
+
f"failure group already promoted: {promotion.failure_group_id}"
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
connection.execute(
|
|
92
|
+
"""
|
|
93
|
+
INSERT INTO golden_case_promotions (
|
|
94
|
+
case_id, task_json, expected_json, check_type, source,
|
|
95
|
+
catastrophic, rubric_json, failure_group_id,
|
|
96
|
+
source_trace_ids_json, promoted_at
|
|
97
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
98
|
+
""",
|
|
99
|
+
(
|
|
100
|
+
promotion.case.case_id,
|
|
101
|
+
json.dumps(promotion.case.task, sort_keys=True),
|
|
102
|
+
json.dumps(promotion.case.expected, sort_keys=True),
|
|
103
|
+
promotion.case.check_type,
|
|
104
|
+
promotion.case.source,
|
|
105
|
+
int(promotion.case.catastrophic),
|
|
106
|
+
json.dumps(list(promotion.case.rubric), sort_keys=True),
|
|
107
|
+
promotion.failure_group_id,
|
|
108
|
+
json.dumps(list(promotion.source_trace_ids)),
|
|
109
|
+
promotion.promoted_at,
|
|
110
|
+
),
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
def get(self, case_id: str) -> GoldenCasePromotion | None:
|
|
114
|
+
with self.connection() as connection:
|
|
115
|
+
row = connection.execute(
|
|
116
|
+
"SELECT * FROM golden_case_promotions WHERE case_id = ?",
|
|
117
|
+
(case_id,),
|
|
118
|
+
).fetchone()
|
|
119
|
+
return self._to_promotion(row) if row is not None else None
|
|
120
|
+
|
|
121
|
+
def list(self) -> list[GoldenCasePromotion]:
|
|
122
|
+
with self.connection() as connection:
|
|
123
|
+
rows = connection.execute(
|
|
124
|
+
"SELECT * FROM golden_case_promotions ORDER BY promoted_at, case_id"
|
|
125
|
+
).fetchall()
|
|
126
|
+
return [self._to_promotion(row) for row in rows]
|
|
127
|
+
|
|
128
|
+
@staticmethod
|
|
129
|
+
def _to_promotion(row: sqlite3.Row) -> GoldenCasePromotion:
|
|
130
|
+
return GoldenCasePromotion(
|
|
131
|
+
case=GoldenCase(
|
|
132
|
+
case_id=row["case_id"],
|
|
133
|
+
task=json.loads(row["task_json"]),
|
|
134
|
+
expected=json.loads(row["expected_json"]),
|
|
135
|
+
check_type=row["check_type"],
|
|
136
|
+
source=row["source"],
|
|
137
|
+
catastrophic=bool(row["catastrophic"]),
|
|
138
|
+
rubric=tuple(json.loads(row["rubric_json"])),
|
|
139
|
+
),
|
|
140
|
+
failure_group_id=row["failure_group_id"],
|
|
141
|
+
source_trace_ids=tuple(json.loads(row["source_trace_ids_json"])),
|
|
142
|
+
promoted_at=row["promoted_at"],
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def promote_failure_group(
|
|
147
|
+
failure_wall: FailureWallStore,
|
|
148
|
+
promotions: GoldenCasePromotionStore,
|
|
149
|
+
group_id: str,
|
|
150
|
+
*,
|
|
151
|
+
case_id: str,
|
|
152
|
+
task: Any,
|
|
153
|
+
expected: Any,
|
|
154
|
+
check_type: str,
|
|
155
|
+
catastrophic: bool = False,
|
|
156
|
+
rubric: Iterable[str] = (),
|
|
157
|
+
) -> GoldenCasePromotion:
|
|
158
|
+
"""Promote a confirmed Failure Wall group into an evaluation golden case.
|
|
159
|
+
|
|
160
|
+
The expected result is supplied by the human promoting the case. The
|
|
161
|
+
failure trace is evidence, not the expected answer.
|
|
162
|
+
"""
|
|
163
|
+
group = failure_wall.get_group(group_id)
|
|
164
|
+
if group is None:
|
|
165
|
+
raise KeyError(f"unknown failure group: {group_id}")
|
|
166
|
+
_require_confirmed_group(group)
|
|
167
|
+
|
|
168
|
+
source_trace_ids = tuple(sorted({record.trace_id for record in group.records}))
|
|
169
|
+
if not source_trace_ids:
|
|
170
|
+
raise ValueError("failure group has no evidence")
|
|
171
|
+
|
|
172
|
+
rubric_values = tuple(rubric)
|
|
173
|
+
case = GoldenCase(
|
|
174
|
+
case_id=case_id,
|
|
175
|
+
task=task,
|
|
176
|
+
expected=expected,
|
|
177
|
+
check_type=check_type,
|
|
178
|
+
source=f"failure-wall:{group.group_id}",
|
|
179
|
+
catastrophic=catastrophic,
|
|
180
|
+
rubric=rubric_values,
|
|
181
|
+
)
|
|
182
|
+
promotion = GoldenCasePromotion(
|
|
183
|
+
case=case,
|
|
184
|
+
failure_group_id=group.group_id,
|
|
185
|
+
source_trace_ids=source_trace_ids,
|
|
186
|
+
promoted_at=datetime.now(UTC).isoformat(),
|
|
187
|
+
)
|
|
188
|
+
promotions.save(promotion)
|
|
189
|
+
return promotion
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _require_confirmed_group(group: FailureGroup) -> None:
|
|
193
|
+
if group.state != "confirmed":
|
|
194
|
+
raise ValueError(
|
|
195
|
+
f"failure group not confirmed: {group.group_id}"
|
|
196
|
+
)
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Durable receipts, so a retried action cannot happen twice."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import urllib.error
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from agent_action_gateway.integrations.adapters.base import ExternalActionProvider
|
|
8
|
+
from agent_action_gateway.policy.fingerprint import fingerprint
|
|
9
|
+
from agent_action_gateway.storage.traces import TraceStore
|
|
10
|
+
|
|
11
|
+
TARGET_KEY = "target"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class UnresolvableReceiptError(RuntimeError):
|
|
15
|
+
"""A receipt cannot be resolved because it lacks a replayable target.
|
|
16
|
+
|
|
17
|
+
An uncertain side effect must be resolved with the provider before any
|
|
18
|
+
retry. Without a durable target the retry cannot be dispatched safely, so
|
|
19
|
+
this fails loudly rather than guessing.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class EffectInFlight(RuntimeError):
|
|
24
|
+
"""The effect was claimed by another attempt that has not finished.
|
|
25
|
+
|
|
26
|
+
This is the honest state. A crash between claiming and completing leaves
|
|
27
|
+
the receipt `pending`, and whether the action landed is genuinely unknown.
|
|
28
|
+
Raising is correct: executing again risks a duplicate, and reporting
|
|
29
|
+
success risks a lie. A person settles it with `agent-gateway receipts
|
|
30
|
+
settle`, or `resolve_unknown()` asks a provider that can look it up.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class OutcomeUnknown(Exception):
|
|
35
|
+
"""Raise this from a tool when the action may or may not have happened.
|
|
36
|
+
|
|
37
|
+
For example: the request was sent and the answer never came. The effect's
|
|
38
|
+
claim then stays unfinished, so the same action is refused until it is
|
|
39
|
+
settled (`agent-gateway receipts settle`, or `resolve_unknown()`), instead
|
|
40
|
+
of being retried blindly.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
#: Errors that can happen after a request was sent: it may have landed.
|
|
45
|
+
_AMBIGUOUS = (TimeoutError, ConnectionResetError, ConnectionAbortedError, BrokenPipeError)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def outcome_is_unknown(exc: BaseException) -> bool:
|
|
49
|
+
"""Whether an error leaves it unknown if the action happened.
|
|
50
|
+
|
|
51
|
+
Unknown: `OutcomeUnknown`; a timeout, reset or broken connection (the
|
|
52
|
+
request may have arrived); an HTTP 5xx; and an interrupt (Ctrl-C, exit)
|
|
53
|
+
in the middle of the call. Everything else (a refused connection, a 4xx,
|
|
54
|
+
an error in your own code) means the action did not happen, so a later
|
|
55
|
+
attempt may run.
|
|
56
|
+
"""
|
|
57
|
+
if isinstance(exc, OutcomeUnknown):
|
|
58
|
+
return True
|
|
59
|
+
if not isinstance(exc, Exception):
|
|
60
|
+
return True # KeyboardInterrupt, SystemExit: stopped mid-call
|
|
61
|
+
if isinstance(exc, urllib.error.HTTPError):
|
|
62
|
+
return exc.code >= 500
|
|
63
|
+
if isinstance(exc, urllib.error.URLError):
|
|
64
|
+
return isinstance(exc.reason, _AMBIGUOUS)
|
|
65
|
+
return isinstance(exc, _AMBIGUOUS)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def claim_effect(
|
|
69
|
+
store: TraceStore,
|
|
70
|
+
run_id: str,
|
|
71
|
+
step_id: str,
|
|
72
|
+
action: str,
|
|
73
|
+
arguments: dict[str, Any],
|
|
74
|
+
*,
|
|
75
|
+
scope: str = "",
|
|
76
|
+
identity_fields: tuple[str, ...] = (),
|
|
77
|
+
) -> tuple[Any, bool]:
|
|
78
|
+
"""Claim an effect before executing it.
|
|
79
|
+
|
|
80
|
+
Returns `(receipt, owned)`. `owned` is true only for the caller that created
|
|
81
|
+
the receipt, which is the single caller permitted to execute the effect.
|
|
82
|
+
|
|
83
|
+
This needs no provider. The effect key is derived from the action and its
|
|
84
|
+
arguments, so two claims of the same effect collide in the database no
|
|
85
|
+
matter which run, process or host they came from.
|
|
86
|
+
"""
|
|
87
|
+
effect_key = fingerprint(
|
|
88
|
+
action, arguments, scope=scope, identity_fields=identity_fields
|
|
89
|
+
)
|
|
90
|
+
return store.claim_receipt(effect_key, run_id, step_id, action, arguments)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def execute_side_effect(
|
|
94
|
+
store: TraceStore,
|
|
95
|
+
provider: ExternalActionProvider,
|
|
96
|
+
run_id: str,
|
|
97
|
+
step_id: str,
|
|
98
|
+
arguments: dict[str, Any],
|
|
99
|
+
target: str,
|
|
100
|
+
) -> str:
|
|
101
|
+
# The replay target is persisted separately from the caller-supplied
|
|
102
|
+
# arguments, so recovery never depends on the caller's payload shape.
|
|
103
|
+
durable_arguments = dict(arguments)
|
|
104
|
+
durable_arguments.setdefault(TARGET_KEY, target)
|
|
105
|
+
receipt = store.create_receipt(
|
|
106
|
+
run_id, step_id, "external_action", durable_arguments
|
|
107
|
+
)
|
|
108
|
+
if receipt.state != "unknown":
|
|
109
|
+
raise RuntimeError(f"unexpected receipt state: {receipt.state}")
|
|
110
|
+
try:
|
|
111
|
+
provider_ref = provider.execute(target, receipt.intent_key)
|
|
112
|
+
except BaseException as exc:
|
|
113
|
+
if not outcome_is_unknown(exc):
|
|
114
|
+
store.mark_failed(receipt.intent_key)
|
|
115
|
+
raise
|
|
116
|
+
store.mark_done(receipt.intent_key, provider_ref)
|
|
117
|
+
return provider_ref
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def resolve_unknown(store: TraceStore, provider: ExternalActionProvider) -> int:
|
|
121
|
+
resolved = 0
|
|
122
|
+
for receipt in store.unknown_receipts():
|
|
123
|
+
# The persisted target is checked before anything is asked of the
|
|
124
|
+
# provider. Without it neither reconciliation nor a safe replay is
|
|
125
|
+
# possible, so this is a manual-review condition, not a retry.
|
|
126
|
+
target = receipt.arguments.get(TARGET_KEY)
|
|
127
|
+
if not target:
|
|
128
|
+
raise UnresolvableReceiptError(
|
|
129
|
+
f"receipt {receipt.intent_key} has no persisted {TARGET_KEY}; "
|
|
130
|
+
"resolve it manually instead of retrying an uncertain side effect"
|
|
131
|
+
)
|
|
132
|
+
# The target is passed through so a provider that reconciles by
|
|
133
|
+
# replaying its idempotent request can be answered without a
|
|
134
|
+
# lookup-by-key endpoint.
|
|
135
|
+
provider_ref = provider.find(receipt.intent_key, target)
|
|
136
|
+
if provider_ref is not None:
|
|
137
|
+
store.mark_resolved(receipt.intent_key, provider_ref)
|
|
138
|
+
resolved += 1
|
|
139
|
+
continue
|
|
140
|
+
provider_ref = provider.execute(target, receipt.intent_key)
|
|
141
|
+
store.mark_done(receipt.intent_key, provider_ref)
|
|
142
|
+
resolved += 1
|
|
143
|
+
return resolved
|