@alexgreensh/token-optimizer 5.13.81 → 5.13.82

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 (39) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +1 -1
  4. package/package.json +1 -1
  5. package/skills/token-optimizer/assets/savings_story.js +6 -4
  6. package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
  7. package/skills/token-optimizer/scripts/_measure/continuity.py +30 -3
  8. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +32 -15
  9. package/skills/token-optimizer/scripts/_measure/daemon.py +25 -2
  10. package/skills/token-optimizer/scripts/_measure/dashboard.py +2 -1
  11. package/skills/token-optimizer/scripts/_measure/feature_health.py +14 -5
  12. package/skills/token-optimizer/scripts/_measure/install_baseline.py +2 -1
  13. package/skills/token-optimizer/scripts/_measure/like_for_like.py +329 -0
  14. package/skills/token-optimizer/scripts/_measure/limit_units.py +39 -0
  15. package/skills/token-optimizer/scripts/_measure/model_families.py +133 -0
  16. package/skills/token-optimizer/scripts/_measure/own_price_card.py +38 -14
  17. package/skills/token-optimizer/scripts/_measure/pilot_report.py +197 -48
  18. package/skills/token-optimizer/scripts/_measure/pricing.py +7 -2
  19. package/skills/token-optimizer/scripts/_measure/quality_archive.py +41 -19
  20. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +2 -0
  21. package/skills/token-optimizer/scripts/_measure/savings.py +155 -80
  22. package/skills/token-optimizer/scripts/_measure/sessions.py +7 -2
  23. package/skills/token-optimizer/scripts/_measure/trends.py +20 -2
  24. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +37 -4
  25. package/skills/token-optimizer/scripts/antigravity_doctor.py +42 -6
  26. package/skills/token-optimizer/scripts/antigravity_install.py +18 -9
  27. package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
  28. package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
  29. package/skills/token-optimizer/scripts/cursor_coach.py +5 -4
  30. package/skills/token-optimizer/scripts/cursor_install.py +1 -0
  31. package/skills/token-optimizer/scripts/delta_serve.py +174 -0
  32. package/skills/token-optimizer/scripts/devin_source.py +1 -1
  33. package/skills/token-optimizer/scripts/hermes_doctor.py +2 -1
  34. package/skills/token-optimizer/scripts/hermes_install.py +2 -1
  35. package/skills/token-optimizer/scripts/measure.py +14 -21
  36. package/skills/token-optimizer/scripts/read_cache.py +19 -76
  37. package/skills/token-optimizer/scripts/reset_epoch.py +5 -3
  38. package/skills/token-optimizer/scripts/session_activity.py +1 -1
  39. package/skills/token-optimizer/scripts/session_store.py +5 -6
