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,89 @@
|
|
|
1
|
+
"""DeepSeek Harness recommender: `modelPolicies` entries for the dsh-compaction-basic plugin config.
|
|
2
|
+
|
|
3
|
+
dsh sets the threshold as a fraction of the window (`thresholdRatio`), capped by the output reserve plus
|
|
4
|
+
`headroomTokens`. The snippet sets `headroomTokens: 0` so the ratio alone decides, as long as the value stays
|
|
5
|
+
below window - reserve (the effective max). Where the user's plugin config lives is not verified, so the snippet
|
|
6
|
+
names the plugin and leaves placement to the user; `apply` does not write dsh config.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any, ClassVar
|
|
12
|
+
|
|
13
|
+
from . import Omitted, Recommender, Snippet, evidence, knobs, register, safe_value
|
|
14
|
+
from .units import fraction_for
|
|
15
|
+
|
|
16
|
+
KN = "dsh.plugin.compaction-basic.modelPolicies"
|
|
17
|
+
RETAIN_RATIO = 0.16 # plugin default; thresholdRatio must stay above it
|
|
18
|
+
PROVIDER = "deepseek-official"
|
|
19
|
+
SUMMARY_MAX = 65_536 # the plugin's default summary cap (= default headroomTokens)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def ratio_for(v: int, window: int) -> float:
|
|
23
|
+
"""thresholdRatio that triggers at or just below v tokens (rounded down to 3 decimals)."""
|
|
24
|
+
return fraction_for(v, window, 3).value
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def policy_row(model: str, window: int, v: int) -> str:
|
|
28
|
+
"""One modelPolicies entry that triggers at or just below v tokens."""
|
|
29
|
+
r = ratio_for(v, window)
|
|
30
|
+
return (
|
|
31
|
+
f" - provider: {PROVIDER}\n model: {model}\n"
|
|
32
|
+
f" thresholdRatio: {r} # ≈ {int(r * window) // 1000}k of {window:,}\n"
|
|
33
|
+
f" headroomTokens: 0\n"
|
|
34
|
+
f" maxTokens: {SUMMARY_MAX} # summary cap; without it dsh derives 0 from headroomTokens"
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@register
|
|
39
|
+
class DshRecommender(Recommender):
|
|
40
|
+
harness = "dsh"
|
|
41
|
+
formats: ClassVar[dict[str, tuple[str, ...]]] = {"global": ("yaml",), "project": ("yaml",), "agent": ("yaml",)}
|
|
42
|
+
|
|
43
|
+
def setting(self, g: dict[str, Any], threshold: int) -> str:
|
|
44
|
+
r = ratio_for(threshold, int(g["max_window"]))
|
|
45
|
+
if r <= RETAIN_RATIO:
|
|
46
|
+
return f"# {threshold}: ratio {r} is not above dsh's retainRatio {RETAIN_RATIO}; pick a larger threshold"
|
|
47
|
+
return "config:\n modelPolicies:\n" + policy_row(g["model"], int(g["max_window"]), threshold)
|
|
48
|
+
|
|
49
|
+
def generate(self, result: dict[str, Any], scope: str, profile: str, fmt: str | None, provider: str) -> list:
|
|
50
|
+
fmt = fmt or "yaml"
|
|
51
|
+
if fmt != "yaml":
|
|
52
|
+
return [Omitted(self.harness, f"format {fmt} is not available; dsh plugin config is YAML")]
|
|
53
|
+
if scope != "global":
|
|
54
|
+
return [Omitted(self.harness, "dsh policies are per provider/model, not per project or agent role; "
|
|
55
|
+
"use the global snippet")] # fmt: skip
|
|
56
|
+
out: list[Snippet | Omitted] = []
|
|
57
|
+
rows = []
|
|
58
|
+
notes: list[str] = []
|
|
59
|
+
ev = []
|
|
60
|
+
for g in sorted(result["groups"], key=lambda g: -g["n_turns"]):
|
|
61
|
+
if g["harness"] != self.harness or g["role"] != "main":
|
|
62
|
+
continue
|
|
63
|
+
v, why = safe_value(g, profile, result, 1, 10**9)
|
|
64
|
+
if v is None:
|
|
65
|
+
out.append(Omitted(self.harness, why))
|
|
66
|
+
continue
|
|
67
|
+
r = ratio_for(v, int(g["max_window"]))
|
|
68
|
+
if r <= RETAIN_RATIO:
|
|
69
|
+
out.append(Omitted(self.harness, f"{g['model']}: ratio {r} is not above retainRatio {RETAIN_RATIO}"))
|
|
70
|
+
continue
|
|
71
|
+
rows.append(policy_row(g["model"], int(g["max_window"]), v))
|
|
72
|
+
ev.append(evidence(g, profile))
|
|
73
|
+
if not rows:
|
|
74
|
+
return out or [Omitted(self.harness, "no dsh main sessions in this history")]
|
|
75
|
+
content = (
|
|
76
|
+
"# under the @deepseek-ai/dsh-compaction-basic plugin's config\n"
|
|
77
|
+
"config:\n modelPolicies:\n" + "\n".join(rows)
|
|
78
|
+
)
|
|
79
|
+
notes += [
|
|
80
|
+
f"provider is set to {PROVIDER}; change it to the provider id your route uses (see request/context in the "
|
|
81
|
+
"session log).",
|
|
82
|
+
"headroomTokens: 0 lets thresholdRatio decide; dsh still caps the trigger at window - reserved output.",
|
|
83
|
+
"Subagents use the same policy for the same model; dsh has no separate subagent threshold.",
|
|
84
|
+
]
|
|
85
|
+
warn = [knobs()["knobs"][KN]["note"]]
|
|
86
|
+
out.insert(0, Snippet(self.harness, scope, profile, fmt, f"dsh · compaction-basic · {profile}",
|
|
87
|
+
"the compaction-basic plugin entry in your dsh profile / cordis.yml", content, "",
|
|
88
|
+
"delete the modelPolicies entries above", ev, notes, warn, [KN])) # fmt: skip
|
|
89
|
+
return out
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Gemini CLI recommender: `model.compressionThreshold` in settings.json, a fraction of the model's token limit.
|
|
2
|
+
|
|
3
|
+
The key is global, so one fraction serves every model; the most-used model sets it and the notes say where it lands
|
|
4
|
+
for the others. Experimental: the adapter has not been checked against a real Gemini CLI log, and `apply` does not
|
|
5
|
+
write Gemini settings: recommend-only.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from typing import Any, ClassVar
|
|
12
|
+
|
|
13
|
+
from . import Omitted, Recommender, Snippet, evidence, knobs, register, safe_value
|
|
14
|
+
from .units import fraction_for, shared_fraction
|
|
15
|
+
|
|
16
|
+
KN = "gemini.settings.model.compressionThreshold"
|
|
17
|
+
TARGETS = {"global": "~/.gemini/settings.json", "project": ".gemini/settings.json in the project root"}
|
|
18
|
+
PATHS = {"global": "~/.gemini/settings.json", "project": ".gemini/settings.json"}
|
|
19
|
+
PLACES = 3
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _merge_py(path: str, v: float) -> str:
|
|
23
|
+
code = (
|
|
24
|
+
"import json,os,sys;p=os.path.expanduser(sys.argv[1]);"
|
|
25
|
+
"d=json.load(open(p)) if os.path.exists(p) and open(p).read().strip() else {};"
|
|
26
|
+
"d.setdefault('model',{})['compressionThreshold']=float(sys.argv[2]);"
|
|
27
|
+
"open(p,'w').write(json.dumps(d,indent=2)+'\\n')"
|
|
28
|
+
)
|
|
29
|
+
return f'cp {path} {path}.bak 2>/dev/null; python3 -c "{code}" {path} {v:g}'
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@register
|
|
33
|
+
class GeminiRecommender(Recommender):
|
|
34
|
+
harness = "gemini-cli"
|
|
35
|
+
formats: ClassVar[dict[str, tuple[str, ...]]] = {"global": ("json",), "project": ("json",)}
|
|
36
|
+
|
|
37
|
+
def setting(self, g: dict[str, Any], threshold: int) -> str:
|
|
38
|
+
f = fraction_for(threshold, int(g["max_window"]), PLACES)
|
|
39
|
+
return json.dumps({"model": {"compressionThreshold": f.value}}, indent=2)
|
|
40
|
+
|
|
41
|
+
def generate(self, result: dict[str, Any], scope: str, profile: str, fmt: str | None, provider: str) -> list:
|
|
42
|
+
if scope not in self.formats:
|
|
43
|
+
return [Omitted(self.harness, "Gemini CLI has one compression threshold for every model and agent; use "
|
|
44
|
+
"the global or project snippet")] # fmt: skip
|
|
45
|
+
fmt = fmt or "json"
|
|
46
|
+
if fmt != "json":
|
|
47
|
+
return [Omitted(self.harness, f"format {fmt} is not available; settings.json is JSON")]
|
|
48
|
+
out: list[Snippet | Omitted] = []
|
|
49
|
+
picks: list[tuple[dict[str, Any], int]] = []
|
|
50
|
+
for g in sorted(result["groups"], key=lambda g: -g["n_turns"]):
|
|
51
|
+
if g["harness"] != self.harness or g["role"] != "main":
|
|
52
|
+
continue
|
|
53
|
+
v, why = safe_value(g, profile, result, 1, 10**9)
|
|
54
|
+
if v is None:
|
|
55
|
+
out.append(Omitted(self.harness, why))
|
|
56
|
+
else:
|
|
57
|
+
picks.append((g, v))
|
|
58
|
+
if not picks:
|
|
59
|
+
return out or [Omitted(self.harness, "no Gemini CLI main sessions in this history")]
|
|
60
|
+
f, others = shared_fraction([(g["model"], v, int(g["max_window"])) for g, v in picks], PLACES)
|
|
61
|
+
if not 0 < f.value <= 1:
|
|
62
|
+
return [*out, Omitted(self.harness, f"{picks[0][0]['model']}: fraction {f.value:g} is outside (0, 1]")]
|
|
63
|
+
g, v = picks[0]
|
|
64
|
+
w = int(g["max_window"])
|
|
65
|
+
notes = [
|
|
66
|
+
f"{f.value:g} of {w:,} triggers at {f.tokens:,} prompt tokens (the pick is {v:,}); this value follows "
|
|
67
|
+
f"{g['model']} (most turns).",
|
|
68
|
+
*([f"Also seen: {x}" for x in others]),
|
|
69
|
+
"Gemini CLI compares the last request's prompt tokens, cached ones included, as the replay does.",
|
|
70
|
+
"Restart Gemini CLI after the change. A system settings file (/Library/Application Support/GeminiCli/"
|
|
71
|
+
"settings.json on macOS) overrides the user and project files.",
|
|
72
|
+
]
|
|
73
|
+
if f.note:
|
|
74
|
+
notes.append(f.note)
|
|
75
|
+
warn = [
|
|
76
|
+
"Experimental: built from Gemini CLI's source; no real Gemini CLI log has been replayed yet.",
|
|
77
|
+
str(knobs()["knobs"][KN]["note"]),
|
|
78
|
+
]
|
|
79
|
+
path = PATHS[scope]
|
|
80
|
+
content = json.dumps({"model": {"compressionThreshold": f.value}}, indent=2)
|
|
81
|
+
out.insert(0, Snippet(self.harness, scope, profile, fmt, f"Gemini CLI · {scope} · {profile}: compression",
|
|
82
|
+
TARGETS[scope], content, _merge_py(path, f.value),
|
|
83
|
+
f"delete model.compressionThreshold from {path} (or restore {path}.bak)",
|
|
84
|
+
[evidence(g, profile) for g, _ in picks], notes, warn, [KN])) # fmt: skip
|
|
85
|
+
return out
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""OpenCode recommender: a per-model `limit` in opencode.json (OpenCode 1.x), with the 2.x `compaction.buffer` share.
|
|
2
|
+
|
|
3
|
+
OpenCode 1.x has no threshold key of its own. It compacts at `limit.input - compaction.reserved` for a model whose
|
|
4
|
+
limit sets `input`, else at `context - max output`, and `compaction.reserved` (global) does nothing for a model
|
|
5
|
+
without `limit.input`. A per-model `limit` with `input = threshold + reserved` sets the point exactly. `limit` needs
|
|
6
|
+
`context` and `output` too: context is the window compactlab used, output is OpenCode's own cap (32,000; a larger
|
|
7
|
+
value changes nothing). OpenCode 2.x (pre-release) replaces this with a global `compaction.buffer`, a share of the
|
|
8
|
+
window kept free, which the notes give. `apply` does not write OpenCode config: recommend-only.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
from typing import Any, ClassVar
|
|
15
|
+
|
|
16
|
+
from ..sim.baseline import OPENCODE_AUTO_OFF, OPENCODE_OUTPUT_CAP, defaults
|
|
17
|
+
from . import Omitted, Recommender, Snippet, evidence, register, safe_value
|
|
18
|
+
from .units import free_share
|
|
19
|
+
|
|
20
|
+
KN_LIMIT = "opencode.config.provider.models.limit"
|
|
21
|
+
KN_BUFFER = "opencode.config.compaction.buffer"
|
|
22
|
+
TARGETS = {"global": "~/.config/opencode/opencode.json", "project": "opencode.json in the project root"}
|
|
23
|
+
PATHS = {"global": "~/.config/opencode/opencode.json", "project": "opencode.json"}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _split(model: str) -> tuple[str, str]:
|
|
27
|
+
prov, sep, mid = model.partition("/")
|
|
28
|
+
return (prov, mid) if sep else ("<providerID>", model)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def limit_for(threshold: int, window: int) -> dict[str, int]:
|
|
32
|
+
reserved = int(defaults()["opencode"]["reserved_default"]) # = min(20000, output) with output 32,000
|
|
33
|
+
return {"context": window, "input": threshold + reserved, "output": OPENCODE_OUTPUT_CAP}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def config_for(picks: list[tuple[str, int, int]]) -> dict[str, Any]:
|
|
37
|
+
prov: dict[str, Any] = {}
|
|
38
|
+
for model, threshold, window in picks:
|
|
39
|
+
p, m = _split(model)
|
|
40
|
+
prov.setdefault(p, {"models": {}})["models"][m] = {"limit": limit_for(threshold, window)}
|
|
41
|
+
return {"provider": prov}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _merge_py(path: str, cfg: dict[str, Any]) -> str:
|
|
45
|
+
code = (
|
|
46
|
+
"import json,os,sys;p=os.path.expanduser(sys.argv[1]);"
|
|
47
|
+
"d=json.load(open(p)) if os.path.exists(p) and open(p).read().strip() else {};"
|
|
48
|
+
"[d.setdefault('provider',{}).setdefault(pv,{}).setdefault('models',{}).setdefault(m,{})"
|
|
49
|
+
".update(limit=x['limit']) for pv,pm in json.loads(sys.argv[2])['provider'].items() "
|
|
50
|
+
"for m,x in pm['models'].items()];"
|
|
51
|
+
"open(p,'w').write(json.dumps(d,indent=2)+'\\n')"
|
|
52
|
+
)
|
|
53
|
+
return f"cp {path} {path}.bak 2>/dev/null; python3 -c \"{code}\" {path} '{json.dumps(cfg)}'"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@register
|
|
57
|
+
class OpenCodeRecommender(Recommender):
|
|
58
|
+
harness = "opencode"
|
|
59
|
+
formats: ClassVar[dict[str, tuple[str, ...]]] = {"global": ("json",), "project": ("json",)}
|
|
60
|
+
|
|
61
|
+
def setting(self, g: dict[str, Any], threshold: int) -> str:
|
|
62
|
+
return json.dumps(config_for([(g["model"], threshold, int(g["max_window"]))]), indent=2)
|
|
63
|
+
|
|
64
|
+
def generate(self, result: dict[str, Any], scope: str, profile: str, fmt: str | None, provider: str) -> list:
|
|
65
|
+
if scope not in self.formats:
|
|
66
|
+
return [Omitted(self.harness, "OpenCode has no per-agent compaction setting; the per-model limit in the "
|
|
67
|
+
"global or project config applies to subagents too")] # fmt: skip
|
|
68
|
+
fmt = fmt or "json"
|
|
69
|
+
if fmt != "json":
|
|
70
|
+
return [Omitted(self.harness, f"format {fmt} is not available; opencode.json is JSON")]
|
|
71
|
+
out: list[Snippet | Omitted] = []
|
|
72
|
+
picks: list[tuple[str, int, int]] = []
|
|
73
|
+
ev, notes = [], []
|
|
74
|
+
for g in sorted(result["groups"], key=lambda g: -g["n_turns"]):
|
|
75
|
+
if g["harness"] != self.harness or g["role"] != "main":
|
|
76
|
+
continue
|
|
77
|
+
if str(g.get("current_note") or "").startswith(OPENCODE_AUTO_OFF):
|
|
78
|
+
why = f"{g['model']}: {g['current_note']}, so a limit would never take effect; set compaction.auto "
|
|
79
|
+
out.append(Omitted(self.harness, why + "to true first if you want it to"))
|
|
80
|
+
continue
|
|
81
|
+
v, why = safe_value(g, profile, result, 1, 10**9)
|
|
82
|
+
if v is None:
|
|
83
|
+
out.append(Omitted(self.harness, why))
|
|
84
|
+
continue
|
|
85
|
+
w = int(g["max_window"])
|
|
86
|
+
picks.append((g["model"], v, w))
|
|
87
|
+
ev.append(evidence(g, profile))
|
|
88
|
+
buf = free_share(v, w)
|
|
89
|
+
src = g.get("window_source", "?")
|
|
90
|
+
notes.append(f"{g['model']}: context {w:,} is the window compactlab used ({src}); correct it if "
|
|
91
|
+
f"OpenCode's model catalog says otherwise. On OpenCode 2.x set compaction.buffer to "
|
|
92
|
+
f"\"{buf.value:g}%\" instead (keeps {w - buf.tokens:,} free, compacts at {buf.tokens:,}; "
|
|
93
|
+
"global for every model)" + (f"; {buf.note}" if buf.note else "")) # fmt: skip
|
|
94
|
+
if not picks:
|
|
95
|
+
return out or [Omitted(self.harness, "no OpenCode main sessions in this history")]
|
|
96
|
+
cfg = config_for(picks)
|
|
97
|
+
reserved = int(defaults()["opencode"]["reserved_default"])
|
|
98
|
+
notes += [
|
|
99
|
+
f"OpenCode 1.x compacts at limit.input - compaction.reserved; with reserved unset it is {reserved:,}, so "
|
|
100
|
+
f"input is the threshold + {reserved:,}. If you set compaction.reserved, add that instead.",
|
|
101
|
+
"OpenCode counts the last reply's output as well as its context, so it compacts up to one reply earlier "
|
|
102
|
+
"than the replay.",
|
|
103
|
+
"Subagent sessions on the same model use the same limit.",
|
|
104
|
+
]
|
|
105
|
+
warn = [
|
|
106
|
+
f"limit replaces the model's catalog limits: output is set to {OPENCODE_OUTPUT_CAP:,} (OpenCode's own "
|
|
107
|
+
"cap); use the model's real max output if it is lower.",
|
|
108
|
+
"A custom-provider model with no limit in your config has no known window, and OpenCode 1.x never "
|
|
109
|
+
"compacts it by itself; this limit turns automatic compaction on for it.",
|
|
110
|
+
]
|
|
111
|
+
path = PATHS[scope]
|
|
112
|
+
models = [f"{_split(m)[0]}/{_split(m)[1]}" for m, _, _ in picks]
|
|
113
|
+
out.insert(0, Snippet(self.harness, scope, profile, fmt, f"OpenCode · {scope} · {profile}: per-model limit",
|
|
114
|
+
TARGETS[scope], json.dumps(cfg, indent=2), _merge_py(path, cfg),
|
|
115
|
+
f"delete limit from provider.<id>.models.<model> for {', '.join(models)} in {path} "
|
|
116
|
+
f"(or restore {path}.bak)", ev, notes, warn, [KN_LIMIT, KN_BUFFER])) # fmt: skip
|
|
117
|
+
return out
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Turn a recommended token threshold into a harness's own unit.
|
|
2
|
+
|
|
3
|
+
compactlab picks thresholds in tokens. Several harnesses take a fraction of the window instead (dsh, Gemini CLI,
|
|
4
|
+
OpenCode 2.x as a share kept free) or a token count kept free below a limit (OpenCode 1.x). A fraction is rounded so
|
|
5
|
+
the trigger never lands above the recommended threshold, and the result says how many tokens one step of the last
|
|
6
|
+
decimal is on that window, so a snippet can say when the window makes the fraction coarse. A global fraction shared
|
|
7
|
+
by models with different windows lands at different token counts; `shared_fraction` says where it lands for each.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import math
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
|
|
15
|
+
COARSE_TOKENS = 5_000 # a rounding step wider than this is worth a note
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class Fraction:
|
|
20
|
+
value: float # what to write
|
|
21
|
+
tokens: int # where it triggers on this window
|
|
22
|
+
step_tokens: int # tokens per unit of the last decimal on this window
|
|
23
|
+
note: str = "" # set when the step is coarse
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def fraction_for(threshold: int, window: int, places: int = 3) -> Fraction:
|
|
27
|
+
"""The largest fraction with `places` decimals whose trigger (fraction x window) is at or below `threshold`."""
|
|
28
|
+
scale = 10**places
|
|
29
|
+
units = math.floor(threshold / window * scale + 1e-9)
|
|
30
|
+
value = units / scale
|
|
31
|
+
step = math.ceil(window / scale)
|
|
32
|
+
tokens = int(value * window)
|
|
33
|
+
note = ""
|
|
34
|
+
if step > COARSE_TOKENS:
|
|
35
|
+
note = (f"one step of {1 / scale:g} is {step:,} tokens on a {window:,}-token window, so {value:g} triggers at "
|
|
36
|
+
f"{tokens:,} instead of {threshold:,}") # fmt: skip
|
|
37
|
+
return Fraction(value, tokens, step, note)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def free_share(threshold: int, window: int, places: int = 1) -> Fraction:
|
|
41
|
+
"""The share of the window to keep free (e.g. OpenCode 2.x `compaction.buffer`), in percent with `places`
|
|
42
|
+
decimals, rounded up so the trigger window x (1 - share) is at or below `threshold`."""
|
|
43
|
+
scale = 10**places
|
|
44
|
+
units = math.ceil((1 - threshold / window) * 100 * scale - 1e-9)
|
|
45
|
+
pct = units / scale
|
|
46
|
+
step = math.ceil(window / (100 * scale))
|
|
47
|
+
tokens = int(window * (1 - pct / 100))
|
|
48
|
+
note = ""
|
|
49
|
+
if step > COARSE_TOKENS:
|
|
50
|
+
note = f"one step of {1 / scale:g}% is {step:,} tokens on a {window:,}-token window"
|
|
51
|
+
return Fraction(pct, tokens, step, note)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def shared_fraction(targets: list[tuple[str, int, int]], places: int = 3) -> tuple[Fraction, list[str]]:
|
|
55
|
+
"""One global fraction for several (model, threshold, window) targets, most important first: the first target's
|
|
56
|
+
fraction, and a line for every other target saying where that fraction lands on its window."""
|
|
57
|
+
_, threshold, window = targets[0]
|
|
58
|
+
f = fraction_for(threshold, window, places)
|
|
59
|
+
lines = []
|
|
60
|
+
for m, t, w in targets[1:]:
|
|
61
|
+
at = int(f.value * w)
|
|
62
|
+
lines.append(f"{m}: {f.value:g} of {w:,} triggers at {at:,} (its own pick: {t:,})")
|
|
63
|
+
return f, lines
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Self-contained HTML report: template.html (inline CSS/JS/SVG, no network) + the result JSON."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
from datetime import UTC, datetime
|
|
8
|
+
from importlib import resources
|
|
9
|
+
|
|
10
|
+
TEMPLATE = resources.files("compactlab.report").joinpath("template.html").read_text()
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def render_html(result: dict, redact: bool = False) -> str:
|
|
14
|
+
"""Deterministic: the same result renders to the same bytes (no wall-clock timestamps)."""
|
|
15
|
+
data = json.loads(json.dumps(result))
|
|
16
|
+
ts = data.get("data_through")
|
|
17
|
+
data["generated"] = ("data through " + datetime.fromtimestamp(ts, UTC).strftime("%Y-%m-%d")) if ts else ""
|
|
18
|
+
from ..recommend import generate_all, setting
|
|
19
|
+
|
|
20
|
+
data["recommendations"] = generate_all(data)
|
|
21
|
+
for g in data["groups"]: # the Copy button's text for every slider position, from the harness's recommender
|
|
22
|
+
g["settings"] = [setting(g, T) for T in g["grid"]]
|
|
23
|
+
if redact:
|
|
24
|
+
for s in data.get("sessions", []):
|
|
25
|
+
s["id"] = "s-" + hashlib.sha256(s["id"].encode()).hexdigest()[:10]
|
|
26
|
+
payload = json.dumps(data, separators=(",", ":"), sort_keys=True).replace("</", "<\\/")
|
|
27
|
+
return TEMPLATE.replace("__DATA__", payload)
|