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.
- compactlab/__init__.py +3 -0
- compactlab/adapters/__init__.py +2 -0
- compactlab/adapters/base.py +212 -0
- compactlab/adapters/cache.py +396 -0
- compactlab/adapters/claude_code.py +226 -0
- compactlab/adapters/codex.py +298 -0
- compactlab/adapters/dsh.py +287 -0
- compactlab/adapters/gemini_cli.py +259 -0
- compactlab/adapters/opencode.py +375 -0
- compactlab/apply/__init__.py +582 -0
- compactlab/cli/__init__.py +5 -0
- compactlab/cli/main.py +2436 -0
- compactlab/data/config_knobs.json +158 -0
- compactlab/data/harness_defaults.json +72 -0
- compactlab/data/harness_formats.json +300 -0
- compactlab/data/pricing.json +51 -0
- compactlab/engine/__init__.py +138 -0
- compactlab/engine/live.py +306 -0
- compactlab/engine/settings.py +175 -0
- compactlab/engine/watch.py +82 -0
- compactlab/eval/__init__.py +1 -0
- compactlab/eval/deep.py +390 -0
- compactlab/eval/executors.py +84 -0
- compactlab/eval/factcheck.py +75 -0
- compactlab/lens.py +80 -0
- compactlab/model/__init__.py +285 -0
- compactlab/pricing/__init__.py +211 -0
- compactlab/pricing/auto.py +118 -0
- compactlab/pricing/ids.py +148 -0
- compactlab/pricing/refresh.py +299 -0
- compactlab/publish.py +125 -0
- compactlab/py.typed +0 -0
- compactlab/recommend/__init__.py +201 -0
- compactlab/recommend/claude_code.py +172 -0
- compactlab/recommend/codex.py +104 -0
- compactlab/recommend/dsh.py +89 -0
- compactlab/recommend/gemini_cli.py +85 -0
- compactlab/recommend/opencode.py +117 -0
- compactlab/recommend/units.py +63 -0
- compactlab/report/__init__.py +3 -0
- compactlab/report/html.py +27 -0
- compactlab/report/template.html +1189 -0
- compactlab/service/__init__.py +1 -0
- compactlab/service/core.py +220 -0
- compactlab/service/http.py +133 -0
- compactlab/service/lock.py +92 -0
- compactlab/service/policy.py +258 -0
- compactlab/service/schedule.py +212 -0
- compactlab/share.py +553 -0
- compactlab/sim/__init__.py +1 -0
- compactlab/sim/baseline.py +214 -0
- compactlab/sim/calibrate.py +108 -0
- compactlab/sim/engine.py +1130 -0
- compactlab/sim/select.py +238 -0
- compactlab/sim/timing.py +134 -0
- compactlab/synth.py +416 -0
- compactlab/term/__init__.py +0 -0
- compactlab/term/style.py +134 -0
- compactlab/term/top.py +531 -0
- compactlab/term/views.py +598 -0
- compactlab/term/widgets.py +238 -0
- compactlab/verify.py +462 -0
- compactlab-0.2.0.dist-info/METADATA +243 -0
- compactlab-0.2.0.dist-info/RECORD +67 -0
- compactlab-0.2.0.dist-info/WHEEL +4 -0
- compactlab-0.2.0.dist-info/entry_points.txt +2 -0
- compactlab-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"""The harness's default compaction point and the user's currently configured one."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
from importlib import resources
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from ..pricing.ids import claude_settings_key, parse
|
|
13
|
+
|
|
14
|
+
_DEFAULTS: dict[str, Any] | None = None
|
|
15
|
+
OPENCODE_AUTO_OFF = "compaction.auto is false" # read_current's note when OpenCode never compacts by itself
|
|
16
|
+
OPENCODE_OUTPUT_CAP = 32_000 # OpenCode's OUTPUT_TOKEN_MAX: the most output it reserves for any model
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def defaults() -> dict[str, Any]:
|
|
20
|
+
global _DEFAULTS
|
|
21
|
+
if _DEFAULTS is None:
|
|
22
|
+
_DEFAULTS = json.loads(resources.files("compactlab").joinpath("data/harness_defaults.json").read_text())
|
|
23
|
+
return _DEFAULTS
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _claude_rule(d: dict[str, Any], model: str, window: int | None) -> dict[str, Any] | None:
|
|
27
|
+
"""The Claude Code default rule for `model`: by name, else by window (`min_window`: a model Claude Code knows with
|
|
28
|
+
a native window that large, such as a Claude model newer than the list)."""
|
|
29
|
+
m = model.lower()
|
|
30
|
+
for r in d["rules"]:
|
|
31
|
+
if any(p in m for p in r["match"]):
|
|
32
|
+
return r
|
|
33
|
+
if window and parse(model).id.startswith("claude-"):
|
|
34
|
+
return next((r for r in d["rules"] if r.get("min_window") and window >= r["min_window"]), None)
|
|
35
|
+
return None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def default_threshold(harness: str, model: str, window: int) -> tuple[int, str]:
|
|
39
|
+
"""(threshold, explanation). Never above the window. See default_note_zh() for the Chinese note."""
|
|
40
|
+
d = defaults().get(harness)
|
|
41
|
+
if harness == "claude-code" and d:
|
|
42
|
+
r = _claude_rule(d, model, window)
|
|
43
|
+
if r:
|
|
44
|
+
return min(int(r["threshold"]), window), r["note"]
|
|
45
|
+
return window, d["otherwise_note"]
|
|
46
|
+
if harness == "codex" and d:
|
|
47
|
+
return int(window * d["fraction"]), d["note"]
|
|
48
|
+
if harness == "dsh" and d:
|
|
49
|
+
return dsh_trigger(window, d["threshold_ratio"], d["headroom_tokens"]), d["note"]
|
|
50
|
+
if harness == "opencode" and d:
|
|
51
|
+
return max(window - int(d["output_reserve"]), 0), d["note"]
|
|
52
|
+
if harness == "gemini-cli" and d:
|
|
53
|
+
return int(window * d["fraction"]), d["note"]
|
|
54
|
+
return window, "unknown harness: assuming compaction at the context window"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def dsh_trigger(window: int, ratio: float, headroom: int) -> int:
|
|
58
|
+
"""dsh-compaction-basic pressure point: min(window x ratio, window - reserved output - headroom).
|
|
59
|
+
The reserve is the route's max output (256k for DeepSeek's own API). A smaller window cannot fit that, so for
|
|
60
|
+
windows up to twice the reserve the route's own cap is assumed to be a quarter of the window."""
|
|
61
|
+
reserved = int(defaults()["dsh"]["reserved_output"])
|
|
62
|
+
if window <= 2 * reserved:
|
|
63
|
+
reserved = window // 4
|
|
64
|
+
return max(int(min(window * ratio, window - reserved - headroom)), 0)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def effective_max(harness: str, window: int) -> int:
|
|
68
|
+
"""Largest threshold the harness will actually honour."""
|
|
69
|
+
if harness == "codex":
|
|
70
|
+
return int(window * defaults()["codex"]["fraction"])
|
|
71
|
+
if harness == "dsh":
|
|
72
|
+
return dsh_trigger(window, 1.0, 0) # thresholdRatio 1 with headroomTokens 0: only the output reserve remains
|
|
73
|
+
if harness == "opencode":
|
|
74
|
+
return max(window - int(defaults()["opencode"]["reserved_default"]), 0) # limit.input = window, reserved kept
|
|
75
|
+
return window
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def read_current(harness: str, model: str, path: Path | None) -> tuple[int | None, str]:
|
|
79
|
+
"""Currently configured threshold for `model` from one config file, read-only.
|
|
80
|
+
Returns (value or None for 'not set / auto', description)."""
|
|
81
|
+
if harness == "dsh":
|
|
82
|
+
return None, "not read: where dsh keeps the compaction-basic plugin config is not verified"
|
|
83
|
+
if path is None or not path.exists():
|
|
84
|
+
return None, "no config file"
|
|
85
|
+
text = path.read_text()
|
|
86
|
+
if harness in ("opencode", "gemini-cli"):
|
|
87
|
+
try:
|
|
88
|
+
d = json.loads(text) if text.strip() else {}
|
|
89
|
+
except ValueError:
|
|
90
|
+
return None, f"{path.name} is not strict JSON (comments are not read)"
|
|
91
|
+
return (_opencode_current if harness == "opencode" else _gemini_current)(
|
|
92
|
+
d if isinstance(d, dict) else {}, model, path.name
|
|
93
|
+
)
|
|
94
|
+
if harness == "claude-code":
|
|
95
|
+
try:
|
|
96
|
+
d = json.loads(text) if text.strip() else {}
|
|
97
|
+
except ValueError:
|
|
98
|
+
return None, f"{path.name} is not strict JSON"
|
|
99
|
+
table = d.get("modelSettings") or {}
|
|
100
|
+
# keyed by canonical name, which also covers dated and Bedrock / Vertex IDs of the same model (not its [1m]
|
|
101
|
+
# variant, which is a different model to Claude Code)
|
|
102
|
+
canon = claude_settings_key(model)
|
|
103
|
+
mid = parse(model)
|
|
104
|
+
key = next(
|
|
105
|
+
(k for k in (canon, model) if k in table),
|
|
106
|
+
next((k for k in table if parse(k).id == mid.id and parse(k).one_m == mid.one_m), model),
|
|
107
|
+
)
|
|
108
|
+
ms = table.get(key) or {}
|
|
109
|
+
v = ms.get("autoCompactWindow") if isinstance(ms, dict) else None
|
|
110
|
+
src = f"modelSettings.{key}.autoCompactWindow"
|
|
111
|
+
if v is None:
|
|
112
|
+
v, src = d.get("autoCompactWindow"), "autoCompactWindow"
|
|
113
|
+
if v is None or v == "auto":
|
|
114
|
+
return None, "not set (harness default)"
|
|
115
|
+
return int(v), f"{src} in {path.name}"
|
|
116
|
+
if harness == "codex":
|
|
117
|
+
top = text[: m.start()] if (m := re.search(r"^[ \t]*\[", text, re.M)) else text
|
|
118
|
+
mm = re.search(r"^[ \t]*model_auto_compact_token_limit[ \t]*=[ \t]*([\d_]+)", top, re.M)
|
|
119
|
+
if not mm:
|
|
120
|
+
return None, "not set (harness default)"
|
|
121
|
+
return int(mm.group(1).replace("_", "")), f"model_auto_compact_token_limit in {path.name}"
|
|
122
|
+
return None, "unsupported harness"
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _obj(v: Any) -> dict[str, Any]:
|
|
126
|
+
return v if isinstance(v, dict) else {}
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _num(v: Any) -> int:
|
|
130
|
+
return int(v) if isinstance(v, int | float) and not isinstance(v, bool) and v > 0 else 0
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _opencode_current(d: dict[str, Any], model: str, name: str) -> tuple[int | None, str]:
|
|
134
|
+
"""OpenCode 1.x: limit.input - compaction.reserved when the model's limit sets input, else context - output."""
|
|
135
|
+
comp = _obj(d.get("compaction"))
|
|
136
|
+
if comp.get("auto") is False:
|
|
137
|
+
return None, f"{OPENCODE_AUTO_OFF} in {name}: OpenCode does not compact by itself"
|
|
138
|
+
prov, _, mid = model.partition("/")
|
|
139
|
+
lim = _obj(_obj(_obj(_obj(_obj(d.get("provider")).get(prov)).get("models")).get(mid)).get("limit"))
|
|
140
|
+
if not _num(lim.get("context")):
|
|
141
|
+
return None, "not set (harness default)"
|
|
142
|
+
out = min(_num(lim.get("output")), OPENCODE_OUTPUT_CAP) or OPENCODE_OUTPUT_CAP
|
|
143
|
+
key = f"provider.{prov}.models.{mid}.limit"
|
|
144
|
+
if _num(lim.get("input")):
|
|
145
|
+
res = comp.get("reserved")
|
|
146
|
+
reserved = int(res) if isinstance(res, int) else min(int(defaults()["opencode"]["reserved_default"]), out)
|
|
147
|
+
return max(_num(lim["input"]) - reserved, 0), f"{key}.input - reserved {reserved:,} in {name}"
|
|
148
|
+
return max(_num(lim["context"]) - out, 0), f"{key}.context - output {out:,} in {name}"
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _gemini_current(d: dict[str, Any], model: str, name: str) -> tuple[int | None, str]:
|
|
152
|
+
from ..adapters.gemini_cli import token_limit
|
|
153
|
+
|
|
154
|
+
v = _obj(d.get("model")).get("compressionThreshold")
|
|
155
|
+
if not isinstance(v, int | float) or isinstance(v, bool) or not 0 < v <= 1:
|
|
156
|
+
return None, "not set (harness default)"
|
|
157
|
+
return int(v * token_limit(model)), f"model.compressionThreshold {v:g} in {name}"
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
IDLE_ENV = "CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS"
|
|
161
|
+
MAX_CONTEXT_ENV = "CLAUDE_CODE_MAX_CONTEXT_TOKENS"
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def read_env_int(path: Path | None, name: str, environ: dict[str, str] | None = None) -> int | None:
|
|
165
|
+
"""An integer Claude Code setting from settings.json's `env` block, else this process's environment."""
|
|
166
|
+
d: Any = {}
|
|
167
|
+
if path is not None and path.exists():
|
|
168
|
+
try:
|
|
169
|
+
text = path.read_text()
|
|
170
|
+
d = json.loads(text) if text.strip() else {}
|
|
171
|
+
except (OSError, ValueError):
|
|
172
|
+
d = {}
|
|
173
|
+
env = d.get("env") if isinstance(d, dict) else None
|
|
174
|
+
env = env if isinstance(env, dict) else {}
|
|
175
|
+
raw = env.get(name) or (environ if environ is not None else os.environ).get(name)
|
|
176
|
+
try:
|
|
177
|
+
return int(str(raw).replace("_", "")) if raw else None
|
|
178
|
+
except ValueError:
|
|
179
|
+
return None
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def read_idle(path: Path | None, environ: dict[str, str] | None = None) -> tuple[bool | None, int | None, str]:
|
|
183
|
+
"""Claude Code's idle compaction as configured, read-only: (`idleCompaction` or None when not set, the minimum
|
|
184
|
+
context from CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS or None, description). The env var counts from settings.json's
|
|
185
|
+
`env` block first, then this process's environment."""
|
|
186
|
+
d: dict = {}
|
|
187
|
+
if path is not None and path.exists():
|
|
188
|
+
try:
|
|
189
|
+
text = path.read_text()
|
|
190
|
+
d = json.loads(text) if text.strip() else {}
|
|
191
|
+
except (OSError, ValueError):
|
|
192
|
+
return None, None, f"{path.name} unreadable: idle compaction assumed on"
|
|
193
|
+
d = d if isinstance(d, dict) else {}
|
|
194
|
+
v = d.get("idleCompaction")
|
|
195
|
+
enabled = v if isinstance(v, bool) else None
|
|
196
|
+
env = d.get("env")
|
|
197
|
+
env = env if isinstance(env, dict) else {}
|
|
198
|
+
raw = env.get(IDLE_ENV) or (environ if environ is not None else os.environ).get(IDLE_ENV)
|
|
199
|
+
try:
|
|
200
|
+
min_tokens = int(str(raw).replace("_", "")) if raw else None
|
|
201
|
+
except ValueError:
|
|
202
|
+
min_tokens = None
|
|
203
|
+
where = f"idleCompaction in {path.name}" if enabled is not None and path else "not set (on by default)"
|
|
204
|
+
return enabled, min_tokens, where + (f"; {IDLE_ENV}={min_tokens:,}" if min_tokens else "")
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def default_note_zh(harness: str, model: str, window: int | None = None) -> str:
|
|
208
|
+
d = defaults().get(harness) or {}
|
|
209
|
+
if harness == "claude-code" and d:
|
|
210
|
+
r = _claude_rule(d, model, window)
|
|
211
|
+
if r:
|
|
212
|
+
return str(r.get("note_zh", r["note"]))
|
|
213
|
+
return str(d.get("otherwise_note_zh", d.get("otherwise_note", "")))
|
|
214
|
+
return str(d.get("note_zh", d.get("note", "")))
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Estimate the re-discovery penalty from compactions that already happened in the history."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import statistics
|
|
6
|
+
from dataclasses import asdict, dataclass
|
|
7
|
+
|
|
8
|
+
from ..model import Session
|
|
9
|
+
|
|
10
|
+
WINDOW = 20 # turns inspected before/after a compaction
|
|
11
|
+
MIN_OBSERVED = 5
|
|
12
|
+
PRIOR_STEP_TOKENS = 2000 # tokens one re-discovery call brings back, paired with the prior penalty
|
|
13
|
+
MIN_STEP_SAMPLES = 20
|
|
14
|
+
|
|
15
|
+
REDISCOVERY_TOOLS = (
|
|
16
|
+
"Read",
|
|
17
|
+
"Grep",
|
|
18
|
+
"Glob",
|
|
19
|
+
"LS",
|
|
20
|
+
"WebFetch",
|
|
21
|
+
"WebSearch",
|
|
22
|
+
"read_file",
|
|
23
|
+
"shell",
|
|
24
|
+
"exec_command",
|
|
25
|
+
"exec",
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class PenaltyParams:
|
|
31
|
+
rho: float = 0.04 # re-read tokens per dropped context token
|
|
32
|
+
fixed_tokens: int = 6000 # extra tokens re-added per compaction regardless of size
|
|
33
|
+
correction_turns: float = 0.3 # extra user-correction turns per compaction
|
|
34
|
+
source: str = "prior" # "prior" | "observed"
|
|
35
|
+
n_observed: int = 0
|
|
36
|
+
|
|
37
|
+
def to_dict(self) -> dict:
|
|
38
|
+
return asdict(self)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _is_rediscovery(key: str) -> bool:
|
|
42
|
+
return key.split(":", 1)[0] in REDISCOVERY_TOOLS or key.split(":", 1)[0].startswith("mcp__")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def repeat_stats(s: Session, start: int, end: int) -> tuple[int, int, int]:
|
|
46
|
+
"""(repeated tool calls, estimated tokens of repeats, correction phrases) in turns [start,end),
|
|
47
|
+
where 'repeated' means the same tool+argument appeared in turns before `start` or earlier in the window."""
|
|
48
|
+
seen: set[str] = set()
|
|
49
|
+
for t in s.turns[:start]:
|
|
50
|
+
seen.update(t.tool_keys)
|
|
51
|
+
reps = toks = corr = 0
|
|
52
|
+
for t in s.turns[start:end]:
|
|
53
|
+
for i, k in enumerate(t.tool_keys):
|
|
54
|
+
if _is_rediscovery(k) and k in seen:
|
|
55
|
+
reps += 1
|
|
56
|
+
toks += t.tool_result_tokens[i] if i < len(t.tool_result_tokens) else 2000
|
|
57
|
+
seen.add(k)
|
|
58
|
+
if t.corrects():
|
|
59
|
+
corr += 1
|
|
60
|
+
return reps, toks, corr
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def calibrate(sessions: list[Session], base_tokens: int, summary_tokens: int) -> PenaltyParams:
|
|
64
|
+
excess_tok: list[float] = []
|
|
65
|
+
dropped: list[float] = []
|
|
66
|
+
excess_corr: list[float] = []
|
|
67
|
+
for s in sessions:
|
|
68
|
+
bounds = [c.turn_index for c in s.compactions]
|
|
69
|
+
for c in s.compactions:
|
|
70
|
+
a = c.turn_index
|
|
71
|
+
# a full window of history before (so "repeated" can be told from "first seen") and after, and no other
|
|
72
|
+
# compaction inside either window: before and after must describe the same kind of work
|
|
73
|
+
if a <= WINDOW or a + WINDOW > len(s.turns) or any(0 < abs(b - a) < WINDOW for b in bounds):
|
|
74
|
+
continue
|
|
75
|
+
_, after_t, after_c = repeat_stats(s, a, a + WINDOW)
|
|
76
|
+
_, before_t, before_c = repeat_stats(s, a - WINDOW, a)
|
|
77
|
+
pre = c.pre_tokens or s.turns[a - 1].ctx
|
|
78
|
+
excess_tok.append(max(after_t - before_t, 0))
|
|
79
|
+
excess_corr.append(max(after_c - before_c, 0))
|
|
80
|
+
dropped.append(max(pre - base_tokens - summary_tokens, 1))
|
|
81
|
+
n = len(dropped)
|
|
82
|
+
if n < MIN_OBSERVED:
|
|
83
|
+
return PenaltyParams(n_observed=n)
|
|
84
|
+
rho = min(max(sum(excess_tok) / sum(dropped), 0.0), 0.5)
|
|
85
|
+
return PenaltyParams(
|
|
86
|
+
rho=rho, fixed_tokens=0, correction_turns=statistics.fmean(excess_corr), source="observed", n_observed=n
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def rediscovery_step(sessions: list[Session], pen: PenaltyParams) -> int:
|
|
91
|
+
"""Tokens one re-discovery call brings back: re-read tokens / this = re-discovery calls (turns of wall-clock).
|
|
92
|
+
|
|
93
|
+
It must be in the same units as the re-read tokens. An observed penalty measured them as the summed results of
|
|
94
|
+
repeated re-discovery calls, so the matching size is the mean of those calls' results (a median of many tiny
|
|
95
|
+
results would turn a few hundred tokens into thousands of turns). A prior penalty pairs with the prior step.
|
|
96
|
+
"""
|
|
97
|
+
if pen.source != "observed":
|
|
98
|
+
return PRIOR_STEP_TOKENS
|
|
99
|
+
sizes = [
|
|
100
|
+
t.tool_result_tokens[i]
|
|
101
|
+
for s in sessions
|
|
102
|
+
for t in s.turns
|
|
103
|
+
for i, k in enumerate(t.tool_keys)
|
|
104
|
+
if i < len(t.tool_result_tokens) and _is_rediscovery(k)
|
|
105
|
+
]
|
|
106
|
+
if len(sizes) < MIN_STEP_SAMPLES:
|
|
107
|
+
return PRIOR_STEP_TOKENS
|
|
108
|
+
return max(int(statistics.fmean(sizes)), 1)
|