@@ -0,0 +1,329 @@
1
+ """Like-for-like transformation pricing.
2
+
3
+ Both transformation arms are priced at the CURRENT reference card for the model
4
+ family that did the work. Generation movement inside one priced family (Opus
5
+ 4.x -> Opus 5.x, Sonnet 4.6 -> Sonnet 5.x, gpt-5-codex -> gpt-5.4,
6
+ gemini-2.5-pro -> gemini-3-pro) therefore cannot appear as a Token Optimizer
7
+ saving or loss. Movement between families/providers still changes the priced
8
+ cost, because routing routine work to a cheaper family is a real behavior
9
+ change. Unknown models stay unpriced (R10); they are never silently borrowed.
10
+ """
11
+
12
+ from . import model_families
13
+
14
+ _CLASSES = ("fresh_input", "cache_read", "cache_create_5m", "cache_create_1h",
15
+ "output", "unsplit")
16
+
17
+
18
+ def _num(value):
19
+ try:
20
+ return float(value or 0.0)
21
+ except (TypeError, ValueError):
22
+ return 0.0
23
+
24
+
25
+ def model_key(facade, model):
26
+ """Stable comparison group for a recorded model id.
27
+
28
+ `_normalize_model_name` collapses Claude generation ids to their family while
29
+ leaving foreign provider ids intact. The group key must be stable across pricing
30
+ updates; valuation resolves the newest reference card at measurement time.
31
+ """
32
+ if not isinstance(model, str) or not model.strip():
33
+ return None
34
+ try:
35
+ key = facade._normalize_model_name(model)
36
+ except Exception:
37
+ key = None
38
+ # sonnet_legacy exists for historical exact-card pricing. For a like-for-like
39
+ # transformation it is still the Sonnet family and must use the same reference
40
+ # bucket as newer Sonnets.
41
+ if key == "sonnet_legacy":
42
+ key = "sonnet"
43
+ if key in ("opus", "sonnet", "haiku", "fable"):
44
+ return key
45
+ return model_families.foreign_group_key(facade, model) or key or model.strip().lower()
46
+
47
+
48
+ def empty_classes():
49
+ return {key: 0.0 for key in _CLASSES}
50
+
51
+
52
+ def add_parts(classes, parts, multiplier=1.0):
53
+ """Add one per-model class bucket, normalizing legacy key spellings."""
54
+ if not isinstance(parts, dict):
55
+ return
56
+ # cache_create is the TOTAL write volume, with cache_create_1h/5m its TTL
57
+ # split. Treating it as an additional unsplit bucket double-counts every
58
+ # modern write. Follow _add_routing_buckets: only the unaccounted remainder
59
+ # is priced as 5-minute writes.
60
+ cc = _num(parts.get("cache_create"))
61
+ write1 = _num(parts.get("cache_create_1h"))
62
+ write5 = _num(parts.get("cache_create_5m"))
63
+ write5 += max(0.0, cc - write1 - write5)
64
+ classes["fresh_input"] += (_num(parts.get("fresh_input")) + _num(parts.get("input"))) * multiplier
65
+ classes["cache_read"] += _num(parts.get("cache_read")) * multiplier
66
+ classes["cache_create_5m"] += write5 * multiplier
67
+ classes["cache_create_1h"] += write1 * multiplier
68
+ classes["output"] += _num(parts.get("output")) * multiplier
69
+ classes["unsplit"] += _num(parts.get("unsplit")) * multiplier
70
+
71
+
72
+ def merge_model_classes(into, extra, scale=1.0):
73
+ """Merge {model_group: class bucket}; safe for frozen-anchor state copies."""
74
+ if not isinstance(extra, dict):
75
+ return into
76
+ for model, parts in extra.items():
77
+ if not isinstance(model, str) or not isinstance(parts, dict):
78
+ continue
79
+ target = into.setdefault(model, empty_classes())
80
+ for key in _CLASSES:
81
+ target[key] = target.get(key, 0.0) + _num(parts.get(key)) * scale
82
+ return into
83
+
84
+
85
+ def scale_model_classes(classes, scale):
86
+ return merge_model_classes({}, classes, scale)
87
+
88
+
89
+ def total_tokens(classes):
90
+ if isinstance(classes, dict) and all(not isinstance(v, dict) for v in classes.values()):
91
+ return sum(_num(classes.get(key)) for key in _CLASSES)
92
+ total = 0.0
93
+ for parts in (classes or {}).values():
94
+ if isinstance(parts, dict):
95
+ total += sum(_num(parts.get(key)) for key in _CLASSES)
96
+ return total
97
+
98
+
99
+ def _class_vector_from_row(facade, row):
100
+ try:
101
+ fresh, write, read, output = facade._session_token_vector(row[:5])
102
+ except Exception:
103
+ fresh, write, read, output = 0.0, 0.0, 0.0, 0.0
104
+ classes = empty_classes()
105
+ classes["fresh_input"] = fresh
106
+ # Preserve the 5m/1h write split when the row carries it. `_session_token_vector`
107
+ # clamps the combined write against input; scale the recorded split into that
108
+ # clamped total rather than pretending every write was 5-minute TTL.
109
+ write5, write1 = _num(row[2]), _num(row[3])
110
+ recorded = write5 + write1
111
+ if write > 0 and recorded > 0:
112
+ classes["cache_create_5m"] = write * max(0.0, write5) / recorded
113
+ classes["cache_create_1h"] = write * max(0.0, write1) / recorded
114
+ else:
115
+ classes["cache_create_5m"] = write
116
+ classes["cache_read"] = read
117
+ classes["output"] = output
118
+ return classes
119
+
120
+
121
+ def rows_to_model_classes(facade, rows):
122
+ """Aggregate detailed per-model classes from `_price_parent_rows` rows.
123
+
124
+ Modern rows carry model_usage_breakdown_json. Older rows only carry the session
125
+ model mix; for those, the session's total class vector is allocated across that
126
+ mix. The allocation is labelled estimated through `estimated_tokens` by the
127
+ caller if needed, but it preserves the total volume instead of dropping it.
128
+ """
129
+ import json
130
+ out = {}
131
+ for row in rows or ():
132
+ detailed = False
133
+ try:
134
+ breakdown = json.loads(row[9]) if row[9] else {}
135
+ except Exception:
136
+ breakdown = {}
137
+ if isinstance(breakdown, dict) and breakdown:
138
+ for model, parts in breakdown.items():
139
+ key = model_key(facade, model)
140
+ if key and isinstance(parts, dict):
141
+ before = total_tokens(out.get(key) or {})
142
+ add_parts(out.setdefault(key, empty_classes()), parts)
143
+ detailed = detailed or total_tokens(out.get(key) or {}) > before
144
+ if detailed:
145
+ continue
146
+ weights = None
147
+ for blob_index in (5, 6):
148
+ try:
149
+ raw = json.loads(row[blob_index]) if len(row) > blob_index and row[blob_index] else {}
150
+ except Exception:
151
+ raw = {}
152
+ if isinstance(raw, dict) and raw:
153
+ weights = {model_key(facade, model): _num(value)
154
+ for model, value in raw.items() if model_key(facade, model)}
155
+ weights = {model: value for model, value in weights.items() if value > 0}
156
+ if weights:
157
+ break
158
+ vector = _class_vector_from_row(facade, row)
159
+ if not weights:
160
+ fallback = None
161
+ for default in ("_default_model_for_runtime", "_default_model"):
162
+ try:
163
+ fallback = model_key(facade, getattr(facade, default)())
164
+ if fallback:
165
+ break
166
+ except Exception:
167
+ continue
168
+ weights = {fallback or "unknown": 1.0}
169
+ total = sum(weights.values()) or 1.0
170
+ for model, weight in weights.items():
171
+ target = out.setdefault(model, empty_classes())
172
+ share = weight / total
173
+ for key in _CLASSES:
174
+ target[key] += vector.get(key, 0.0) * share
175
+ return out
176
+
177
+
178
+ def value_model_classes(facade, model_classes):
179
+ """Value class buckets at today's reference card per model family.
180
+
181
+ Returns None when no usable volume exists. Coverage is priced tokens / all
182
+ tokens, including cache reads in the denominator because they are real billed
183
+ volume in this comparison. Unsplit tokens use the fresh-input rate as a stated
184
+ minimum rather than being silently dropped.
185
+ """
186
+ usd = 0.0
187
+ priced_tokens = 0.0
188
+ all_tokens = 0.0
189
+ unsplit_tokens = 0.0
190
+ unpriced_tokens = 0.0
191
+ unpriced_models = set()
192
+ references = {}
193
+ for key, parts in (model_classes or {}).items():
194
+ if not isinstance(parts, dict):
195
+ continue
196
+ volume = sum(_num(parts.get(k)) for k in _CLASSES)
197
+ if volume <= 0:
198
+ continue
199
+ all_tokens += volume
200
+ try:
201
+ reference = facade._routing_reference_model(key)
202
+ rates = facade._routing_class_rates(reference or key)
203
+ except Exception:
204
+ reference, rates = key, None
205
+ references[key] = reference or key
206
+ if not rates:
207
+ unpriced_tokens += volume
208
+ unpriced_models.add(key)
209
+ continue
210
+ cost = (
211
+ _num(parts.get("fresh_input")) * _num(rates.get("fresh_input")) +
212
+ _num(parts.get("output")) * _num(rates.get("output")) +
213
+ _num(parts.get("cache_read")) * _num(rates.get("cache_read")) +
214
+ _num(parts.get("cache_create_5m")) * _num(rates.get("cache_create_5m")) +
215
+ _num(parts.get("cache_create_1h")) * _num(rates.get("cache_create_1h")) +
216
+ _num(parts.get("unsplit")) * _num(rates.get("fresh_input"))
217
+ ) / 1_000_000.0
218
+ unsplit_tokens += _num(parts.get("unsplit"))
219
+ usd += cost
220
+ priced_tokens += volume
221
+ if all_tokens <= 0:
222
+ return None
223
+ return {
224
+ "usd": usd,
225
+ "coverage": priced_tokens / all_tokens,
226
+ "priced_tokens": priced_tokens,
227
+ "total_tokens": all_tokens,
228
+ "unpriced_tokens": unpriced_tokens,
229
+ "unpriced_models": sorted(unpriced_models),
230
+ "unsplit_tokens": unsplit_tokens,
231
+ "reference_models": references,
232
+ }
233
+
234
+
235
+ def usable_value(facade, metrics, minimum_coverage=0.80):
236
+ classes = (metrics or {}).get("model_classes")
237
+ valued = value_model_classes(facade, classes)
238
+ if valued and valued["coverage"] >= minimum_coverage:
239
+ return valued
240
+ return None
241
+
242
+
243
+ def price_arms(facade, before, now, own=None, minimum_coverage=0.80):
244
+ """Choose the best honest like-for-like dollar value for both arms.
245
+
246
+ Detailed per-model evidence is preferred. The older own-average card is a
247
+ degraded fallback for anchors pinned before that evidence existed; the fixed
248
+ card is the last resort. Returns (before_usd, now_usd, basis, detail).
249
+ """
250
+ before_usd, now_usd = before["flat_usd"], now["flat_usd"]
251
+ like_before = usable_value(facade, before, minimum_coverage)
252
+ like_now = usable_value(facade, now, minimum_coverage)
253
+ if like_before and like_now:
254
+ return like_before["usd"], like_now["usd"], "current_model_reference", {
255
+ "before": like_before, "now": like_now}
256
+ if callable(own):
257
+ own = own()
258
+ if own:
259
+ return own["before_usd"], own["now_usd"], "own_prices", None
260
+ return before_usd, now_usd, "fixed_card", None
261
+
262
+
263
+ def price_basis_label(basis):
264
+ return ("the same current model-family reference prices"
265
+ if basis == "current_model_reference" else
266
+ "your current average prices" if basis == "own_prices" else
267
+ "one fixed fallback price card")
268
+
269
+
270
+ def pool_price_disclosures(pool):
271
+ """JSON-safe pricing provenance for `_weight_pool_payload`."""
272
+ detail = (pool or {}).get("price_detail") or {}
273
+ before, now = detail.get("before") or {}, detail.get("now") or {}
274
+ return {
275
+ "price_coverage": now.get("coverage"),
276
+ "before_price_coverage": before.get("coverage"),
277
+ "unpriced_tokens": round(float(now.get("unpriced_tokens") or 0.0)),
278
+ "unpriced_models": now.get("unpriced_models"),
279
+ "unsplit_tokens_priced_at_input": round(float(now.get("unsplit_tokens") or 0.0)),
280
+ "reference_models": now.get("reference_models"),
281
+ }
282
+
283
+
284
+ def method_disclosures(weight_pool, subagent_window=None):
285
+ """Machine-readable reconciliation of the transformation's accounting choices."""
286
+ if not weight_pool:
287
+ return {}
288
+ price_basis = weight_pool.get("price_basis") or "fixed_card"
289
+ unit = weight_pool.get("work_unit") or "api_call"
290
+ return {
291
+ # Do not add `_subagent_pool_savings` on top of the work-normalized pool:
292
+ # session_activity prefers daily_usage_json, the COMBINED parent+delegated
293
+ # usage map written by collection, so delegated requests are already inside
294
+ # both weight-pool arms. subagent_window_* remains a drill-down diagnostic;
295
+ # adding its delta here would double count the same billed requests.
296
+ "subagent_accounting": {
297
+ "included_in_session_weight_pool": True,
298
+ "counted_when_to_caused": True,
299
+ "counting_method": ("inside the work-normalized pool: nested delegated usage/calls are "
300
+ "combined into parent rows, and standalone sidechain rows are "
301
+ "included only when request-claim parser evidence makes them disjoint"),
302
+ "separate_delta_added": False,
303
+ "diagnostic_actual_usd": round(float((subagent_window or {}).get("actual_usd") or 0.0), 2),
304
+ "diagnostic_counterfactual_usd": round(float((subagent_window or {}).get("counterfactual_usd") or 0.0), 2),
305
+ "diagnostic_transformation_usd": round(float((subagent_window or {}).get("transformation_usd") or 0.0), 2),
306
+ "reason": ("Nested subagent tokens/calls are already combined into parent rows; "
307
+ "standalone sidechain rows are included only when request-claim parser "
308
+ "evidence makes them disjoint. A TO-caused reduction is therefore counted "
309
+ "in the pool itself. The raw subagent scan overlaps those rows, so its "
310
+ "delta is drill-down evidence only; adding it would double count."),
311
+ },
312
+ "cost_per_message_comparison": {
313
+ "same_price_basis": price_basis == "current_model_reference",
314
+ "trend_price_basis": "current_model_reference",
315
+ "transformation_price_basis": price_basis,
316
+ "trend_unit": "message",
317
+ "transformation_unit": unit,
318
+ "difference_reason": (
319
+ "Both cards now use the same current per-model-family reference prices, "
320
+ "but the trend is cost per message while the transformation is cost per "
321
+ f"{unit}. A change in messages per API call can move the two indices "
322
+ "differently even when their price basis is identical."
323
+ if unit == "api_call" else
324
+ "Both cards now use the same current per-model-family reference prices, "
325
+ "but the transformation cross-check can use API calls while the trend uses "
326
+ "messages. A change in messages per API call can move them differently."
327
+ ),
328
+ },
329
+ }
@@ -16,6 +16,45 @@ from pathlib import Path
16
16
  LIMIT_UNITS_LABEL = "share of window, modeled at API-rate weights"
