@alexgreensh/token-optimizer 5.13.64 → 5.13.66

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 (26) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +62 -13
  4. package/hooks/userpromptsubmit_runner.py +13 -1
  5. package/package.json +1 -1
  6. package/skills/token-optimizer/scripts/_measure/__init__.py +16 -0
  7. package/skills/token-optimizer/scripts/_measure/_compat.py +200 -0
  8. package/skills/token-optimizer/scripts/_measure/audit.py +6949 -0
  9. package/skills/token-optimizer/scripts/_measure/cache_policy.py +6997 -0
  10. package/skills/token-optimizer/scripts/_measure/cli.py +2722 -0
  11. package/skills/token-optimizer/scripts/_measure/continuity.py +4630 -0
  12. package/skills/token-optimizer/scripts/_measure/daemon.py +6773 -0
  13. package/skills/token-optimizer/scripts/_measure/dashboard.py +4358 -0
  14. package/skills/token-optimizer/scripts/_measure/lifecycle.py +5952 -0
  15. package/skills/token-optimizer/scripts/_measure/pricing.py +2101 -0
  16. package/skills/token-optimizer/scripts/_measure/quality_archive.py +7138 -0
  17. package/skills/token-optimizer/scripts/_measure/runtime.py +1231 -0
  18. package/skills/token-optimizer/scripts/_measure/savings.py +7702 -0
  19. package/skills/token-optimizer/scripts/_measure/sessions.py +4784 -0
  20. package/skills/token-optimizer/scripts/_measure/trends.py +2432 -0
  21. package/skills/token-optimizer/scripts/cloud_kit.py +7 -8
  22. package/skills/token-optimizer/scripts/codex_doctor.py +14 -0
  23. package/skills/token-optimizer/scripts/devin_source.py +1 -0
  24. package/skills/token-optimizer/scripts/hermes_doctor.py +13 -0
  25. package/skills/token-optimizer/scripts/hermes_install.py +11 -0
  26. package/skills/token-optimizer/scripts/measure.py +2428 -60928
