agentcost 0.3.2__tar.gz → 0.4.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.
Files changed (65) hide show
  1. {agentcost-0.3.2 → agentcost-0.4.0}/CHANGELOG.md +39 -0
  2. {agentcost-0.3.2 → agentcost-0.4.0}/PKG-INFO +1 -1
  3. agentcost-0.4.0/VERSION +1 -0
  4. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/__init__.py +4 -0
  5. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/agents/gate.py +152 -40
  6. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/agents/sync.py +90 -1
  7. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/anthropic_interceptor.py +5 -0
  8. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/gemini_interceptor.py +5 -0
  9. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/interceptor.py +5 -0
  10. agentcost-0.4.0/agentcost/limits.py +621 -0
  11. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/openai_interceptor.py +3 -0
  12. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/tracker.py +49 -0
  13. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost.egg-info/PKG-INFO +1 -1
  14. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost.egg-info/SOURCES.txt +3 -0
  15. agentcost-0.4.0/examples/gateway_quickstart.py +43 -0
  16. {agentcost-0.3.2 → agentcost-0.4.0}/tests/test_gate.py +121 -2
  17. agentcost-0.4.0/tests/test_limits.py +345 -0
  18. agentcost-0.3.2/VERSION +0 -1
  19. {agentcost-0.3.2 → agentcost-0.4.0}/.env.example +0 -0
  20. {agentcost-0.3.2 → agentcost-0.4.0}/.gitattributes +0 -0
  21. {agentcost-0.3.2 → agentcost-0.4.0}/.gitignore +0 -0
  22. {agentcost-0.3.2 → agentcost-0.4.0}/CONTRIBUTING.md +0 -0
  23. {agentcost-0.3.2 → agentcost-0.4.0}/LICENSE +0 -0
  24. {agentcost-0.3.2 → agentcost-0.4.0}/MANIFEST.in +0 -0
  25. {agentcost-0.3.2 → agentcost-0.4.0}/README.md +0 -0
  26. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/_reentrancy.py +0 -0
  27. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/agents/__init__.py +0 -0
  28. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/agents/_common.py +0 -0
  29. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/agents/antigravity.py +0 -0
  30. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/agents/claude_code.py +0 -0
  31. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/agents/codex.py +0 -0
  32. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/agents/hooks.py +0 -0
  33. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/agents/sync_hook.py +0 -0
  34. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/analyzer.py +0 -0
  35. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/batcher.py +0 -0
  36. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/capabilities.py +0 -0
  37. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/cli.py +0 -0
  38. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/config.py +0 -0
  39. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/cost_calculator.py +0 -0
  40. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/http_client.py +0 -0
  41. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/token_counter.py +0 -0
  42. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost/trace.py +0 -0
  43. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost.egg-info/dependency_links.txt +0 -0
  44. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost.egg-info/entry_points.txt +0 -0
  45. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost.egg-info/requires.txt +0 -0
  46. {agentcost-0.3.2 → agentcost-0.4.0}/agentcost.egg-info/top_level.txt +0 -0
  47. {agentcost-0.3.2 → agentcost-0.4.0}/demo_sdk.py +0 -0
  48. {agentcost-0.3.2 → agentcost-0.4.0}/e2e_workflows.py +0 -0
  49. {agentcost-0.3.2 → agentcost-0.4.0}/pyproject.toml +0 -0
  50. {agentcost-0.3.2 → agentcost-0.4.0}/requirements.txt +0 -0
  51. {agentcost-0.3.2 → agentcost-0.4.0}/setup.cfg +0 -0
  52. {agentcost-0.3.2 → agentcost-0.4.0}/setup.py +0 -0
  53. {agentcost-0.3.2 → agentcost-0.4.0}/test_e2e.py +0 -0
  54. {agentcost-0.3.2 → agentcost-0.4.0}/tests/__init__.py +0 -0
  55. {agentcost-0.3.2 → agentcost-0.4.0}/tests/test_agent_accuracy.py +0 -0
  56. {agentcost-0.3.2 → agentcost-0.4.0}/tests/test_agents.py +0 -0
  57. {agentcost-0.3.2 → agentcost-0.4.0}/tests/test_analyzer.py +0 -0
  58. {agentcost-0.3.2 → agentcost-0.4.0}/tests/test_antigravity.py +0 -0
  59. {agentcost-0.3.2 → agentcost-0.4.0}/tests/test_external_trace.py +0 -0
  60. {agentcost-0.3.2 → agentcost-0.4.0}/tests/test_gateway_compat.py +0 -0
  61. {agentcost-0.3.2 → agentcost-0.4.0}/tests/test_interceptor_enrichment.py +0 -0
  62. {agentcost-0.3.2 → agentcost-0.4.0}/tests/test_sdk.py +0 -0
  63. {agentcost-0.3.2 → agentcost-0.4.0}/tests/test_session_names.py +0 -0
  64. {agentcost-0.3.2 → agentcost-0.4.0}/tests/test_trace.py +0 -0
  65. {agentcost-0.3.2 → agentcost-0.4.0}/tests/test_trace_interceptors.py +0 -0