17
17
 
18
18
 
19
+ def net_positive_debit(by_category, debit_key, credit_key):
20
+ debit = by_category.pop(debit_key, None)
21
+ if not debit:
22
+ return 0, 0.0, 0
23
+ d_tok = int(debit.get("tokens_saved", 0) or 0)
24
+ d_cost = float(debit.get("cost_saved_usd", 0.0) or 0.0)
25
+ d_events = int(debit.get("events", 0) or 0)
26
+ credit = by_category.setdefault(credit_key, {"events": 0, "tokens_saved": 0, "cost_saved_usd": 0.0})
27
+ credit["tokens_saved"] = int(credit.get("tokens_saved", 0) or 0) - d_tok
28
+ credit["cost_saved_usd"] = round(float(credit.get("cost_saved_usd", 0.0) or 0.0) - d_cost, 4)
29
+ return -2 * d_tok, -2 * d_cost, -d_events
30
+
31
+
32
+ def net_delta_reread_compression(by_feature):
33
+ out = {feature: dict(data) for feature, data in (by_feature or {}).items()}
34
+ debit = out.pop("delta_read_reread", None)
35
+ if not debit:
36
+ return out
37
+ target = out.setdefault("delta_read", {
38
+ "events": 0, "original_tokens": 0, "compressed_tokens": 0,
39
+ "tokens_saved": 0, "cost_saved_usd": 0.0,
40
+ })
41
+ for key in ("original_tokens", "compressed_tokens", "tokens_saved",
42
+ "unpriced_credit_tokens", "unpriced_debit_tokens", "unpriced_tokens"):
43
+ target[key] = int(target.get(key, 0) or 0) + int(debit.get(key, 0) or 0)
44
+ target["cost_saved_usd"] = round(
45
+ float(target.get("cost_saved_usd", 0.0) or 0.0)
46
+ + float(debit.get("cost_saved_usd", 0.0) or 0.0), 6)
47
+ return out
48
+
49
+
50
+ def net_delta_reread_tokens(rows):
51
+ out = dict(rows or {})
52
+ debit = int(out.pop("delta_read_reread", 0) or 0)
53
+ if debit:
54
+ out["delta_read"] = int(out.get("delta_read", 0) or 0) + debit
55
+ return out
56
+
57
+
19
58
  def _resolve_card(facade, model, tier=None, per_request=False, full_input=0):
