diff options
| author | Mohamed Hegazy <8000722+mhegazy@users.noreply.github.com> | 2026-10-15 15:41:17 -0700 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-10-15 15:41:17 -0700 |
| commit | 4db747859e151db177af7ed7cd8b5a20c5995ca2 (patch) | |
| tree | 0bb5096a412783bc3aadae2d18fcc3d08c1cf107 /plugins/security-guidance/hooks | |
| parent | f698d8bca315d40f1771a3a12746bd793f842f07 (diff) | |
| parent | 48805c9f91eb029cb49286cad82dde3381ef7e3c (diff) | |
Merge pull request #6589 from anthropics/mhegazy/sg-review-cost-log
security-guidance: log each review's token use and estimated cost
Diffstat (limited to 'plugins/security-guidance/hooks')
| -rw-r--r-- | plugins/security-guidance/hooks/_base.py | 42 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 5 |
2 files changed, 47 insertions, 0 deletions
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py index f05a0094..1daa6642 100644 --- a/plugins/security-guidance/hooks/_base.py +++ b/plugins/security-guidance/hooks/_base.py @@ -7,6 +7,7 @@ circular import). It must stay free of any other intra-plugin imports. """ import json import os +import re import threading from datetime import datetime @@ -168,6 +169,10 @@ _USAGE = { # reported it manually. "http_err_last": 0, # most recent HTTP error code this invocation "http_err_count": 0, # total HTTP errors (4xx + 5xx + network) + # For the usage log line only: model ids as recorded (the requested alias + # on the Agent SDK path), and whether any call had no price-table entry. + "models": [], + "default_priced": False, } _USAGE_LOCK = threading.Lock() @@ -204,12 +209,15 @@ def _record_usage(usage, model, cost_usd=None): cw = int(u.get("cache_creation_input_tokens") or 0) except (TypeError, ValueError): return + default_priced = False if cost_usd is None: pin, pout = _PRICE_DEFAULT + default_priced = True m = (model or "").lower() for k, v in sorted(_PRICE_PER_MTOK.items(), key=lambda kv: -len(kv[0])): if m.startswith(k): pin, pout = v + default_priced = False break cost_usd = (i * pin + o * pout + cr * pin * 0.1 + cw * pin * 1.25) / 1_000_000 with _USAGE_LOCK: @@ -219,6 +227,10 @@ def _record_usage(usage, model, cost_usd=None): _USAGE["cw"] += cw _USAGE["cost"] += float(cost_usd or 0.0) _USAGE["n"] += 1 + _USAGE["default_priced"] = _USAGE["default_priced"] or default_priced + name = re.sub(r"[^A-Za-z0-9_.:/@-]", "_", str(model or ""))[:80] + if name and name not in _USAGE["models"]: + _USAGE["models"].append(name) def _record_http_error(status): @@ -245,6 +257,36 @@ def _record_http_error(status): _USAGE["http_err_count"] += 1 +# Set by main() and the review handlers: which review this invocation runs +# and for which Claude Code session, so the usage log line can be attributed. +_USAGE_CONTEXT = {"session_id": "", "review": "stop"} + + +def _log_usage(usage): + """Write this invocation's review usage to the debug log. + + `usage` is a `_usage_metrics()` snapshot, the same numbers that go out + with the hook's metrics. The raw-HTTP review leaves no Claude Code + transcript and no OpenTelemetry event; without this line nothing on the + machine records what it used. `est_cost_usd` is that same rollup: list + prices (the inner CLI's own figure on the Agent SDK path), `~` appended + when a model had no price-table entry and the default rate was used. + """ + if not usage.get("api_calls"): + return + with _USAGE_LOCK: + models = ",".join(_USAGE["models"]) or "-" + approx = "~" if _USAGE["default_priced"] else "" + debug_log( + f"Review usage: review={_USAGE_CONTEXT.get('review') or '-'} " + f"session={_USAGE_CONTEXT.get('session_id') or '-'} " + f"model={models} calls={usage['api_calls']} " + f"in={usage['tok_in']} out={usage['tok_out']} " + f"cache_read={usage['tok_cache_r']} cache_write={usage['tok_cache_w']} " + f"est_cost_usd={usage['cost_usd']:.4f}{approx}" + ) + + def _usage_metrics(): """Snapshot the accumulator as metric keys. Returns {} when no API calls AND no HTTP errors were made so skip-path emits don't burn key budget. diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 1da44e48..87cfb86a 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -83,6 +83,7 @@ from _base import ( # noqa: E402,F401 PROVENANCE_TAG, PROVENANCE_BANNER, _read_plugin_version_int, _PV, _USAGE, _USAGE_LOCK, _PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics, + _USAGE_CONTEXT, _log_usage, state_dir as _resolve_state_dir, write_hook_output as _write_hook_output, ) @@ -274,6 +275,7 @@ def emit_metrics( add decision/reason as above. Defaults to "PostToolUse" (commit-review and push-sweep are the most common callers); handle_stop_hook passes "Stop". """ + _log_usage(_usage_metrics()) head = {} if _PV and "pv" not in metrics: head["pv"] = _PV @@ -1202,6 +1204,7 @@ def handle_commit_review_posttooluse(input_data): the Stop hook won't re-flag the same (filePath, vulnerableCode) pair. """ session_id = input_data.get("session_id", "default") + _USAGE_CONTEXT["review"] = "commit" tool_input = input_data.get("tool_input", {}) tool_response = input_data.get("tool_response", {}) cwd = input_data.get("cwd", "") @@ -1756,6 +1759,7 @@ def handle_push_sweep_posttooluse(input_data): command = tool_input.get("command", "") or "" cwd = input_data.get("cwd") session_id = input_data.get("session_id", "") + _USAGE_CONTEXT["review"] = "push" bash_output = ( (tool_response.get("stdout", "") or "") + "\n" @@ -2498,6 +2502,7 @@ def main(): sys.exit(0) session_id = input_data.get("session_id", "default") + _USAGE_CONTEXT["session_id"] = re.sub(r"[^A-Za-z0-9_.-]", "_", str(session_id))[:80] tool_name = input_data.get("tool_name", "") tool_input = input_data.get("tool_input", {}) hook_event_name = input_data.get("hook_event_name", "") |
