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
compactlab/term/top.py
ADDED
|
@@ -0,0 +1,531 @@
|
|
|
1
|
+
"""`compactlab top`: a live terminal view of the latest result (htop / btop style).
|
|
2
|
+
|
|
3
|
+
The screen is built by `frame(state, cols, rows)`, a pure function returning segment lines, and keys are handled by
|
|
4
|
+
`handle(state, key)`; the curses loop only draws lines and reads keys. That keeps the layout testable without a
|
|
5
|
+
terminal, and the same frame is printed once when stdout is not a TTY. Nothing here writes settings: `c` copies the
|
|
6
|
+
setting for the selected model to the clipboard, `r` asks the local service (or an in-process lite run) to
|
|
7
|
+
recalibrate.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import contextlib
|
|
13
|
+
import json
|
|
14
|
+
import shutil
|
|
15
|
+
import subprocess
|
|
16
|
+
import time
|
|
17
|
+
import urllib.request
|
|
18
|
+
from collections.abc import Callable
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from ..recommend import setting
|
|
24
|
+
from .style import Line, Style, clip, cw, pad, width
|
|
25
|
+
from .views import PGLYPH, PROFILES, figs, keep_reason, label, status, totals, verdict
|
|
26
|
+
from .widgets import braille, chip, fmin, fpct, fusd, k, pack, was_now
|
|
27
|
+
|
|
28
|
+
KEYS = [
|
|
29
|
+
("↑ ↓ j k", "select"),
|
|
30
|
+
("← → h l", "fold / expand a harness"),
|
|
31
|
+
("p", "cycle profile: cost, balanced, time, each model's own"),
|
|
32
|
+
("%", "lead with % of the default or $ per day"),
|
|
33
|
+
("r", "recalibrate now (the local service, else an in-process lite run)"),
|
|
34
|
+
("c", "copy the selected model's setting (never writes it)"),
|
|
35
|
+
("/", "filter models; Enter keeps it, Esc clears it"),
|
|
36
|
+
("?", "this help"),
|
|
37
|
+
("q", "quit"),
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class TopState:
|
|
43
|
+
res: dict[str, Any]
|
|
44
|
+
sel: int = 0
|
|
45
|
+
folded: set[str] = field(default_factory=set)
|
|
46
|
+
profile: str | None = None # None: each group's own selected profile
|
|
47
|
+
unit: str = "pct"
|
|
48
|
+
filt: str = ""
|
|
49
|
+
mode: str = "normal" # normal | filter | help
|
|
50
|
+
msg: str = ""
|
|
51
|
+
service: dict[str, Any] = field(default_factory=dict) # {"up": bool, "next": str, "age": str}
|
|
52
|
+
left_rows: int = 0 # set by frame(): where the tree pane starts, for mouse clicks
|
|
53
|
+
left_top: int = 0
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def prof_of(st: TopState, g: dict[str, Any]) -> str:
|
|
57
|
+
return st.profile or g.get("profile") or "balanced"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def rows(st: TopState) -> list[tuple[str, Any]]:
|
|
61
|
+
"""The tree: ('h', harness) then ('g', group index) per model and role, filtered and folded."""
|
|
62
|
+
out: list[tuple[str, Any]] = []
|
|
63
|
+
q = st.filt.lower()
|
|
64
|
+
gs = st.res["groups"]
|
|
65
|
+
for h in sorted({g["harness"] for g in gs}):
|
|
66
|
+
idx = [
|
|
67
|
+
i
|
|
68
|
+
for i, g in enumerate(gs)
|
|
69
|
+
if g["harness"] == h and (not q or q in (g["model"] + label(g["model"])).lower())
|
|
70
|
+
]
|
|
71
|
+
if not idx:
|
|
72
|
+
continue
|
|
73
|
+
out.append(("h", h))
|
|
74
|
+
if h in st.folded:
|
|
75
|
+
continue
|
|
76
|
+
idx.sort(
|
|
77
|
+
key=lambda i: (
|
|
78
|
+
status(gs[i], prof_of(st, gs[i])) != "set",
|
|
79
|
+
-abs((figs(gs[i], prof_of(st, gs[i])) or {"d": 0})["d"]),
|
|
80
|
+
)
|
|
81
|
+
)
|
|
82
|
+
out += [("g", i) for i in idx]
|
|
83
|
+
return out
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def selected(st: TopState) -> tuple[str, Any] | None:
|
|
87
|
+
r = rows(st)
|
|
88
|
+
return r[min(st.sel, len(r) - 1)] if r else None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def handle(st: TopState, key: str) -> str | None:
|
|
92
|
+
"""Update the state for one key; returns an action for the loop ('quit', 'recal', 'copy') or None."""
|
|
93
|
+
r = rows(st)
|
|
94
|
+
if st.mode == "help":
|
|
95
|
+
st.mode = "normal"
|
|
96
|
+
return "quit" if key == "q" else None
|
|
97
|
+
if st.mode == "filter":
|
|
98
|
+
if key in ("ENTER", "ESC"):
|
|
99
|
+
st.mode = "normal"
|
|
100
|
+
if key == "ESC":
|
|
101
|
+
st.filt = ""
|
|
102
|
+
elif key == "BACKSPACE":
|
|
103
|
+
st.filt = st.filt[:-1]
|
|
104
|
+
elif len(key) == 1 and key.isprintable():
|
|
105
|
+
st.filt += key
|
|
106
|
+
st.sel = 0
|
|
107
|
+
return None
|
|
108
|
+
if key == "q":
|
|
109
|
+
return "quit"
|
|
110
|
+
if key == "ESC": # closes the filter or help (above); never quits, so a stray escape sequence is harmless
|
|
111
|
+
st.msg = ""
|
|
112
|
+
return None
|
|
113
|
+
if key in ("DOWN", "j", "WHEELDOWN"):
|
|
114
|
+
st.sel = min(st.sel + 1, max(len(r) - 1, 0))
|
|
115
|
+
elif key in ("UP", "k", "WHEELUP"):
|
|
116
|
+
st.sel = max(st.sel - 1, 0)
|
|
117
|
+
elif key in ("LEFT", "h", "RIGHT", "l", "ENTER"):
|
|
118
|
+
cur = selected(st)
|
|
119
|
+
if cur:
|
|
120
|
+
h = cur[1] if cur[0] == "h" else st.res["groups"][cur[1]]["harness"]
|
|
121
|
+
if key in ("LEFT", "h"):
|
|
122
|
+
st.folded.add(h)
|
|
123
|
+
st.sel = rows(st).index(("h", h))
|
|
124
|
+
elif cur[0] == "h":
|
|
125
|
+
st.folded.discard(h)
|
|
126
|
+
elif key == "p":
|
|
127
|
+
order: list[str | None] = [None, *PROFILES]
|
|
128
|
+
st.profile = order[(order.index(st.profile) + 1) % len(order)]
|
|
129
|
+
st.msg = "profile: " + (st.profile or "each model's own")
|
|
130
|
+
elif key == "%":
|
|
131
|
+
st.unit = "usd" if st.unit == "pct" else "pct"
|
|
132
|
+
elif key == "/":
|
|
133
|
+
st.mode = "filter"
|
|
134
|
+
elif key == "?":
|
|
135
|
+
st.mode = "help"
|
|
136
|
+
elif key == "r":
|
|
137
|
+
return "recal"
|
|
138
|
+
elif key == "c":
|
|
139
|
+
return "copy"
|
|
140
|
+
elif key.startswith("CLICK:"):
|
|
141
|
+
y = int(key.split(":")[1]) - st.left_top
|
|
142
|
+
if 0 <= y < st.left_rows and y < len(r):
|
|
143
|
+
st.sel = y
|
|
144
|
+
return None
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def snippet(g: dict[str, Any], threshold: int) -> str:
|
|
148
|
+
"""The setting for one model, in the harness's own syntax (the report's Copy button gives the same)."""
|
|
149
|
+
return setting(g, threshold)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
# ---------- the frame ----------
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _meters(st: TopState, cols: int) -> list[Line]:
|
|
156
|
+
t = totals(st.res, st.profile)
|
|
157
|
+
toks: list[Line] = []
|
|
158
|
+
if t["n"]:
|
|
159
|
+
toks.append([("Σ ", "dim"), *chip(t["pc"], fusd(t["d"]) + "/d", st.unit), (" cost", "dim")])
|
|
160
|
+
toks.append([*chip(t["pt"], fmin(t["dm"]) + "/d", st.unit), (" wall-clock", "dim")])
|
|
161
|
+
toks.append([(f"{t['n']} model{'s' if t['n'] != 1 else ''} to change", "dim")])
|
|
162
|
+
sv = st.service
|
|
163
|
+
if sv.get("age"): # only once something has calibrated; no placeholders
|
|
164
|
+
nxt = f" · next {sv['next']}" if sv.get("next") else ""
|
|
165
|
+
toks.append([("◴ ", "dim"), ("calibrated " + sv["age"], "ink"), (nxt, "dim")])
|
|
166
|
+
if sv.get("known"): # only once a service was set up
|
|
167
|
+
toks.append([("● ", "good" if sv.get("up") else "dim"), ("service " + ("up" if sv.get("up") else "not running"),
|
|
168
|
+
"ink" if sv.get("up") else "dim")]) # fmt: skip
|
|
169
|
+
toks.append([(PGLYPH.get(st.profile or "", "◆") + " ", "acc"), (st.profile or "own profile", "ink")])
|
|
170
|
+
v = verdict(st.res, prof=st.profile)
|
|
171
|
+
return ([clip(v, cols)] if v else []) + pack(toks, cols, " ")
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _tree(st: TopState, cols: int, height: int) -> list[Line]:
|
|
175
|
+
gs = st.res["groups"]
|
|
176
|
+
r = rows(st)
|
|
177
|
+
start = max(0, min(st.sel - height + 1, len(r) - height)) if len(r) > height else 0
|
|
178
|
+
out: list[Line] = []
|
|
179
|
+
for n, (kind, v) in enumerate(r[start : start + height], start):
|
|
180
|
+
mark = "▶" if n == st.sel else " "
|
|
181
|
+
if kind == "h":
|
|
182
|
+
hg = [g for g in gs if g["harness"] == v]
|
|
183
|
+
setd = sum((figs(g, prof_of(st, g)) or {"d": 0})["d"] for g in hg if status(g, prof_of(st, g)) == "set")
|
|
184
|
+
line: Line = [
|
|
185
|
+
(mark, "acc_b"),
|
|
186
|
+
("▸ " if v in st.folded else "▾ ", "dim"),
|
|
187
|
+
(v, "title"),
|
|
188
|
+
(" " + fusd(setd), "dim"),
|
|
189
|
+
]
|
|
190
|
+
else:
|
|
191
|
+
g = gs[v]
|
|
192
|
+
p = prof_of(st, g)
|
|
193
|
+
f = figs(g, p)
|
|
194
|
+
s = status(g, p)
|
|
195
|
+
name = f"{label(g['model'])} {'sub' if g['role'] == 'subagent' else g['role']}"
|
|
196
|
+
line = [(mark, "acc_b"), (" ", None), (name, "hl" if n == st.sel else "ink" if s != "noop" else "dim")]
|
|
197
|
+
tail: Line = []
|
|
198
|
+
if s == "noop":
|
|
199
|
+
tail = [("✓ no change", "dim")]
|
|
200
|
+
elif f:
|
|
201
|
+
if s == "set":
|
|
202
|
+
_, b = was_now(f["was"], f["now"], 6)
|
|
203
|
+
tail = [*b, (" ", None), *chip(f["pc"], None, st.unit)]
|
|
204
|
+
else:
|
|
205
|
+
tail = [("keep current" if s == "cur" else "keep default", "dim")]
|
|
206
|
+
room = cols - width(line) - width(tail) - 1
|
|
207
|
+
line = [*line, (" " * max(room, 1), None), *tail] if room >= 1 else clip(line, cols)
|
|
208
|
+
out.append(pad(line, cols))
|
|
209
|
+
return out + [pad([], cols)] * (height - len(out))
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _detail(st: TopState, cols: int, height: int) -> list[Line]:
|
|
213
|
+
cur = selected(st)
|
|
214
|
+
if not cur:
|
|
215
|
+
return [pad([("no models match the filter", "dim")], cols)] + [pad([], cols)] * (height - 1)
|
|
216
|
+
if cur[0] == "h":
|
|
217
|
+
hg = [g for g in st.res["groups"] if g["harness"] == cur[1]]
|
|
218
|
+
sub = {"groups": hg}
|
|
219
|
+
t = totals(sub, st.profile)
|
|
220
|
+
body: list[Line] = [[(cur[1], "title"), (f" {len(hg)} groups", "dim")]]
|
|
221
|
+
if t["n"]:
|
|
222
|
+
body += pack([[*chip(t["pc"], fusd(t["d"]) + "/day", st.unit), (" cost", "dim")],
|
|
223
|
+
[*chip(t["pt"], fmin(t["dm"]) + "/day", st.unit), (" time", "dim")]], cols) # fmt: skip
|
|
224
|
+
body.append([("→ expand with l / →; select a model for its curve", "dim")])
|
|
225
|
+
return [pad(x, cols) for x in body[:height]] + [pad([], cols)] * max(height - len(body), 0)
|
|
226
|
+
g = st.res["groups"][cur[1]]
|
|
227
|
+
p = prof_of(st, g)
|
|
228
|
+
pr, d = g["profiles"][p], g["default"]
|
|
229
|
+
f = figs(g, p)
|
|
230
|
+
s = status(g, p)
|
|
231
|
+
ttl = g.get("cache_ttl")
|
|
232
|
+
cache = (f" · cache {ttl // 3600} h" if ttl >= 3600 else f" · cache {ttl // 60} min") if ttl else ""
|
|
233
|
+
cache = cache if g["harness"] == "claude-code" else "" # only Anthropic bills by cache tier
|
|
234
|
+
body = [[(label(g["model"]), "title"), (f" · {g['role']} · {g['harness']} · {g['n_sessions']} sessions · "
|
|
235
|
+
f"{g['days']:.1f} d{cache}", "dim")]] # fmt: skip
|
|
236
|
+
if s == "noop":
|
|
237
|
+
body += [
|
|
238
|
+
[("✓ never reaches the default threshold: nothing to tune", "good")],
|
|
239
|
+
[(f"peak {k(g.get('peak_max'))} · p50 {k(g.get('peak_p50'))} · default {k(d['threshold'])}", "dim")],
|
|
240
|
+
]
|
|
241
|
+
elif f:
|
|
242
|
+
ans = [[(k(pr["threshold"]), "big")], [*chip(f["pc"], None, st.unit), (" cost", "dim")],
|
|
243
|
+
[*chip(f["pt"], None, st.unit), (" wall-clock", "dim")],
|
|
244
|
+
[(f"{fusd(f['d'])} · {fmin(f['dm'])} per day vs default {k(d['threshold'])}", "dim")]] # fmt: skip
|
|
245
|
+
if st.unit != "pct":
|
|
246
|
+
ans[1] = [(fusd(f["d"], True), ("good" if f["d"] < 0 else "warn") + "_b"), (" cost", "dim")]
|
|
247
|
+
ans[2] = [(fmin(f["dm"], True), ("good" if f["dm"] < 0 else "warn") + "_b"), (" wall-clock", "dim")]
|
|
248
|
+
body += pack(ans, cols)
|
|
249
|
+
if s in ("keep", "cur"):
|
|
250
|
+
body += pack([[(("▪ keep current: " if s == "cur" else "▪ keep default: ") + keep_reason(g, p), "dim")]],
|
|
251
|
+
cols) # fmt: skip
|
|
252
|
+
# cost and time vs threshold, both as % of the default, with default / current / profile marks
|
|
253
|
+
grid = g["grid"]
|
|
254
|
+
cc = [
|
|
255
|
+
(c - d["combined_cost"]) / d["combined_cost"] * 100 if d["combined_cost"] else 0.0
|
|
256
|
+
for c in g["combined_cost"]
|
|
257
|
+
]
|
|
258
|
+
tt = [(x - d["time_s"]) / d["time_s"] * 100 if d["time_s"] else 0.0 for x in g["time_s"]]
|
|
259
|
+
lo, hi = min(min(cc), min(tt), 0.0), max(max(cc), max(tt), 0.0)
|
|
260
|
+
ax = 7
|
|
261
|
+
cw_ = max(cols - ax, 8)
|
|
262
|
+
col = lambda v: round((v - grid[0]) / ((grid[-1] - grid[0]) or 1) * (cw_ - 1)) # noqa: E731
|
|
263
|
+
vl = [(col(d["threshold"]), "dim", "┊")]
|
|
264
|
+
if g.get("current"):
|
|
265
|
+
vl.append((col(g["current"]["threshold"]), "dim", "╎"))
|
|
266
|
+
vl.append((col(pr["threshold"]), "acc_b", "┃"))
|
|
267
|
+
ch = max(min(height - len(body) - 6, 14), 3)
|
|
268
|
+
plot = braille([(tt, "dim"), (cc, "acc")], cw_, ch, lo, hi, vl)
|
|
269
|
+
for i, ln in enumerate(plot):
|
|
270
|
+
tick = f"{hi:+.0f}%" if i == 0 else f"{lo:+.0f}%" if i == len(plot) - 1 else ""
|
|
271
|
+
body.append([(tick.rjust(ax - 1) + " ", "dim"), *ln])
|
|
272
|
+
lo_t, hi_t, sel = k(grid[0]), k(grid[-1]), k(pr["threshold"])
|
|
273
|
+
c0 = col(pr["threshold"]) - len(sel) // 2
|
|
274
|
+
if len(lo_t) < c0 and c0 + len(sel) < cw_ - len(hi_t): # selected threshold labelled under its marker
|
|
275
|
+
axis: Line = [(lo_t + " " * (c0 - len(lo_t)), "dim"), (sel, "acc_b"),
|
|
276
|
+
(" " * (cw_ - len(hi_t) - c0 - len(sel)) + hi_t, "dim")] # fmt: skip
|
|
277
|
+
else:
|
|
278
|
+
axis = [(lo_t + " " * max(cw_ - len(lo_t) - len(hi_t), 1) + hi_t, "dim")]
|
|
279
|
+
body.append([(" " * ax, None), *axis])
|
|
280
|
+
legend = " ┊ default ┃ profile" + (" ╎ current" if g.get("current") else "")
|
|
281
|
+
body.append([(" " * ax, None), ("⠿ cost", "acc"), (" ⠿ wall-clock", "dim"), (legend, "dim")])
|
|
282
|
+
a, b = was_now(f["was"], f["now"], max(min(cols - 26, 40), 6))
|
|
283
|
+
body.append([("cost was ", "dim"), *a, (f" ${f['was']:,.1f}", "dim")])
|
|
284
|
+
body.append(
|
|
285
|
+
[
|
|
286
|
+
(" now ", "dim"),
|
|
287
|
+
*b,
|
|
288
|
+
(f" ${f['now']:,.1f} ", "ink"),
|
|
289
|
+
(fpct(f["pc"]), "good" if f["d"] < 0 else "warn"),
|
|
290
|
+
]
|
|
291
|
+
)
|
|
292
|
+
if f["d"] < 0:
|
|
293
|
+
body.append([(" ", None), ("░ = saved", "good")])
|
|
294
|
+
toks = []
|
|
295
|
+
for n in PROFILES:
|
|
296
|
+
fn = figs(g, n)
|
|
297
|
+
tok: Line = [(PGLYPH[n] + " ", "acc" if n == p else "dim"), (f"{n} {k(g['profiles'][n]['threshold'])} ", "ink")]
|
|
298
|
+
if fn and not g["no_action_needed"]:
|
|
299
|
+
tok.append((fpct(fn["pc"]), "good" if fn["d"] < 0 else "warn"))
|
|
300
|
+
toks.append(tok)
|
|
301
|
+
body += pack(toks, cols, " ")
|
|
302
|
+
return [pad(x, cols) for x in body[:height]] + [pad([], cols)] * max(height - len(body), 0)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def frame(st: TopState, cols: int, nrows: int) -> list[Line]:
|
|
306
|
+
"""The whole screen: exactly `nrows` lines, none wider than `cols`."""
|
|
307
|
+
cols, nrows = max(cols, 30), max(nrows, 10)
|
|
308
|
+
title: Line = [(" compactlab top ", "acc_b"), (" " + ("% of default" if st.unit == "pct" else "$ / day"), "dim")]
|
|
309
|
+
hint = "? help · q quit"
|
|
310
|
+
top = [*title, (" " * max(cols - width(title) - cw(hint), 1), None), (hint, "dim")]
|
|
311
|
+
out = [clip(top, cols), *_meters(st, cols), [("─" * cols, "frame")]]
|
|
312
|
+
body_h = nrows - len(out) - 1
|
|
313
|
+
if cols >= 80:
|
|
314
|
+
lw = max(28, min(46, cols * 38 // 100))
|
|
315
|
+
left, right = _tree(st, lw, body_h), _detail(st, cols - lw - 3, body_h)
|
|
316
|
+
st.left_top, st.left_rows = len(out), body_h
|
|
317
|
+
out += [[*left[i], (" │ ", "frame"), *right[i]] for i in range(body_h)]
|
|
318
|
+
else: # narrow: the tree above, the detail below
|
|
319
|
+
th = max(min(len(rows(st)), body_h // 3), 3)
|
|
320
|
+
st.left_top, st.left_rows = len(out), th
|
|
321
|
+
out += [*_tree(st, cols, th), [("─" * cols, "frame")], *_detail(st, cols, body_h - th - 1)]
|
|
322
|
+
if st.mode == "filter":
|
|
323
|
+
status_line: Line = [("/ ", "acc_b"), (st.filt + "▏", "ink"), (" Enter keeps · Esc clears", "dim")]
|
|
324
|
+
else:
|
|
325
|
+
status_line = (
|
|
326
|
+
[(st.msg, "ink")]
|
|
327
|
+
if st.msg
|
|
328
|
+
else [("↑↓ select · ←→ fold · p profile · % unit · r recal · c copy · / filter", "dim")]
|
|
329
|
+
)
|
|
330
|
+
out.append(status_line)
|
|
331
|
+
if st.mode == "help":
|
|
332
|
+
out = _overlay(out, cols)
|
|
333
|
+
return [pad(clip(x, cols), cols) for x in out[:nrows]]
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _overlay(screen: list[Line], cols: int) -> list[Line]:
|
|
337
|
+
keyw = max(cw(a) for a, _ in KEYS)
|
|
338
|
+
body: list[Line] = [[(a + " " * (keyw - cw(a)) + " ", "acc"), (b, "ink")] for a, b in KEYS]
|
|
339
|
+
body += [[], [("cost = list-price estimate · % = change vs the harness default · any key closes", "dim")]]
|
|
340
|
+
w = min(cols - 4, max(width(x) for x in body) + 4)
|
|
341
|
+
from .widgets import panel
|
|
342
|
+
|
|
343
|
+
box = panel([("keys", "title")], body, w)
|
|
344
|
+
y0, x0 = 3, max((cols - w) // 2, 0)
|
|
345
|
+
for i, ln in enumerate(box):
|
|
346
|
+
if y0 + i < len(screen):
|
|
347
|
+
screen[y0 + i] = [(" " * x0, None), *ln]
|
|
348
|
+
return screen
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
# ---------- data, service, clipboard ----------
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def service_state(state_dir: Path) -> dict[str, Any]:
|
|
355
|
+
"""Whether the local service answers (its endpoint file + /api/health), and the calibration times."""
|
|
356
|
+
st = state_dir / "service" / "state.json"
|
|
357
|
+
ep = state_dir / "service" / "endpoint.json"
|
|
358
|
+
out: dict[str, Any] = {"up": False, "known": st.exists() or ep.exists()}
|
|
359
|
+
if st.exists():
|
|
360
|
+
try:
|
|
361
|
+
s = json.loads(st.read_text())
|
|
362
|
+
if s.get("last_ok"):
|
|
363
|
+
out["age"] = _ago(time.time() - s["last_ok"]) + " ago"
|
|
364
|
+
except ValueError:
|
|
365
|
+
pass
|
|
366
|
+
if ep.exists():
|
|
367
|
+
try:
|
|
368
|
+
e = json.loads(ep.read_text())
|
|
369
|
+
with urllib.request.urlopen(f"http://{e['host']}:{e['port']}/api/health", timeout=0.5) as r:
|
|
370
|
+
h = json.loads(r.read())
|
|
371
|
+
out["up"], out["endpoint"] = True, e
|
|
372
|
+
if h.get("next_calibration"):
|
|
373
|
+
out["next"] = time.strftime("%H:%M", time.localtime(h["next_calibration"]))
|
|
374
|
+
except (OSError, ValueError, KeyError):
|
|
375
|
+
pass
|
|
376
|
+
return out
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _ago(sec: float) -> str:
|
|
380
|
+
sec = max(sec, 0)
|
|
381
|
+
return f"{sec / 60:.0f}m" if sec < 3600 else f"{sec / 3600:.1f}h" if sec < 86400 else f"{sec / 86400:.1f}d"
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def recal_service(state_dir: Path, endpoint: dict[str, Any]) -> bool:
|
|
385
|
+
token = (state_dir / "service" / "token").read_text().strip()
|
|
386
|
+
req = urllib.request.Request(f"http://{endpoint['host']}:{endpoint['port']}/api/recalibrate", method="POST",
|
|
387
|
+
headers={"Authorization": "Bearer " + token}) # fmt: skip
|
|
388
|
+
try:
|
|
389
|
+
with urllib.request.urlopen(req, timeout=2) as r: # loopback only
|
|
390
|
+
return r.status in (202, 409)
|
|
391
|
+
except OSError:
|
|
392
|
+
return False
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def copy(text: str) -> bool:
|
|
396
|
+
for cmd in (["pbcopy"], ["wl-copy"], ["xclip", "-selection", "clipboard"]):
|
|
397
|
+
if shutil.which(cmd[0]):
|
|
398
|
+
try:
|
|
399
|
+
subprocess.run(cmd, input=text, text=True, check=True, timeout=5)
|
|
400
|
+
return True
|
|
401
|
+
except (OSError, subprocess.SubprocessError):
|
|
402
|
+
continue
|
|
403
|
+
return False
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def act(st: TopState, action: str, state_dir: Path, recalibrate: Callable[[], dict[str, Any] | None]) -> None:
|
|
407
|
+
if action == "copy":
|
|
408
|
+
cur = selected(st)
|
|
409
|
+
if not cur or cur[0] != "g":
|
|
410
|
+
st.msg = "select a model to copy its setting"
|
|
411
|
+
return
|
|
412
|
+
g = st.res["groups"][cur[1]]
|
|
413
|
+
p = prof_of(st, g)
|
|
414
|
+
if status(g, p) != "set":
|
|
415
|
+
what = {"keep": "keep default", "cur": "keep current", "noop": "no change"}[status(g, p)]
|
|
416
|
+
st.msg = f"{label(g['model'])}: {what}: nothing to copy"
|
|
417
|
+
return
|
|
418
|
+
text = snippet(g, g["profiles"][p]["threshold"])
|
|
419
|
+
st.msg = ("copied: " if copy(text) else "no clipboard tool; the setting: ") + text
|
|
420
|
+
elif action == "recal":
|
|
421
|
+
ep = st.service.get("endpoint")
|
|
422
|
+
if ep and recal_service(state_dir, ep):
|
|
423
|
+
st.msg = "service: recalibration started"
|
|
424
|
+
else:
|
|
425
|
+
st.msg = "recalibrating in-process (lite)…"
|
|
426
|
+
res = recalibrate()
|
|
427
|
+
if res:
|
|
428
|
+
st.res = res
|
|
429
|
+
st.msg = "recalibrated in-process (lite)"
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
# ---------- curses ----------
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def run(st: TopState, state_dir: Path, reload: Callable[[], dict[str, Any] | None],
|
|
436
|
+
recalibrate: Callable[[], dict[str, Any] | None], interval: float = 5.0) -> None: # fmt: skip
|
|
437
|
+
import curses
|
|
438
|
+
import os
|
|
439
|
+
|
|
440
|
+
os.environ.setdefault("ESCDELAY", "25") # a bare Esc is a key, not the start of a slow escape sequence
|
|
441
|
+
|
|
442
|
+
def main(scr: Any) -> None:
|
|
443
|
+
curses.curs_set(0)
|
|
444
|
+
curses.use_default_colors()
|
|
445
|
+
pairs: dict[str, int] = {}
|
|
446
|
+
if curses.has_colors():
|
|
447
|
+
curses.start_color()
|
|
448
|
+
from .style import PALETTE, ROLE_BASE, _cube
|
|
449
|
+
|
|
450
|
+
for n, (role, (rgb, basic)) in enumerate(PALETTE.items(), 1):
|
|
451
|
+
c = (
|
|
452
|
+
_cube(rgb)
|
|
453
|
+
if curses.COLORS >= 256
|
|
454
|
+
else {"31": 1, "32": 2, "33": 3, "91": 1, "90": 8, "97": 7}.get(basic, 7)
|
|
455
|
+
)
|
|
456
|
+
try:
|
|
457
|
+
curses.init_pair(n, c if c < curses.COLORS else -1, -1)
|
|
458
|
+
pairs[role] = curses.color_pair(n)
|
|
459
|
+
except curses.error:
|
|
460
|
+
pass
|
|
461
|
+
for alias, base in ROLE_BASE.items():
|
|
462
|
+
if base in pairs:
|
|
463
|
+
pairs[alias] = pairs[base]
|
|
464
|
+
curses.mousemask(curses.ALL_MOUSE_EVENTS | getattr(curses, "REPORT_MOUSE_POSITION", 0))
|
|
465
|
+
scr.timeout(int(interval * 1000))
|
|
466
|
+
last = time.time()
|
|
467
|
+
while True:
|
|
468
|
+
h, w = scr.getmaxyx()
|
|
469
|
+
scr.erase()
|
|
470
|
+
for y, ln in enumerate(frame(st, w - 1, h)):
|
|
471
|
+
x = 0
|
|
472
|
+
for text, role in ln:
|
|
473
|
+
attr = pairs.get(role or "", 0) | (
|
|
474
|
+
curses.A_BOLD if role and (role.endswith("_b") or role in ("title", "big", "hl")) else 0
|
|
475
|
+
)
|
|
476
|
+
if role == "hl":
|
|
477
|
+
attr |= curses.A_REVERSE
|
|
478
|
+
with contextlib.suppress(curses.error): # the bottom-right cell raises after drawing
|
|
479
|
+
scr.addstr(y, x, text, attr)
|
|
480
|
+
x += cw(text)
|
|
481
|
+
scr.refresh()
|
|
482
|
+
try: # get_wch raises on the refresh timeout instead of returning -1
|
|
483
|
+
ch = scr.get_wch() if hasattr(scr, "get_wch") else scr.getch()
|
|
484
|
+
except curses.error:
|
|
485
|
+
ch = None
|
|
486
|
+
key = _key(ch, curses)
|
|
487
|
+
if key is None:
|
|
488
|
+
if time.time() - last >= interval:
|
|
489
|
+
new = reload()
|
|
490
|
+
if new:
|
|
491
|
+
st.res = new
|
|
492
|
+
st.service = service_state(state_dir)
|
|
493
|
+
last = time.time()
|
|
494
|
+
continue
|
|
495
|
+
a = handle(st, key)
|
|
496
|
+
if a == "quit":
|
|
497
|
+
return
|
|
498
|
+
if a:
|
|
499
|
+
st.msg = "working…"
|
|
500
|
+
scr.addstr(h - 1, 0, st.msg[: max(w - 2, 0)])
|
|
501
|
+
scr.refresh()
|
|
502
|
+
act(st, a, state_dir, recalibrate)
|
|
503
|
+
|
|
504
|
+
with contextlib.suppress(curses.error):
|
|
505
|
+
curses.wrapper(main)
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def _key(ch: Any, curses: Any) -> str | None:
|
|
509
|
+
if ch in (-1, None):
|
|
510
|
+
return None
|
|
511
|
+
if ch == curses.KEY_RESIZE:
|
|
512
|
+
return "RESIZE"
|
|
513
|
+
if ch == curses.KEY_MOUSE:
|
|
514
|
+
try:
|
|
515
|
+
_, x, y, _, b = curses.getmouse()
|
|
516
|
+
except curses.error:
|
|
517
|
+
return None
|
|
518
|
+
if b & getattr(curses, "BUTTON4_PRESSED", 0):
|
|
519
|
+
return "WHEELUP"
|
|
520
|
+
if b & getattr(curses, "BUTTON5_PRESSED", 1 << 21):
|
|
521
|
+
return "WHEELDOWN"
|
|
522
|
+
return f"CLICK:{y}:{x}"
|
|
523
|
+
named = {curses.KEY_UP: "UP", curses.KEY_DOWN: "DOWN", curses.KEY_LEFT: "LEFT", curses.KEY_RIGHT: "RIGHT",
|
|
524
|
+
curses.KEY_BACKSPACE: "BACKSPACE", curses.KEY_ENTER: "ENTER"} # fmt: skip
|
|
525
|
+
if isinstance(ch, int):
|
|
526
|
+
return named.get(ch)
|
|
527
|
+
return {"\n": "ENTER", "\r": "ENTER", "\x1b": "ESC", "\x7f": "BACKSPACE", "\b": "BACKSPACE"}.get(ch, ch)
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def static(st: TopState, style: Style, cols: int, nrows: int) -> str:
|
|
531
|
+
return style.lines(frame(st, cols, nrows))
|