20
59
  """Return the exact rate card dict for *model*, or None if unknown (R9/R10)."""
21
60
  if not model:
@@ -0,0 +1,133 @@
1
+ """Cross-provider model families for like-for-like transformation pricing.
2
+
3
+ A family is a capability tier, not a bare provider name: mini/nano/pro tiers stay
4
+ separate because moving work between them is real routing, while versioned members
5
+ of one tier (gpt-5-codex -> gpt-5.4, gemini-2.5-pro -> gemini-3-pro) are generation
6
+ movement and must use one current reference card.
7
+ """
8
+ import re
9
+
10
+ _GPT_RE = re.compile(r"^gpt-(\d+)(o)?(?:\.(\d+))?(?:-(.+))?$")
11
+ _GEMINI_VERSION_RE = re.compile(r"^gemini-(?:omni-)?(\d+)(?:\.(\d+))?")
12
+ _MODIFIER_RE = re.compile(r"-(?:preview|latest)(?:-customtools)?$")
13
+
14
+
15
+ def _version(major, minor):
16
+ return (int(major), int(minor or 0))
17
+
18
+
19
+ def openai_family(model):
20
+ """(stable group key, version) for a priced OpenAI id, or None."""
21
+ if not isinstance(model, str):
22
+ return None
23
+ value = model.lower()
24
+ m = _GPT_RE.fullmatch(value)
25
+ if not m:
26
+ o_series = re.fullmatch(r"o(\d+)(?:-(mini|pro))?", value)
27
+ if o_series:
28
+ # o1 -> o3 is a generation move inside one reasoning tier.
29
+ return (f"openai:o-{o_series.group(2) or 'standard'}", _version(o_series.group(1), 0))
30
+ return None
31
+ suffix = (m.group(4) or "").lower()
32
+ if m.group(2):
33
+ suffix = "omni" + (("-" + suffix) if suffix else "")
34
+ base = _MODIFIER_RE.sub("", suffix)
35
+ base = base.removesuffix("-customtools")
36
+ if base.startswith("turbo") and m.group(1) == "3":
37
+ # gpt-3.5-turbo is a far cheaper tier than the gpt-4 flagships.
38
+ tier = "3.5-turbo"
39
+ elif base in ("", "codex", "codex-max", "chat", "sol", "omni", "turbo", "1106"):
40
+ # Flagship generations: gpt-4 / 4-turbo / 4o / 4.1 / 5.x / codex(-max).
41
+ tier = "standard"
42
+ elif base.endswith("mini"):
43
+ tier = "mini"
44
+ elif base.endswith("nano"):
45
+ tier = "nano"
46
+ elif base.endswith("pro"):
47
+ tier = "pro"
48
+ elif base.startswith("cyber"):
49
+ tier = "cyber"
50
+ elif base.startswith("terra"):
51
+ tier = "terra"
52
+ elif base.startswith("luna"):
53
+ tier = "luna"
54
+ elif base.startswith("astra-law"):
55
+ tier = "astra-law"
56
+ elif base.startswith("astra"):
57
+ tier = "astra"
58
+ elif base.startswith("rosalind"):
59
+ tier = "rosalind"
60
+ elif base.startswith("omni"):
61
+ tier = base
62
+ else:
63
+ tier = base or "standard"
64
+ return (f"openai:gpt-{tier}", _version(m.group(1), m.group(3)))
65
+
66
+
67
+ def gemini_family(model):
68
+ """(stable group key, version) for a priced Gemini id, or None."""
69
+ if not isinstance(model, str):
70
+ return None
71
+ value = model.lower()
72
+ if not value.startswith("gemini-"):
73
+ return None
74
+ vm = _GEMINI_VERSION_RE.match(value)
75
+ version = _version(vm.group(1), vm.group(2)) if vm else (0, 0)
76
+ if value.startswith("gemini-omni-"):
77
+ # The multimodal omni tier is priced about 2x standard flash.
78
+ tier = "omni-flash" if "flash" in value else "omni"
79
+ elif "flash-lite" in value:
80
+ tier = "flash-lite"
81
+ elif "flash" in value:
82
+ tier = "flash"
83
+ elif "pro" in value:
84
+ tier = "pro"
85
+ elif value.startswith("gemini-gemma"):
86
+ tier = value[len("gemini-"):].split("-it")[0].rstrip("-")
87
+ elif value.startswith("gemini-robotics"):
88
+ tier = "robotics"
89
+ elif vm:
90
+ rest = value[vm.end():].strip("-")
91
+ tier = rest.split("-", 1)[0] if rest else "standard"
92
+ else:
93
+ tier = value[len("gemini-"):].replace("-latest", "") or "standard"
94
+ return (f"gemini:{tier}", version)
95
+
96
+
97
+ def foreign_group_key(facade, model):
98
+ """Stable like-for-like group for a priced OpenAI/Gemini id, or None."""
99
+ for normalizer, classifier in (
100
+ ("_normalize_openai_model_name", openai_family),
101
+ ("_normalize_gemini_model_name", gemini_family)):
102
+ try:
103
+ exact = getattr(facade, normalizer)(model)
104
+ except Exception:
105
+ exact = None
106
+ if exact:
107
+ family = classifier(exact)
108
+ if family:
109
+ return family[0]
110
+ return None
111
+
112
+
113
+ def newest_reference(group, openai_table=None, gemini_table=None):
114
+ """Newest exact model id in a stable group, or None when the group is foreign
115
+ to the supplied rate tables. Versionless aliases lose to versioned cards."""
116
+ if not isinstance(group, str):
117
+ return None
118
+ if group.startswith("openai:"):
119
+ table, classifier = openai_table or {}, openai_family
120
+ elif group.startswith("gemini:"):
121
+ table, classifier = gemini_table or {}, gemini_family
122
+ else:
123
+ return None
124
+ best = None
125
+ for key in table:
126
+ family = classifier(key)
127
+ if not family or family[0] != group:
128
+ continue
129
+ preview_penalty = 0 if ("preview" not in key and "latest" not in key) else -1
130
+ score = (family[1][0], family[1][1], preview_penalty, -len(key))
131
+ if best is None or score > best[0]:
132
+ best = (score, key)
133
+ return best[1] if best else None
@@ -1,18 +1,20 @@
1
- """Price the work-normalized transformation at the user's own current prices.
1
+ """Like-for-like price evidence for the work-normalized transformation.
2
2
 
