contextgate-core 0.6.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,242 @@
1
+ """
2
+ `smarty audit`: where do an agent session's tokens actually go, and what is worth optimizing?
3
+
4
+ Reads real Claude Code transcripts and prices every token with the provider cost model:
5
+
6
+ J = sum over API calls t of [ input_t + Wcw * cache_write_t + Wcr * cache_read_t ] + Wout * output_t
7
+
8
+ (defaults Wcw=1.25, Wcr=0.10, Wout=5.0 relative to the base input price: ASSUMPTIONS, override on the command line).
9
+
10
+ Key consequences, all computed here from your own data rather than assumed:
11
+ * A token in the cached prefix costs Wcw once and Wcr on every later call, so unit_cost = Wcw + Wcr * (n - 1)
12
+ (n = API calls in the session). Cutting 1 prefix token saves unit_cost; cutting 1 *call* saves Wcr * prefix.
13
+ * With a prefix of ~70k tokens the fixed prefix is typically >80% of a short session, so tool-output compression and
14
+ prompt compression can only ever touch the small remainder (an independent JetBrains test of RTK found no net saving).
15
+ * The user-controllable slice of the prefix (instruction files, skill listing, connector/MCP names, agent list) is
16
+ attributed per source so the recommendations are concrete.
17
+ Stdlib only; no network; no LLM.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import json
24
+ import math
25
+ import os
26
+ import statistics
27
+ import sys
28
+ from typing import Any
29
+
30
+ os.environ.setdefault("SMARTY_LIGHT_TOKENS", "1")
31
+
32
+ from . import ab_compare as ab # noqa: E402
33
+ from . import repo_indexer as ri # noqa: E402
34
+
35
+ DEFAULT_WEIGHTS = {"cw": 1.25, "cr": 0.10, "out": 5.0}
36
+ HOST_ATTACHMENTS = {"prompt_snapshot"} # a transcript copy of the host's own system prompt: not user-controllable
37
+ CONTROLLABLE = ("instructions", "skill_listing", "deferred_tools_delta", "agent_listing_delta", "mcp_instructions_delta")
38
+
39
+
40
+ def _att_text(a: dict) -> str:
41
+ if a.get("type") == "instructions" and isinstance(a.get("files"), list):
42
+ return "\n".join(str(x.get("content", "")) for x in a["files"] if isinstance(x, dict))
43
+ c = a.get("content")
44
+ if isinstance(c, str):
45
+ return c
46
+ return json.dumps(c if c is not None else {k: v for k, v in a.items() if k != "type"}, ensure_ascii=False)
47
+
48
+
49
+ def analyze_session(path: str, w: dict[str, float] | None = None) -> dict[str, Any] | None:
50
+ """Cost decomposition + first-turn attribution for one transcript. None if it has fewer than 2 API calls."""
51
+ w = w or DEFAULT_WEIGHTS
52
+ usage: dict[str, dict] = {}
53
+ order: list[str] = []
54
+ atts: dict[str, int] = {}
55
+ instr_files: dict[str, int] = {}
56
+ results: dict[str, int] = {}
57
+ call_of_tool: dict[str, int] = {}
58
+ user_tokens = 0
59
+ seen_assistant = False
60
+ with open(path, encoding="utf-8") as f:
61
+ for line in f:
62
+ try:
63
+ d = json.loads(line)
64
+ except ValueError:
65
+ continue
66
+ t = d.get("type")
67
+ if t == "assistant":
68
+ seen_assistant = True
69
+ m = d.get("message", {})
70
+ if m.get("id") and m.get("usage") and m["id"] not in usage:
71
+ usage[m["id"]] = m["usage"]
72
+ order.append(m["id"])
73
+ for b in m.get("content", []) or []:
74
+ if isinstance(b, dict) and b.get("type") == "tool_use":
75
+ call_of_tool[b["id"]] = len(order)
76
+ elif t == "attachment" and not seen_assistant:
77
+ a = d.get("attachment", {})
78
+ typ = a.get("type", "?")
79
+ atts[typ] = atts.get(typ, 0) + ri.est_tokens(_att_text(a))
80
+ if typ == "instructions" and isinstance(a.get("files"), list):
81
+ for x in a["files"]:
82
+ if isinstance(x, dict):
83
+ instr_files[x.get("path", "?")] = ri.est_tokens(str(x.get("content", "")))
84
+ elif t == "user":
85
+ c = d.get("message", {}).get("content")
86
+ if isinstance(c, list):
87
+ for b in c:
88
+ if isinstance(b, dict) and b.get("type") == "tool_result":
89
+ results[b.get("tool_use_id", "")] = ri.est_tokens(ab._result_text(b.get("content")))
90
+ elif not seen_assistant and not user_tokens:
91
+ user_tokens = ri.est_tokens(ab._prompt_text(d) or "")
92
+ if not seen_assistant and not user_tokens and isinstance(c, list):
93
+ user_tokens = ri.est_tokens(ab._prompt_text(d) or "")
94
+ U = [usage[i] for i in order]
95
+ n = len(U)
96
+ if n < 2:
97
+ return None
98
+
99
+ def total_in(u: dict) -> float:
100
+ return u.get("input_tokens", 0) + w["cw"] * u.get("cache_creation_input_tokens", 0) + w["cr"] * u.get("cache_read_input_tokens", 0)
101
+
102
+ P = sum(U[0].get(k, 0) for k in ("input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens"))
103
+ cost_in = sum(total_in(u) for u in U)
104
+ out = w["out"] * sum(u.get("output_tokens", 0) for u in U)
105
+ fixed = total_in(U[0]) + (n - 1) * w["cr"] * P
106
+ host = atts.get("prompt_snapshot", 0)
107
+ layer = {k: v for k, v in atts.items() if k not in HOST_ATTACHMENTS}
108
+ unit = w["cw"] + w["cr"] * (n - 1)
109
+ return {
110
+ "path": path, "calls": n, "prefix_tokens": P,
111
+ "prefix_cache_write": U[0].get("cache_creation_input_tokens", 0), "prefix_cache_read": U[0].get("cache_read_input_tokens", 0),
112
+ "cost_total": cost_in + out, "cost_fixed_prefix": fixed, "cost_growth": cost_in - fixed, "cost_output": out,
113
+ "unit_cost_per_prefix_token": unit, "turn_cost": w["cr"] * P,
114
+ "user_prompt_tokens": user_tokens, "host_system_prompt_tokens": host,
115
+ "layer_tokens": layer, "instruction_files": instr_files,
116
+ "tool_definitions_and_other_tokens": max(0, P - sum(layer.values()) - host - user_tokens),
117
+ "tool_result_tokens": sum(results.values()),
118
+ "tool_result_cost": sum(tok * (w["cw"] + w["cr"] * max(0, n - call_of_tool.get(tid, n))) for tid, tok in results.items()),
119
+ }
120
+
121
+
122
+ def _mean(rows: list[dict], key: str) -> float:
123
+ return statistics.mean(r[key] for r in rows)
124
+
125
+
126
+ def aggregate(rows: list[dict], cold: bool = False, w: dict[str, float] | None = None) -> dict[str, Any]:
127
+ w = w or DEFAULT_WEIGHTS
128
+ n = _mean(rows, "calls")
129
+ P = _mean(rows, "prefix_tokens")
130
+ cost = _mean(rows, "cost_total")
131
+ if cold: # the cache expired between sessions: the whole prefix is a write at call 1, then reads
132
+ delta = (w["cw"] - w["cr"]) * P - (_mean(rows, "prefix_cache_write") * (w["cw"] - w["cr"]))
133
+ cost += delta
134
+ unit = w["cw"] + w["cr"] * (n - 1)
135
+ layer_keys = {k for r in rows for k in r["layer_tokens"]}
136
+ layer = {k: statistics.mean(r["layer_tokens"].get(k, 0) for r in rows) for k in layer_keys}
137
+ files: dict[str, float] = {}
138
+ for r in rows:
139
+ for p, t in r["instruction_files"].items():
140
+ files[p] = files.get(p, 0) + t / len(rows)
141
+ return {
142
+ "sessions": len(rows), "mean_calls": n, "mean_prefix_tokens": P, "cold_cache": cold, "mean_cost_total": cost,
143
+ "share_fixed_prefix": _mean(rows, "cost_fixed_prefix") / cost if not cold else None,
144
+ "share_growth": _mean(rows, "cost_growth") / cost, "share_output": _mean(rows, "cost_output") / cost,
145
+ "share_tool_results": _mean(rows, "tool_result_cost") / cost,
146
+ "share_user_prompt": _mean(rows, "user_prompt_tokens") * unit / cost,
147
+ "unit_cost": unit, "turn_cost": w["cr"] * P, "turn_share": w["cr"] * P / cost,
148
+ "host_system_prompt_tokens": _mean(rows, "host_system_prompt_tokens"),
149
+ "tool_definitions_and_other_tokens": _mean(rows, "tool_definitions_and_other_tokens"),
150
+ "layer_tokens": layer, "instruction_files": files,
151
+ "layer_cost": {k: v * unit for k, v in layer.items()}, "layer_share": {k: v * unit / cost for k, v in layer.items()},
152
+ }
153
+
154
+
155
+ def recommendations(agg: dict[str, Any], reduction: float = 0.5) -> list[dict]:
156
+ """Rule-based, with the projected saving of cutting each controllable source by `reduction`."""
157
+ unit, cost = agg["unit_cost"], agg["mean_cost_total"]
158
+ recs = []
159
+
160
+ def add(source: str, tokens: float, action: str) -> None:
161
+ if tokens >= 300:
162
+ recs.append({"source": source, "tokens": round(tokens), "per_session_cost": round(tokens * unit),
163
+ "projected_saving_pct": round(100 * tokens * reduction * unit / cost, 1), "action": action})
164
+
165
+ lt = agg["layer_tokens"]
166
+ for p, t in sorted(agg["instruction_files"].items(), key=lambda kv: -kv[1]):
167
+ add(f"instructions: {p}", t, "loaded into EVERY session: keep only rules the agent cannot infer; deduplicate with project files")
168
+ add("skill listing", lt.get("skill_listing", 0), "every installed skill's name+description is paid per session: remove skills/plugins you do not use")
169
+ add("connector / MCP tool names", lt.get("deferred_tools_delta", 0), "disable MCP servers and connectors this project does not need")
170
+ add("subagent listing", lt.get("agent_listing_delta", 0), "remove unused custom agents")
171
+ add("MCP server instructions", lt.get("mcp_instructions_delta", 0), "servers add instruction text per session: trim or disable unused ones")
172
+ recs.sort(key=lambda r: -r["per_session_cost"])
173
+ return recs
174
+
175
+
176
+ def required_pairs(sd_pct: float, effect_pct: float, z_alpha: float = 1.96, z_power: float = 0.84) -> int:
177
+ """Paired-t sample size (normal approximation) to detect a mean paired change of `effect_pct` given its sd."""
178
+ return max(2, math.ceil(((z_alpha + z_power) * sd_pct / abs(effect_pct)) ** 2))
179
+
180
+
181
+ def report(rows: list[dict], w: dict[str, float]) -> dict[str, Any]:
182
+ warm, cold = aggregate(rows, False, w), aggregate(rows, True, w)
183
+ print(f"sessions: {warm['sessions']} mean API calls: {warm['mean_calls']:.1f} prefix at call 1: {warm['mean_prefix_tokens']:.0f} tokens")
184
+ print(f"weights: cache-write x{w['cw']}, cache-read x{w['cr']}, output x{w['out']} (cost in base-input-token equivalents)\n")
185
+ print(f"{'where the cost goes (warm cache)':44}{'share':>8}")
186
+ for lab, k in (("fixed prefix (system prompt, tools, instructions...)", "share_fixed_prefix"),
187
+ (" of which tool results + messages that persist", "share_tool_results"),
188
+ ("context growth (everything appended)", "share_growth"), ("output tokens", "share_output"),
189
+ ("your typed prompt", "share_user_prompt")):
190
+ print(f"{lab:44}{100 * warm[k]:>7.1f}%")
191
+ print(f"\none avoided API call saves {warm['turn_cost']:.0f} weighted tokens = {100 * warm['turn_share']:.1f}% of an average session")
192
+ print(f"one prefix token costs {warm['unit_cost']:.2f} weighted tokens per session (write once + {warm['mean_calls'] - 1:.1f} re-reads)")
193
+ print(f"cold cache (prefix expired between sessions): mean session cost {cold['mean_cost_total']:.0f} vs {warm['mean_cost_total']:.0f} warm "
194
+ f"({100 * (cold['mean_cost_total'] / warm['mean_cost_total'] - 1):+.0f}%)")
195
+ print(f"\nprefix composition: host system prompt ~{warm['host_system_prompt_tokens']:.0f}, tool definitions + other host overhead ~"
196
+ f"{warm['tool_definitions_and_other_tokens']:.0f} (not controllable from a project), user layer below (controllable)")
197
+ print(f"{'user-controllable source':34}{'tokens':>8}{'cost/session':>14}{'share':>8}")
198
+ for k in CONTROLLABLE:
199
+ if warm["layer_tokens"].get(k):
200
+ print(f"{k:34}{warm['layer_tokens'][k]:>8.0f}{warm['layer_cost'][k]:>14.0f}{100 * warm['layer_share'][k]:>7.1f}%")
201
+ recs = recommendations(warm)
202
+ print("\nrecommendations (projected saving if the source is cut by 50%):")
203
+ for r in recs:
204
+ print(f" - {r['source']}: {r['tokens']} tokens, ~{r['per_session_cost']} weighted/session -> up to -{r['projected_saving_pct']}%\n {r['action']}")
205
+ total_pct = sum(r["projected_saving_pct"] for r in recs)
206
+ print(f"\nupper bound from trimming all of the above by 50%: about -{total_pct:.1f}% of session cost")
207
+ return {"warm": warm, "cold": cold, "recommendations": recs}
208
+
209
+
210
+ def main(argv: list[str] | None = None) -> int:
211
+ ap = argparse.ArgumentParser(prog="token_audit", description=__doc__.split("\n")[1])
212
+ ap.add_argument("paths", nargs="*", help=".jsonl transcripts and/or project directories")
213
+ ap.add_argument("--match", help="select Claude Code project directories by name substring")
214
+ ap.add_argument("--last", type=int, help="newest N sessions")
215
+ ap.add_argument("--w-cw", type=float, default=DEFAULT_WEIGHTS["cw"])
216
+ ap.add_argument("--w-cr", type=float, default=DEFAULT_WEIGHTS["cr"])
217
+ ap.add_argument("--w-out", type=float, default=DEFAULT_WEIGHTS["out"])
218
+ ap.add_argument("--json", dest="json_out")
219
+ ap.add_argument("--power", nargs=2, type=float, metavar=("SD_PCT", "EFFECT_PCT"),
220
+ help="print the paired sample size needed to detect EFFECT_PCT given SD_PCT, then exit")
221
+ a = ap.parse_args(argv)
222
+ if a.power:
223
+ print(f"paired runs needed (alpha=0.05, power=0.8): {required_pairs(*a.power)}")
224
+ return 0
225
+ try:
226
+ paths = ab.expand_inputs(a.paths, a.last, a.match)
227
+ except ab.InputError as exc:
228
+ print(f"error: {exc}", file=sys.stderr)
229
+ return 2
230
+ w = {"cw": a.w_cw, "cr": a.w_cr, "out": a.w_out}
231
+ rows = [r for r in (analyze_session(p, w) for p in paths) if r]
232
+ if not rows:
233
+ print("error: no session with at least 2 API calls found", file=sys.stderr)
234
+ return 2
235
+ out = report(rows, w)
236
+ if a.json_out:
237
+ json.dump(out, open(a.json_out, "w"), indent=2, default=str)
238
+ return 0
239
+
240
+
241
+ if __name__ == "__main__":
242
+ sys.exit(main())