agent-stoploss 1.0.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.
@@ -0,0 +1,13 @@
1
+ """agent-stoploss: stop AI agents from burning tokens on broken tools."""
2
+
3
+ __version__ = "1.0.0"
4
+
5
+ from .config import Config, ConfigError # noqa: E402
6
+ from .engine import Decision, Verdict # noqa: E402
7
+ from .guard import StopLoss # noqa: E402
8
+ from .run import Run, StopEvent, Stopped, StreamingNotSupported, ToolFailed, current_run # noqa: E402
9
+
10
+ __all__ = [
11
+ "StopLoss", "Stopped", "StopEvent", "ToolFailed", "StreamingNotSupported",
12
+ "Run", "current_run", "Config", "ConfigError", "Decision", "Verdict",
13
+ ]
@@ -0,0 +1,304 @@
1
+ """Claude Agent SDK integration.
2
+
3
+ from claude_agent_sdk import ClaudeAgentOptions
4
+ from agent_stoploss import StopLoss, Stopped
5
+ from agent_stoploss.claude_agent import guarded_query
6
+
7
+ guard = StopLoss.from_file("stoploss.yaml")
8
+ try:
9
+ async for message in guarded_query(guard, prompt="...", options=ClaudeAgentOptions(...),
10
+ agent="weekly-report"):
11
+ ...
12
+ except Stopped as stop:
13
+ print(stop.reason)
14
+
15
+ The SDK runs the agent loop itself, so agent-stoploss joins it in two places:
16
+
17
+ - hooks before and after every tool call (PreToolUse, PostToolUse,
18
+ PostToolUseFailure) see the calls, the results and the errors;
19
+ - the messages the SDK yields carry each model response's token usage.
20
+
21
+ The usage on an assistant message is a snapshot taken early in the response:
22
+ input and cache counts are final, output tokens are not, and calls Claude
23
+ Code makes for itself do not appear at all. Each ResultMessage carries the
24
+ true totals per model (``model_usage``, cumulative over a client session);
25
+ the difference is added to the current step there. Budget checks during the
26
+ run therefore see input in full and output late.
27
+
28
+ In enforce mode a stop denies the pending tool call and ends the agent's turn
29
+ (``continue: false``); guarded_query then raises Stopped. A stop decided after
30
+ a tool result (a 401, say) takes effect at the agent's next tool call: Claude
31
+ Code lets the model answer once more before the hooks can end the turn. Warnings reach the
32
+ model as additional context on the next hook. In shadow mode the hooks only
33
+ record and always return an empty answer.
34
+
35
+ ``claude-agent-sdk`` is imported only when the hooks are built, so this module
36
+ loads without it.
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ import dataclasses
42
+ import warnings
43
+ from typing import Any, AsyncIterator, Awaitable, Callable
44
+
45
+ from .errors import status_from_text
46
+ from .run import Run, Stopped, ToolFailed
47
+
48
+ HookOutput = dict[str, Any]
49
+ Callback = Callable[[dict[str, Any], "str | None", Any], Awaitable[HookOutput]]
50
+
51
+ _USAGE_FIELDS = ("input_tokens", "output_tokens", "cache_read_input_tokens", "cache_creation_input_tokens")
52
+
53
+
54
+ class StopLossHooks:
55
+ """Hooks and message tracking for one run.
56
+
57
+ For ``query()`` use guarded_query. With ``ClaudeSDKClient``, or to keep
58
+ your own control of the loop:
59
+
60
+ async with guard.run(agent="report") as run:
61
+ sl = StopLossHooks(run)
62
+ async with ClaudeSDKClient(options=sl.options(options)) as client:
63
+ await client.query("...")
64
+ async for message in client.receive_response():
65
+ sl.observe(message)
66
+ sl.finish()
67
+ """
68
+
69
+ def __init__(self, run: Run):
70
+ self.run = run
71
+ self.stopped: Stopped | None = None
72
+ self._usage: dict[str, dict[str, int]] = {} # message id -> usage recorded so far
73
+ self._tool_ids: set[str] = set() # tool_use ids of recorded messages
74
+ self._hook_step = False # a hook opened the step before its message arrived
75
+ self._since_result: dict[str, dict[str, int]] = {} # model -> usage recorded since the last result
76
+ self._session_totals: dict[str, dict[str, int]] = {} # model -> model_usage at the last result
77
+
78
+ # -- wiring -----------------------------------------------------------
79
+
80
+ def callbacks(self) -> dict[str, Callback]:
81
+ """The hook callbacks by event name, without the SDK's wrappers."""
82
+ return {"PreToolUse": self._pre_tool, "PostToolUse": self._post_tool,
83
+ "PostToolUseFailure": self._tool_failed}
84
+
85
+ def hooks(self) -> dict[str, list[Any]]:
86
+ """``ClaudeAgentOptions.hooks`` for every tool."""
87
+ from claude_agent_sdk import HookMatcher
88
+
89
+ return {event: [HookMatcher(matcher=None, hooks=[cb])] for event, cb in self.callbacks().items()}
90
+
91
+ def options(self, options: Any = None) -> Any:
92
+ """A copy of ``options`` with these hooks added ahead of any already set."""
93
+ from claude_agent_sdk import ClaudeAgentOptions
94
+
95
+ options = options if options is not None else ClaudeAgentOptions()
96
+ merged: dict[str, list[Any]] = {event: list(matchers) for event, matchers in (options.hooks or {}).items()}
97
+ for event, matchers in self.hooks().items():
98
+ merged[event] = matchers + merged.get(event, [])
99
+ return dataclasses.replace(options, hooks=merged)
100
+
101
+ # -- messages ---------------------------------------------------------
102
+
103
+ def observe(self, message: Any) -> None:
104
+ """Pass every message the SDK yields. Records model usage; in enforce
105
+ mode raises Stopped when the spend crosses a limit."""
106
+ kind = type(message).__name__
107
+ if kind == "ResultMessage":
108
+ self._reconcile(message)
109
+ return
110
+ if kind != "AssistantMessage":
111
+ return
112
+ for block in getattr(message, "content", None) or ():
113
+ if type(block).__name__ == "ToolUseBlock":
114
+ self._tool_ids.add(block.id)
115
+ usage = _usage_of(getattr(message, "usage", None))
116
+ if usage is None:
117
+ return
118
+ key = getattr(message, "message_id", None) or f"obj-{id(message)}"
119
+ model = getattr(message, "model", None)
120
+ before = self._usage.get(key)
121
+ try:
122
+ if before is None:
123
+ # The first part of a response: a model call, in the step a
124
+ # hook may already have opened for its tool calls.
125
+ self._usage[key] = usage
126
+ self._record(usage, model, same_step=False)
127
+ self._hook_step = False
128
+ else:
129
+ # A later part of the same response: only what it adds.
130
+ delta = {k: max(0, usage[k] - before[k]) for k in _USAGE_FIELDS}
131
+ self._usage[key] = {k: max(usage[k], before[k]) for k in _USAGE_FIELDS}
132
+ if any(delta.values()):
133
+ self._record(delta, model, same_step=True)
134
+ except Stopped as stop:
135
+ self.stopped = stop
136
+ raise
137
+
138
+ def finish(self) -> None:
139
+ """Call after the last message. Raises Stopped if this run was stopped."""
140
+ if self.stopped is not None and self.run.enforce:
141
+ self.stopped.summary = self.run.summary() # with the result's totals added
142
+ raise self.stopped
143
+
144
+ def _reconcile(self, result: Any) -> None:
145
+ """Add what the result's totals hold beyond what the messages showed."""
146
+ totals = _model_usage_of(getattr(result, "model_usage", None))
147
+ if totals is not None:
148
+ # Cumulative over the session: this query is the growth since the last result.
149
+ query = {m: {k: u[k] - self._session_totals.get(m, {}).get(k, 0) for k in _USAGE_FIELDS}
150
+ for m, u in totals.items()}
151
+ self._session_totals = totals
152
+ else:
153
+ usage = _usage_of(getattr(result, "usage", None)) # per query
154
+ model = next(reversed(self._since_result), None) if self._since_result else None
155
+ query = {model: usage} if usage is not None else {}
156
+ since, self._since_result = self._since_result, {}
157
+ for model, usage in query.items():
158
+ seen = _match(since, model)
159
+ delta = {k: max(0, usage[k] - seen.get(k, 0)) for k in _USAGE_FIELDS}
160
+ if any(delta.values()):
161
+ self._record(delta, model, same_step=True)
162
+ self._since_result = {} # the next query starts from zero
163
+
164
+ def _record(self, usage: dict[str, int], model: str | None, same_step: bool) -> None:
165
+ bucket = self._since_result.setdefault(model, dict.fromkeys(_USAGE_FIELDS, 0))
166
+ for k in _USAGE_FIELDS:
167
+ bucket[k] += usage[k]
168
+ self.run.record_model_call(usage["input_tokens"], usage["output_tokens"], model=model,
169
+ cache_read_tokens=usage["cache_read_input_tokens"],
170
+ cache_write_tokens=usage["cache_creation_input_tokens"],
171
+ same_step=same_step or self._hook_step)
172
+
173
+ # -- hooks ------------------------------------------------------------
174
+
175
+ async def _pre_tool(self, data: dict[str, Any], tool_use_id: str | None, context: Any) -> HookOutput:
176
+ def check() -> None:
177
+ tid = tool_use_id or data.get("tool_use_id")
178
+ if tid not in self._tool_ids and not self._hook_step:
179
+ # The hook ran before the message that asked for this call
180
+ # was observed: open its step now, so the call is counted in it.
181
+ self.run.before_model_call()
182
+ self._hook_step = True
183
+ self.run.before_tool(data.get("tool_name", "?"), data.get("tool_input"))
184
+
185
+ return self._answer("PreToolUse", check)
186
+
187
+ async def _post_tool(self, data: dict[str, Any], tool_use_id: str | None, context: Any) -> HookOutput:
188
+ def check() -> None:
189
+ tool, args = data.get("tool_name", "?"), data.get("tool_input")
190
+ response = data.get("tool_response")
191
+ latency = data.get("duration_ms")
192
+ failure = _error_result(response)
193
+ if failure is not None:
194
+ self.run.after_tool(tool, args, error=ToolFailed(failure, status_from_text(failure)),
195
+ latency_ms=latency)
196
+ else:
197
+ self.run.after_tool(tool, args, result=response, latency_ms=latency)
198
+
199
+ return self._answer("PostToolUse", check)
200
+
201
+ async def _tool_failed(self, data: dict[str, Any], tool_use_id: str | None, context: Any) -> HookOutput:
202
+ def check() -> None:
203
+ if data.get("is_interrupt"):
204
+ return # cancelled by the user, not a failure of the tool
205
+ error = str(data.get("error") or "tool failed")
206
+ self.run.after_tool(data.get("tool_name", "?"), data.get("tool_input"),
207
+ error=ToolFailed(error, status_from_text(error)),
208
+ latency_ms=data.get("duration_ms"))
209
+
210
+ return self._answer("PostToolUseFailure", check)
211
+
212
+ def _answer(self, event: str, check: Callable[[], None]) -> HookOutput:
213
+ try:
214
+ check()
215
+ except Stopped as stop:
216
+ self.stopped = stop
217
+ return _halt(event, stop)
218
+ except Exception as exc: # a fault here must not break the agent
219
+ warnings.warn(f"agent-stoploss: {event} hook failed, call not checked: {exc!r}",
220
+ RuntimeWarning, stacklevel=2)
221
+ return {}
222
+ texts = self.run.notice_texts()
223
+ if not texts:
224
+ return {}
225
+ return {"hookSpecificOutput": {"hookEventName": event, "additionalContext": "\n\n".join(texts)}}
226
+
227
+
228
+ async def guarded_query(guard: Any, *, prompt: Any, options: Any = None, agent: str | None = None,
229
+ run_id: str | None = None, metadata: dict[str, Any] | None = None,
230
+ query: Callable[..., AsyncIterator[Any]] | None = None) -> AsyncIterator[Any]:
231
+ """``claude_agent_sdk.query`` as one run of ``guard``: yields the same
232
+ messages; in enforce mode raises Stopped once the agent has been halted.
233
+ ``query`` replaces the SDK function, for tests."""
234
+ if query is None:
235
+ from claude_agent_sdk import query
236
+
237
+ async with guard.run(agent=agent, run_id=run_id, metadata=metadata) as run:
238
+ sl = StopLossHooks(run)
239
+ stream = query(prompt=prompt, options=sl.options(options))
240
+ try:
241
+ async for message in stream:
242
+ sl.observe(message)
243
+ yield message
244
+ except GeneratorExit:
245
+ # The caller stopped reading: neither a success nor a failure.
246
+ run.end("interrupted")
247
+ raise
248
+ finally:
249
+ close = getattr(stream, "aclose", None)
250
+ if close is not None:
251
+ await close()
252
+ sl.finish()
253
+
254
+
255
+ def _usage_of(usage: Any) -> dict[str, int] | None:
256
+ if not isinstance(usage, dict):
257
+ return None
258
+ out = {k: int(usage.get(k) or 0) for k in _USAGE_FIELDS}
259
+ return out if any(out.values()) else None
260
+
261
+
262
+ _MODEL_USAGE_FIELDS = {"input_tokens": "inputTokens", "output_tokens": "outputTokens",
263
+ "cache_read_input_tokens": "cacheReadInputTokens",
264
+ "cache_creation_input_tokens": "cacheCreationInputTokens"}
265
+
266
+
267
+ def _match(recorded: dict[str, dict[str, int]], model: str | None) -> dict[str, int]:
268
+ """What was recorded for ``model``, also when one name is the other plus a
269
+ date or provider suffix (``claude-haiku-5-5`` and ``claude-haiku-5-5-20261001``)."""
270
+ if model in recorded:
271
+ return recorded[model]
272
+ for name, usage in recorded.items():
273
+ if name and model and (name.startswith(model) or model.startswith(name)):
274
+ return usage
275
+ return {}
276
+
277
+
278
+ def _model_usage_of(model_usage: Any) -> dict[str, dict[str, int]] | None:
279
+ if not isinstance(model_usage, dict) or not model_usage:
280
+ return None
281
+ return {model: {k: int((u or {}).get(src) or 0) for k, src in _MODEL_USAGE_FIELDS.items()}
282
+ for model, u in model_usage.items() if isinstance(u, dict)}
283
+
284
+
285
+ def _error_result(response: Any) -> str | None:
286
+ """The error text of a tool result flagged as an error (MCP tools report
287
+ failures as results with is_error / isError), else None."""
288
+ if not isinstance(response, dict) or not (response.get("is_error") or response.get("isError")):
289
+ return None
290
+ content = response.get("content")
291
+ if isinstance(content, list):
292
+ text = " ".join(str(c.get("text", "")) for c in content if isinstance(c, dict)).strip()
293
+ else:
294
+ text = str(content or "").strip()
295
+ return text or "tool returned an error"
296
+
297
+
298
+ def _halt(event: str, stop: Stopped) -> HookOutput:
299
+ reason = f"agent-stoploss stopped this run: {stop.reason}"
300
+ out: HookOutput = {"continue_": False, "stopReason": reason, "systemMessage": reason}
301
+ if event == "PreToolUse":
302
+ out["hookSpecificOutput"] = {"hookEventName": "PreToolUse", "permissionDecision": "deny",
303
+ "permissionDecisionReason": reason}
304
+ return out
agent_stoploss/cli.py ADDED
@@ -0,0 +1,138 @@
1
+ """agent-stoploss command line.
2
+
3
+ agent-stoploss replay LOGS... [--config stoploss.yaml] [--json]
4
+ agent-stoploss dashboard LOGS... [--config stoploss.yaml] [--port 8740]
5
+ agent-stoploss check-config stoploss.yaml
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ from . import __version__
16
+ from .config import Config, ConfigError
17
+ from .replay import Report, replay, suggest_max_tokens
18
+
19
+ NAMES = {
20
+ "run_budget": "run budget",
21
+ "loop_call": "same call repeated",
22
+ "loop_result": "same result repeated",
23
+ "circuit_breaker": "tool keeps failing",
24
+ "terminal_error": "error retrying cannot fix",
25
+ "pricing": "unpriced model (strict_pricing)",
26
+ }
27
+
28
+
29
+ def _load_config(path: str | None) -> Config:
30
+ if path:
31
+ return Config.from_file(path)
32
+ default = Path("stoploss.yaml")
33
+ return Config.from_file(default) if default.exists() else Config.from_dict({})
34
+
35
+
36
+ def _money(x: float) -> str:
37
+ return f"${x:,.2f}" if x >= 0.01 or x == 0 else f"${x:,.4f}"
38
+
39
+
40
+ def format_report(report: Report, limit: int = 20) -> str:
41
+ t = report.totals()
42
+ lines = []
43
+ w = lines.append
44
+ w(f"agent-stoploss replay (config {report.config_hash})")
45
+ w("")
46
+ w(f"Runs {t['runs']:>8} "
47
+ f"({t['labelled']} labelled by the developer, the rest by heuristic)")
48
+ w(f"Recorded spend {t['tokens']:>8,} tokens {_money(t['cost_usd'])}")
49
+ w(f"Would have stopped {t['would_stop']:>8}")
50
+ for mech, n in t["by_mechanism"].items():
51
+ w(f" {NAMES.get(mech, mech):<24}{n:>6}")
52
+ w(f"Would have saved {t['saved_tokens']:>8,} tokens {_money(t['saved_cost_usd'])}")
53
+ if t["excess_tokens_not_ok"]:
54
+ share = 100 * t["saved_in_excess_tokens"] / t["excess_tokens_not_ok"]
55
+ w(f" of the excess in runs not ok: {share:.0f}%")
56
+ w("")
57
+
58
+ broke = report.broke
59
+ missed = sorted(report.missed, key=lambda r: -r.excess)
60
+ width = max([len(r.run_id) for r in broke[:limit] + missed[:limit]] + [10])
61
+ w(f"Runs labelled ok that would have been stopped: {len(broke)}")
62
+ for r in broke[:limit]:
63
+ w(f" {r.run_id:<{width}} step {r.stop_step:<4} {NAMES.get(r.mechanism, r.mechanism)}: {r.reason}")
64
+ if len(broke) > limit:
65
+ w(f" ... and {len(broke) - limit} more (use --json)")
66
+ w("")
67
+
68
+ w(f"Runs not ok, above the minimum, not stopped by anything: {len(missed)}")
69
+ for r in missed[:limit]:
70
+ w(f" {r.run_id:<{width}} {r.tokens:>9,} tokens, {r.excess:>9,} above the minimum [{r.outcome}]")
71
+ if len(missed) > limit:
72
+ w(f" ... and {len(missed) - limit} more (use --json)")
73
+
74
+ suggestion = suggest_max_tokens(report)
75
+ if suggestion:
76
+ w("")
77
+ w(f"Suggested run_budget.max_tokens: {suggestion:,} "
78
+ "(1.5 x the most expensive run labelled ok)")
79
+ return "\n".join(lines)
80
+
81
+
82
+ def main(argv: list[str] | None = None) -> int:
83
+ parser = argparse.ArgumentParser(prog="agent-stoploss",
84
+ description="Stop AI agents from burning tokens on broken tools.")
85
+ parser.add_argument("--version", action="version", version=f"agent-stoploss {__version__}")
86
+ sub = parser.add_subparsers(dest="command", required=True)
87
+
88
+ p = sub.add_parser("replay", help="what a config would have done to recorded runs")
89
+ p.add_argument("logs", nargs="+", help="journal files or directories")
90
+ p.add_argument("--config", help="config file (default: ./stoploss.yaml if present)")
91
+ p.add_argument("--json", action="store_true", help="full result as JSON")
92
+ p.add_argument("--limit", type=int, default=20, help="rows per list in the text report")
93
+
94
+ d = sub.add_parser("dashboard", help="local page to explore runs and tune thresholds")
95
+ d.add_argument("logs", nargs="+", help="journal files or directories")
96
+ d.add_argument("--config", help="config to start from (default: ./stoploss.yaml if present)")
97
+ d.add_argument("--port", type=int, default=8740)
98
+ d.add_argument("--no-browser", action="store_true", help="do not open a browser")
99
+
100
+ c = sub.add_parser("check-config", help="validate a config file")
101
+ c.add_argument("path")
102
+
103
+ args = parser.parse_args(argv)
104
+ try:
105
+ if args.command == "check-config":
106
+ cfg = Config.from_file(args.path)
107
+ print(f"{args.path}: OK (mode {cfg.mode}, config {cfg.hash})")
108
+ if cfg.mode == "enforce" and cfg.max_tokens is None and cfg.max_cost_usd is None:
109
+ print("note: enforce mode with no run budget; only the mechanisms can stop a run")
110
+ return 0
111
+
112
+ cfg = _load_config(args.config)
113
+ if args.command == "dashboard":
114
+ from .dashboard import serve
115
+
116
+ path = args.config or ("stoploss.yaml" if Path("stoploss.yaml").exists() else None)
117
+ serve(args.logs, cfg, path, port=args.port, open_browser=not args.no_browser)
118
+ return 0
119
+ report = replay(args.logs, cfg)
120
+ if args.json:
121
+ json.dump(report.to_dict(), sys.stdout, indent=2, default=str)
122
+ print()
123
+ else:
124
+ print(format_report(report, args.limit))
125
+ return 0
126
+ except ConfigError as e:
127
+ print(str(e), file=sys.stderr)
128
+ return 2
129
+ except FileNotFoundError as e:
130
+ print(f"not found: {e}", file=sys.stderr)
131
+ return 2
132
+ except OSError as e:
133
+ print(f"agent-stoploss: {e}", file=sys.stderr)
134
+ return 1
135
+
136
+
137
+ if __name__ == "__main__":
138
+ sys.exit(main())