3
3
  The transformation compares cost per unit of work in a baseline window with
4
- the same figure now, both priced on ONE card so a vendor price change or a
5
- model switch cannot count as a saving. That card used to be a fixed Opus 4.x
6
- card for every user, which put a Sonnet, Haiku or other-provider user's result
7
- in dollars two to five times their own. Here the card is the user's own: for
8
- each token class, what they actually paid per million tokens this period,
9
- averaged over the models they ran.
4
+ the same figure now, both priced on one CURRENT reference card per model
5
+ family. Generation movement inside a family (Opus 4.x -> Opus 5.x) is vendor
6
+ or model drift and cannot count as a Token Optimizer saving or loss; movement
7
+ between families still counts because routing work is real behavior change.
8
+ This module preserves the detailed per-model class evidence needed to reprice
9
+ a frozen baseline as current reference cards change.
10
10
 
11
11
  A baseline pinned before per-class token sums were kept cannot be re-priced
12
- until those sums are rebuilt from its transcripts; until then the fixed card
13
- stays in use and is named as such on the page.
12
+ until those sums are rebuilt from its transcripts; until then the older fixed
13
+ card stays in use and is named as such on the page.
14
14
  """
15
15
 
16
+ from . import like_for_like
17
+
16
18
  CLASSES = ("input", "output", "cache_read", "cache_write")
17
19
  _ZERO = {"sessions": 0, "usd": 0.0, "tokens": 0.0, "flat_usd": 0.0, "api_calls": 0, "messages": 0}
18
20
  # A rebuilt baseline may differ this much from the pinned one and still lend it
@@ -60,6 +62,7 @@ def price_rows(facade, rows, tier, api_calls_unknown=None):
60
62
  return {"sessions": len(rows), "usd": usd, "tokens": tokens,
61
63
  "flat_usd": flat_usd, "api_calls": api_calls, "messages": messages,
62
64
  "classes": classes,
65
+ "model_classes": like_for_like.rows_to_model_classes(facade, rows),
63
66
  # Sessions whose dated per-day call evidence was never recorded.
64
67
  # api_calls is then a lower bound, not a measured total.
65
68
  "api_calls_unknown": int(api_calls_unknown or 0)}
@@ -81,14 +84,22 @@ def lend_classes(frozen, fresh):
81
84
  """Give a frozen month its class split from the same month re-read from the