@@ -7,6 +7,45 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.4.0] - 2026-11-30
11
+
12
+ ### Added
13
+ - **Runtime limits.** The project's guardrails and budget are applied before
14
+ each call, in this process, from a policy held in memory and refreshed every
15
+ minute (`agentcost/limits.py`). Each guardrail's mode decides what a breaking
16
+ call does: `observe` (runs, recorded), `warn` (runs, one warning per agent
17
+ and rule), `block` (raises `agentcost.LimitReached` before anything is
18
+ sent), or `downgrade` (sent to the guardrail's fallback model). Applies to
19
+ OpenAI, Anthropic and Gemini calls, sync, async and streamed. LangChain
20
+ calls can be stopped but not switched; a switch there becomes a warning.
21
+ - Checked before each call: a paused agent (always refused), the allowed
22
+ models, the budget hard cap (refused, or switched to the budget's fallback
23
+ model), and the per-run cost limit, from the run's recorded spend plus an
24
+ estimate for this call.
25
+ - Checked in `track_costs.tool(...)`, before the tool runs: allowed tools,
26
+ read-only (write-tagged tools) and tool calls per run. A tool has no cheaper
27
+ model, so `downgrade` stops it.
28
+ - Every decision travels in the call's event as `metadata.limit_decision`; a
29
+ refused call or a tool decision is sent as a record of its own, which the
30
+ server stores as a decision, never as usage.
31
+ - The tools a request offers the model are reported by name, once per new
32
+ set, so a guardrail can cover a tool before it first runs.
33
+ - The policy is fetched with `If-None-Match`, by the SDK and by
34
+ `agentcost sync`; an unchanged policy costs a 304 with no body.
35
+ - `init(limits=False)` turns it off. It is off in `local_mode`. Existing
36
+ guardrails start in `observe`, so upgrading changes no call until a mode is
37
+ chosen in the dashboard. With no current policy (never fetched, or older
38
+ than a day) calls are allowed, unless the project fails closed.
39
+ - Coding-agent gate: follows each guardrail's mode. `block` and `downgrade`
40
+ refuse (a coding agent's model cannot be switched from outside), `warn`
41
+ lets the call run and shows the reason in Claude Code, `observe` lets it
42
+ run. A policy without modes, from an older server, still refuses every
43
+ breach. An agent paused in the dashboard has its prompts and tools refused.
44
+ - Coding-agent gate: every decision is kept locally and sent with the next
45
+ `agentcost sync`, so the dashboard shows what was stopped on each machine.
46
+ Refusals are kept every time; observations and warnings once per session,
47
+ rule and action. A failed send is retried without being counted twice.
48
+
10
49
  ## [0.3.2] - 2026-11-30
11
50
 
12
51
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: agentcost
3
- Version: 0.3.2
3
+ Version: 0.4.0
4
4
  Summary: Track LLM costs across OpenAI, Anthropic, Gemini, LangChain, and 3500+ models with zero code changes
5
5
  Home-page: https://agentcost.tech
6
6
  Author: Kushagra Agrawal
@@ -0,0 +1 @@
1
+ 0.4.0
@@ -90,6 +90,9 @@ from .tracker import (
90
90
  # Trace helpers for reading the active context (advanced usage)
91
91
  from .trace import current_trace_id, current_trace_fields
92
92
 
93
+ # Runtime limits: raised instead of a call or tool the project refuses.
94
+ from .limits import LimitReached
95
+
93
96
  # Expose configuration
94
97
  from .config import AgentCostConfig, DEFAULT_PRICING
95
98
 
@@ -127,6 +130,7 @@ except Exception:
127
130
  GeminiInterceptor = None # type: ignore
128
131
 
129
132
  __all__ = [
133
+ "LimitReached",
130
134
  # Version
131
135
  "__version__",
132
136
 
@@ -78,40 +78,31 @@ def _run_totals(source: Any, sync: Any, hook: Dict[str, Any], priced: bool) -> D
78
78
  return totals
79
79
 
80
80
 
81
- def decide(source_name: str, hook: Dict[str, Any]) -> Optional[str]:
82
- """Why this tool call or prompt is refused, or None to let it through."""
83
- from agentcost.agents import SOURCES, sync
81
+ # What each rule's mode means here. A coding agent's model cannot be switched
82
+ # from outside, so "downgrade" stops the call, as it does for an SDK tool.
83
+ _ACTION = {"observe": "observed", "warn": "warned", "block": "blocked", "downgrade": "blocked"}
84
84
 
85
- policy = sync.read_json(sync.home() / "policy.json")
86
- source = SOURCES.get(source_name)
87
- if not policy or source is None:
88
- return None
89
85
 
86
+ def _rail_breach(
87
+ source: Any, sync: Any, hook: Dict[str, Any], policy: Dict[str, Any],
88
+ rail: Dict[str, Any], agent: str, source_name: str,
89
+ ) -> Optional[Dict[str, Any]]:
90
+ """The first guardrail this tool call or prompt breaks, or None."""
90
91
  event, tool = hook.get("hook_event_name"), hook.get("tool_name")
91
- rails = policy.get("guardrails") or {}
92
- subagent = hook.get("agent_type")
93
- agent = f"{source_name}/{subagent}" if subagent else source_name
94
- # A subagent without a boundary of its own answers to the agent's.
95
- rail = rails.get(agent) or rails.get(source_name) or {}
96
92
 
97
93
  if event == "PreToolUse" and tool and source.GATES_TOOLS:
98
94
  allowed = rail.get("allowed_tools")
99
95
  if allowed is not None and tool not in allowed:
100
- return f"{tool} is not among the tools this project allows {agent} to use."
96
+ return {"rule": "tool", "tool": tool,
97
+ "reason": f"{tool} is not among the tools this project allows {agent} to use."}
101
98
  if rail.get("read_only") and (policy.get("tool_tags") or {}).get(tool) == "write":
102
- return f"{agent} is read-only in this project, and {tool} writes."
99
+ return {"rule": "read_only", "tool": tool,
100
+ "reason": f"{agent} is read-only in this project, and {tool} writes."}
103
101
 
104
102
  max_calls = rail.get("max_tool_calls_per_run")
105
103
  max_cost = rail.get("max_cost_per_run_usd")
106
104
  models = rail.get("allowed_models")
107
- budget = policy.get("budget") or {}
108
- capped = (
109
- event == "UserPromptSubmit"
110
- and budget.get("exhausted")
111
- and budget.get("mode") == "hard_cap"
112
- and _in_period(budget)
113
- )
114
- if not (max_calls or max_cost or capped or models is not None):
105
+ if not (max_calls or max_cost or models is not None):
115
106
  return None
116
107
 
117
108
  run = _run_totals(source, sync, hook, priced=bool(max_cost))
@@ -120,33 +111,147 @@ def decide(source_name: str, hook: Dict[str, Any]) -> Optional[str]:
120
111
  # call used. A session's very first prompt has neither and is let through.
121
112
  model = hook.get("model") or run["model"]
122
113
  if models is not None and model and model not in models:
123
- return (
114
+ return {"rule": "model", "model": model, "reason": (
124
115
  f"{model} is not among the models this project allows {source_name} to use "
125
116
  f"({', '.join(models) or 'none'}). Switch model to continue."
126
- )
117
+ )}
127
118
 
128
119
  # The call being asked about is already in the log and so already counted:
129
120
  # the limit is passed only when the count goes over it.
130
121
  if max_calls and event == "PreToolUse" and run["tool_calls"] > max_calls:
131
- return (
122
+ return {"rule": "tool_calls", "tool": tool, "model": model, "reason": (
132
123
  f"this session has reached the limit of {max_calls} tool "
133
124
  f"call{'' if max_calls == 1 else 's'} this project allows {source_name} "
134
125
  f"in one run. Start a new session."
135
- )
126
+ )}
136
127
  if max_cost and run["cost"] > max_cost:
137
- return (
128
+ return {"rule": "run_cost", "model": model, "reason": (
138
129
  f"this session has used ${run['cost']:.2f}, over the ${max_cost:.2f} this "
139
130
  f"project allows {source_name} per run. Start a new session."
140
- )
141
- if capped:
142
- settings = (sync.load_config()["sources"].get(source_name)) or {}
143
- billing = settings.get("billing") or run["billing"] or source.detect_billing()
144
- # Only metered usage spends the budget. Unknown is not refused.
145
- if billing == "api":
146
- return (
147
- f"the project's monthly budget of {budget.get('budget')} "
148
- f"{budget.get('currency') or 'USD'} is spent."
149
- )
131
+ )}
132
+ return None
133
+
134
+
135
+ def _budget_breach(
136
+ source: Any, sync: Any, hook: Dict[str, Any], policy: Dict[str, Any], source_name: str,
137
+ ) -> Optional[Dict[str, Any]]:
138
+ """A spent hard-capped budget refuses new prompts of metered usage."""
139
+ budget = policy.get("budget") or {}
140
+ capped = (
141
+ hook.get("hook_event_name") == "UserPromptSubmit"
142
+ and budget.get("exhausted")
143
+ and budget.get("mode") == "hard_cap"
144
+ and _in_period(budget)
145
+ )
146
+ if not capped:
147
+ return None
148
+ settings = (sync.load_config()["sources"].get(source_name)) or {}
149
+ billing = (
150
+ settings.get("billing")
151
+ or _run_totals(source, sync, hook, priced=False)["billing"]
152
+ or source.detect_billing()
153
+ )
154
+ # Only metered usage spends the budget. Unknown is not refused.
155
+ if billing != "api":
156
+ return None
157
+ return {"rule": "budget", "reason": (
158
+ f"the project's monthly budget of {budget.get('budget')} "
159
+ f"{budget.get('currency') or 'USD'} is spent."
160
+ )}
161
+
162
+
163
+ def judge(source_name: str, hook: Dict[str, Any]) -> Optional[Dict[str, Any]]:
164
+ """What the project's limits say about this tool call or prompt.
165
+
166
+ None when nothing applies; otherwise the rule broken, the reason, the
167
+ agent, and the action its mode asks for: ``blocked`` refuses the call,
168
+ ``warned`` and ``observed`` let it run and are recorded.
169
+ """
170
+ from agentcost.agents import SOURCES, sync
171
+
172
+ policy = sync.read_json(sync.home() / "policy.json")
173
+ source = SOURCES.get(source_name)
174
+ if not policy or source is None:
175
+ return None
176
+
177
+ rails = policy.get("guardrails") or {}
178
+ subagent = hook.get("agent_type")
179
+ agent = f"{source_name}/{subagent}" if subagent else source_name
180
+ # A subagent without a boundary of its own answers to the agent's.
181
+ rail = rails.get(agent) or rails.get(source_name) or {}
182
+
183
+ paused = policy.get("paused_agents") or []
184
+ if agent in paused or source_name in paused:
185
+ return {"rule": "paused", "action": "blocked", "agent": agent, "reason":
186
+ f"{agent} is paused in AgentCost. Resume it in the dashboard to continue."}
187
+
188
+ breach = _rail_breach(source, sync, hook, policy, rail, agent, source_name)
189
+ # A policy from a server that predates modes enforced every rule.
190
+ action = _ACTION.get(rail.get("mode") or "block", "blocked")
191
+ if breach and action == "blocked":
192
+ return {**breach, "action": action, "agent": agent}
193
+
194
+ # The budget cap has no mode of its own: once it is spent, it stops.
195
+ budget = _budget_breach(source, sync, hook, policy, source_name)
196
+ if budget:
197
+ return {**budget, "action": "blocked", "agent": agent}
198
+ if breach:
199
+ return {**breach, "action": action, "agent": agent}
200
+ return None
201
+
202
+
203
+ def decide(source_name: str, hook: Dict[str, Any]) -> Optional[str]:
204
+ """Why this tool call or prompt is refused, or None to let it through."""
205
+ verdict = judge(source_name, hook)
206
+ return verdict["reason"] if verdict and verdict["action"] == "blocked" else None
207
+
208
+
209
+ def record(verdict: Dict[str, Any], hook: Dict[str, Any]) -> None:
210
+ """Keep the decision for the next sync, which sends it to the dashboard.
211
+
212
+ A refusal is kept every time. A rule that only observes or warns is kept
213
+ once per session, rule and action: it would otherwise be kept on every
214
+ tool call.
215
+ """
216
+ from agentcost.agents import sync
217
+
218
+ session = str(hook.get("session_id") or "")
219
+ name = "".join(ch for ch in session if ch.isalnum() or ch == "-") or "unknown"
220
+ if verdict["action"] != "blocked":
221
+ seen_path = sync.home() / "runs" / f"{name}.limits.json"
222
+ seen = sync.read_json(seen_path)
223
+ key = f"{verdict['agent']}:{verdict['rule']}:{verdict['action']}"
224
+ if seen.get(key):
225
+ return
226
+ sync.write_json(seen_path, {**seen, key: True})
227
+
228
+ tool = verdict.get("tool") or hook.get("tool_name")
229
+ line = {
230
+ "agent_name": verdict["agent"],
231
+ "rule": verdict["rule"],
232
+ "action": verdict["action"],
233
+ "detail": verdict["reason"],
234
+ "model": verdict.get("model") or hook.get("model"),
235
+ "tool_name": tool if hook.get("hook_event_name") == "PreToolUse" else None,
236
+ "session_id": session or None,
237
+ "timestamp": datetime.now(timezone.utc).isoformat(),
238
+ }
239
+ path = sync.home() / DECISIONS_FILE
240
+ path.parent.mkdir(parents=True, exist_ok=True)
241
+ with open(path, "a", encoding="utf-8") as handle:
242
+ handle.write(json.dumps(line) + "\n")
243
+
244
+
245
+ DECISIONS_FILE = "decisions.jsonl"
246
+
247
+
248
+ def answer(source_name: str, hook: Dict[str, Any], verdict: Dict[str, Any]) -> Optional[Dict[str, Any]]:
249
+ """What the hook prints for a verdict, or None to print nothing."""
250
+ if verdict["action"] == "blocked":
251
+ return refusal(hook, verdict["reason"])
252
+ if verdict["action"] == "warned" and source_name == "claude-code":
253
+ # Shown to the person, not the model; the call goes ahead.
254
+ return {"systemMessage": f"{PREFIX}{verdict['reason']} (Allowed: this rule only warns.)"}
150
255
  return None
151
256
 
152
257
 
@@ -172,9 +277,16 @@ def refusal(hook: Dict[str, Any], reason: str) -> Dict[str, Any]:
172
277
  def main(argv: Any) -> int:
173
278
  try:
174
279
  hook = json.loads(sys.stdin.buffer.read() or b"{}")
175
- reason = decide(argv[1], hook)
176
- if reason:
177
- sys.stdout.write(json.dumps(refusal(hook, reason)))
280
+ verdict = judge(argv[1], hook)
281
+ if not verdict:
282
+ return 0
283
+ reply = answer(argv[1], hook, verdict)
284
+ if reply:
285
+ sys.stdout.write(json.dumps(reply))
286
+ try:
287
+ record(verdict, hook)
288
+ except Exception: # noqa: BLE001 -- the answer matters, the record less
289
+ pass
178
290
  except Exception: # noqa: BLE001
179
291
  pass
180
292
  return 0
@@ -10,6 +10,7 @@ two sessions at the same moment neither loses a call nor counts one twice.
10
10
 
11
11
  from __future__ import annotations
12
12
 
13
+ import hashlib
13
14
  import json
14
15
  import os
15
16
  import time
@@ -210,12 +211,19 @@ def refresh_policy(config: Dict[str, Any], force: bool = False) -> Optional[Dict
210
211
 
211
212
  import requests
212
213
 
214
+ headers = {"Authorization": f"Bearer {config['api_key']}"}
215
+ if held.get("version") and not force:
216
+ headers["If-None-Match"] = f'"{held["version"]}"'
213
217
  try:
214
218
  response = requests.get(
215
219
  f"{config['base_url'].rstrip('/')}/v1/guardrails/policy",
216
- headers={"Authorization": f"Bearer {config['api_key']}"},
220
+ headers=headers,
217
221
  timeout=90 if force else 10,
218
222
  )
223
+ if response.status_code == 304 and held:
224
+ held["at"] = time.time()
225
+ write_json(path, held)
226
+ return held
219
227
  served = response.json() if response.ok else None
220
228
  except (requests.RequestException, ValueError):
221
229
  served = None
@@ -227,6 +235,9 @@ def refresh_policy(config: Dict[str, Any], force: bool = False) -> Optional[Dict
227
235
  "guardrails": {rail["agent_name"]: rail for rail in served.get("guardrails") or []},
228
236
  "tool_tags": served.get("tool_tags") or {},
229
237
  "budget": served.get("budget") or {},
238
+ # Pausing an agent in the dashboard refuses its next prompt or tool.
239
+ "paused_agents": served.get("paused_agents") or [],
240
+ "version": served.get("version") or "",
230
241
  }
231
242
  write_json(path, policy)
232
243
  return policy
@@ -384,6 +395,9 @@ def run_sync(
384
395
  state.setdefault("names", {}).update(remember)
385
396
  result["named"] = len(records)
386
397
 
398
+ if result["ok"]:
399
+ result["decisions"] = _send_decisions(send)
400
+
387
401
  state["last_sync"] = datetime.now(timezone.utc).isoformat()
388
402
  write_json(home() / "state.json", state)
389
403
 
@@ -397,6 +411,81 @@ def run_sync(
397
411
  return result
398
412
 
399
413
 
414
+ def _decision_record(line: Dict[str, Any], raw: str) -> Dict[str, Any]:
415
+ """A decision the gate kept, as the record the SDKs send for one: the
416
+ server stores it as a decision, never as usage."""
417
+ record: Dict[str, Any] = {
418
+ # From the line itself, so a retried send is recognised, not doubled.
419
+ "event_id": "gate-" + hashlib.sha256(raw.encode("utf-8")).hexdigest()[:32],
420
+ "agent_name": line.get("agent_name") or "unknown",
421
+ "model": line.get("model") or "none",
422
+ "input_tokens": 0,
423
+ "output_tokens": 0,
424
+ "total_tokens": 0,
425
+ "cost": 0.0,
426
+ "latency_ms": 0,
427
+ "timestamp": line.get("timestamp") or datetime.now(timezone.utc).isoformat(),
428
+ "success": line.get("action") != "blocked",
429
+ "metadata": {
430
+ "limit_decision": {
431
+ "rule": line.get("rule"),
432
+ "action": line.get("action"),
433
+ "detail": line.get("detail"),
434
+ "model": line.get("model"),
435
+ "tool_name": line.get("tool_name"),
436
+ "cost_avoided_usd": 0.0,
437
+ "standalone": True,
438
+ }
439
+ },
440
+ }
441
+ if line.get("tool_name"):
442
+ record["tool_name"] = line["tool_name"]
443
+ if line.get("session_id"):
444
+ record["metadata"]["session_id"] = line["session_id"]
445
+ return record
446
+
447
+
448
+ def _send_decisions(send: Sender) -> int:
449
+ """Send what the gate stopped, warned about or observed since the last sync.
450
+
451
+ The file is moved aside before reading, so a decision the gate writes
452
+ meanwhile waits for the next sync instead of being lost. Kept for a retry
453
+ if the send fails.
454
+ """
455
+ from .gate import DECISIONS_FILE
456
+
457
+ live = home() / DECISIONS_FILE
458
+ pending = home() / (DECISIONS_FILE + ".sending")
459
+ if not pending.exists():
460
+ if not live.exists():
461
+ return 0
462
+ try:
463
+ os.replace(live, pending)
464
+ except OSError:
465
+ return 0
466
+
467
+ records = []
468
+ try:
469
+ for raw in pending.read_text(encoding="utf-8").splitlines():
470
+ try:
471
+ line = json.loads(raw)
472
+ except ValueError:
473
+ continue
474
+ if isinstance(line, dict):
475
+ records.append(_decision_record(line, raw))
476
+ except OSError:
477
+ return 0
478
+
479
+ for index in range(0, len(records), MAX_SERVER_BATCH_SIZE):
480
+ if not send(records[index : index + MAX_SERVER_BATCH_SIZE]):
481
+ return 0
482
+ try:
483
+ pending.unlink()
484
+ except OSError:
485
+ pass
486
+ return len(records)
487
+
488
+
400
489
  def _http_sender(config: Dict[str, Any]) -> Sender:
401
490
  from ..http_client import AgentCostHTTPClient
402
491
 
@@ -26,6 +26,7 @@ from .cost_calculator import calculate_cost
26
26
  from .config import get_config
27
27
  from .capabilities import CAPABILITY_KEY, fingerprint
28
28
  from ._reentrancy import in_tracking, enter_tracking, exit_tracking
29
+ from . import limits as _limits
29
30
 
30
31
 
31
32
  def _hash_input(input_text: str) -> str:
@@ -348,6 +349,7 @@ class AnthropicInterceptor:
348
349
  model = kwargs.get("model", "unknown")
349
350
  agent_name = _get_effective_agent_name(config)
350
351
  input_text = _request_text(kwargs)
352
+ model = _limits.gate(agent_name, model, kwargs, input_text, token)
351
353
  input_hash = _hash_input(input_text)
352
354
  caps = fingerprint(kwargs)
353
355
 
@@ -403,6 +405,7 @@ class AnthropicInterceptor:
403
405
  model = kwargs.get("model", "unknown")
404
406
  agent_name = _get_effective_agent_name(config)
405
407
  input_text = _request_text(kwargs)
408
+ model = _limits.gate(agent_name, model, kwargs, input_text, None)
406
409
  input_hash = _hash_input(input_text)
407
410
  caps = fingerprint(kwargs)
408
411
 
@@ -436,6 +439,7 @@ class AnthropicInterceptor:
436
439
  model = kwargs.get("model", "unknown")
437
440
  agent_name = _get_effective_agent_name(config)
438
441
  input_text = _request_text(kwargs)
442
+ model = _limits.gate(agent_name, model, kwargs, input_text, token)
439
443
  input_hash = _hash_input(input_text)
440
444
  caps = fingerprint(kwargs)
441
445
 
@@ -492,6 +496,7 @@ class AnthropicInterceptor:
492
496
  model = kwargs.get("model", "unknown")
493
497
  agent_name = _get_effective_agent_name(config)
494
498
  input_text = _request_text(kwargs)
499
+ model = _limits.gate(agent_name, model, kwargs, input_text, None)
495
500
  input_hash = _hash_input(input_text)
496
501
  caps = fingerprint(kwargs)
497
502
 
@@ -17,6 +17,7 @@ from .config import get_config
17
17
  from .capabilities import CAPABILITY_KEY, fingerprint, merge_config
18
18
  from .cost_calculator import calculate_cost
19
19
  from ._reentrancy import in_tracking, enter_tracking, exit_tracking
20
+ from . import limits as _limits
20
21
 
21
22
 
22
23
  def _hash_contents(contents: Any) -> str:
@@ -253,6 +254,7 @@ class GeminiInterceptor:
253
254
  return original(client_self, *args, **kwargs)
254
255
  token = enter_tracking()
255
256
  model, agent, input_hash, started, caps = interceptor._call_context(kwargs)
257
+ model = _limits.gate(agent, model, kwargs, "", token)
256
258
  response, error = None, None
257
259
  try:
258
260
  response = original(client_self, *args, **kwargs)
@@ -277,6 +279,7 @@ class GeminiInterceptor:
277
279
  return await original(client_self, *args, **kwargs)
278
280
  token = enter_tracking()
279
281
  model, agent, input_hash, started, caps = interceptor._call_context(kwargs)
282
+ model = _limits.gate(agent, model, kwargs, "", token)
280
283
  response, error = None, None
281
284
  try:
282
285
  response = await original(client_self, *args, **kwargs)
@@ -301,6 +304,7 @@ class GeminiInterceptor:
301
304
  return original(client_self, *args, **kwargs)
302
305
  token = enter_tracking()
303
306
  model, agent, input_hash, started, caps = interceptor._call_context(kwargs)
307
+ model = _limits.gate(agent, model, kwargs, "", token)
304
308
  try:
305
309
  stream = original(client_self, *args, **kwargs)
306
310
  except Exception as exc:
@@ -330,6 +334,7 @@ class GeminiInterceptor:
330
334
  return await original(client_self, *args, **kwargs)
331
335
  token = enter_tracking()
332
336
  model, agent, input_hash, started, caps = interceptor._call_context(kwargs)
337
+ model = _limits.gate(agent, model, kwargs, "", token)
333
338
  try:
334
339
  stream = await original(client_self, *args, **kwargs)
335
340
  except Exception as exc:
@@ -22,6 +22,7 @@ from .config import get_config
22
22
  # or Anthropic SDK call, this depth counter prevents the lower-level
23
23
  # interceptor from emitting a duplicate event.
24
24
  from ._reentrancy import in_tracking, enter_tracking, exit_tracking
25
+ from . import limits as _limits
25
26
 
26
27
 
27
28
  def _get_effective_agent_name(config, explicit: Optional[str] = None) -> str:
@@ -259,6 +260,7 @@ class LangChainInterceptor:
259
260
 
260
261
  input_text = TokenCounter.extract_text_from_input(input_data)
261
262
  input_tokens = TokenCounter.count_tokens(input_text, model_name)
263
+ _limits.gate(agent_name, model_name, {}, input_text, depth_token, can_downgrade=False)
262
264
 
263
265
  error_message = None
264
266
  response = None
@@ -324,6 +326,7 @@ class LangChainInterceptor:
324
326
 
325
327
  input_text = TokenCounter.extract_text_from_input(input_data)
326
328
  input_tokens = TokenCounter.count_tokens(input_text, model_name)
329
+ _limits.gate(agent_name, model_name, {}, input_text, depth_token, can_downgrade=False)
327
330
 
328
331
  error_message = None
329
332
  response = None
@@ -382,6 +385,7 @@ class LangChainInterceptor:
382
385
 
383
386
  input_text = TokenCounter.extract_text_from_input(input_data)
384
387
  input_tokens = TokenCounter.count_tokens(input_text, model_name)
388
+ _limits.gate(agent_name, model_name, {}, input_text, None, can_downgrade=False)
385
389
 
386
390
  accumulated_content = ""
387
391
  reported_input = 0
@@ -472,6 +476,7 @@ class LangChainInterceptor:
472
476
  # Count input tokens
473
477
  input_text = TokenCounter.extract_text_from_input(input_data)
474
478
  input_tokens = TokenCounter.count_tokens(input_text, model_name)
479
+ _limits.gate(agent_name, model_name, {}, input_text, None, can_downgrade=False)
475
480
 
476
481
  # Accumulate streamed content
477
482
  accumulated_content = ""