@@ -0,0 +1,2101 @@
1
+ """Definition-only implementations; mutable state belongs to measure."""
2
+ from __future__ import annotations
3
+ from . import _compat
4
+
5
+
6
+ def _get_model_cost(model, input_tokens, output_tokens, cache_read=None, cache_create=None, tier=None,
7
+ cache_create_1h=None, cache_create_5m=None, per_request=None):
8
+ """Calculate USD cost for a given model and token counts using the active pricing tier.
9
+
10
+ Returns cost in USD. OpenAI/Codex and Gemini models use provider-specific
11
+ rate cards; Claude models use the selected Claude provider tier.
12
+
13
+ For Claude models, cache_create tokens are priced by TTL tier when the split is known:
14
+ - cache_create_1h: 1-hour TTL writes (2x input rate, e.g. $10/MTok for Opus)
15
+ - cache_create_5m: 5-minute TTL writes (1.25x input rate, e.g. $6.25/MTok for Opus)
16
+ When the split is unavailable (both None), the total cache_create uses the 5m rate
17
+ (conservative; 5m is the more common tier for most Claude Code workloads).
18
+
19
+ per_request=True says the token counts are ONE API request. Only then does a
20
+ model with a prompt-length card (Haiku 5.5 over 100K) pay it: the tier is
21
+ decided per request, so a session total, a per-day sum or a 1M-token rate
22
+ probe must be priced on the base card or it reads ~5x too high.
23
+ """
24
+ _measure_facade = _compat.facade()
25
+ if tier is None:
26
+ tier = _measure_facade._load_pricing_tier()
27
+ tier_data = _measure_facade.PRICING_TIERS.get(tier, _measure_facade.PRICING_TIERS["anthropic"])
28
+
29
+ full_input = int(input_tokens or 0) + int(cache_read or 0) + int(cache_create or 0)
30
+
31
+ for norm_fn, pricing, lc_pricing, lc_threshold in (
32
+ (_measure_facade._normalize_openai_model_name, _measure_facade.OPENAI_MODEL_PRICING, _measure_facade.OPENAI_LONG_CONTEXT_PRICING, _measure_facade.OPENAI_LONG_CONTEXT_INPUT_THRESHOLD),
33
+ (_measure_facade._normalize_gemini_model_name, _measure_facade.GEMINI_MODEL_PRICING, _measure_facade.GEMINI_LONG_CONTEXT_PRICING, _measure_facade.GEMINI_LONG_CONTEXT_INPUT_THRESHOLD),
34
+ ):
35
+ key = norm_fn(model)
36
+ if key:
37
+ rates = pricing[key]
38
+ if full_input > lc_threshold and key in lc_pricing:
39
+ rates = lc_pricing[key]
40
+ return (
41
+ input_tokens * rates["input"] / 1e6
42
+ + output_tokens * rates["output"] / 1e6
43
+ + cache_read * rates["cache_read"] / 1e6
44
+ + cache_create * rates.get("cache_write", 0) / 1e6
45
+ )
46
+
47
+ normalized = _measure_facade._claude_price_key(model, tier_data["claude_models"]) if model else None
48
+ if normalized and normalized in tier_data["claude_models"]:
49
+ rates = tier_data["claude_models"][normalized]
50
+ lc_models = tier_data.get("claude_models_lc") or {}
51
+ else:
52
+ # Non-Claude model: use Anthropic tier rates for Claude, skip for others
53
+ rates = _measure_facade.PRICING_TIERS["anthropic"]["claude_models"].get(normalized or "", None)
54
+ lc_models = _measure_facade.PRICING_TIERS["anthropic"].get("claude_models_lc") or {}
55
+ if rates is None:
56
+ return 0.0
57
+
58
+ # Prompt-length surcharge: Anthropic counts ALL of a request's input
59
+ # (input + cache reads + cache writes = full_input) against the
60
+ # long-context threshold. Haiku 5.5 >100K pays 5x on every rate. Applies
61
+ # to a single request only (per_request); aggregates use the base card.
62
+ if (per_request and normalized in lc_models
63
+ and full_input > _measure_facade.ANTHROPIC_LONG_CONTEXT_INPUT_THRESHOLD):
64
+ rates = lc_models[normalized]
65
+
66
+ # Price cache-write tokens by TTL tier when the split is available.
67
+ # 1h tier = 2x input (cache_write_1h); 5m tier = 1.25x input (cache_write).
68
+ # Fall back to 5m rate for the full total when no split is stored.
69
+ if cache_create_1h is not None and cache_create_5m is not None:
70
+ split_1h = int(cache_create_1h or 0)
71
+ split_5m = int(cache_create_5m or 0)
72
+ unsplit = max(0, int(cache_create or 0) - split_1h - split_5m)
73
+ cc_write_cost = (
74
+ split_1h * rates.get("cache_write_1h", rates["cache_write"]) / 1e6
75
+ + (split_5m + unsplit) * rates["cache_write"] / 1e6
76
+ )
77
+ else:
78
+ cc_write_cost = int(cache_create or 0) * rates["cache_write"] / 1e6
79
+
80
+ cost = (
81
+ input_tokens * rates["input"] / 1e6
82
+ + output_tokens * rates["output"] / 1e6
83
+ + cache_read * rates["cache_read"] / 1e6
84
+ + cc_write_cost
85
+ )
86
+ return cost
87
+
88
+
89
+ def _bundled_prices_path():
90
+ _measure_facade = _compat.facade()
91
+ override = _measure_facade.os.environ.get("TOKEN_OPTIMIZER_PRICES_FILE", "").strip()
92
+ if override:
93
+ return _measure_facade.Path(override).expanduser()
94
+ return _measure_facade.Path(_measure_facade.__file__).resolve().parent.parent / "pricing" / "prices.json"
95
+
96
+
97
+ def _claude_cards(table, mult=None):
98
+ """Tier-adjusted copy of a fallback card table (vertex-regional is +10%)."""
99
+ _measure_facade = _compat.facade()
100
+ return {key: {f: round(v * mult, 6) for f, v in card.items()} for key, card in table.items()}
101
+
102
+
103
+ def _pricing_as_of():
104
+ """Date that pricing is resolved against: the wall clock in production, or a pinned date
105
+ from TOKEN_OPTIMIZER_PRICING_AS_OF (YYYY-MM-DD) so the test suite stays regime-stable across
106
+ the 2026-09-01 Sonnet flip. Falls back to now() on an unparseable override."""
107
+ _measure_facade = _compat.facade()
108
+ override = _measure_facade.os.environ.get("TOKEN_OPTIMIZER_PRICING_AS_OF")
109
+ if override:
110
+ try:
111
+ return _measure_facade.datetime.strptime(override, "%Y-%m-%d") # naive; treated as UTC downstream
112
+ except ValueError:
113
+ pass
114
+ return _measure_facade.datetime.now(_measure_facade.timezone.utc)
115
+
116
+
117
+ def _apply_sonnet_intro_pricing(as_of=None):
118
+ """Swap the Anthropic-tier sonnet card to the introductory rate while it is in effect.
119
+ Idempotent (always recomputes from the canonical standard card, so repeated calls / a
120
+ date change are safe). Returns True when the introductory rate is active. A naive `as_of`
121
+ (or env date) is interpreted as UTC so the boundary compares apples to apples."""
122
+ _measure_facade = _compat.facade()
123
+ d = as_of or _measure_facade._pricing_as_of()
124
+ if d.tzinfo is None:
125
+ d = d.replace(tzinfo=_measure_facade.timezone.utc)
126
+ # 2026-08-29: the launch "introductory" rate became the STANDARD Sonnet 5 price and
127
+ # the scheduled 2026-09-01 increase was cancelled. Verbatim from
128
+ # platform.claude.com/docs/en/about-claude/pricing: "The $2/$10 per million
129
+ # input/output token pricing for Claude Sonnet 5, announced at launch as
130
+ # introductory pricing through August 31, 2026, is now the standard price. The
131
+ # previously scheduled increase to $3/$15 per million input/output tokens on
132
+ # September 1, 2026 will not occur."
133
+ # The date gate is therefore retired: $2/$10 applies at every `as_of`. The old
134
+ # gate would have silently repriced EVERY Sonnet-5 dollar in every card by +50%
135
+ # on 2026-09-01. `_SONNET_STANDARD_RATES` is retained as the Sonnet 4.6/4.5 card,
136
+ # which is what the `sonnet_legacy` bucket prices against.
137
+ _measure_facade.PRICING_TIERS["anthropic"]["claude_models"]["sonnet"] = dict(_measure_facade._SONNET_INTRO_RATES)
138
+ return True
139
+
140
+
141
+ def _apply_gpt56_sol_promo_pricing(as_of=None):
142
+ """Swap the gpt-5.6-sol card to the promotional rate while it is in effect.
143
+
144
+ Idempotent (always recomputes from the canonical standard card, so repeated
145
+ calls / a date change are safe). Returns True when the promotional rate is
146
+ active. A naive `as_of` (or env date) is interpreted as UTC so the boundary
147
+ compares apples to apples.
148
+ """
149
+ _measure_facade = _compat.facade()
150
+ d = as_of or _measure_facade._pricing_as_of()
151
+ if d.tzinfo is None:
152
+ d = d.replace(tzinfo=_measure_facade.timezone.utc)
153
+ if d < _measure_facade._GPT56_SOL_PROMO_UNTIL:
154
+ _measure_facade.OPENAI_MODEL_PRICING["gpt-5.6-sol"] = dict(_measure_facade._GPT56_SOL_PROMO)
155
+ _measure_facade.OPENAI_LONG_CONTEXT_PRICING["gpt-5.6-sol"] = dict(_measure_facade._GPT56_SOL_LC_PROMO)
156
+ return True
157
+ _measure_facade.OPENAI_MODEL_PRICING["gpt-5.6-sol"] = dict(_measure_facade._GPT56_SOL_STANDARD)
158
+ _measure_facade.OPENAI_LONG_CONTEXT_PRICING["gpt-5.6-sol"] = dict(_measure_facade._GPT56_SOL_LC_STANDARD)
159
+ return False
160
+
161
+
162
+ def _clean_price_cards(section):
163
+ """Keep only well-formed cards: safe key, finite non-negative rates, input+output present."""
164
+ _measure_facade = _compat.facade()
165
+ out = {}
166
+ if not isinstance(section, dict):
167
+ return out
168
+ for key, card in section.items():
169
+ if not isinstance(key, str) or not _measure_facade._PRICE_KEY_RE.match(key) or not isinstance(card, dict):
170
+ continue
171
+ clean = {}
172
+ for field in _measure_facade._PRICE_FIELDS:
173
+ value = card.get(field)
174
+ if value is None:
175
+ continue
176
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
177
+ clean = None
178
+ break
179
+ value = float(value)
180
+ if not _measure_facade.math.isfinite(value) or value < 0 or value > 1000:
181
+ clean = None
182
+ break
183
+ clean[field] = value
184
+ if clean and "input" in clean and "output" in clean:
185
+ out[key] = clean
186
+ return out
187
+
188
+
189
+ def _apply_bundled_prices(path=None):
190
+ """Merge pricing/prices.json over the built-in rate tables. Returns True when applied."""
191
+ _measure_facade = _compat.facade()
192
+ path = _measure_facade.Path(path) if path else _measure_facade._bundled_prices_path()
193
+ _measure_facade.BUNDLED_PRICES_STATUS.update(loaded=False, path=str(path), generated_at=None, error=None)
194
+ if _measure_facade.os.environ.get("TOKEN_OPTIMIZER_BUNDLED_PRICES", "1").strip() == "0":
195
+ _measure_facade.BUNDLED_PRICES_STATUS["error"] = "disabled by TOKEN_OPTIMIZER_BUNDLED_PRICES=0"
196
+ return False
197
+ try:
198
+ if path.stat().st_size > _measure_facade._PRICES_FILE_MAX_BYTES:
199
+ raise ValueError("prices file too large")
200
+ doc = _measure_facade.json.loads(path.read_text(encoding="utf-8"))
201
+ if not isinstance(doc, dict) or doc.get("schema") != 1:
202
+ raise ValueError("unsupported prices schema")
203
+ except (OSError, ValueError) as exc:
204
+ _measure_facade.BUNDLED_PRICES_STATUS["error"] = str(exc)
205
+ return False
206
+
207
+ claude = _measure_facade._clean_price_cards(doc.get("anthropic"))
208
+ for card in claude.values():
209
+ card.setdefault("cache_read", round(card["input"] * 0.1, 6))
210
+ card.setdefault("cache_write", round(card["input"] * 1.25, 6))
211
+ card.setdefault("cache_write_1h", round(card["input"] * 2, 6))
212
+ claude_lc = _measure_facade._clean_price_cards(doc.get("anthropic_long_context"))
213
+ for card in claude_lc.values():
214
+ card.setdefault("cache_read", round(card["input"] * 0.1, 6))
215
+ card.setdefault("cache_write", round(card["input"] * 1.25, 6))
216
+ card.setdefault("cache_write_1h", round(card["input"] * 2, 6))
217
+ # First-party rates apply on Vertex global and Bedrock; Vertex regional is +10%.
218
+ for tier_name, tier in _measure_facade.PRICING_TIERS.items():
219
+ mult = 1.1 if tier_name == "vertex-regional" else 1.0
220
+ for key, card in claude.items():
221
+ tier["claude_models"][key] = {f: round(v * mult, 6) for f, v in card.items()}
222
+ lc_table = tier.setdefault("claude_models_lc", {})
223
+ for key, card in claude_lc.items():
224
+ lc_table[key] = {f: round(v * mult, 6) for f, v in card.items()}
225
+ for table, section in ((_measure_facade.OPENAI_MODEL_PRICING, "openai"),
226
+ (_measure_facade.OPENAI_LONG_CONTEXT_PRICING, "openai_long_context"),
227
+ (_measure_facade.GEMINI_MODEL_PRICING, "gemini"),
228
+ (_measure_facade.GEMINI_LONG_CONTEXT_PRICING, "gemini_long_context")):
229
+ for key, card in _measure_facade._clean_price_cards(doc.get(section)).items():
230
+ # The dated promo switch owns this card, so the swap back to the
231
+ # standard rate still happens on its date whatever the feed says.
232
+ if key in _measure_facade._PROMO_MANAGED_OPENAI_KEYS:
233
+ continue
234
+ card.setdefault("cache_read", card["input"])
235
+ card.pop("cache_write_1h", None)
236
+ table[key] = card
237
+ _measure_facade.BUNDLED_PRICES_STATUS.update(loaded=True, generated_at=doc.get("generated_at"))
238
+ return True
239
+
240
+
241
+ def _resolve_cache_profile(model, runtime=None):
242
+ """Resolve a model id (+ runtime) to its provider cache profile.
243
+
244
+ Returns the (profile_key, profile_dict). Pure lookup, never raises.
245
+ Resolution: OpenAI/Gemini/code review model families first (provider-specific
246
+ rate cards already recognize these), then Claude (Claude Code vs raw API by
247
+ runtime), else the honest "unknown/none" profile.
248
+ """
249
+ _measure_facade = _compat.facade()
250
+ if _measure_facade._normalize_openai_model_name(model):
251
+ return "openai", _measure_facade.PROVIDER_CACHE_PROFILES["openai"]
252
+ if _measure_facade._normalize_gemini_model_name(model):
253
+ return "gemini", _measure_facade.PROVIDER_CACHE_PROFILES["gemini"]
254
+ value = _measure_facade._strip_provider_prefixes(model) if model else ""
255
+ if value.startswith("deepseek"):
256
+ return "deepseek", _measure_facade.PROVIDER_CACHE_PROFILES["deepseek"]
257
+ if _measure_facade._normalize_model_name(model) in ("fable", "opus", "sonnet", "haiku"):
258
+ if runtime == "claude":
259
+ # Claude Code: the platform requests a 1h cache (no user knob).
260
+ return "claude_code", _measure_facade.PROVIDER_CACHE_PROFILES["claude_code"]
261
+ # Raw Anthropic API/SDK/harness session (e.g. Hermes -> Anthropic): the
262
+ # 5-min default applies and the user can set a 1h cache_control.
263
+ return "anthropic_api", _measure_facade.PROVIDER_CACHE_PROFILES["anthropic_api"]
264
+ return "unknown", _measure_facade.PROVIDER_CACHE_PROFILES["unknown"]
265
+
266
+
267
+ def _strip_provider_prefixes(model):
268
+ _measure_facade = _compat.facade()
269
+ value = str(model).strip().lower()
270
+ while True:
271
+ dotted = _measure_facade._DOTTED_PROVIDER_PREFIX_RE.match(value)
272
+ if dotted:
273
+ value = value[dotted.end():]
274
+ continue
275
+ slash = value.find("/")
276
+ colon = value.find(":")
277
+ if slash == -1 and colon == -1:
278
+ return value
279
+ if slash != -1 and (colon == -1 or slash < colon):
280
+ idx = slash
281
+ delimiter = "/"
282
+ else:
283
+ idx = colon
284
+ delimiter = ":"
285
+ prefix = value[:idx]
286
+ rest = value[idx + 1:]
287
+ if not rest or not _measure_facade.re.search(r"[a-z]", rest):
288
+ return value
289
+ if delimiter == "/" or prefix in _measure_facade._KNOWN_PROVIDER_PREFIXES:
290
+ value = rest
291
+ continue
292
+ return value
293
+
294
+
295
+ def _load_pricing_tier():
296
+ """Load pricing tier preference from config (user, then the project
297
+ layer via _read_config_flag). Defaults to 'anthropic'."""
298
+ _measure_facade = _compat.facade()
299
+ try:
300
+ tier = _measure_facade._read_config_flag("pricing_tier", "anthropic")
301
+ if isinstance(tier, str) and tier in _measure_facade.PRICING_TIERS:
302
+ return tier
303
+ except Exception:
304
+ pass
305
+ return "anthropic"
306
+
307
+
308
+ def _pricing_tier_label(tier):
309
+ _measure_facade = _compat.facade()
310
+ if _measure_facade.detect_runtime() == "codex":
311
+ return "OpenAI API pricing for recognized Codex models"
312
+ return _measure_facade.PRICING_TIERS.get(tier, {}).get("label", "Anthropic API")
313
+
314
+
315
+ def _save_pricing_tier(tier):
316
+ """Persist pricing tier preference via the atomic+locked config writer."""
317
+ _measure_facade = _compat.facade()
318
+ _measure_facade._write_config_flag("pricing_tier", tier)
319
+
320
+
321
+ def _is_priced_model(model, tier=None):
322
+ """True when Token Optimizer has an exact rate card for this model id."""
323
+ _measure_facade = _compat.facade()
324
+ if _measure_facade._normalize_openai_model_name(model):
325
+ return True
326
+ if _measure_facade._normalize_gemini_model_name(model):
327
+ return True
328
+ if tier is None:
329
+ tier = _measure_facade._load_pricing_tier()
330
+ tier_data = _measure_facade.PRICING_TIERS.get(tier, _measure_facade.PRICING_TIERS["anthropic"])
331
+ claude_models = tier_data.get("claude_models", {})
332
+ normalized = _measure_facade._claude_price_key(model, claude_models) if model else None
333
+ return bool(normalized and normalized in claude_models)
334
+
335
+
336
+ def _price_aliases(table):
337
+ """Priced ids of a rate table, longest first; cached until the table changes."""
338
+ _measure_facade = _compat.facade()
339
+ sig = (id(table), len(table))
340
+ cached = _measure_facade._PRICE_ALIAS_CACHE.get(sig)
341
+ # keys() == frozenset compares in C without building sets: this runs once
342
+ # per priced request, so a per-call copy of the table showed up in profiles.
343
+ if cached is None or table.keys() != cached[1]:
344
+ cached = (tuple(sorted(table, key=len, reverse=True)), frozenset(table))
345
+ _measure_facade._PRICE_ALIAS_CACHE[sig] = cached
346
+ return cached[0]
347
+
348
+
349
+ def _match_price_alias(value, table):
350
+ """Longest priced id that `value` equals or that `value` is a snapshot of
351
+ (the id plus a date or number suffix). A different variant (-mini, -lite,
352
+ -image, a later generation) has its own price and never matches a shorter
353
+ card. Memoized per alias set so repeated model ids resolve with one lookup."""
354
+ _measure_facade = _compat.facade()
355
+ aliases = _measure_facade._price_aliases(table)
356
+ memo = _measure_facade._PRICE_MATCH_MEMO.get(id(table))
357
+ if memo is None or memo[0] is not aliases:
358
+ memo = (aliases, {})
359
+ _measure_facade._PRICE_MATCH_MEMO[id(table)] = memo
360
+ hit = memo[1].get(value, _measure_facade._MISSING)
361
+ if hit is _measure_facade._MISSING:
362
+ hit = next((a for a in aliases
363
+ if value == a or (value.startswith(a)
364
+ and _measure_facade._PRICE_SNAPSHOT_RE.fullmatch(value, len(a)))), None)
365
+ if len(memo[1]) < 4096:
366
+ memo[1][value] = hit
367
+ return hit
368
+
369
+
370
+ def _normalize_openai_model_name(model):
371
+ """Return a priced OpenAI model id, or None when we cannot price exactly."""
372
+ _measure_facade = _compat.facade()
373
+ if not model:
374
+ return None
375
+ value = _measure_facade.re.sub(r"[\s_]+", "-", _measure_facade._strip_provider_prefixes(model))
376
+ if not value or value in {"codex", "openai", "unknown"}:
377
+ return None
378
+ if value in ("gpt-5.6", "gpt-5.6-sol-pro"):
379
+ return "gpt-5.6-sol" # bare alias: OpenAI's docs name Sol the default 5.6; "Sol Pro" is its marketing name
380
+ # Every priced id is an alias, longest first so "gpt-5.4-mini" wins over
381
+ # "gpt-5.4" and dated snapshots ("gpt-5.4-2026-03-05") map to their base.
382
+ alias = _measure_facade._match_price_alias(value, _measure_facade.OPENAI_MODEL_PRICING)
383
+ if alias == "gpt-5.6":
384
+ return "gpt-5.6-sol" # dated bare-5.6 ids follow the same Sol default
385
+ if alias:
386
+ return alias
387
+ if _measure_facade.re.fullmatch(r"gpt-5\.6(?:" + _measure_facade._PRICE_SNAPSHOT_RE.pattern + ")", value):
388
+ return "gpt-5.6-sol"
389
+ return None
390
+
391
+
392
+ def _normalize_gemini_model_name(model):
393
+ """Return a priced Gemini model id, or None when we cannot price exactly."""
394
+ _measure_facade = _compat.facade()
395
+ if not model:
396
+ return None
397
+ value = _measure_facade._strip_provider_prefixes(model)
398
+ if not value.startswith("gemini-"):
399
+ return None
400
+ if value.startswith("gemini-2.0"):
401
+ if value not in _measure_facade._GEMINI_DEPRECATION_WARNED:
402
+ _measure_facade._GEMINI_DEPRECATION_WARNED.add(value)
403
+ print(f"[Token Optimizer] WARNING: {value} was deprecated June 1, 2026. Migrate to gemini-2.5-flash or gemini-3.5-flash.", file=_measure_facade.sys.stderr)
404
+ return None
405
+ hit = _measure_facade._match_price_alias(value, _measure_facade.GEMINI_MODEL_PRICING)
406
+ if hit:
407
+ return hit
408
+ # A preview build of a priced model ("-preview", "-preview-05-20",
409
+ # "-preview-09-2025") is the same model; any other variant is not.
410
+ base = _measure_facade.re.sub(r"-preview(?:-\d{2}-\d{2,4})?$", "", value)
411
+ return _measure_facade._match_price_alias(base, _measure_facade.GEMINI_MODEL_PRICING) if base != value else None
412
+
413
+
414
+ def _resolve_session_model(session_id=None):
415
+ """Return the dominant normalized model name for cost attribution.
416
+
417
+ Resolution order:
418
+ 1. Explicit session_id → most frequent `message.model` in that JSONL
419
+ 2. CLAUDE_MODEL environment variable (set by Claude Code hook runner)
420
+ 3. Most recent session's dominant model from trends DB
421
+ 4. Fall back to "sonnet"
422
+
423
+ Never raises. Always returns a normalized name ("opus"|"sonnet"|"haiku"|"sonnet" default).
424
+ """
425
+ _measure_facade = _compat.facade()
426
+ if _measure_facade.detect_runtime() == 'codex':
427
+ # Claude message.model/environment/defaults are not Codex telemetry.
428
+ # Do not cache across model switches, or borrow another task's model.
429
+ path = _measure_facade.codex_session.find_session_jsonl_by_id(session_id) if session_id else None
430
+ model = None
431
+ if path:
432
+ for record in _measure_facade.codex_session._iter_json_records(path):
433
+ candidate = _measure_facade.codex_session._extract_model(_measure_facade.codex_session._payload(record))
434
+ if candidate:
435
+ model = candidate
436
+ return model or (None if session_id else _measure_facade._codex_config_model()) or 'unknown'
437
+ cache_key = session_id or "__env_or_recent__"
438
+ if cache_key in _measure_facade._RESOLVED_MODEL_CACHE:
439
+ return _measure_facade._RESOLVED_MODEL_CACHE[cache_key]
440
+
441
+ result = None
442
+
443
+ # 1. Try session JSONL
444
+ if session_id:
445
+ session_id = _measure_facade.sanitize_session_id(session_id)
446
+ try:
447
+ # The session id names its transcript exactly; find it wherever it
448
+ # lives rather than trusting a cwd lookup that can guess another
449
+ # project's dir (#265).
450
+ candidate = next(iter(sorted((_measure_facade.CLAUDE_DIR / "projects").glob(f"*/{session_id}.jsonl"))), None)
451
+ if candidate is None:
452
+ projects_dir = _measure_facade.find_projects_dir()
453
+ candidate = projects_dir / f"{session_id}.jsonl" if projects_dir else None
454
+ if candidate is not None:
455
+ if candidate.exists():
456
+ counts = {}
457
+ with open(candidate, "r", encoding="utf-8", errors="replace") as f:
458
+ for line in f:
459
+ try:
460
+ data = _measure_facade.json.loads(line)
461
+ msg = data.get("message") if isinstance(data, dict) else None
462
+ if isinstance(msg, dict):
463
+ m = msg.get("model")
464
+ norm = _measure_facade._normalize_model_name(m) if m else None
465
+ if norm:
466
+ counts[norm] = counts.get(norm, 0) + 1
467
+ except (_measure_facade.json.JSONDecodeError, KeyError, TypeError):
468
+ continue
469
+ if counts:
470
+ result = max(counts, key=counts.get)
471
+ except (OSError, PermissionError):
472
+ pass
473
+
474
+ # 2. Try CLAUDE_MODEL env var — but only for Claude-family runtimes. A
475
+ # foreign runtime (cursor, grok, opencode, copilot, antigravity) running
476
+ # on a host that also has CLAUDE_MODEL set would otherwise be priced at
477
+ # Claude model rates, the exact cross-runtime leak the isolation pass
478
+ # closes for detect_context_window() and quick_scan().
479
+ if not result:
480
+ _rt = _measure_facade.detect_runtime()
481
+ if _rt in ("claude", "hermes"):
482
+ env_model = _measure_facade.os.environ.get("CLAUDE_MODEL") or _measure_facade.os.environ.get("ANTHROPIC_MODEL")
483
+ if env_model:
484
+ norm = _measure_facade._normalize_model_name(env_model)
485
+ if norm in ("opus", "sonnet", "haiku"):
486
+ result = norm
487
+
488
+ # 3. Try trends DB for most-recent dominant model
489
+ if not result:
490
+ try:
491
+ if _measure_facade.TRENDS_DB.exists():
492
+ conn = _measure_facade._init_trends_db()
493
+ _measure_facade.ensure_activity_view(conn)
494
+ try:
495
+ row = conn.execute(
496
+ "SELECT model_usage_json FROM session_activity "
497
+ "WHERE model_usage_json IS NOT NULL AND model_usage_json != '' "
498
+ "ORDER BY date DESC LIMIT 1"
499
+ ).fetchone()
500
+ if row and row[0]:
501
+ mu = _measure_facade.json.loads(row[0])
502
+ if isinstance(mu, dict) and mu:
503
+ # normalize keys and sum
504
+ norm_counts = {}
505
+ for k, v in mu.items():
506
+ nk = _measure_facade._normalize_model_name(k) or k
507
+ try:
508
+ norm_counts[nk] = norm_counts.get(nk, 0) + int(v)
509
+ except (TypeError, ValueError):
510
+ continue
511
+ if norm_counts:
512
+ result = max(norm_counts, key=norm_counts.get)
513
+ finally:
514
+ conn.close()
515
+ except (_measure_facade.sqlite3.Error, _measure_facade.json.JSONDecodeError, OSError):
516
+ pass
517
+
518
+ if not result or result not in ("opus", "sonnet", "haiku"):
519
+ result = "sonnet"
520
+
521
+ _measure_facade._RESOLVED_MODEL_CACHE[cache_key] = result
522
+ return result
523
+
524
+
525
+ def _simulate_model_switch(session_data, target_model=None):
526
+ """Estimate cost delta if target_model was used instead of the dominant model.
527
+
528
+ Returns dict with: current_cost, target_cost, savings_usd, savings_pct.
529
+ """
530
+ _measure_facade = _compat.facade()
531
+ model_usage = session_data.get("model_usage", {})
532
+ total_input = session_data.get("total_input_tokens", 0)
533
+ total_output = session_data.get("total_output_tokens", 0)
534
+ cache_hit = session_data.get("cache_hit_rate", 0)
535
+ cache_read = _measure_facade._safe_int(total_input * cache_hit)
536
+ uncached = max(0, total_input - cache_read)
537
+
538
+ dom_model = max(model_usage, key=model_usage.get) if model_usage else "unknown"
539
+ current_cost = _measure_facade._get_model_cost(dom_model, uncached, total_output, cache_read, 0)
540
+ target_cost = _measure_facade._get_model_cost(target_model, uncached, total_output, cache_read, 0)
541
+ savings = current_cost - target_cost
542
+
543
+ return {
544
+ "current_cost": round(current_cost, 4),
545
+ "target_cost": round(target_cost, 4),
546
+ "savings_usd": round(max(0, savings), 4),
547
+ "savings_pct": round(savings / current_cost * 100, 1) if current_cost > 0 else 0,
548
+ }
549
+
550
+
551
+ def _cost_from_model_breakdown(model_usage_breakdown, tier=None, cache_create_1h=None, cache_create_5m=None):
552
+ """Calculate exact known cost from per-model token buckets."""
553
+ _measure_facade = _compat.facade()
554
+ if not isinstance(model_usage_breakdown, dict):
555
+ return 0.0
556
+ total = 0.0
557
+ for model, parts in model_usage_breakdown.items():
558
+ if not isinstance(parts, dict):
559
+ continue
560
+ # Long-context pricing applies per request, never to a session sum.
561
+ requests = parts.get('requests')
562
+ if isinstance(requests, list) and requests:
563
+ total += sum(_measure_facade._cost_from_model_breakdown({model: request}, tier=tier)
564
+ for request in requests if isinstance(request, dict))
565
+ # Bucket totals include deltas from records that were never
566
+ # appended to requests (e.g. a cache-read-only turn with zero
567
+ # input/output, or cache_create which requests never carry).
568
+ # Price the unpriced remainder at the aggregate rate instead of
569
+ # silently dropping those tokens from the cost.
570
+ remainder = {
571
+ key: max(0, int(parts.get(key) or 0) - sum(
572
+ int(request.get(key) or 0) for request in requests
573
+ if isinstance(request, dict)))
574
+ for key in ('fresh_input', 'cache_read', 'output',
575
+ 'cache_create', 'cache_create_1h', 'cache_create_5m')
576
+ }
577
+ if any(remainder.values()):
578
+ total += _measure_facade._cost_from_model_breakdown({model: remainder}, tier=tier)
579
+ continue
580
+ part_1h = parts.get("cache_create_1h")
581
+ part_5m = parts.get("cache_create_5m")
582
+ if part_1h is None and part_5m is None and len(model_usage_breakdown) == 1:
583
+ part_1h = cache_create_1h
584
+ part_5m = cache_create_5m
585
+ total += _measure_facade._get_model_cost(
586
+ model,
587
+ int(parts.get("fresh_input") or 0),
588
+ int(parts.get("output") or 0),
589
+ int(parts.get("cache_read") or 0),
590
+ int(parts.get("cache_create") or 0),
591
+ tier=tier,
592
+ cache_create_1h=part_1h,
593
+ cache_create_5m=part_5m,
594
+ )
595
+ return total
596
+
597
+
598
+ def _resolve_platform_models(runtime):
599
+ """Resolve a platform's real tier->model ladder from ITS OWN config, or None.
600
+
601
+ Only user-configured platforms need this; None means "use the routing table".
602
+ - opencode: reads opencode.json (`model` / `small_model`, provider-qualified).
603
+ small_model -> budget, model -> mid/capable/frontier. Absent field or
604
+ unreadable config -> None (table fallback).
605
+ - hermes: a Claude runtime with no per-tier model config, so the Claude ladder
606
+ in the table is already correct -> None.
607
+ Never raises.
608
+ """
609
+ _measure_facade = _compat.facade()
610
+ try:
611
+ if runtime != "opencode":
612
+ return None
613
+ from runtime_env import opencode_config_home
614
+ cfg_path = opencode_config_home() / "opencode.json"
615
+ if not cfg_path.is_file():
616
+ return None
617
+ with cfg_path.open("r", encoding="utf-8") as handle:
618
+ cfg = _measure_facade.json.load(handle)
619
+ if not isinstance(cfg, dict):
620
+ return None
621
+
622
+ def _leaf(value):
623
+ # "anthropic/claude-sonnet-4" -> "claude-sonnet-4"; keep advisory-friendly.
624
+ _measure_facade = _compat.facade()
625
+ if not (isinstance(value, str) and value.strip()):
626
+ return None
627
+ return value.strip().rsplit("/", 1)[-1]
628
+
629
+ main = _leaf(cfg.get("model"))
630
+ small = _leaf(cfg.get("small_model")) or main
631
+ main = main or small
632
+ if not main:
633
+ return None
634
+ return {"budget": small, "mid": main, "capable": main, "frontier": main}
635
+ except Exception:
636
+ return None
637
+
638
+
639
+ def _cmd_route(args):
640
+ """Recommend a model and reasoning effort for a task on the CURRENT platform.
641
+
642
+ Works on every supported runtime (it reads only the task text and the
643
+ detected platform, never the Claude tree), so it is intentionally NOT a
644
+ Claude-targeting command. Fails open to a safe middle recommendation.
645
+ """
646
+ _measure_facade = _compat.facade()
647
+ import json as _json
648
+ as_json = "--json" in args
649
+ task = ""
650
+ _eq = [a for a in args if a.startswith("--task=")]
651
+ if "--task" in args:
652
+ i = args.index("--task")
653
+ if i + 1 < len(args):
654
+ task = args[i + 1]
655
+ elif _eq:
656
+ task = _eq[-1][len("--task="):]
657
+ else:
658
+ # Positional task: keep every token except the recognized --json flag so
659
+ # task words that happen to start with "--" are not silently dropped.
660
+ task = " ".join(a for a in args[1:] if a != "--json")
661
+ _rt = _measure_facade.detect_runtime()
662
+ try:
663
+ import routing_advisor
664
+ rec = routing_advisor.recommend(task, _rt, models=_measure_facade._resolve_platform_models(_rt))
665
+ except Exception as _e:
666
+ # Router module unavailable: a real, non-cheap default with the same
667
+ # keys as a normal recommendation so JSON consumers never KeyError.
668
+ # Model name comes from the platform's own ladder, never a hardcoded
669
+ # Claude tier under a non-Claude runtime.
670
+ _mid = "sonnet"
671
+ try:
672
+ _row = routing_advisor.ROUTING_TABLES.get(_rt) or routing_advisor._GENERIC_ROW
673
+ _mid = _row["models"]["mid"]
674
+ except Exception:
675
+ if _rt == "codex":
676
+ _mid = "gpt-5.6-terra"
677
+ rec = {
678
+ "model": _mid, "effort": "medium", "significance": "standard",
679
+ "confidence": "low", "category": "simple", "tier": "mid",
680
+ "effort_kind": "advisory", "effort_knob": "effort",
681
+ "floor": {"min_tier": "mid", "min_effort": "medium"},
682
+ "why": f"router unavailable ({type(_e).__name__}); safe default",
683
+ }
684
+ if as_json:
685
+ print(_json.dumps(rec))
686
+ return
687
+ print(f" model: {rec.get('model')}")
688
+ print(f" effort: {rec.get('effort')} ({rec.get('effort_knob', 'effort')})")
689
+ print(f" why: {rec.get('why')}")
690
+
691
+
692
+ def generate_model_routing_block(trends=None):
693
+ """Generate the model + effort routing block for the CURRENT platform.
694
+
695
+ Renders the current platform's own model ladder and effort control, states
696
+ the easy-only rule for the cheapest models and lowest efforts, and points at
697
+ the live `route` command. Recent model-mix stats are added as evidence when
698
+ available. Returns markdown suitable for instruction-file injection.
699
+ """
700
+ _measure_facade = _compat.facade()
701
+ try:
702
+ import routing_advisor
703
+ except Exception:
704
+ return None
705
+
706
+ runtime = _measure_facade.detect_runtime()
707
+ row = routing_advisor.platform_row(runtime)
708
+ resolved = _measure_facade._resolve_platform_models(runtime)
709
+ models = resolved if isinstance(resolved, dict) else row["models"]
710
+
711
+ easy_m, easy_e = routing_advisor.baseline("easy", runtime, models=resolved)
712
+ std_m, std_e = routing_advisor.baseline("standard", runtime, models=resolved)
713
+ hard_m, hard_e = routing_advisor.baseline("hard", runtime, models=resolved)
714
+ knob = row["effort_knob"]
715
+
716
+ lines = [
717
+ "## Model & Effort Routing (by Token Optimizer)",
718
+ f"For each task pick both a model and an effort level. Effort maps to this "
719
+ f"platform's {knob}.",
720
+ f"- Easy (typo, rename, format, grep, single-file): {easy_m} at {easy_e} effort.",
721
+ f"- Standard (a bounded feature or fix): {std_m} at {std_e} effort.",
722
+ f"- Hard (security, migrations, concurrency, architecture): {hard_m} at {hard_e} effort.",
723
+ f"- The cheapest models ({models.get('budget')}) and the lowest efforts are for "
724
+ f"easy work only. Never route a significant task there.",
725
+ "- For a specific task, run: `measure.py route --task \"...\"`.",
726
+ ]
727
+
728
+ if trends is None:
729
+ try:
730
+ trends = _measure_facade._collect_trends_data(days=30)
731
+ except Exception:
732
+ trends = None
733
+ try:
734
+ model_mix = (trends or {}).get("model_mix", {})
735
+ total = sum(model_mix.values()) if isinstance(model_mix, dict) else 0
736
+ if total:
737
+ top = ", ".join(f"{round(v / total * 100)}% {k}"
738
+ for k, v in sorted(model_mix.items(), key=lambda kv: -kv[1])[:3])
739
+ lines.append(f"- Your last 30 days: {top}.")
740
+ except Exception:
741
+ # Malformed trends never break the routing policy block.
742
+ pass
743
+
744
+ return "\n".join(lines)
745
+
746
+
747
+ def _dominant_turn_model(turns):
748
+ """Most frequent non-empty model id across a session's turns."""
749
+ _measure_facade = _compat.facade()
750
+ counts = {}
751
+ for t in turns:
752
+ m = t.get("model")
753
+ if m and not str(m).startswith("<"):
754
+ counts[m] = counts.get(m, 0) + 1
755
+ return max(counts, key=counts.get) if counts else None
756
+
757
+
758
+ def _detect_explicit_ttl(turns, tier_data, profile, dominant_model=None, detail_out=None):
759
+ """explicit_ttl detector: a gap > the profile's EFFECTIVE TTL followed by a
760
+ re-WRITE of the prior cached prefix is cache-expiry waste.
761
+
762
+ The detection boundary is per-profile (`effective_ttl_seconds`):
763
+ - anthropic_api: 300s (the live 5-min default; the user CAN raise it).
764
+ - claude_code: 3600s. Claude Code REQUESTS a 1-hour cache (v2.1.129 fixed
765
+ the silent downgrade to 5 min), and empirically the prefix survives
766
+ sub-hour pauses, so only pauses LONGER than the hour count as waste.
767
+
768
+ The "recoverable" value depends on the profile's `recoverable_kind`:
769
+ - recoverable_1h (anthropic_api): the honest 1h-cache_control counterfactual
770
+ — banks the avoidable repeat-write cost minus the 2x-vs-1.25x premium on
771
+ the first (unavoidable) write, floored at 0.
772
+ - avoidable_behavioral (claude_code): there is NO setting to extend the
773
+ cache; the only lever is behavioral (resume within the hour / batch
774
+ related work). The avoidable value is the full waste delta a within-hour
775
+ resume would have spared (read at 0.1x instead of re-writing). No
776
+ first-write premium is netted (Claude Code already writes at 1h rates).
777
+
778
+ Returns (wasted_tokens, wasted_cost_usd, recoverable_usd, had_waste).
779
+ """
780
+ _measure_facade = _compat.facade()
781
+ boundary = profile.get("effective_ttl_seconds")
782
+ # Default to the CONSERVATIVE kind: an unknown recoverable_kind must never
783
+ # inflate the recoverable claim (recoverable_1h is the most aggressive
784
+ # accounting). avoidable_behavioral books no 1h-cache_control counterfactual.
785
+ recoverable_kind = profile.get("recoverable_kind", "avoidable_behavioral")
786
+ # Only the recoverable_1h branch needs the repeat-write annuity + first-write
787
+ # accumulators; for any other kind they are computed and discarded, so gate
788
+ # their accumulation on that kind.
789
+ track_repeat_write = recoverable_kind == "recoverable_1h"
790
+ session_waste_tokens = 0
791
+ session_waste_cost = 0.0
792
+ session_repeat_write_cost = 0.0
793
+ first_write_tokens = 0
794
+ had = False
795
+
796
+ # Hoist the model->rate lookup out of the per-turn loop: the session is
797
+ # resolved to a single cache profile via its dominant model, so its rates are
798
+ # constant for the whole session. W5: the caller already resolved the
799
+ # dominant model (the same value used to pick this profile); reuse it instead
800
+ # of re-scanning every turn. Fall back to a local scan only if not supplied.
801
+ model = dominant_model if dominant_model is not None else _measure_facade._dominant_turn_model(turns)
802
+ rates = _measure_facade._claude_rates_for_model(model, tier_data)
803
+ if rates is None:
804
+ return 0, 0.0, 0.0, False
805
+ write_5m = rates.get("cache_write", rates.get("input", 3.0))
806
+ write_1h = rates.get("cache_write_1h", write_5m)
807
+ read_rate = rates.get("cache_read", rates.get("input", 3.0) * 0.1)
808
+ # No per-turn TTL split in the log: price the re-write at the profile's actual
809
+ # write rate. Claude Code holds a 1h cache (avoidable_behavioral -> write_1h);
810
+ # raw API/SDK runs at the 5m default (recoverable_1h -> write_5m).
811
+ default_write = write_1h if recoverable_kind == "avoidable_behavioral" else write_5m
812
+
813
+ prev = None
814
+ for turn in turns:
815
+ cc = int(turn.get("cache_creation", 0) or 0)
816
+ cc_1h = int(turn.get("cache_creation_1h", 0) or 0)
817
+ cc_5m = int(turn.get("cache_creation_5m", 0) or 0)
818
+ if track_repeat_write and cc > 0 and first_write_tokens == 0:
819
+ first_write_tokens = cc
820
+ if prev is not None:
821
+ gap = turn.get("gap_since_prev_seconds")
822
+ # Threshold basis is executor occupancy (#287); the dollars below
823
+ # stay on the billed aggregate `cc`.
824
+ prev_cached = _measure_facade._turn_prefix_cached(prev)
825
+ if (
826
+ gap is not None
827
+ and boundary is not None
828
+ and gap > boundary
829
+ and prev_cached > 0
830
+ and _measure_facade._turn_resume_write(turn) >= _measure_facade._CACHE_REWRITE_PREFIX_FRACTION * prev_cached
831
+ ):
832
+ if cc_1h or cc_5m:
833
+ split_1h = min(cc_1h, cc)
834
+ split_5m = max(0, cc - split_1h)
835
+ paid = (split_1h * write_1h + split_5m * write_5m) / 1e6
836
+ else:
837
+ paid = cc * default_write / 1e6
838
+ avoided_read = cc * read_rate / 1e6
839
+ session_waste_tokens += cc
840
+ session_waste_cost += max(0.0, paid - avoided_read)
841
+ if track_repeat_write:
842
+ session_repeat_write_cost += cc * write_5m / 1e6
843
+ had = True
844
+ if detail_out is not None and gap > detail_out.get("max_gap", 0):
845
+ detail_out["max_gap"] = gap # W8: widest waste-triggering gap
846
+ prev = turn
847
+
848
+ recoverable = 0.0
849
+ if had:
850
+ if recoverable_kind == "recoverable_1h":
851
+ # 1h-cache_control counterfactual (anthropic_api only): repeat writes
852
+ # avoided, less the 2x-vs-1.25x premium on the first write.
853
+ first_premium = 0.0
854
+ if first_write_tokens > 0:
855
+ first_premium = first_write_tokens * (write_1h - write_5m) / 1e6
856
+ recoverable = max(0.0, session_repeat_write_cost - first_premium)
857
+ else:
858
+ # avoidable_behavioral (claude_code): no TTL setting to buy back the
859
+ # waste; a within-the-hour resume would have spared the whole delta.
860
+ recoverable = session_waste_cost
861
+ return session_waste_tokens, session_waste_cost, recoverable, had
862
+
863
+
864
+ def _detect_automatic_collapse(turns, profile, dominant_model=None, detail_out=None):
865
+ """automatic_discount / explicit_storage detector (OpenAI, Gemini, code review).
866
+
867
+ These providers never emit a cache-CREATION event; the cache is automatic and
868
+ cached reads are discounted. Expiry shows up as a COLLAPSE in the cached/prompt
869
+ ratio: turn N has a healthy cached ratio, the gap to turn N+1 exceeds the
870
+ profile TTL, and turn N+1's cached ratio collapses while its prompt size stays
871
+ comparable. The collapsed (lost) cached tokens are re-billed at the FULL input
872
+ rate instead of the discounted cached rate.
873
+
874
+ waste_cost = lost_cached_tokens * (input_rate - cached_rate).
875
+ For these providers the recoverable value EQUALS the waste cost (resuming
876
+ within the cache window would have avoided the full premium; there is no
877
+ extra-write premium to net out as in the explicit_ttl 1h counterfactual).
878
+
879
+ Returns (wasted_tokens, wasted_cost_usd, recoverable_usd, had_waste).
880
+ """
881
+ _measure_facade = _compat.facade()
882
+ ttl = profile.get("effective_ttl_seconds") or 300
883
+ session_waste_tokens = 0
884
+ session_waste_cost = 0.0
885
+ had = False
886
+
887
+ prev = None
888
+ for turn in turns:
889
+ cr = int(turn.get("cache_read", 0) or 0)
890
+ inp = int(turn.get("input_tokens", 0) or 0) # total billed input (incl. cached)
891
+ prompt = max(inp, cr) # turn's prompt size (input_tokens already includes cached)
892
+ ratio = (cr / prompt) if prompt > 0 else 0.0
893
+ if prev is not None:
894
+ gap = turn.get("gap_since_prev_seconds")
895
+ # Codex turns carry timestamps but not a precomputed gap; derive it.
896
+ if gap is None:
897
+ gap = _measure_facade._gap_seconds(prev.get("timestamp"), turn.get("timestamp"))
898
+ prev_cr = int(prev.get("cache_read", 0) or 0)
899
+ prev_inp = int(prev.get("input_tokens", 0) or 0)
900
+ prev_prompt = max(prev_inp, prev_cr)
901
+ prev_ratio = (prev_cr / prev_prompt) if prev_prompt > 0 else 0.0
902
+ if (
903
+ gap is not None
904
+ and gap > ttl
905
+ and prev_ratio >= _measure_facade._CACHE_COLLAPSE_HEALTHY_RATIO
906
+ and ratio < _measure_facade._CACHE_COLLAPSE_THRESHOLD_RATIO
907
+ and prompt >= _measure_facade._CACHE_COLLAPSE_PROMPT_COMPARABLE_FRACTION * prev_prompt
908
+ ):
909
+ # Lost cached tokens = what WOULD have been cached at the prior
910
+ # healthy ratio but now reads as fresh input.
911
+ # W1: the recoverable cached prefix can never exceed what the
912
+ # PREVIOUS turn actually had cached (prev_cr). prev_ratio*prompt
913
+ # extrapolates the prior hit-rate onto this (possibly larger)
914
+ # turn, which can overstate the lost volume when the prompt grew;
915
+ # cap at the real prior cached volume so waste stays grounded.
916
+ lost = min(int(prev_ratio * prompt) - cr, prev_cr)
917
+ if lost > 0:
918
+ # W2: turns may omit `model` (e.g. a tool-result-only turn);
919
+ # fall back to the session's dominant model for rate lookup
920
+ # so the rate is found instead of the pair being dropped.
921
+ rr = _measure_facade._input_and_cached_read_rates(turn.get("model") or dominant_model)
922
+ if rr is not None:
923
+ input_rate, cached_rate = rr
924
+ premium = lost * (input_rate - cached_rate) / 1e6
925
+ session_waste_tokens += lost
926
+ session_waste_cost += max(0.0, premium)
927
+ had = True
928
+ if detail_out is not None and gap > detail_out.get("max_gap", 0):
929
+ detail_out["max_gap"] = gap # W8: widest collapse gap
930
+ prev = turn
931
+
932
+ # For automatic-discount providers, recoverable == waste (no extra-write
933
+ # premium to net out; staying within the window avoids the whole delta).
934
+ return session_waste_tokens, session_waste_cost, session_waste_cost, had
935
+
936
+
937
+ def _gap_seconds(ts_a, ts_b):
938
+ """Seconds between two ISO/epoch timestamps, or None if unparseable."""
939
+ _measure_facade = _compat.facade()
940
+ def _parse(ts):
941
+ _measure_facade = _compat.facade()
942
+ if ts is None:
943
+ return None
944
+ if isinstance(ts, (int, float)):
945
+ return float(ts)
946
+ s = str(ts).strip()
947
+ if not s:
948
+ return None
949
+ try:
950
+ if s.endswith("Z"):
951
+ s = s[:-1] + "+00:00"
952
+ dt = _measure_facade.datetime.fromisoformat(s)
953
+ # W3: a tz-NAIVE ISO timestamp would otherwise be interpreted in the
954
+ # host's LOCAL zone by .timestamp(), so two naive stamps compared
955
+ # across a DST shift (or on a non-UTC host) would yield a wrong gap.
956
+ # Force UTC for naive values; aware values keep their own offset.
957
+ if dt.tzinfo is None:
958
+ dt = dt.replace(tzinfo=_measure_facade.timezone.utc)
959
+ return dt.timestamp()
960
+ except ValueError:
961
+ try:
962
+ return float(s)
963
+ except ValueError:
964
+ return None
965
+ a = _parse(ts_a)
966
+ b = _parse(ts_b)
967
+ if a is None or b is None:
968
+ return None
969
+ return abs(b - a)
970
+
971
+
972
+ def _cache_remedy_text(remedy_key):
973
+ """Return the verified, per-profile cache remedy text.
974
+
975
+ Verified 2026-06-11 against current public docs (Anthropic prompt-caching,
976
+ Claude Code CHANGELOG, OpenAI prompt-caching, Gemini context-caching,
977
+ code review context-caching). Each remedy reflects exactly what that provider
978
+ actually offers — no overclaiming.
979
+ """
980
+ _measure_facade = _compat.facade()
981
+ remedies = {
982
+ "anthropic_api": (
983
+ 'Anthropic API/SDK/agent harness: set cache_control '
984
+ '{"type":"ephemeral","ttl":"1h"} on stable prefixes. 1h write costs 2x '
985
+ "input once, then reads at 0.1x — cheaper than re-writing every 5min."
986
+ ),
987
+ "claude_code": (
988
+ "Claude Code already holds a 1-hour cache. Waste comes from pauses "
989
+ "longer than an hour: resuming within the hour keeps the prefix warm. "
990
+ "No setting can extend this further today."
991
+ ),
992
+ "openai": (
993
+ "OpenAI/Codex prompt caching is automatic (~5-10min inactivity, max ~1h) "
994
+ "with NO TTL knob below the policy level. Behavioral remedy: keep the "
995
+ "prompt PREFIX stable (exact-match, >=1024 tokens) and resume within the "
996
+ "window. For long-lived prefixes set prompt_cache_retention=\"24h\"."
997
+ ),
998
+ "gemini": (
999
+ "Gemini 2.5+ has automatic implicit caching (no knob). For long stable "
1000
+ "contexts, use EXPLICIT context caching: create a cached_content resource "
1001
+ "with a user-set ttl (default 1h) — note per-hour storage is billed for "
1002
+ "the cached tokens, so size the TTL to your reuse pattern."
1003
+ ),
1004
+ "deepseek": (
1005
+ "code review Context Caching on Disk is automatic (no knob); cache hits cost "
1006
+ "1/10 of input. Keep prompt prefixes stable and reuse them promptly while "
1007
+ "the on-disk cache is warm (it clears within hours-to-days of disuse)."
1008
+ ),
1009
+ "none": (
1010
+ "This model has no prompt cache; prefix churn does not affect its cost. "
1011
+ "There is no cache-TTL waste to remedy here."
1012
+ ),
1013
+ }
1014
+ return remedies.get(remedy_key, remedies["none"])
1015
+
1016
+
1017
+ def _cache_coverage_gaps(runtime):
1018
+ """Return the explicit not-measurable coverage-gap list (parity rule).
1019
+
1020
+ Each entry: {platform, measurable, reason}. Platforms whose per-turn cache +
1021
+ timestamp data the Python engine cannot read are honestly listed here rather
1022
+ than silently dropped. A platform that is wired for measurement
1023
+ (_CACHE_WIRED_RUNTIMES) or is the active runtime is omitted — so a wired
1024
+ platform can never be both measured and listed as a gap.
1025
+ """
1026
+ _measure_facade = _compat.facade()
1027
+ return [
1028
+ {"platform": platform, "measurable": False, "reason": reason}
1029
+ for platform, reason in _measure_facade._CACHE_COVERAGE_GAP_REASONS.items()
1030
+ if platform != runtime and platform not in _measure_facade._CACHE_WIRED_RUNTIMES
1031
+ ]
1032
+
1033
+
1034
+ def _session_mix_class_terms(rate_class, *model_usage_blobs):
1035
+ """(terms, unpriced_share) for ONE session's own token-weighted model usage at
1036
+ one token class, or None when no usable usage is present.
1037
+
1038
+ *terms* is [(share, usd_per_mtok)] for every model id with an exact rate card
1039
+ (any provider); *unpriced_share* is the share of the session's recorded tokens
1040
+ held by ids with no exact card. *rate_class* is a key of _routing_class_rates
1041
+ ("fresh_input", "output", "cache_create_1h", ...). Each id is priced at its
1042
+ own generation card (Opus 5.5 is not the Opus family rate); an id without an
1043
+ exact card contributes no term and is never borrowed from a family.
1044
+
1045
+ Shares are taken over the session's TOTAL recorded tokens, so a priced sliver
1046
+ is never inflated to stand for the whole mix. The caller prices the unpriced
1047
+ share at zero and discloses it.
1048
+
1049
+ Blobs are tried in order (model_usage_json, then all_model_usage_json); the
1050
+ first that parses to a non-empty dict wins. Never raises.
1051
+ """
1052
+ _measure_facade = _compat.facade()
1053
+ raw = None
1054
+ for blob in model_usage_blobs:
1055
+ if not blob:
1056
+ continue
1057
+ try:
1058
+ data = _measure_facade.json.loads(blob)
1059
+ except (_measure_facade.json.JSONDecodeError, TypeError, ValueError):
1060
+ continue
1061
+ if isinstance(data, dict) and data:
1062
+ raw = data
1063
+ break
1064
+ if not raw:
1065
+ return None
1066
+ total = 0.0
1067
+ weights = {}
1068
+ for key, val in raw.items():
1069
+ try:
1070
+ val = float(val)
1071
+ except (TypeError, ValueError):
1072
+ continue
1073
+ if val <= 0 or not isinstance(key, str) or key.startswith("<"):
1074
+ continue
1075
+ weights[key] = weights.get(key, 0.0) + val
1076
+ total += val
1077
+ if total <= 0:
1078
+ return None
1079
+ terms = []
1080
+ priced = 0.0
1081
+ for key, val in weights.items():
1082
+ rates = _measure_facade._routing_class_rates(key)
1083
+ rate = (rates or {}).get(rate_class)
1084
+ if rate:
1085
+ terms.append((val / total, float(rate)))
1086
+ priced += val
1087
+ return terms, max(0.0, 1.0 - priced / total)
1088
+
1089
+
1090
+ def _stored_model_is_unpriced(model):
1091
+ """True when a savings row records a model id that has no exact rate card.
1092
+ Rate-card keys and bare family labels ("opus", "sonnet_4_5") are known; a row
1093
+ with no model, or a known one, is not unpriced."""
1094
+ _measure_facade = _compat.facade()
1095
+ if not isinstance(model, str) or not model.strip():
1096
+ return False
1097
+ if _measure_facade._routing_card_exact(model):
1098
+ return False
1099
+ try:
1100
+ cards = _measure_facade.PRICING_TIERS.get(_measure_facade._load_pricing_tier(), _measure_facade.PRICING_TIERS["anthropic"])["claude_models"]
1101
+ except Exception:
1102
+ cards = {}
1103
+ return model not in cards
1104
+
1105
+
1106
+ def _session_model_reprice(conn, cutoff, session_uuid=None, by_day=None, unpriced_out=None):
1107
+ """Per-event_type USD correction from repricing savings_events at each event's
1108
+ OWN session model mix. Returns (deltas_by_event_type, repriced_tokens,
1109
+ unmeasured_tokens). With *session_uuid* only that session's rows count; with
1110
+ *by_day* the deltas are keyed (local YYYY-MM-DD, event_type). When
1111
+ *unpriced_out* is a dict, ``unpriced_out["tokens"]`` accumulates the saved
1112
+ tokens that belong to models with no exact rate card.
1113
+
1114
+ THE DEFECT THIS REPAIRS. _log_savings_event stamps every row with
1115
+ _resolve_session_model(), which falls back to "sonnet" whenever the session
1116
+ JSONL cannot be read (sub-agent / sidechain sessions, sessions still open when
1117
+ the event is written); older rows carry model IS NULL and are priced at the
1118
+ flat _estimate_compression_cost_per_mtok fallback. Measured on the real ledger
1119
+ (30d, 2026-08-29): 18.9M saved tokens carry model IS NULL and 13.9M carry
1120
+ model='sonnet', while the session_log rows they join to record 17.8M and 4.6M
1121
+ of those same tokens inside sessions whose OWN token-weighted usage is Opus.
1122
+ The rate card is correct; the per-row model stamp is not.
1123
+
1124
+ WHAT THIS DELIBERATELY IS NOT. It is not a reprice to the WINDOW's blended
1125
+ model mix. That would lift a saving made inside a session Token Optimizer had
1126
+ routed to a cheaper model up to an Opus-heavy window average, claiming the
1127
+ routing win a second time inside the context pool -- and
1128
+ _compute_model_routing_savings already owns that delta for the tokens that
1129
+ WERE sent. Pricing each event against its own session keeps the two pools
1130
+ disjoint by construction: a genuinely-Sonnet session stays at the Sonnet rate.
1131
+
1132
+ HONESTY BOUNDARY. session_log.model_usage_json is a measured column (real
1133
+ token counts), but attributing one never-sent saving to a session's blended
1134
+ rate is an ALLOCATION, not a measurement -- we cannot know which turn's model
1135
+ would have carried tokens that were never sent. So the corrected figure is
1136
+ labelled "estimated" wherever it surfaces (see _window_overage_usd), and rows
1137
+ that cannot be joined to a session are NOT MEASURED: they keep their
1138
+ event-time price and are counted separately rather than guessed at.
1139
+
1140
+ UNPRICED MODELS. The share of a session's tokens that ran on a model with no
1141
+ exact rate card (a local or third-party model, a generation without a card) is
1142
+ priced at zero, not at the Sonnet stand-in the event writer stamped. Those
1143
+ tokens are reported through *unpriced_out*. Stored rows are never changed.
1144
+
1145
+ Degrades to ({}, 0, 0) on any schema or query problem. An older DB without
1146
+ session_uuid / model_usage_json simply does not get the repair; a schema error
1147
+ must never be allowed to reach the caller's blanket handler and zero out the
1148
+ whole savings summary (that failure mode vanished an entire dashboard card on
1149
+ 2026-08-28).
1150
+ """
1151
+ _measure_facade = _compat.facade()
1152
+ deltas, repriced_tokens, unmeasured_tokens = {}, 0, 0
1153
+ try:
1154
+ se_cols = {r[1] for r in conn.execute("PRAGMA table_info(savings_events)").fetchall()}
1155
+ sl_cols = {r[1] for r in conn.execute("PRAGMA table_info(session_log)").fetchall()}
1156
+ if "session_uuid" not in se_cols or "session_uuid" not in sl_cols:
1157
+ return {}, 0, 0
1158
+ # by_day / session_uuid serve the status-bar buckets. The delta is linear
1159
+ # in (tokens, cost) per session, so splitting by local day sums back to
1160
+ # exactly the window delta.
1161
+ params = [cutoff]
1162
+ if session_uuid is not None:
1163
+ # Same rows as the savings buckets (non-UUID ids live in session_id).
1164
+ # Those rows have no session_uuid to join, so they stay unmeasured here.
1165
+ params.extend([session_uuid, session_uuid])
1166
+ reprice_sql = _measure_facade._REPRICE_SQL[(
1167
+ _measure_facade._counted_table(conn, "savings_events"),
1168
+ "model_usage_json" in sl_cols,
1169
+ "all_model_usage_json" in sl_cols,
1170
+ bool(by_day),
1171
+ session_uuid is not None,
1172
+ "model" in se_cols,
1173
+ )]
1174
+ rows = conn.execute(reprice_sql, tuple(params)).fetchall()
1175
+ except (_measure_facade.sqlite3.Error, TypeError, ValueError):
1176
+ return {}, 0, 0
1177
+ for day, event_type, tok, cost, mu_json, amu_json, row_model in rows:
1178
+ if event_type in _measure_facade._REPRICE_SKIP_EVENT_TYPES:
1179
+ continue # non-input-rate class; keep the event-time price verbatim
1180
+ try:
1181
+ tok = int(tok or 0)
1182
+ except (TypeError, ValueError):
1183
+ continue
1184
+ if tok <= 0:
1185
+ # Zero-token markers (nudges) and debit rows carry no rate to correct.
1186
+ continue
1187
+ mix = _measure_facade._session_mix_class_terms(
1188
+ _measure_facade._EVENT_RATE_CLASS.get(event_type, "fresh_input"), mu_json, amu_json)
1189
+ if mix is None and _measure_facade._stored_model_is_unpriced(row_model):
1190
+ # No session match, but the row itself names a model with no rate
1191
+ # card: its dollars are priced at zero and the tokens disclosed.
1192
+ key = (day, event_type) if by_day else event_type
1193
+ if cost:
1194
+ deltas[key] = deltas.get(key, 0.0) - float(cost)
1195
+ if unpriced_out is not None:
1196
+ unpriced_out["tokens"] = unpriced_out.get("tokens", 0) + tok
1197
+ continue
1198
+ if mix is None:
1199
+ unmeasured_tokens += tok
1200
+ continue
1201
+ terms, unpriced_share = mix
1202
+ # The priced share is charged at each model's own card; the unpriced share
1203
+ # is charged nothing. The delta moves the stored cost to that total.
1204
+ new_cost = sum(sh * rate for sh, rate in terms) * tok / 1_000_000.0
1205
+ delta = new_cost - float(cost or 0.0)
1206
+ if unpriced_out is not None and unpriced_share > 0:
1207
+ unpriced_out["tokens"] = unpriced_out.get("tokens", 0) + tok * unpriced_share
1208
+ if delta:
1209
+ key = (day, event_type) if by_day else event_type
1210
+ deltas[key] = deltas.get(key, 0.0) + delta
1211
+ repriced_tokens += tok
1212
+ return deltas, repriced_tokens, unmeasured_tokens
1213
+
1214
+
1215
+ def _model_mix_shares(days=None, since=None):
1216
+ """Return {model: share_fraction} of total tokens over the window, + total.
1217
+
1218
+ Reads model_daily (per-day per-model token totals). Shares sum to ~1.0.
1219
+ Returns {"shares": {...}, "total_tokens": int, "days": days} or empty shares
1220
+ when there is no data. Never raises.
1221
+
1222
+ When *since* is a non-empty ISO-8601 timestamp, its DATE part is used as the
1223
+ cutoff (``date >= since_date``) instead of the rolling ``now - days``. This
1224
+ aligns the routing mix to an external boundary (the subscription limit
1225
+ reset) so the routing dollar figure scopes to the same window as the context
1226
+ figure. model_daily is day-granular, so alignment is to the reset DAY (the
1227
+ finest this table supports); sub-day precision is not available here.
1228
+ """
1229
+ _measure_facade = _compat.facade()
1230
+ out = {"shares": {}, "total_tokens": 0, "days": days}
1231
+ try:
1232
+ if not _measure_facade.TRENDS_DB.exists():
1233
+ return out
1234
+ if since:
1235
+ cutoff = str(since)[:10] # date part of the ISO timestamp
1236
+ else:
1237
+ cutoff = (_measure_facade.datetime.now() - _measure_facade.timedelta(days=days)).strftime("%Y-%m-%d")
1238
+ conn = _measure_facade._init_trends_db()
1239
+ try:
1240
+ out["activity_coverage"] = _measure_facade.activity_coverage(conn)
1241
+ rows = conn.execute(
1242
+ "SELECT model, COALESCE(SUM(total_tokens),0) FROM model_daily "
1243
+ "WHERE date >= ? GROUP BY model",
1244
+ (cutoff,),
1245
+ ).fetchall()
1246
+ finally:
1247
+ conn.close()
1248
+ total = sum(int(r[1] or 0) for r in rows)
1249
+ if total <= 0:
1250
+ return out
1251
+ out["shares"] = {r[0]: (int(r[1] or 0) / total) for r in rows if r[0]}
1252
+ out["total_tokens"] = total
1253
+ except (_measure_facade.sqlite3.Error, OSError):
1254
+ pass
1255
+ return out
1256
+
1257
+
1258
+ def _default_model_for_runtime():
1259
+ """Representative model id to price a session against when the era's model mix
1260
+ has no priced entries at all. Runtime-aware so a Codex user is never priced at
1261
+ Anthropic rates (and vice versa)."""
1262
+ _measure_facade = _compat.facade()
1263
+ return "gpt-5-codex" if _measure_facade.detect_runtime() == "codex" else "sonnet"
1264
+
1265
+
1266
+ def _friendly_model(model):
1267
+ """Human label for a model id: 'opus' -> 'Opus', 'gpt-5.2-codex' -> 'GPT-5.2-Codex'."""
1268
+ _measure_facade = _compat.facade()
1269
+ m = _measure_facade._strip_provider_prefixes(str(model or "")) or str(model or "")
1270
+ if m in ("opus", "sonnet", "haiku"):
1271
+ return m.capitalize()
1272
+ if m.startswith("gpt-") or m.startswith("o3") or m.startswith("o4"):
1273
+ return m.upper().replace("CODEX", "Codex").replace("MINI", "mini").replace("NANO", "nano").replace("PRO", "Pro")
1274
+ return m
1275
+
1276
+
1277
+ def _mix_label(shares):
1278
+ """Short label for a model mix: the dominant model + its share, e.g. '95% Opus'
1279
+ or '62% GPT-5.2-Codex'. Provider-agnostic display string. 'mixed' when empty."""
1280
+ _measure_facade = _compat.facade()
1281
+ priced = {m: s for m, s in (shares or {}).items() if s and s > 0}
1282
+ if not priced:
1283
+ return "mixed"
1284
+ top, share = max(priced.items(), key=lambda kv: kv[1])
1285
+ return f"{round(share * 100)}% {_measure_facade._friendly_model(top)}"
1286
+
1287
+
1288
+ def _model_rate_per_mtok(model):
1289
+ """Conservative $/MTok proxy for a model: its input rate.
1290
+
1291
+ model_daily.total_tokens mixes input/cache/output, so this UNDERSTATES true
1292
+ cost (output is up to 5x input). Using the input rate keeps routing savings
1293
+ conservative and defensible. Returns 0.0 for unpriced models.
1294
+ """
1295
+ _measure_facade = _compat.facade()
1296
+ try:
1297
+ return _measure_facade._get_model_cost(model, 1_000_000, 0) # input-only -> $/MTok input
1298
+ except Exception:
1299
+ return 0.0
1300
+
1301
+
1302
+ def _model_output_rate_per_mtok(model):
1303
+ """$/MTok OUTPUT rate for a model (e.g. Opus $25 vs Sonnet $5). 0.0 if unpriced."""
1304
+ _measure_facade = _compat.facade()
1305
+ try:
1306
+ return _measure_facade._get_model_cost(model, 0, 1_000_000) # output-only -> $/MTok output
1307
+ except Exception:
1308
+ return 0.0
1309
+
1310
+
1311
+ def _session_output_fraction(days=None):
1312
+ """Measured OUTPUT share of the FRESH-rate token mix, from the user's session_log.
1313
+
1314
+ Returns SUM(output) / SUM(fresh_input + output) over the window, clamped to
1315
+ [0, 1]. The denominator deliberately EXCLUDES cache-read and cache-creation
1316
+ tokens: those are priced separately at their own (cheap) cache rates, so the
1317
+ blend here only governs the split between FRESH input and output — the two
1318
+ classes that share the full input/output rate axis. Using total input_tokens
1319
+ (which is dominated by cache-read) as the denominator collapsed this fraction
1320
+ to ~0.5% and made the blended rate effectively the input rate, understating
1321
+ routing savings ~3x. Fresh input and output are taken from _session_token_vector
1322
+ so the negative-fresh clamp is applied consistently. Grounded in the user's OWN
1323
+ data, never an invented multiplier. Returns 0.0 (input-only, conservative) when
1324
+ there is no usable history.
1325
+ """
1326
+ _measure_facade = _compat.facade()
1327
+ try:
1328
+ if not _measure_facade.TRENDS_DB.exists():
1329
+ return 0.0
1330
+ cutoff = (_measure_facade.datetime.now() - _measure_facade.timedelta(days=days)).strftime("%Y-%m-%d")
1331
+ conn = _measure_facade._init_trends_db()
1332
+ _measure_facade.ensure_activity_view(conn)
1333
+ try:
1334
+ # Quality filter removed (audit 2026-08-29): this is a
1335
+ # volume-weighted metric (SUM(output)/SUM(fresh+output)), so
1336
+ # gating by count is irrelevant. Short sessions with real output
1337
+ # tokens must be included.
1338
+ rows = conn.execute(
1339
+ "SELECT input_tokens, output_tokens, cache_create_5m_tokens, "
1340
+ "cache_create_1h_tokens, cache_hit_rate FROM session_activity "
1341
+ "WHERE input_tokens IS NOT NULL AND date >= ? "
1342
+ "AND COALESCE(is_sidechain, 0) = 0",
1343
+ (cutoff,),
1344
+ ).fetchall()
1345
+ finally:
1346
+ conn.close()
1347
+ fresh_total = 0.0
1348
+ out_total = 0.0
1349
+ for r in rows:
1350
+ fi, _cw, _cr, out = _measure_facade._session_token_vector(r)
1351
+ fresh_total += fi
1352
+ out_total += out
1353
+ denom = fresh_total + out_total
1354
+ if denom <= 0:
1355
+ return 0.0
1356
+ return max(0.0, min(1.0, out_total / denom))
1357
+ except (_measure_facade.sqlite3.Error, OSError):
1358
+ return 0.0
1359
+
1360
+
1361
+ def _foreign_savings_card_exact(model):
1362
+ """Accept rate-card IDs and dated snapshots, without arbitrary suffixes."""
1363
+ _measure_facade = _compat.facade()
1364
+ value = _measure_facade.re.sub(r"[\s_]+", "-", _measure_facade._strip_provider_prefixes(model))
1365
+ base = _measure_facade.re.sub(r"-\d{4}-\d{2}-\d{2}$", "", value)
1366
+ if base == "gpt-5.6":
1367
+ return True
1368
+ return base in _measure_facade.OPENAI_MODEL_PRICING or base in _measure_facade.GEMINI_MODEL_PRICING
1369
+
1370
+
1371
+ def _routing_card_exact(model):
1372
+ """True when `model` resolves to an exact rate card.
1373
+
1374
+ A Claude id names a generation (claude-opus-5-5, claude-sonnet-4-6) and is
1375
+ exact only when that generation's own card exists. An id whose generation has
1376
+ no card (claude-opus-99, claude-opus-5-99) would otherwise fall back to a
1377
+ broader card, such as the Opus 5 card or the bare family rate; that is a
1378
+ stand-in, not a known price. Sonnet 3, 3.5 and 3.7 ids are the verified
1379
+ aliases of the legacy Sonnet card. A bare family label ("opus",
1380
+ "sonnet_legacy") with no generation is priced at its family card.
1381
+ """
1382
+ _measure_facade = _compat.facade()
1383
+ if not isinstance(model, str) or not model:
1384
+ return False
1385
+ if _measure_facade._normalize_openai_model_name(model) or _measure_facade._normalize_gemini_model_name(model):
1386
+ return _measure_facade._foreign_savings_card_exact(model)
1387
+ try:
1388
+ cards = dict(_measure_facade.PRICING_TIERS["anthropic"]["claude_models"])
1389
+ cards.update(_measure_facade.PRICING_TIERS.get(_measure_facade._load_pricing_tier(), {}).get("claude_models", {}))
1390
+ except Exception:
1391
+ return False
1392
+ low = model.lower()
1393
+ legacy = _measure_facade._CLAUDE_LEGACY_ID_RE.search(low)
1394
+ if legacy:
1395
+ major, minor, family = legacy.groups()
1396
+ if major == "3" and family == "sonnet" and minor in (None, "5", "7"):
1397
+ return "sonnet_legacy" in cards
1398
+ family_major = f"{family}_{major}"
1399
+ else:
1400
+ generation = _measure_facade._CLAUDE_GENERATION_RE.search(low)
1401
+ if not generation:
1402
+ key = _measure_facade._claude_price_key(model, cards)
1403
+ return bool(key and key in cards)
1404
+ family, major, minor = generation.groups()
1405
+ family = "fable" if family == "mythos" else family
1406
+ family_major, minor = f"{family}_{major}", minor
1407
+ return (family_major + (f"_{minor}" if minor else "")) in cards
1408
+ key = family_major + (f"_{minor}" if minor else "")
1409
+ return key in cards
1410
+
1411
+
1412
+ def _routing_model_status(model):
1413
+ """"priced" (exact rate card), "free" (a provider's explicitly free tier,
1414
+ id suffix ":free") or "unpriced" (no rate card, price unknown)."""
1415
+ _measure_facade = _compat.facade()
1416
+ if _measure_facade._routing_card_exact(model):
1417
+ return "priced"
1418
+ if isinstance(model, str) and model.lower().endswith(":free"):
1419
+ return "free"
1420
+ return "unpriced"
1421
+
1422
+
1423
+ def _routing_class_rates(model):
1424
+ """$/MTok per token class for one model id, from its own generation card.
1425
+
1426
+ Probes _get_model_cost so every provider and generation card
1427
+ (Opus 5.5 $4/$20, Opus 4.1 $15/$75, Sonnet 5.5 cache reads $0.10, ...)
1428
+ prices exactly as the rest of the product does. Returns None unless the id has
1429
+ an exact rate card (see _routing_model_status): an unknown model is not free
1430
+ and a missing generation is not its family's price, so callers leave such a
1431
+ model out of a comparison instead of pricing it at zero or at a stand-in rate.
1432
+ """
1433
+ # Family pseudo-ids from the model-daily mix; a bare "sonnet_legacy" would
1434
+ # otherwise resolve to the current Sonnet card.
1435
+ _measure_facade = _compat.facade()
1436
+ probe = "claude-sonnet-4-6" if model == "sonnet_legacy" else model
1437
+ if not _measure_facade._routing_card_exact(probe):
1438
+ return None
1439
+ try:
1440
+ m = 1
1441
+ rates = {
1442
+ "fresh_input": _measure_facade._get_model_cost(probe, m, 0),
1443
+ "output": _measure_facade._get_model_cost(probe, 0, m),
1444
+ "cache_read": _measure_facade._get_model_cost(probe, 0, 0, m),
1445
+ "cache_create_5m": _measure_facade._get_model_cost(probe, 0, 0, 0, m, cache_create_1h=0, cache_create_5m=m),
1446
+ "cache_create_1h": _measure_facade._get_model_cost(probe, 0, 0, 0, m, cache_create_1h=m, cache_create_5m=0),
1447
+ }
1448
+ rates = {key: value * 1_000_000 for key, value in rates.items()}
1449
+ except Exception:
1450
+ return None
1451
+ if not any(v > 0 for v in rates.values()):
1452
+ return None
1453
+ # Rows without a class split are priced at the input rate (conservative).
1454
+ rates["unsplit"] = rates["fresh_input"]
1455
+ return rates
1456
+
1457
+
1458
+ def _newest_generation_model(family):
1459
+ """Model id of the newest generation card of a Claude family in the active
1460
+ rate table, or None. Legacy Sonnet cards are not generation cards."""
1461
+ _measure_facade = _compat.facade()
1462
+ try:
1463
+ tier = _measure_facade._load_pricing_tier()
1464
+ cards = _measure_facade.PRICING_TIERS.get(tier, _measure_facade.PRICING_TIERS["anthropic"])["claude_models"]
1465
+ best = None
1466
+ for key in cards:
1467
+ m = _measure_facade._GENERATION_KEY_RE.match(key)
1468
+ if m and m.group(1) == family:
1469
+ gen = (int(m.group(2)), int(m.group(3) or 0))
1470
+ if best is None or gen > best[0]:
1471
+ best = (gen, key)
1472
+ if best:
1473
+ major, minor = best[0]
1474
+ return f"claude-{family}-{major}-{minor}" if best[1].count("_") == 2 else f"claude-{family}-{major}"
1475
+ except Exception:
1476
+ pass
1477
+ return None
1478
+
1479
+
1480
+ def _routing_target_model():
1481
+ """Model id of the lighter arm routing is priced against: the newest Sonnet
1482
+ generation card in the active rate table."""
1483
+ _measure_facade = _compat.facade()
1484
+ return _measure_facade._newest_generation_model("sonnet") or "sonnet"
1485
+
1486
+
1487
+ def _routing_reference_model(family):
1488
+ """The model id whose card values a family in the standardized routing
1489
+ comparison, in both arms: the newest generation card of its tier (legacy
1490
+ Sonnet is valued as Sonnet). Other labels (provider models) stand for
1491
+ themselves."""
1492
+ _measure_facade = _compat.facade()
1493
+ if family == "sonnet_legacy":
1494
+ family = "sonnet"
1495
+ return _measure_facade._newest_generation_model(family) or family
1496
+
1497
+
1498
+ def _bucket_int(value):
1499
+ _measure_facade = _compat.facade()
1500
+ try:
1501
+ return max(0, int(value or 0))
1502
+ except (TypeError, ValueError):
1503
+ return 0
1504
+
1505
+
1506
+ def _add_routing_buckets(dst, parts):
1507
+ """Add one per-model usage bucket ({fresh_input, cache_read, cache_create,
1508
+ cache_create_1h, cache_create_5m, output}) into class totals. Cache writes
1509
+ without a TTL split are priced at the 5-minute rate, as _get_model_cost does."""
1510
+ _measure_facade = _compat.facade()
1511
+ cc = _measure_facade._bucket_int(parts.get("cache_create"))
1512
+ h1 = _measure_facade._bucket_int(parts.get("cache_create_1h"))
1513
+ m5 = _measure_facade._bucket_int(parts.get("cache_create_5m"))
1514
+ m5 += max(0, cc - h1 - m5)
1515
+ dst["fresh_input"] = dst.get("fresh_input", 0) + _measure_facade._bucket_int(parts.get("fresh_input"))
1516
+ dst["cache_read"] = dst.get("cache_read", 0) + _measure_facade._bucket_int(parts.get("cache_read"))
1517
+ dst["output"] = dst.get("output", 0) + _measure_facade._bucket_int(parts.get("output"))
1518
+ dst["cache_create_1h"] = dst.get("cache_create_1h", 0) + h1
1519
+ dst["cache_create_5m"] = dst.get("cache_create_5m", 0) + m5
1520
+
1521
+
1522
+ def _routing_pending_sessions(days=None, since=None):
1523
+ """Window sessions whose usage collect has not finished re-reading.
1524
+
1525
+ A row counts when its transcript is still on disk and either its per-day
1526
+ usage is missing (the daily-usage backfill rebuilds it) or, for a Claude
1527
+ Code transcript under the projects folder that collect walks, it was parsed
1528
+ by an older usage parser (collect re-parses it). A row whose transcript is
1529
+ gone keeps its stored numbers and never counts. Pending is scoped to the
1530
+ requested window: a record whose KNOWN last activity day predates the
1531
+ cutoff holds no in-window work, while a record with no dated evidence at
1532
+ all stays conservatively pending (review A6). Never raises; 0 on error."""
1533
+ _measure_facade = _compat.facade()
1534
+ try:
1535
+ if not _measure_facade.TRENDS_DB.exists():
1536
+ return 0
1537
+ cutoff = str(since)[:10] if since else (_measure_facade.datetime.now() - _measure_facade.timedelta(days=days)).strftime("%Y-%m-%d")
1538
+ conn = _measure_facade._init_trends_db()
1539
+ try:
1540
+ columns = {r[1] for r in conn.execute("PRAGMA table_info(session_log)").fetchall()}
1541
+ has_version = "usage_parser_version" in columns
1542
+ last_activity = (
1543
+ "COALESCE(NULLIF(last_activity_day, ''), NULLIF(date, ''))"
1544
+ if "last_activity_day" in columns else "NULLIF(date, '')")
1545
+ rows = conn.execute(
1546
+ "SELECT jsonl_path, daily_usage_json, "
1547
+ + ("usage_parser_version" if has_version else "NULL") + "," + last_activity +
1548
+ " FROM session_log WHERE jsonl_path LIKE '%.jsonl'",
1549
+ ()).fetchall()
1550
+ finally:
1551
+ conn.close()
1552
+ projects = _measure_facade.os.path.normcase(_measure_facade.os.path.abspath(str(_measure_facade.CLAUDE_DIR / "projects"))) + _measure_facade.os.sep
1553
+ walked = not _measure_facade._use_codex_session_adapter()
1554
+ pending = 0
1555
+ for path, du_raw, version, last_day in rows:
1556
+ daily_missing = du_raw is None
1557
+ stale = (has_version and walked
1558
+ and (version is None or int(version) < _measure_facade._USAGE_PARSER_VERSION)
1559
+ and _measure_facade.os.path.normcase(_measure_facade.os.path.abspath(path)).startswith(projects))
1560
+ if not (daily_missing or stale):
1561
+ continue
1562
+ # Last KNOWN activity day: the repaired bounds first, then the
1563
+ # retained daily-usage keys for rows whose bounds were never
1564
+ # stamped. Unknown coverage stays pending (conservative).
1565
+ last_activity_day = str(last_day or "")[:10] or None
1566
+ if last_activity_day is None and du_raw:
1567
+ usage_days = _measure_facade._activity_days(_measure_facade._safe_json_dict(du_raw))
1568
+ if usage_days:
1569
+ last_activity_day = usage_days[-1]
1570
+ if last_activity_day is not None and last_activity_day < cutoff:
1571
+ continue
1572
+ if _measure_facade.os.path.exists(path):
1573
+ pending += 1
1574
+ return pending
1575
+ except (_measure_facade.sqlite3.Error, OSError, TypeError, ValueError):
1576
+ return 0
1577
+
1578
+
1579
+ def _routing_usage_by_model(days=None, since=None):
1580
+ """Token usage per model id and token class over the window.
1581
+
1582
+ Returns {model_id: {class: tokens}} (classes in _ROUTING_CLASSES). Source per
1583
+ session row, best first:
1584
+ 1. daily_usage_json: per-day, per-model class buckets (parent + subagents),
1585
+ cut to the window by day.
1586
+ 2. model_usage_breakdown_json: per-model class buckets for the session; any
1587
+ tokens in all_model_usage_json beyond those buckets (subagent work) go
1588
+ to "unsplit".
1589
+ 3. all_model_usage_json / model_usage_json: token totals with no class
1590
+ split, all "unsplit".
1591
+ Never raises; empty when there is no data.
1592
+ """
1593
+ _measure_facade = _compat.facade()
1594
+ out = {}
1595
+ try:
1596
+ if not _measure_facade.TRENDS_DB.exists():
1597
+ return out
1598
+ cutoff = str(since)[:10] if since else (_measure_facade.datetime.now() - _measure_facade.timedelta(days=days)).strftime("%Y-%m-%d")
1599
+ conn = _measure_facade._init_trends_db()
1600
+ _measure_facade.ensure_activity_view(conn)
1601
+ try:
1602
+ columns = {r[1] for r in conn.execute("PRAGMA table_info(session_log)")}
1603
+ first = "first_activity_day" if "first_activity_day" in columns else "NULL"
1604
+ last = "last_activity_day" if "last_activity_day" in columns else "NULL"
1605
+ rows = conn.execute(
1606
+ "SELECT date,daily_usage_json,model_usage_breakdown_json,all_model_usage_json,model_usage_json,"
1607
+ + first + "," + last + " FROM session_log").fetchall()
1608
+ finally:
1609
+ conn.close()
1610
+ for row_date, du_raw, mb_raw, amu_raw, mu_raw, first_day, last_day in rows:
1611
+ du = _measure_facade._safe_json_dict(du_raw)
1612
+ if du:
1613
+ undated_day = ""
1614
+ for day, models in du.items():
1615
+ day = undated_day if day == _measure_facade.UNDATED_USAGE_KEY else day
1616
+ if not isinstance(models, dict) or str(day) < cutoff:
1617
+ continue
1618
+ for model, parts in models.items():
1619
+ if isinstance(parts, dict) and _measure_facade._normalize_model_name(model):
1620
+ _measure_facade._add_routing_buckets(out.setdefault(model, {}), parts)
1621
+ continue
1622
+ if not first_day or first_day != last_day or first_day < cutoff:
1623
+ continue
1624
+ totals = _measure_facade._safe_json_dict(amu_raw) or _measure_facade._safe_json_dict(mu_raw)
1625
+ mb = _measure_facade._safe_json_dict(mb_raw)
1626
+ for model, parts in mb.items():
1627
+ if isinstance(parts, dict) and _measure_facade._normalize_model_name(model):
1628
+ dst = out.setdefault(model, {})
1629
+ before = sum(dst.get(k, 0) for k in _measure_facade._ROUTING_BILLABLE_CLASSES)
1630
+ _measure_facade._add_routing_buckets(dst, parts)
1631
+ split = sum(dst.get(k, 0) for k in _measure_facade._ROUTING_BILLABLE_CLASSES) - before
1632
+ extra = _measure_facade._bucket_int(totals.get(model)) - split
1633
+ if extra > 0:
1634
+ dst["unsplit"] = dst.get("unsplit", 0) + extra
1635
+ for model, tokens in totals.items():
1636
+ if model not in mb and _measure_facade._normalize_model_name(model):
1637
+ dst = out.setdefault(model, {})
1638
+ dst["unsplit"] = dst.get("unsplit", 0) + _measure_facade._bucket_int(tokens)
1639
+ except (_measure_facade.sqlite3.Error, OSError):
1640
+ return {}
1641
+ return out
1642
+
1643
+
1644
+ def _earliest_model_mix(lookback_days=None):
1645
+ """Measured install-era model mix from the earliest `lookback_days` of model_daily.
1646
+
1647
+ Fallback baseline when no snapshot model_mix was captured (e.g. existing
1648
+ users whose snapshot predates this feature). Measured from the user's own
1649
+ history, so realized routing savings are grounded, not self-reported.
1650
+ Returns {"shares": {...}, "first_date": str} or None.
1651
+ """
1652
+ _measure_facade = _compat.facade()
1653
+ try:
1654
+ if not _measure_facade.TRENDS_DB.exists():
1655
+ return None
1656
+ conn = _measure_facade._init_trends_db()
1657
+ try:
1658
+ first = conn.execute("SELECT MIN(date) FROM model_daily").fetchone()
1659
+ if not first or not first[0]:
1660
+ return None
1661
+ first_date = first[0]
1662
+ end = (_measure_facade.datetime.fromisoformat(first_date) + _measure_facade.timedelta(days=lookback_days)).strftime("%Y-%m-%d")
1663
+ rows = conn.execute(
1664
+ "SELECT model, COALESCE(SUM(total_tokens),0) FROM model_daily "
1665
+ "WHERE date >= ? AND date <= ? GROUP BY model",
1666
+ (first_date, end),
1667
+ ).fetchall()
1668
+ finally:
1669
+ conn.close()
1670
+ total = sum(int(r[1] or 0) for r in rows)
1671
+ if total <= 0:
1672
+ return None
1673
+ return {"shares": {r[0]: int(r[1] or 0) / total for r in rows if r[0]}, "first_date": first_date}
1674
+ except (_measure_facade.sqlite3.Error, OSError, ValueError):
1675
+ return None
1676
+
1677
+
1678
+ def _pretool_baseline_mix():
1679
+ """This user's OWN explicit pre-TO model mix, or None. PER-USER, not a default.
1680
+
1681
+ The normal baseline is each user's earliest measured history (see
1682
+ _earliest_model_mix). This override exists only for a user whose history does
1683
+ not reach back to their pre-Token-Optimizer era, so they can record their own
1684
+ true starting point. It is read per-install from a `pretool_baseline.json` in
1685
+ THIS user's SNAPSHOT_DIR (`{"opus_share": <their value>}`), or their
1686
+ TOKEN_OPTIMIZER_BASELINE_OPUS_SHARE env. There is no shared/default value
1687
+ (unset -> fall back to their own history). Remaining share goes to Sonnet.
1688
+ Never raises.
1689
+ """
1690
+ _measure_facade = _compat.facade()
1691
+ share = 0.0
1692
+ try:
1693
+ bpath = _measure_facade.SNAPSHOT_DIR / "pretool_baseline.json"
1694
+ if bpath.exists():
1695
+ share = float(_measure_facade.json.loads(bpath.read_text(encoding="utf-8")).get("opus_share", 0.0) or 0.0)
1696
+ except (_measure_facade.json.JSONDecodeError, OSError, ValueError, TypeError):
1697
+ share = 0.0
1698
+ if share <= 0.0:
1699
+ share = _measure_facade._BASELINE_OPUS_SHARE
1700
+ if not (0.0 < share <= 1.0):
1701
+ return None
1702
+ return {"opus": share, "sonnet": round(1.0 - share, 4)}
1703
+
1704
+
1705
+ def set_pretool_baseline(args):
1706
+ """Record the user's pre-Token-Optimizer Opus share (CLI: `set-baseline --opus 0.95`).
1707
+
1708
+ Writes pretool_baseline.json to SNAPSHOT_DIR. Use this when your earliest captured
1709
+ history is already optimized, so the "Your transformation" before/after reflects
1710
+ your true pre-TO era. Without it, the transformation falls back to your measured
1711
+ earliest sessions. Never raises fatally.
1712
+ """
1713
+ _measure_facade = _compat.facade()
1714
+ opus = None
1715
+ for i, a in enumerate(args):
1716
+ if a == "--opus" and i + 1 < len(args):
1717
+ try:
1718
+ opus = float(args[i + 1])
1719
+ except ValueError:
1720
+ opus = None
1721
+ if opus is None or not (0.0 < opus <= 1.0):
1722
+ print(" Usage: set-baseline --opus <0..1> (e.g. --opus 0.95 for 95% Opus pre-TO)")
1723
+ try:
1724
+ bp = _measure_facade.SNAPSHOT_DIR / "pretool_baseline.json"
1725
+ if bp.exists():
1726
+ cur = _measure_facade.json.loads(bp.read_text(encoding="utf-8"))
1727
+ print(f" Current baseline: {float(cur.get('opus_share', 0)) * 100:.0f}% Opus")
1728
+ except (_measure_facade.json.JSONDecodeError, OSError, ValueError, TypeError):
1729
+ pass
1730
+ return
1731
+ try:
1732
+ _measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
1733
+ bp = _measure_facade.SNAPSHOT_DIR / "pretool_baseline.json"
1734
+ bp.write_text(_measure_facade.json.dumps({"opus_share": round(opus, 4)}) + "\n", encoding="utf-8")
1735
+ print(f" [Token Optimizer] Pre-TO baseline set: {opus * 100:.0f}% Opus.")
1736
+ print(" 'Your transformation' now prices the before-era at this mix.")
1737
+ print(f" Saved to {_measure_facade._display_path(bp)}")
1738
+ except OSError as e:
1739
+ print(f" [Error] Could not write baseline: {e}")
1740
+
1741
+
1742
+ def _compute_model_routing_savings(days=None, since=None):
1743
+ """Model-routing savings: realized (mix shift vs baseline) + potential (remaining Opus).
1744
+
1745
+ REALIZED: compare current model mix against the install-era baseline (snapshot
1746
+ model_mix, else the earliest model_daily window). If the user moved tokens off
1747
+ expensive models, the counterfactual cost (current volume spread over the
1748
+ baseline mix) minus the current cost, both on one standardized price
1749
+ schedule, is the estimated saving. This is the pillar that can show a
1750
+ realized win (e.g. Opus 94% -> 67%).
1751
+ Models priced above the baseline's costliest model (a premium model the user
1752
+ chose) are left out of the comparison and the rest renormalized, so they do not
1753
+ cancel a real shift toward lighter models; `premium_share` and
1754
+ `premium_cost_usd` report them separately.
1755
+
1756
+ POTENTIAL: an assumption, not a measurement. A fixed share
1757
+ (`routable_fraction`) of Opus fresh input and output is priced at the
1758
+ Opus-to-Sonnet API rate delta. Opus usage without a class split is left out
1759
+ and counted in `potential_unsplit_excluded_tokens`. Cache reads and
1760
+ writes represent main-session history: switching models rebuilds that cache,
1761
+ while routine subagent work carries its own smaller context. The result is
1762
+ shown separately from concrete opportunities.
1763
+
1764
+ Realized routing prices fresh input, cache creation, cache reads and output
1765
+ by class. Usage without a class split stays outside both comparisons and
1766
+ their coverage, and is reported as `unsplit_tokens`. Potential uses the model's
1767
+ own generation card for fresh input and output, and the newest Sonnet card
1768
+ for its target.
1769
+ The class split comes from per-day, per-model session usage.
1770
+
1771
+ Realized routing is a standardized family comparison: the remaining work's
1772
+ class volumes per current family, and the same class volumes spread over the
1773
+ baseline family shares, are valued on one fixed schedule (the newest card of
1774
+ each family's tier) chosen independently of the window's volumes. A
1775
+ generation change inside a family therefore cannot create routing credit.
1776
+ The exact-card cost of the same work and its gap to the standardized value
1777
+ are reported separately (`actual_cost_usd`, `generation_price_delta_usd`).
1778
+ The schedule is assumed because the frozen baseline records no generations,
1779
+ so the result is labelled "estimated".
1780
+
1781
+ Models with no exact rate card are unpriced, not free (an unknown Claude
1782
+ generation does not borrow its family's price): they are left out of the
1783
+ comparison and reported as `unpriced_models`, `unpriced_tokens` and
1784
+ `unpriced_share`. Explicitly free tiers (":free") are left out the same way
1785
+ and reported as `free_models`.
1786
+ Labelled estimated (realized) and opportunity (potential). Never raises.
1787
+ """
1788
+ # `zero` is returned only on no-data / error paths (no current mix, no
1789
+ # baseline, or an exception). Label it "unavailable" so a $0 here reads as
1790
+ # "couldn't compute" rather than a measured zero -- the success return below
1791
+ # sets its own evidence="estimated" when comparable work remains.
1792
+ _measure_facade = _compat.facade()
1793
+ zero = {
1794
+ "realized_cost_usd": 0.0, "potential_cost_usd": 0.0,
1795
+ "potential_tokens": 0, "potential_tokens_monthly": 0,
1796
+ "potential_billable_tokens": 0, "potential_by_class": {}, "unsplit_tokens": 0,
1797
+ "potential_unsplit_excluded_tokens": 0,
1798
+ "premium_models": [], "premium_share": 0.0, "premium_cost_usd": 0.0,
1799
+ "unpriced_models": [], "unpriced_tokens": 0, "unpriced_share": 0.0,
1800
+ "free_models": [], "free_tokens": 0,
1801
+ "compared_share": 0.0,
1802
+ "baseline_rate_basis": {}, "baseline_reference_priced": [],
1803
+ "standardized_baseline_cost_usd": 0.0, "standardized_actual_cost_usd": 0.0,
1804
+ "actual_cost_usd": 0.0, "generation_price_delta_usd": 0.0,
1805
+ "baseline_opus_share": 0.0, "current_opus_share": 0.0,
1806
+ "baseline_source": None, "evidence": "unavailable",
1807
+ }
1808
+ try:
1809
+ current = _measure_facade._model_mix_shares(days=days, since=since)
1810
+ zero["activity_coverage"] = current.get("activity_coverage", {"complete": True, "undated_sessions": 0})
1811
+ cur_shares = current.get("shares", {})
1812
+ cur_total = int(current.get("total_tokens", 0) or 0)
1813
+ if not cur_shares or cur_total <= 0:
1814
+ return zero
1815
+
1816
+ # Baseline mix: explicit pre-TO baseline (user knows it) first, then
1817
+ # snapshot capture, else earliest measured history.
1818
+ baseline_shares = None
1819
+ baseline_source = None
1820
+ explicit = _measure_facade._pretool_baseline_mix()
1821
+ if explicit:
1822
+ baseline_shares = explicit
1823
+ baseline_source = "pretool_baseline"
1824
+ if not baseline_shares:
1825
+ try:
1826
+ snap_path = _measure_facade.SNAPSHOT_DIR / "snapshot_before.json"
1827
+ if snap_path.exists():
1828
+ snap = _measure_facade.json.loads(snap_path.read_text(encoding="utf-8"))
1829
+ mm = ((snap.get("model_mix") or {}).get("shares") or {}) if (snap.get("model_mix") or {}).get("activity_basis") == 1 else {}
1830
+ if mm:
1831
+ baseline_shares = mm
1832
+ baseline_source = "snapshot"
1833
+ except (_measure_facade.json.JSONDecodeError, OSError, ValueError):
1834
+ pass
1835
+ if not baseline_shares:
1836
+ early = _measure_facade._earliest_model_mix()
1837
+ if early:
1838
+ baseline_shares = early["shares"]
1839
+ baseline_source = "history"
1840
+ if not baseline_shares:
1841
+ return zero
1842
+
1843
+ # While collect is still re-reading window sessions (an older usage
1844
+ # parser, or per-day usage not yet rebuilt), their per-class usage is
1845
+ # incomplete and the figure would move pass to pass. Report the count
1846
+ # instead of a number.
1847
+ pending = _measure_facade._routing_pending_sessions(days=days, since=since)
1848
+ if pending:
1849
+ return {**zero, "evidence": "pending", "pending_sessions": pending,
1850
+ "baseline_source": baseline_source}
1851
+
1852
+ # Rows of per-model, per-class usage. When the DB holds none (adapters
1853
+ # that only record model totals), the model-daily mix stands in as
1854
+ # unsplit tokens, reported outside comparison coverage.
1855
+ usage = _measure_facade._routing_usage_by_model(days=days, since=since)
1856
+ from_rows = bool(usage)
1857
+ if not from_rows:
1858
+ usage = {m: {"unsplit": share * cur_total} for m, share in cur_shares.items()}
1859
+
1860
+ # Mix keys from the model-daily fallback are already family buckets.
1861
+ fam_of = {m: (_measure_facade._normalize_model_name(m) if from_rows else m) for m in usage}
1862
+ rates_cache = {}
1863
+
1864
+ def _rates(model):
1865
+ _measure_facade = _compat.facade()
1866
+ if model not in rates_cache:
1867
+ rates_cache[model] = _measure_facade._routing_class_rates(model)
1868
+ return rates_cache[model]
1869
+
1870
+ # Only a model with an exact rate card is compared. A model with no card
1871
+ # is unpriced (not free) and an explicitly free tier is not credited as a
1872
+ # saving: both keep their token counts, are reported, and stay out of
1873
+ # every mix and cost below.
1874
+ priced_usage = {}
1875
+ unpriced_by_model = {}
1876
+ free_by_model = {}
1877
+ unsplit_tokens = 0.0
1878
+ potential_unsplit_excluded = 0.0
1879
+ for m, classes in usage.items():
1880
+ if not fam_of[m]:
1881
+ continue
1882
+ if _rates(m) is not None:
1883
+ unsplit_tokens += classes.get("unsplit", 0)
1884
+ if fam_of[m] == "opus":
1885
+ potential_unsplit_excluded += classes.get("unsplit", 0)
1886
+ split = {k: v for k, v in classes.items() if k != "unsplit"}
1887
+ if sum(split.values()) > 0:
1888
+ priced_usage[m] = split
1889
+ continue
1890
+ tokens = sum(classes.get(k, 0) for k in _measure_facade._ROUTING_CLASSES)
1891
+ bucket = free_by_model if _measure_facade._routing_model_status(m) == "free" else unpriced_by_model
1892
+ bucket[m] = bucket.get(m, 0) + tokens
1893
+
1894
+ fam_models = {}
1895
+ for m in priced_usage:
1896
+ fam_models.setdefault(fam_of[m], []).append(m)
1897
+ fam_classes = {}
1898
+ class_totals = {k: 0.0 for k in _measure_facade._ROUTING_CLASSES}
1899
+ for fam, ms in fam_models.items():
1900
+ dst = fam_classes[fam] = {k: 0.0 for k in _measure_facade._ROUTING_CLASSES}
1901
+ for m in ms:
1902
+ for k in _measure_facade._ROUTING_CLASSES:
1903
+ dst[k] += priced_usage[m].get(k, 0)
1904
+ class_totals[k] += priced_usage[m].get(k, 0)
1905
+ pooled = sum(class_totals.values())
1906
+
1907
+ def _unpriced_report():
1908
+ _measure_facade = _compat.facade()
1909
+ return [mid for mid, _t in sorted(unpriced_by_model.items(), key=lambda kv: -kv[1])]
1910
+
1911
+ def _free_report():
1912
+ _measure_facade = _compat.facade()
1913
+ return [mid for mid, _t in sorted(free_by_model.items(), key=lambda kv: -kv[1])]
1914
+
1915
+ unpriced_tokens = int(sum(unpriced_by_model.values()))
1916
+ free_tokens = int(sum(free_by_model.values()))
1917
+
1918
+ def _coverage_fields():
1919
+ _measure_facade = _compat.facade()
1920
+ total = unpriced_tokens + free_tokens + pooled + unsplit_tokens
1921
+ return {
1922
+ "unpriced_models": _unpriced_report(), "unpriced_tokens": unpriced_tokens,
1923
+ "unpriced_share": round(unpriced_tokens / total, 4) if total > 0 else 0.0,
1924
+ "free_models": _free_report(), "free_tokens": free_tokens,
1925
+ "unsplit_tokens": int(round(unsplit_tokens)),
1926
+ "potential_unsplit_excluded_tokens": int(round(potential_unsplit_excluded)),
1927
+ "baseline_source": baseline_source,
1928
+ }
1929
+
1930
+ if pooled <= 0:
1931
+ return {**zero, **_coverage_fields()}
1932
+
1933
+ # STANDARDIZED ROUTING VALUATION. Realized routing measures a shift of work
1934
+ # between model families, so both arms are valued on one fixed price
1935
+ # schedule: one rate per family and token class, chosen without looking at
1936
+ # how much of that family ran in the window. The frozen baseline records
1937
+ # shares by family only (no generation), so the schedule is a documented
1938
+ # reference-card scenario: each family at the newest generation card of
1939
+ # its tier (legacy Sonnet counts as Sonnet; a provider model stands for
1940
+ # itself). It is the same for present and absent families, so one token of
1941
+ # any generation changes the result only by that token's own contribution,
1942
+ # and a generation change within a family cannot become routing credit.
1943
+ # What the work actually cost at the exact cards used is reported
1944
+ # separately (`actual_cost_usd`, `generation_price_delta_usd`). Because the
1945
+ # scenario is assumed, the result is labelled estimated. A baseline that
1946
+ # recorded generations would replace the reference card in
1947
+ # `_fixed_family_rates` for the families it covers.
1948
+ fam_rate_cache = {}
1949
+ fam_rate_basis = {}
1950
+
1951
+ def _fixed_family_rates(fam):
1952
+ _measure_facade = _compat.facade()
1953
+ if fam in fam_rate_cache:
1954
+ return fam_rate_cache[fam]
1955
+ ref_model = _measure_facade._routing_reference_model(fam)
1956
+ out = _rates(ref_model)
1957
+ if out is None and fam_models.get(fam):
1958
+ # No reference card for a family that did run: its lowest-sorted
1959
+ # model id stands in, so the choice never depends on input order.
1960
+ ref_model = sorted(fam_models[fam])[0]
1961
+ out = _rates(ref_model)
1962
+ if out is not None:
1963
+ fam_rate_basis[fam] = f"reference:{ref_model}"
1964
+ fam_rate_cache[fam] = out
1965
+ return out
1966
+
1967
+ def _renormalized(shares):
1968
+ _measure_facade = _compat.facade()
1969
+ kept = {f: s for f, s in shares.items() if s and s > 0 and _fixed_family_rates(f) is not None}
1970
+ total = sum(kept.values())
1971
+ return {f: s / total for f, s in kept.items()} if total > 0 else {}
1972
+
1973
+ base_priced = _renormalized(baseline_shares)
1974
+
1975
+ # Effective $/MTok of a family under the window's own class mix.
1976
+ def _family_price(f):
1977
+ _measure_facade = _compat.facade()
1978
+ if pooled <= 0:
1979
+ return 0.0
1980
+ r = _fixed_family_rates(f)
1981
+ return sum(class_totals[k] * r[k] for k in _measure_facade._ROUTING_CLASSES) / pooled
1982
+
1983
+ # Models priced above the most expensive model of the baseline are the
1984
+ # user's own choice, not routing: they are taken out of the comparison
1985
+ # so it measures the shift toward lighter models. Their share and cost
1986
+ # are reported separately. A model must be dearer than the baseline's
1987
+ # costliest family on the window's pooled mix AND on the output card:
1988
+ # cache-read rates alone do not rank tiers across generations (Sonnet 4.6
1989
+ # reads cache at $0.30, Opus 5.5 at $0.20), so a lighter older model is
1990
+ # never mistaken for a premium one.
1991
+ ceiling_fam = max(base_priced, key=_family_price, default=None)
1992
+ baseline_ceiling = _family_price(ceiling_fam) if ceiling_fam else 0.0
1993
+ ceiling_output = _fixed_family_rates(ceiling_fam)["output"] if ceiling_fam else 0.0
1994
+ premium = sorted(
1995
+ f for f in fam_classes
1996
+ if _family_price(f) > baseline_ceiling > 0 and _fixed_family_rates(f)["output"] > ceiling_output
1997
+ )
1998
+ premium_share = sum(cur_shares.get(f, 0.0) for f in premium)
1999
+ premium_cost = sum(
2000
+ classes.get(k, 0) * _rates(m)[k]
2001
+ for m, classes in priced_usage.items() if fam_of[m] in premium
2002
+ for k in _measure_facade._ROUTING_CLASSES
2003
+ ) / 1_000_000
2004
+
2005
+ # REALIZED: the remaining work's class volumes, per current family, valued
2006
+ # on the standardized schedule, against the same total class volumes spread
2007
+ # over the baseline family shares on that same schedule. Only the shift
2008
+ # between families moves the number. Never negative. Premium and unpriced
2009
+ # models are outside both arms.
2010
+ kept_models = [m for m in priced_usage if fam_of[m] not in premium]
2011
+ kept_totals = {k: sum(priced_usage[m].get(k, 0) for m in kept_models) for k in _measure_facade._ROUTING_CLASSES}
2012
+ standardized_actual = sum(
2013
+ priced_usage[m].get(k, 0) * _fixed_family_rates(fam_of[m])[k]
2014
+ for m in kept_models for k in _measure_facade._ROUTING_CLASSES
2015
+ ) / 1_000_000
2016
+ standardized_baseline = sum(
2017
+ kept_totals[k] * sum(s * _fixed_family_rates(f)[k] for f, s in base_priced.items())
2018
+ for k in _measure_facade._ROUTING_CLASSES
2019
+ ) / 1_000_000 if base_priced else 0.0
2020
+ # Exact-card API-equivalent cost of the same work (each model's own card).
2021
+ actual_cost = sum(
2022
+ priced_usage[m].get(k, 0) * _rates(m)[k] for m in kept_models for k in _measure_facade._ROUTING_CLASSES
2023
+ ) / 1_000_000
2024
+ realized_cost = max(0.0, standardized_baseline - standardized_actual) if base_priced and kept_models else 0.0
2025
+ compared_tokens = sum(kept_totals.values())
2026
+ window_tokens = unpriced_tokens + free_tokens + pooled + unsplit_tokens
2027
+
2028
+ # POTENTIAL: a fixed share of remaining Opus fresh input and output, priced
2029
+ # at each Opus model's own card minus the current Sonnet card. It is
2030
+ # computed apart from the realized figure: with no target card the
2031
+ # potential is zero and the realized routing above is unaffected. Usage
2032
+ # without a class split cannot be told apart as input or output, so it is
2033
+ # left out and its count is reported.
2034
+ target = _measure_facade._routing_target_model()
2035
+ target_rates = _rates(target)
2036
+ by_class = {k: {"tokens": 0, "usd": 0.0} for k in _measure_facade._ROUTING_CLASSES}
2037
+ for m, classes in priced_usage.items():
2038
+ if fam_of[m] != "opus":
2039
+ continue
2040
+ if target_rates is None:
2041
+ continue
2042
+ m_rates = _rates(m)
2043
+ for k in ("fresh_input", "output"):
2044
+ tok = classes.get(k, 0)
2045
+ if tok:
2046
+ by_class[k]["tokens"] += tok * _measure_facade._ROUTABLE_OPUS_FRACTION
2047
+ by_class[k]["usd"] += tok * _measure_facade._ROUTABLE_OPUS_FRACTION * (m_rates[k] - target_rates[k]) / 1_000_000
2048
+ potential_cost = max(0.0, sum(v["usd"] for v in by_class.values()))
2049
+ potential_tokens = int(round(sum(v["tokens"] for v in by_class.values())))
2050
+ potential_tokens_monthly = int(round(potential_tokens / max(days, 1) * 30))
2051
+ potential_billable_tokens = int(round(sum(by_class[k]["tokens"] for k in _measure_facade._ROUTING_BILLABLE_CLASSES)))
2052
+ opus_share = cur_shares.get("opus", 0.0)
2053
+
2054
+ return {
2055
+ "activity_coverage": zero["activity_coverage"],
2056
+ "realized_cost_usd": round(realized_cost, 4),
2057
+ "potential_cost_usd": round(potential_cost, 4),
2058
+ # Routable tokens cover observed fresh input and output only.
2059
+ "potential_tokens": potential_tokens,
2060
+ "potential_tokens_monthly": potential_tokens_monthly,
2061
+ "potential_billable_tokens": potential_billable_tokens,
2062
+ "potential_token_classes": [k for k in _measure_facade._ROUTING_CLASSES if by_class[k]["tokens"]],
2063
+ "potential_by_class": {
2064
+ k: {"tokens": int(round(v["tokens"])), "usd": round(v["usd"], 4)}
2065
+ for k, v in by_class.items() if v["tokens"] or v["usd"]
2066
+ },
2067
+ "potential_basis": "api_rate_equivalent",
2068
+ "target_model": target,
2069
+ "pricing_basis": "per_token_class_generation_card",
2070
+ # Premium models (priced above the baseline's costliest model) are the
2071
+ # user's own choice: excluded from realized routing, shown here.
2072
+ "premium_models": premium,
2073
+ "premium_share": round(premium_share, 4),
2074
+ "premium_cost_usd": round(premium_cost, 4),
2075
+ # Models with no exact rate card (unpriced) and explicitly free tiers are
2076
+ # left out of the comparison, never priced at zero or at a stand-in rate.
2077
+ **_coverage_fields(),
2078
+ "baseline_opus_share": round(baseline_shares.get("opus", 0.0), 4),
2079
+ "current_opus_share": round(opus_share, 4),
2080
+ "baseline_source": baseline_source,
2081
+ "routable_fraction": _measure_facade._ROUTABLE_OPUS_FRACTION,
2082
+ # Realized routing is a standardized comparison on a fixed price
2083
+ # schedule (newest card per family) in both arms, because the baseline
2084
+ # records no generations. That schedule is an assumption, so the
2085
+ # result is an estimate. The exact-card cost of the same work and its
2086
+ # gap to the standardized valuation are reported apart: the gap is
2087
+ # price/generation, never routing.
2088
+ "realized_basis": "standardized_reference_card",
2089
+ "baseline_rate_basis": {f: fam_rate_basis[f] for f in sorted(set(base_priced) | set(fam_classes)) if f in fam_rate_basis},
2090
+ "baseline_reference_priced": sorted(base_priced),
2091
+ "standardized_baseline_cost_usd": round(standardized_baseline, 4),
2092
+ "standardized_actual_cost_usd": round(standardized_actual, 4),
2093
+ "actual_cost_usd": round(actual_cost, 4),
2094
+ "generation_price_delta_usd": round(actual_cost - standardized_actual, 4),
2095
+ # Share of the window's class tokens inside both arms (premium,
2096
+ # unpriced and free models, and unsplit tokens are outside).
2097
+ "compared_share": round(compared_tokens / window_tokens, 4) if window_tokens > 0 else 0.0,
2098
+ "evidence": "estimated" if compared_tokens > 0 and base_priced else "unavailable",
2099
+ }
2100
+ except Exception:
2101
+ return zero