compactlab 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. compactlab/__init__.py +3 -0
  2. compactlab/adapters/__init__.py +2 -0
  3. compactlab/adapters/base.py +212 -0
  4. compactlab/adapters/cache.py +396 -0
  5. compactlab/adapters/claude_code.py +226 -0
  6. compactlab/adapters/codex.py +298 -0
  7. compactlab/adapters/dsh.py +287 -0
  8. compactlab/adapters/gemini_cli.py +259 -0
  9. compactlab/adapters/opencode.py +375 -0
  10. compactlab/apply/__init__.py +582 -0
  11. compactlab/cli/__init__.py +5 -0
  12. compactlab/cli/main.py +2436 -0
  13. compactlab/data/config_knobs.json +158 -0
  14. compactlab/data/harness_defaults.json +72 -0
  15. compactlab/data/harness_formats.json +300 -0
  16. compactlab/data/pricing.json +51 -0
  17. compactlab/engine/__init__.py +138 -0
  18. compactlab/engine/live.py +306 -0
  19. compactlab/engine/settings.py +175 -0
  20. compactlab/engine/watch.py +82 -0
  21. compactlab/eval/__init__.py +1 -0
  22. compactlab/eval/deep.py +390 -0
  23. compactlab/eval/executors.py +84 -0
  24. compactlab/eval/factcheck.py +75 -0
  25. compactlab/lens.py +80 -0
  26. compactlab/model/__init__.py +285 -0
  27. compactlab/pricing/__init__.py +211 -0
  28. compactlab/pricing/auto.py +118 -0
  29. compactlab/pricing/ids.py +148 -0
  30. compactlab/pricing/refresh.py +299 -0
  31. compactlab/publish.py +125 -0
  32. compactlab/py.typed +0 -0
  33. compactlab/recommend/__init__.py +201 -0
  34. compactlab/recommend/claude_code.py +172 -0
  35. compactlab/recommend/codex.py +104 -0
  36. compactlab/recommend/dsh.py +89 -0
  37. compactlab/recommend/gemini_cli.py +85 -0
  38. compactlab/recommend/opencode.py +117 -0
  39. compactlab/recommend/units.py +63 -0
  40. compactlab/report/__init__.py +3 -0
  41. compactlab/report/html.py +27 -0
  42. compactlab/report/template.html +1189 -0
  43. compactlab/service/__init__.py +1 -0
  44. compactlab/service/core.py +220 -0
  45. compactlab/service/http.py +133 -0
  46. compactlab/service/lock.py +92 -0
  47. compactlab/service/policy.py +258 -0
  48. compactlab/service/schedule.py +212 -0
  49. compactlab/share.py +553 -0
  50. compactlab/sim/__init__.py +1 -0
  51. compactlab/sim/baseline.py +214 -0
  52. compactlab/sim/calibrate.py +108 -0
  53. compactlab/sim/engine.py +1130 -0
  54. compactlab/sim/select.py +238 -0
  55. compactlab/sim/timing.py +134 -0
  56. compactlab/synth.py +416 -0
  57. compactlab/term/__init__.py +0 -0
  58. compactlab/term/style.py +134 -0
  59. compactlab/term/top.py +531 -0
  60. compactlab/term/views.py +598 -0
  61. compactlab/term/widgets.py +238 -0
  62. compactlab/verify.py +462 -0
  63. compactlab-0.2.0.dist-info/METADATA +243 -0
  64. compactlab-0.2.0.dist-info/RECORD +67 -0
  65. compactlab-0.2.0.dist-info/WHEEL +4 -0
  66. compactlab-0.2.0.dist-info/entry_points.txt +2 -0
  67. compactlab-0.2.0.dist-info/licenses/LICENSE +21 -0