82
85
  ledger, when the two still agree. True when `frozen` was changed."""
83
86
  try:
84
- if classes_of(frozen) or not fresh:
87
+ has_classes = bool(classes_of(frozen))
88
+ has_models = bool((frozen or {}).get("model_classes"))
89
+ if (has_classes and has_models) or not fresh:
85
90
  return False
86
91
  split = classes_of(fresh)
87
92
  old, new = float(frozen["flat_usd"]), float(fresh["flat_usd"])
88
93
  if not split or not (old > 0 and new > 0) or abs(new - old) > _REBUILD_TOLERANCE * old:
89
94
  return False
90
- frozen["classes"] = {k: split[k] * old / new for k in CLASSES}
91
- return True
95
+ changed = False
96
+ if split and not has_classes:
97
+ frozen["classes"] = {k: split[k] * old / new for k in CLASSES}
98
+ changed = True
99
+ if fresh.get("model_classes") and not has_models:
100
+ frozen["model_classes"] = like_for_like.scale_model_classes(fresh["model_classes"], old / new)
101
+ changed = True
102
+ return changed
92
103
  except (KeyError, TypeError, ValueError):
93
104
  return False
94
105
 
@@ -160,7 +171,7 @@ def apply(facade, before, now, days):
160
171
 
161
172
 
162
173
  def _blank():
163
- return dict(_ZERO, classes=dict.fromkeys(CLASSES, 0.0))
174
+ return dict(_ZERO, classes=dict.fromkeys(CLASSES, 0.0), model_classes={})
164
175
 
165
176
 
166
177
  def _walk(facade, progress, start, end, budget_seconds, tier):
@@ -169,6 +180,7 @@ def _walk(facade, progress, start, end, budget_seconds, tier):
169
180
  seen = set(progress.get("seen") or [])
170
181
  metrics = progress["metrics"]
171
182
  metrics.setdefault("classes", dict.fromkeys(CLASSES, 0.0))
183
+ metrics.setdefault("model_classes", {})
172
184
  deadline = facade.time.monotonic() + budget_seconds
173
185
  cursor = int(progress.get("cursor") or 0)
174
186
  while cursor < len(files) and facade.time.monotonic() < deadline:
@@ -185,6 +197,7 @@ def _walk(facade, progress, start, end, budget_seconds, tier):
185
197
  metrics[key] += priced[key]
186
198
  for key in CLASSES:
187
199
  metrics["classes"][key] += priced["classes"][key]
200
+ like_for_like.merge_model_classes(metrics["model_classes"], priced.get("model_classes"))
188
201
  progress["cursor"], progress["seen"] = cursor, sorted(seen)
189
202
  return cursor >= len(files)
190
203
 
@@ -206,6 +219,11 @@ def _fill_classes(facade, state, budget_seconds, tier):
206
219
  state["classes_status"] = "unavailable"
207
220
  return
208
221
  fill = state.get("class_fill")
222
+ if (isinstance(fill, dict) and isinstance(fill.get("metrics"), dict)
223
+ and "model_classes" not in fill["metrics"]):
224
+ # A fill started before per-model evidence existed cannot be resumed:
225
+ # its already-seen transcripts would be missing from the new arm.
226
+ fill = None
209
227
  if not isinstance(fill, dict) or not isinstance(fill.get("metrics"), dict):
210
228
  fill = {"cursor": 0, "seen": [], "metrics": _blank()}
211
229
  if not _walk(facade, fill, window[0], window[1], budget_seconds, tier):
@@ -216,6 +234,7 @@ def _fill_classes(facade, state, budget_seconds, tier):
216
234
  if old > 0 and new > 0 and abs(new - old) <= _REBUILD_TOLERANCE * old:
217
235
  scale = old / new
218
236
  state["metrics"]["classes"] = {k: fill["metrics"]["classes"][k] * scale for k in CLASSES}
237
+ state["metrics"]["model_classes"] = like_for_like.scale_model_classes(fill["metrics"].get("model_classes"), scale)
219
238
  state["classes_filled_at"] = facade.datetime.now().isoformat()
220
239
  else:
221
240
  state["classes_status"] = "unavailable"
@@ -242,12 +261,17 @@ def anchor_step(facade, budget_seconds=None, tier=None):
242
261
  window = facade._pretool_window()
243
262
  if window and state.get("window") != list(window):
244
263
  state = {}
264
+ if (state.get("status") == "building" and isinstance(state.get("metrics"), dict)
265
+ and "model_classes" not in state["metrics"]):
266
+ # Same migration rule for an anchor build interrupted by the upgrade.
267
+ state = {}
245
268
  if state.get("status") == "unavailable":
246
269
  return "unavailable"
247
270
  if tier is None:
248
271
  tier = facade._load_pricing_tier()
249
272
  if state.get("status") == "pinned":
250
- if classes_of(state.get("metrics") or {}) or state.get("classes_status") == "unavailable":
273
+ metrics = state.get("metrics") or {}
274
+ if (classes_of(metrics) and metrics.get("model_classes")) or state.get("classes_status") == "unavailable":
251
275
  return "pinned"
252
276
  _fill_classes(facade, state, budget_seconds, tier)
253
277
  facade._write_baseline_state(path, state)