compactlab/lens.py ADDED
@@ -0,0 +1,80 @@
1
+ """A small per-group summary for the compactlab-lens mod (mods/compactlab-lens).
2
+
3
+ The mod reads files of at most 4 MiB and only needs thresholds and per-day impact per model and role, so `simulate`
4
+ writes this alongside the full result. No session ids, paths or transcript text are included.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from .publish import harness_info
12
+ from .sim.select import PROFILE_NAMES
13
+
14
+ LENS_SCHEMA = 1
15
+
16
+
17
+ def _impact(c: dict[str, Any] | None) -> dict[str, Any] | None:
18
+ im = (c or {}).get("impact")
19
+ if not im:
20
+ return None
21
+ return {
22
+ "usd_per_day": im["usd"]["per_day"],
23
+ "usd_per_active_day": im["usd"]["per_active_day"],
24
+ "min_per_day": im["minutes"]["per_day"],
25
+ "wait_min_per_day": im["wait_minutes"]["per_day"],
26
+ "turn_gain_min_per_day": im["turn_gain_minutes"]["per_day"],
27
+ "compactions_per_day": im["compactions"]["per_day"],
28
+ "ref_compactions_per_day": im["ref_compactions"]["per_day"],
29
+ # share of the reference's window cost / total wall-clock (None when the reference is zero)
30
+ "cost_pct": _pct(c, "d_cost"),
31
+ "time_pct": _pct(c, "d_time_s", "d_time_pct"),
32
+ }
33
+
34
+
35
+ def _pct(c: dict[str, Any] | None, delta: str, key: str = "d_cost_pct") -> float | None:
36
+ c = c or {}
37
+ if key not in c:
38
+ return None
39
+ # compare() writes 0.0 when the reference is zero; a nonzero change over a zero reference has no percent
40
+ return None if c[key] == 0 and c.get(delta) else float(c[key])
41
+
42
+
43
+ def summarize(result: dict[str, Any]) -> dict[str, Any]:
44
+ groups = []
45
+ for g in result["groups"]:
46
+ cur = g.get("current")
47
+ groups.append(
48
+ {
49
+ "harness": g["harness"],
50
+ "model": g["model"],
51
+ "role": g["role"],
52
+ "selected": g.get("profile"),
53
+ "default_threshold": g["default"]["threshold"],
54
+ "current_threshold": cur.get("configured", cur["threshold"]) if cur else None,
55
+ "effective_max": g.get("effective_max"),
56
+ "max_window": g.get("max_window"),
57
+ "days": g["days"],
58
+ "active_days": g.get("active_days"),
59
+ "no_action_needed": g["no_action_needed"],
60
+ "profiles": {
61
+ n: {
62
+ "threshold": g["profiles"][n]["threshold"],
63
+ "action": g["comparison"][n]["action"],
64
+ "flags": list(g["profiles"][n]["flags"]),
65
+ "vs_default": _impact(g["comparison"][n]["vs_default"]),
66
+ "vs_current": _impact(g["comparison"][n].get("vs_current")),
67
+ }
68
+ for n in PROFILE_NAMES
69
+ },
70
+ }
71
+ )
72
+ return {
73
+ "schema": LENS_SCHEMA,
74
+ "mode": result.get("mode"),
75
+ "data_through": result.get("data_through"),
76
+ "demo": bool(result.get("demo")),
77
+ "groups": groups,
78
+ # per harness: mode, newest turn, calibration; the file keeps every harness's latest run (publish.py)
79
+ "harnesses": {h: {k: v for k, v in i.items() if k != "options"} for h, i in harness_info(result).items()},
80
+ }
@@ -0,0 +1,285 @@
1
+ """Normalized event model shared by all harness adapters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import re
7
+ import sys
8
+ from dataclasses import dataclass, field
9
+ from typing import Any
10
+
11
+ # A user message that corrects the agent ("I already told you", "你忘了"): counted by the re-discovery penalty.
12
+ CORRECTION_RE = re.compile(
13
+ r"(\bi (already )?(told|said|mentioned)\b|\byou forgot\b|\bas i said\b|\bnot what i\b|"
14
+ r"\bwe (already )?(did|discussed|decided)\b|\balready (told|said|did)\b|"
15
+ r"我说过|我刚才说|你忘了|不是这个|已经说过|之前说过|刚才不是)",
16
+ re.I,
17
+ )
18
+ # Every match of CORRECTION_RE contains one of these (lowercase), starting at most _BEFORE characters after the
19
+ # match starts and ending at most _AFTER characters before it ends ("i already told", "we already discussed"). So
20
+ # the regex need only run on short windows around them, which is many times faster on long messages. `str.lower`
21
+ # keeps positions and differs from the regex's case-insensitive matching only for the four letters below; a text
22
+ # with one of them goes straight to the regex.
23
+ _CORRECTION_WORDS = ("told", "said", "mentioned", "you forgot", "not what i", "we did", "we discussed", "we decided",
24
+ "we already ", "already did", "我说过", "我刚才说", "你忘了", "不是这个", "已经说过", "之前说过",
25
+ "刚才不是") # fmt: skip
26
+ _BEFORE, _AFTER = 10, 9
27
+ _FOLDS_TO_ASCII = ("\u0130", "\u0131", "\u017f", "\u212a") # İ ı ſ K
28
+
29
+
30
+ def corrects(text: str) -> bool:
31
+ """Whether a user message corrects the agent: exactly `CORRECTION_RE.search(text)`, run only where it can match.
32
+
33
+ A window starts _BEFORE characters before a word (the regex sees the real text before it, so `\b` there is
34
+ exact) and ends _AFTER + 1 after it, merged with overlapping ones: a match ends before the window's end, so the
35
+ end of the window never stands in for the end of the text."""
36
+ if not text:
37
+ return False
38
+ if any(c in text for c in _FOLDS_TO_ASCII):
39
+ return CORRECTION_RE.search(text) is not None
40
+ low = text.lower()
41
+ spans = []
42
+ for w in _CORRECTION_WORDS:
43
+ i = low.find(w)
44
+ while i >= 0:
45
+ spans.append((max(i - _BEFORE, 0), i + len(w) + _AFTER + 1))
46
+ i = low.find(w, i + 1)
47
+ if not spans:
48
+ return False
49
+ spans.sort()
50
+ start, end = spans[0]
51
+ for a, b in spans[1:]:
52
+ if a > end:
53
+ if CORRECTION_RE.search(text, start, end):
54
+ return True
55
+ start = a
56
+ end = max(end, b)
57
+ return CORRECTION_RE.search(text, start, end) is not None
58
+
59
+
60
+ @dataclass
61
+ class Turn:
62
+ """One model response (one billed API call)."""
63
+
64
+ ts: float | None # epoch seconds, None if unknown
65
+ ctx: int # total input tokens seen by the model (input+cache_read+cache_write)
66
+ cache_read: int = 0
67
+ cache_write: int = 0
68
+ cache_write_1h: int = 0 # part of cache_write billed at the 1-hour tier (Anthropic usage.cache_creation)
69
+ output: int = 0
70
+ model: str = "unknown"
71
+ tool_keys: list[str] = field(default_factory=list) # e.g. "Read:/a/b.py", normalized
72
+ tool_result_tokens: list[int] = field(default_factory=list) # parallel to tool_keys (estimated)
73
+ user_text: str = "" # user text that preceded this turn (may be empty)
74
+ snippets: list[str] = field(default_factory=list) # truncated tool commands/results, for fact checks
75
+ start_ts: float | None = None # when the request was sent (last user/tool-result line before it)
76
+ correction: bool = False # set by `lean()`: user_text matched CORRECTION_RE before it was dropped
77
+
78
+ def corrects(self) -> bool:
79
+ """Whether the user text before this turn corrects the agent (from the text, or from a lean turn's flag)."""
80
+ return self.correction or corrects(self.user_text)
81
+
82
+
83
+ @dataclass
84
+ class Compaction:
85
+ turn_index: int # index of the first turn *after* the boundary
86
+ pre_tokens: int | None = None
87
+ ts: float | None = None
88
+ summary_text: str = ""
89
+ duration_s: float | None = None # wall-clock spent compacting, if it can be inferred
90
+ trigger: str = "" # "auto" | "manual" (/compact) | "" when the log does not say
91
+ idle: bool = False # Claude Code idle compaction: precomputed while the cache was warm, applied on return
92
+ summary_chars: int = 0 # set by `lean()`: the length of summary_text before it was dropped
93
+
94
+ @property
95
+ def summary_len(self) -> int:
96
+ """Characters of the summary: of its text, or of a lean compaction's recorded length."""
97
+ return len(self.summary_text) if self.summary_text else self.summary_chars
98
+
99
+ def set_summary(self, text: str) -> None:
100
+ """Replace the summary (a parser that learns it after the boundary, possibly on a lean compaction)."""
101
+ self.summary_text, self.summary_chars = text, 0
102
+
103
+
104
+ def is_auto(c: Compaction) -> bool:
105
+ """A compaction the harness made by itself (threshold or idle). Unknown counts as auto; only a logged manual one
106
+ is excluded."""
107
+ return c.trigger != "manual"
108
+
109
+
110
+ def is_threshold(c: Compaction) -> bool:
111
+ """A compaction the auto-compact threshold caused: automatic and not an idle compaction."""
112
+ return is_auto(c) and not c.idle
113
+
114
+
115
+ @dataclass
116
+ class Session:
117
+ id: str
118
+ harness: str # "claude-code" | "codex" | ...
119
+ role: str # "main" | "subagent"
120
+ path: str
121
+ turns: list[Turn] = field(default_factory=list)
122
+ compactions: list[Compaction] = field(default_factory=list)
123
+ context_window: int | None = None
124
+ platform: str | None = None # where the model ran, when the log says (Codex `model_provider`)
125
+ parent_id: str | None = None # fork/resume lineage, when the harness records it
126
+ unknown_events: dict[str, int] = field(default_factory=dict) # event types the parser did not use
127
+ parse_errors: int = 0 # malformed lines skipped
128
+ skipped_inherited: int = 0 # usage events judged to be copied from a parent session
129
+
130
+ @property
131
+ def model(self) -> str:
132
+ counts: dict[str, int] = {}
133
+ for t in self.turns:
134
+ counts[t.model] = counts.get(t.model, 0) + 1
135
+ return max(counts, key=lambda k: counts[k]) if counts else "unknown"
136
+
137
+ @property
138
+ def peak(self) -> int:
139
+ return max((t.ctx for t in self.turns), default=0)
140
+
141
+
142
+ def session_to_dict(s: Session) -> dict:
143
+ """Fast JSON-ready dict (dataclasses.asdict deep-copies and is ~20x slower on large sessions)."""
144
+ d = dict(vars(s))
145
+ d["turns"] = [dict(vars(t)) for t in s.turns]
146
+ d["compactions"] = [dict(vars(c)) for c in s.compactions]
147
+ d["unknown_events"] = dict(s.unknown_events)
148
+ return d
149
+
150
+
151
+ # ---------- lean sessions: what the lite analysis needs, without the transcript's text ----------
152
+ #
153
+ # The lite analysis reads text in three places only: whether a user message corrects the agent (CORRECTION_RE), which
154
+ # tool calls repeat (identity and tool name), and how long a compaction summary is. A lean session keeps those as a
155
+ # flag, a hashed key and a length, and drops the prompts, output snippets and summaries. The scan cache stores lean
156
+ # sessions and the lite analysis runs on them (a fraction of the memory); deep mode, which reads text, parses the
157
+ # logs itself. `lean` is idempotent, and a parser resumed from a lean session keeps working: it only appends to
158
+ # earlier turns, never reads their text.
159
+
160
+ _HASHED = "\x00" # never in a tool key a harness logged
161
+
162
+
163
+ def tool_id(key: str) -> str:
164
+ """A tool key without its argument's text: the tool name (what `_is_rediscovery` reads) and a 96-bit hash of the
165
+ whole key, so equal keys stay equal. `key.split(":", 1)[0]` is the same before and after."""
166
+ if _HASHED in key:
167
+ return sys.intern(key)
168
+ digest = hashlib.blake2b(key.encode(), digest_size=12).hexdigest()
169
+ return sys.intern(f"{key.partition(':')[0]}:{_HASHED}{digest}")
170
+
171
+
172
+ def lean(s: Session) -> Session:
173
+ """Drop the text of a session in place (see above) and share repeated strings; returns it."""
174
+ for t in s.turns:
175
+ if t.user_text:
176
+ t.correction = t.corrects()
177
+ t.user_text = ""
178
+ if t.snippets:
179
+ t.snippets = []
180
+ if t.tool_keys:
181
+ t.tool_keys = [tool_id(k) for k in t.tool_keys]
182
+ t.model = sys.intern(t.model)
183
+ for c in s.compactions:
184
+ if c.summary_text:
185
+ c.summary_chars, c.summary_text = len(c.summary_text), ""
186
+ return s
187
+
188
+
189
+ def lean_dict(d: dict[str, Any]) -> dict[str, Any]:
190
+ """`lean` for a session as `session_to_dict` gives it; returns a new dict and leaves `d` (and its lists) alone."""
191
+ out = dict(d)
192
+ turns = []
193
+ for t in d.get("turns", []):
194
+ t = dict(t)
195
+ if t.get("user_text"):
196
+ t["correction"] = bool(t.get("correction")) or corrects(t["user_text"])
197
+ t["user_text"] = ""
198
+ if t.get("snippets"):
199
+ t["snippets"] = []
200
+ if t.get("tool_keys"):
201
+ t["tool_keys"] = [tool_id(k) for k in t["tool_keys"]]
202
+ turns.append(t)
203
+ out["turns"] = turns
204
+ comps = []
205
+ for c in d.get("compactions", []):
206
+ if c.get("summary_text"):
207
+ c = {**c, "summary_chars": len(c["summary_text"]), "summary_text": ""}
208
+ comps.append(c)
209
+ out["compactions"] = comps
210
+ return out
211
+
212
+
213
+ # what a pending user message that corrects the agent is kept as in the scan cache: `lean` keeps only that it does
214
+ CORRECTION_MARK = "as I said"
215
+
216
+
217
+ def lean_state(st: dict[str, Any]) -> dict[str, Any]:
218
+ """A parser's resume state (`Parser.dump`, without its session) with no text, for the scan cache; resuming from
219
+ it gives the same lean session as a full parse. What the log has not yet attached to a turn keeps only what
220
+ `lean` keeps of it: of a user message, whether it corrects the agent; of a tool call, its key's tool name and
221
+ hash; of its output, the token count. Returns a new dict."""
222
+ out = dict(st)
223
+ if out.get("pending_user"):
224
+ out["pending_user"] = CORRECTION_MARK if corrects(out["pending_user"]) else ""
225
+ if out.get("pending_tools"):
226
+ out["pending_tools"] = [[cid, tool_id(key)] for cid, key in out["pending_tools"]]
227
+ if out.get("pending_results"):
228
+ out["pending_results"] = {cid: ["", toks] for cid, (_, toks) in out["pending_results"].items()}
229
+ return out
230
+
231
+
232
+ def snapshot(s: Session) -> Session:
233
+ """Copy of a session that a parser can keep appending to without affecting the copy's lists."""
234
+ out = Session(**{**vars(s), "turns": list(s.turns), "unknown_events": dict(s.unknown_events)})
235
+ out.compactions = [Compaction(**vars(c)) for c in s.compactions if c.turn_index < len(s.turns)]
236
+ return out
237
+
238
+
239
+ def session_from_dict(d: dict) -> Session:
240
+ d = dict(d)
241
+ d["turns"] = [Turn(**t) for t in d.get("turns", [])]
242
+ d["compactions"] = [Compaction(**c) for c in d.get("compactions", [])]
243
+ return Session(**d)
244
+
245
+
246
+ def drop_inherited(sessions: list[Session]) -> list[Session]:
247
+ """Remove history a resumed or forked session copied from an earlier session's log.
248
+
249
+ Claude Code writes the parent's messages into the new file with their original timestamps, so the same API call
250
+ would be billed and counted once per copy. The earliest session keeps a turn (or compaction); later copies drop
251
+ it and count it in `skipped_inherited`. Sessions left empty are dropped. Turns without a timestamp are kept.
252
+ """
253
+ seen_turns: set[tuple] = set()
254
+ seen_comps: set[tuple] = set()
255
+ out: list[Session] = []
256
+ for s in sorted(sessions, key=lambda x: min((t.ts for t in x.turns if t.ts), default=float("inf"))):
257
+ keep: list[Turn] = []
258
+ new_index: list[int] = [] # original turn index -> index among the kept turns
259
+ for t in s.turns:
260
+ new_index.append(len(keep))
261
+ key = (t.ts, t.ctx, t.cache_read, t.cache_write, t.output, t.model)
262
+ if t.ts is not None and key in seen_turns:
263
+ continue
264
+ if t.ts is not None:
265
+ seen_turns.add(key)
266
+ keep.append(t)
267
+ comps = []
268
+ for c in s.compactions:
269
+ ckey = (c.ts, c.pre_tokens, c.trigger)
270
+ if c.ts is not None and ckey in seen_comps:
271
+ continue
272
+ if c.ts is not None:
273
+ seen_comps.add(ckey)
274
+ if c.turn_index < len(new_index):
275
+ c.turn_index = new_index[c.turn_index]
276
+ else:
277
+ c.turn_index = len(keep)
278
+ if c.turn_index < len(keep):
279
+ comps.append(c)
280
+ if len(keep) != len(s.turns):
281
+ s.skipped_inherited += len(s.turns) - len(keep)
282
+ s.turns, s.compactions = keep, comps
283
+ if s.turns:
284
+ out.append(s)
285
+ return out
@@ -0,0 +1,211 @@
1
+ """Versioned pricing with provenance. Prices are USD per million tokens.
2
+
3
+ Load order (later wins per model row): bundled snapshot -> refreshed cache (`compactlab pricing
4
+ refresh`, skipped with offline=True) -> user override file. Every `Price` records where it came from and how the model
5
+ was matched (`kind`): its own row, the vendor's price for a platform with no row of its own, a borrowed row from the
6
+ same model family, or the fallback row.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from dataclasses import dataclass, replace
13
+ from importlib import resources
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from .ids import family, first_party, nearest, parse, platform_key, platform_name
18
+
19
+ DEFAULT_REFRESHED = Path("~/.compactlab/pricing-refreshed.json")
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class Price:
24
+ input: float
25
+ output: float
26
+ cache_write: float
27
+ cache_read: float
28
+ max_window: int = 200_000
29
+ long_above: int | None = None # requests with ctx above this use the long_* prices
30
+ long_input: float = 0.0
31
+ long_output: float = 0.0
32
+ long_cache_write: float = 0.0
33
+ long_cache_read: float = 0.0
34
+ cache_write_1h: float | None = None # 1-hour cache-write price, where the provider has that tier
35
+ long_cache_write_1h: float | None = None
36
+ key: str = "fallback"
37
+ source: str = "bundled"
38
+ # "exact": the model's own row (for its platform, if any); "vendor": the vendor's list price, used for a platform
39
+ # with no row of its own; "family": borrowed from the closest model of the same family; "fallback": nothing matched
40
+ kind: str = "exact"
41
+ platform: str | None = None
42
+
43
+ def for_ttl(self, ttl: float) -> Price:
44
+ """This price with cache writes at the tier a cache of `ttl` seconds is billed at (unchanged without one)."""
45
+ if ttl < 3600 or self.cache_write_1h is None:
46
+ return self
47
+ long_w = self.long_cache_write_1h if self.long_cache_write_1h is not None else self.long_cache_write
48
+ return replace(self, cache_write=self.cache_write_1h, long_cache_write=long_w)
49
+
50
+ def rates(self, ctx: int) -> tuple[float, float, float, float]:
51
+ """(input, output, cache_write, cache_read) per token for a request of size ctx."""
52
+ if self.long_above is not None and ctx > self.long_above:
53
+ r = (self.long_input, self.long_output, self.long_cache_write, self.long_cache_read)
54
+ else:
55
+ r = (self.input, self.output, self.cache_write, self.cache_read)
56
+ return (r[0] / 1e6, r[1] / 1e6, r[2] / 1e6, r[3] / 1e6)
57
+
58
+
59
+ def _base(r: dict[str, Any], k: str) -> float:
60
+ return float(r.get(k, r["input"]))
61
+
62
+
63
+ def _scaled(v: float, old: float, new: float) -> float:
64
+ """A tier price that was a fixed multiple of `old`, re-expressed against the new base price."""
65
+ return round(v * new / old, 6) if old else v
66
+
67
+
68
+ def _merge_row(prev: dict[str, Any], row: dict[str, Any]) -> dict[str, Any]:
69
+ """`row` over the same model's previous row. Tiers the new row omits are carried from `prev` but re-scaled
70
+ to the new base prices, so a refreshed input/cache price never keeps a stale 1-hour or long-context price."""
71
+ out = {**({"match": prev["match"]} if "match" in prev else {}), **row}
72
+ if "input" not in prev or "input" not in row:
73
+ return out
74
+ ratio = {k: (_base(prev, k), _base(row, k)) for k in ("input", "output", "cache_write", "cache_read")}
75
+ if "cache_write_1h" not in row and "cache_write_1h" in prev:
76
+ out["cache_write_1h"] = _scaled(prev["cache_write_1h"], *ratio["cache_write"])
77
+ plc, nlc = prev.get("long_context"), row.get("long_context")
78
+ if isinstance(plc, dict):
79
+ if nlc is None: # no long-context tier in the refresh: keep the old one, moved with the base prices
80
+ out["long_context"] = {
81
+ k: (v if k == "above_tokens" else _scaled(v, *ratio["cache_write" if k == "cache_write_1h" else k]))
82
+ for k, v in plc.items()
83
+ }
84
+ elif isinstance(nlc, dict) and "cache_write_1h" not in nlc and "cache_write_1h" in plc:
85
+ old, new = _base(plc, "cache_write"), _base(nlc, "cache_write")
86
+ out["long_context"] = {**nlc, "cache_write_1h": _scaled(plc["cache_write_1h"], old, new)}
87
+ return out
88
+
89
+
90
+ class PricingTable:
91
+ def __init__(self, data: dict[str, Any]):
92
+ if data.get("version") not in (1, 2):
93
+ raise ValueError(f"unsupported pricing file version: {data.get('version')!r}")
94
+ self.data = data
95
+ self.default_ttl = int(data.get("default_ttl_seconds", 300))
96
+ self._memo: dict[tuple[str, str | None], Price] = {}
97
+ self._alias: dict[str, str] = {} # exact alternative IDs from each row's `match` list
98
+ self._families: dict[str, dict[tuple[int, ...], str]] = {} # family -> version -> row key (vendor rows)
99
+ for k, row in data["models"].items():
100
+ if ":" in k: # a platform's own row: never borrowed for another model
101
+ continue
102
+ for pat in row.get("match", []):
103
+ self._alias.setdefault(pat.lower(), k)
104
+ fam, ver = family(parse(k).id)
105
+ self._families.setdefault(fam, {}).setdefault(ver, k)
106
+
107
+ @staticmethod
108
+ def bundled() -> dict[str, Any]:
109
+ d: dict[str, Any] = json.loads(resources.files("compactlab").joinpath("data/pricing.json").read_text())
110
+ for row in d["models"].values():
111
+ row.setdefault("source", f"bundled snapshot {d.get('retrieved', '')}".strip())
112
+ return d
113
+
114
+ @classmethod
115
+ def load(
116
+ cls, override: str | Path | None = None, refreshed: str | Path | None = DEFAULT_REFRESHED, offline: bool = False
117
+ ) -> PricingTable:
118
+ base = cls.bundled()
119
+ layers: list[tuple[Path, str]] = []
120
+ if refreshed and not offline:
121
+ layers.append((Path(refreshed).expanduser(), "refreshed"))
122
+ if override:
123
+ layers.append((Path(override).expanduser(), "user"))
124
+ bundled_date = str(base.get("retrieved", ""))
125
+ for path, label in layers:
126
+ if not path.exists():
127
+ continue
128
+ user = json.loads(path.read_text())
129
+ # a refresh older than the bundled snapshot (made before upgrading compactlab) only adds models the
130
+ # bundle lacks: the newer bundled price wins where both have one
131
+ stale = label == "refreshed" and str(user.get("retrieved") or "9999") < bundled_date
132
+ for k, row in user.get("models", {}).items():
133
+ if stale and k in base["models"]:
134
+ continue
135
+ prev = base["models"].get(k, {})
136
+ row = _merge_row(prev, row)
137
+ row.setdefault("source", f"{label}: {path.name} {user.get('retrieved', '')}".strip())
138
+ base["models"][k] = row
139
+ for k in ("fallback", "default_ttl_seconds", "note"):
140
+ if k in user:
141
+ base[k] = user[k]
142
+ return cls(base)
143
+
144
+ def lookup(self, model: str, platform: str | None = None) -> Price:
145
+ """The price for `model` as a harness logged it, on `platform` (a models.dev provider ID or a harness's name
146
+ for it; the ID's own shape is used when None). Order: the platform's own row, the model's row (exact key, then
147
+ a `match` alias), the closest row of the same family, the fallback row."""
148
+ ck = (model, platform)
149
+ if ck not in self._memo:
150
+ self._memo[ck] = self._lookup(model, platform)
151
+ return self._memo[ck]
152
+
153
+ def _lookup(self, model: str, platform: str | None) -> Price:
154
+ mid = parse(model)
155
+ # a platform the harness recorded (Codex model_provider, OpenCode provider ID) wins over the ID's shape: an
156
+ # OpenCode `anthropic/claude-…` is Anthropic's own API although OpenRouter spells IDs the same way
157
+ plat = platform_name(platform) if platform else mid.platform
158
+ vendor = first_party(mid.id)
159
+ rows = self.data["models"]
160
+ if plat and plat != vendor:
161
+ for k in (platform_key(plat, mid), platform_key(plat, parse(mid.id))):
162
+ if k in rows:
163
+ # tiers the platform row omits (1-hour cache writes, long context) follow the vendor's, scaled
164
+ own = rows.get(mid.id) or {}
165
+ return self._price(k, _merge_row(own, rows[k]) if own else rows[k], "exact", plat, mid.one_m)
166
+ raw = (model or "").strip().lower()
167
+ own = "vendor" if plat and plat != vendor else "exact"
168
+ for k in (raw, mid.id):
169
+ if k in rows:
170
+ return self._price(k, rows[k], own, plat, mid.one_m)
171
+ alias = self._alias.get(raw) or self._alias.get(mid.id)
172
+ if alias:
173
+ return self._price(alias, rows[alias], own, plat, mid.one_m)
174
+ fam, ver = family(mid.id)
175
+ cands = self._families.get(fam, {})
176
+ v = nearest(ver, list(cands)) if mid.id else None
177
+ if v is not None:
178
+ return self._price(cands[v], rows[cands[v]], "family", plat, mid.one_m)
179
+ # last resort: the longest `match` pattern contained in the ID (gpt-5.1-codex-max -> the gpt-5-codex row);
180
+ # override files written for the old substring matching keep working this way
181
+ best, best_len = None, 0
182
+ for k, row in rows.items():
183
+ for pat in row.get("match", []) if ":" not in k else []:
184
+ p = pat.lower()
185
+ if (p in raw or p in mid.id) and len(p) > best_len:
186
+ best, best_len = k, len(p)
187
+ if best:
188
+ return self._price(best, rows[best], "family", plat, mid.one_m)
189
+ return self._price("fallback", self.data["fallback"], "fallback", plat, mid.one_m)
190
+
191
+ def _price(self, key: str, row: dict[str, Any], kind: str, platform: str | None, one_m: bool) -> Price:
192
+ lc = row.get("long_context") or {}
193
+ window = int(row.get("max_window", 200_000))
194
+ return Price(
195
+ input=row["input"],
196
+ output=row["output"],
197
+ cache_write=row.get("cache_write", row["input"]),
198
+ cache_read=row.get("cache_read", row["input"]),
199
+ max_window=max(window, 1_000_000) if one_m else window, # the [1m] variant of a 200K model
200
+ long_above=lc.get("above_tokens"),
201
+ long_input=lc.get("input", 0),
202
+ long_output=lc.get("output", 0),
203
+ long_cache_write=lc.get("cache_write", 0),
204
+ long_cache_read=lc.get("cache_read", 0),
205
+ cache_write_1h=row.get("cache_write_1h"),
206
+ long_cache_write_1h=lc.get("cache_write_1h"),
207
+ key=key,
208
+ source=str(row.get("source", "fallback row" if key == "fallback" else "bundled")),
209
+ kind=kind,
210
+ platform=platform,
211
+ )