codebaton 0.1.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.
@@ -0,0 +1,476 @@
1
+ """Local models (Ollama): memory safety check, install, and the Codex-ready variant.
2
+
3
+ Why this exists: a model that does not fit in memory freezes the whole Mac (it happened
4
+ with gpt-oss-20b on an 18 GB machine: ~14 GB resident plus a growing prompt cache; see
5
+ docs/decisions.md D-038/D-039). So before downloading or loading a local model the router
6
+ estimates how much memory it needs *while running* and compares that with the machine.
7
+
8
+ How the estimate works (no download needed):
9
+ - The Ollama registry serves a model's manifest (layer sizes) and its GGUF weights file. We
10
+ read only the first megabytes of the GGUF file, whose header holds the model's own numbers:
11
+ ``<arch>.context_length``, ``<arch>.block_count`` (layers), ``attention.head_count_kv``
12
+ and ``attention.key_length`` / ``value_length``.
13
+ - Running memory = weights + context cache + overhead. The context cache (KV cache) for
14
+ ``ctx`` tokens is ``ctx * layers * kv_heads * (key_len + value_len) * bytes_per_value``;
15
+ Ollama here runs with ``OLLAMA_KV_CACHE_TYPE=q8_0`` (about 1.06 bytes per value).
16
+ - Codex sends ~40-47K tokens of instructions with every request, so local models run with a
17
+ 64K context (``AGENT_CONTEXT``); models whose maximum context is smaller cannot be used.
18
+
19
+ Estimates are saved in ``~/.codebaton/models.json`` so the launch-time check is instant.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import re
26
+ import struct
27
+ import subprocess
28
+ import sys
29
+ import urllib.request
30
+ from dataclasses import asdict, dataclass
31
+ from pathlib import Path
32
+ from typing import Any
33
+
34
+ from codebaton.core.usage_cache import router_home
35
+
36
+ REGISTRY = "https://registry.ollama.ai/v2"
37
+ AGENT_CONTEXT = 65536 # tokens; Codex's own prompt needs ~40-47K
38
+ MIN_CONTEXT = AGENT_CONTEXT
39
+ KV_BYTES_PER_VALUE = 1.0625 # q8_0
40
+ OVERHEAD_GB = 1.0 # runtime buffers and a margin for the prompt cache
41
+ RECOMMENDED_MODEL = "qwen3:4b"
42
+ GB = 1e9
43
+
44
+
45
+ @dataclass
46
+ class ModelEstimate:
47
+ name: str # base model, e.g. qwen3:4b
48
+ download_gb: float
49
+ max_context: int | None
50
+ weights_gb: float
51
+ kv_gb: float
52
+ need_gb: float # running memory at AGENT_CONTEXT
53
+ context: int = AGENT_CONTEXT
54
+ exact: bool = True # False when we fell back to a rough rule of thumb
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class Assessment:
59
+ level: str # ok | tight | too_big
60
+ need_gb: float
61
+ total_gb: float
62
+ free_gb: float | None
63
+
64
+ def summary(self) -> str:
65
+ free = (
66
+ f"{self.free_gb:.1f} GB free right now"
67
+ if self.free_gb is not None
68
+ else "free memory unknown"
69
+ )
70
+ verdict = {
71
+ "ok": "fits comfortably",
72
+ "tight": "tight: close other apps first",
73
+ "too_big": "too big: your Mac may freeze",
74
+ }[self.level]
75
+ return (
76
+ f"needs about {self.need_gb:.1f} GB of memory while running; "
77
+ f"your Mac has {self.total_gb:.0f} GB total, {free} -> {verdict}"
78
+ )
79
+
80
+
81
+ # -- machine memory ---------------------------------------------------------------------------
82
+
83
+
84
+ def total_memory_gb() -> float:
85
+ try:
86
+ out = subprocess.run(
87
+ ["sysctl", "-n", "hw.memsize"], capture_output=True, text=True, check=False
88
+ ).stdout
89
+ return int(out.strip()) / (1024**3)
90
+ except (OSError, ValueError):
91
+ return 0.0
92
+
93
+
94
+ def parse_vm_stat(text: str) -> float | None:
95
+ """Free memory in GB from macOS ``vm_stat``: free + inactive + speculative + purgeable."""
96
+ page = re.search(r"page size of (\d+) bytes", text)
97
+ if not page:
98
+ return None
99
+ size = int(page.group(1))
100
+ pages = 0
101
+ for key in ("Pages free", "Pages inactive", "Pages speculative", "Pages purgeable"):
102
+ m = re.search(rf"{key}:\s+(\d+)", text)
103
+ if m:
104
+ pages += int(m.group(1))
105
+ return pages * size / (1024**3)
106
+
107
+
108
+ def free_memory_gb() -> float | None:
109
+ if sys.platform != "darwin":
110
+ return None
111
+ try:
112
+ out = subprocess.run(["vm_stat"], capture_output=True, text=True, check=False).stdout
113
+ except OSError:
114
+ return None
115
+ return parse_vm_stat(out)
116
+
117
+
118
+ def assess(need_gb: float, total_gb: float, free_gb: float | None) -> Assessment:
119
+ """ok: at most half of the machine and currently free. too_big: over 75% of the machine."""
120
+ if total_gb <= 0:
121
+ return Assessment("tight", need_gb, total_gb, free_gb)
122
+ if need_gb > 0.75 * total_gb:
123
+ level = "too_big"
124
+ elif need_gb > 0.5 * total_gb or (free_gb is not None and need_gb > free_gb):
125
+ level = "tight"
126
+ else:
127
+ level = "ok"
128
+ return Assessment(level, need_gb, total_gb, free_gb)
129
+
130
+
131
+ # -- registry + GGUF header ---------------------------------------------------------------------
132
+
133
+
134
+ def _split(name: str) -> tuple[str, str]:
135
+ repo, _, tag = name.partition(":")
136
+ if "/" not in repo:
137
+ repo = f"library/{repo}"
138
+ return repo, tag or "latest"
139
+
140
+
141
+ def _get(url: str, headers: dict[str, str], timeout: float = 30) -> bytes:
142
+ req = urllib.request.Request(url, headers=headers) # noqa: S310 - fixed https registry URL
143
+ with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310
144
+ data: bytes = resp.read()
145
+ return data
146
+
147
+
148
+ def parse_gguf_header(data: bytes) -> dict[str, Any]:
149
+ """Return the key/value metadata from the start of a GGUF file (arrays are skipped)."""
150
+ if data[:4] != b"GGUF":
151
+ raise ValueError("not a GGUF file")
152
+ off = 8
153
+ _, n_kv = struct.unpack_from("<QQ", data, off)
154
+ off += 16
155
+ sizes = {0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 1, 10: 8, 11: 8, 12: 8}
156
+ fmts = {
157
+ 0: "<B",
158
+ 1: "<b",
159
+ 2: "<H",
160
+ 3: "<h",
161
+ 4: "<I",
162
+ 5: "<i",
163
+ 6: "<f",
164
+ 7: "<?",
165
+ 10: "<Q",
166
+ 11: "<q",
167
+ 12: "<d",
168
+ }
169
+
170
+ def read_str() -> str:
171
+ nonlocal off
172
+ (length,) = struct.unpack_from("<Q", data, off)
173
+ off += 8
174
+ text = data[off : off + length].decode("utf-8", "replace")
175
+ off += length
176
+ return text
177
+
178
+ def read_value(kind: int) -> Any:
179
+ nonlocal off
180
+ if kind == 8:
181
+ return read_str()
182
+ if kind == 9: # array: skip contents
183
+ (elem,) = struct.unpack_from("<I", data, off)
184
+ (count,) = struct.unpack_from("<Q", data, off + 4)
185
+ off += 12
186
+ if elem == 8:
187
+ for _ in range(count):
188
+ read_str()
189
+ else:
190
+ off += sizes[elem] * count
191
+ return None
192
+ (value,) = struct.unpack_from(fmts[kind], data, off)
193
+ off += sizes[kind]
194
+ return value
195
+
196
+ meta: dict[str, Any] = {}
197
+ for _ in range(n_kv):
198
+ key = read_str()
199
+ (kind,) = struct.unpack_from("<I", data, off)
200
+ off += 4
201
+ meta[key] = read_value(kind)
202
+ return meta
203
+
204
+
205
+ def kv_cache_gb(meta: dict[str, Any], context: int) -> float | None:
206
+ arch = meta.get("general.architecture")
207
+ layers = meta.get(f"{arch}.block_count")
208
+ kv_heads = meta.get(f"{arch}.attention.head_count_kv")
209
+ heads = meta.get(f"{arch}.attention.head_count")
210
+ width = meta.get(f"{arch}.embedding_length")
211
+ key_len = meta.get(f"{arch}.attention.key_length")
212
+ value_len = meta.get(f"{arch}.attention.value_length")
213
+ if not isinstance(layers, int) or not isinstance(kv_heads, int):
214
+ return None
215
+ if not isinstance(key_len, int) and isinstance(width, int) and isinstance(heads, int) and heads:
216
+ key_len = width // heads
217
+ if not isinstance(value_len, int):
218
+ value_len = key_len
219
+ if not isinstance(key_len, int) or not isinstance(value_len, int):
220
+ return None
221
+ return context * layers * kv_heads * (key_len + value_len) * KV_BYTES_PER_VALUE / GB
222
+
223
+
224
+ def rough_estimate(name: str, download_gb: float, max_context: int | None = None) -> ModelEstimate:
225
+ """Rule of thumb when exact numbers are unavailable: weights + 1.2x weights + overhead.
226
+
227
+ Deliberately high: hybrid models (per-layer settings) usually need less.
228
+ """
229
+ kv = download_gb * 1.2
230
+ return ModelEstimate(
231
+ name,
232
+ round(download_gb, 2),
233
+ max_context,
234
+ round(download_gb, 2),
235
+ round(kv, 2),
236
+ round(download_gb + kv + OVERHEAD_GB, 1),
237
+ exact=False,
238
+ )
239
+
240
+
241
+ def registry_estimate(name: str, context: int = AGENT_CONTEXT) -> ModelEstimate:
242
+ """Estimate running memory for ``name`` from the Ollama registry, without downloading it."""
243
+ repo, tag = _split(name)
244
+ manifest = json.loads(
245
+ _get(
246
+ f"{REGISTRY}/{repo}/manifests/{tag}",
247
+ {"Accept": "application/vnd.docker.distribution.manifest.v2+json"},
248
+ )
249
+ )
250
+ layers = manifest.get("layers", [])
251
+ download = sum(int(layer.get("size", 0)) for layer in layers) / GB
252
+ model = next(
253
+ (ly for ly in layers if str(ly.get("mediaType", "")).endswith("image.model")), None
254
+ )
255
+ if model is None:
256
+ return rough_estimate(name, download)
257
+ weights = int(model.get("size", 0)) / GB
258
+ try:
259
+ meta = parse_gguf_header(
260
+ _get(
261
+ f"{REGISTRY}/{repo}/blobs/{model['digest']}",
262
+ {"Range": "bytes=0-16000000"},
263
+ timeout=60,
264
+ )
265
+ )
266
+ except (ValueError, struct.error, OSError):
267
+ return rough_estimate(name, download)
268
+ arch = meta.get("general.architecture")
269
+ max_ctx = meta.get(f"{arch}.context_length")
270
+ kv = kv_cache_gb(meta, context)
271
+ if kv is None:
272
+ return rough_estimate(name, download, max_ctx if isinstance(max_ctx, int) else None)
273
+ return ModelEstimate(
274
+ name=name,
275
+ download_gb=round(download, 2),
276
+ max_context=max_ctx if isinstance(max_ctx, int) else None,
277
+ weights_gb=round(weights, 2),
278
+ kv_gb=round(kv, 2),
279
+ need_gb=round(weights + kv + OVERHEAD_GB, 1),
280
+ context=context,
281
+ )
282
+
283
+
284
+ # -- on-demand Ollama server --------------------------------------------------------------------
285
+
286
+ OLLAMA_URL = "http://127.0.0.1:11434"
287
+ # Same settings Homebrew's service uses; the memory estimate assumes the q8_0 KV cache.
288
+ SERVER_ENV = {"OLLAMA_FLASH_ATTENTION": "1", "OLLAMA_KV_CACHE_TYPE": "q8_0"}
289
+
290
+
291
+ def ollama_running(timeout: float = 1.0) -> bool:
292
+ try:
293
+ _get(f"{OLLAMA_URL}/api/version", {}, timeout=timeout)
294
+ return True
295
+ except OSError:
296
+ return False
297
+
298
+
299
+ def start_ollama_server(log_path: Path, wait_seconds: float = 20) -> subprocess.Popen[bytes] | None:
300
+ """Start `ollama serve` for this session if no server is running. Returns the process we
301
+ started (to stop later), or None if one was already running or it could not start."""
302
+ import os
303
+ import time
304
+
305
+ if ollama_running():
306
+ return None
307
+ log_path.parent.mkdir(parents=True, exist_ok=True)
308
+ log = log_path.open("ab")
309
+ try:
310
+ proc = subprocess.Popen(
311
+ ["ollama", "serve"],
312
+ stdout=log,
313
+ stderr=log,
314
+ env={**os.environ, **SERVER_ENV},
315
+ start_new_session=True, # not tied to the terminal; we stop it ourselves
316
+ )
317
+ except OSError:
318
+ log.close()
319
+ return None
320
+ deadline = time.monotonic() + wait_seconds
321
+ while time.monotonic() < deadline:
322
+ if ollama_running(timeout=0.5):
323
+ return proc
324
+ if proc.poll() is not None:
325
+ return None
326
+ time.sleep(0.3)
327
+ return proc
328
+
329
+
330
+ def stop_ollama_server(proc: subprocess.Popen[bytes] | None) -> None:
331
+ if proc is None or proc.poll() is not None:
332
+ return
333
+ proc.terminate()
334
+ try:
335
+ proc.wait(timeout=10)
336
+ except subprocess.TimeoutExpired:
337
+ proc.kill()
338
+
339
+
340
+ def models_dir() -> Path:
341
+ import os
342
+
343
+ return Path(os.environ.get("OLLAMA_MODELS", Path.home() / ".ollama" / "models"))
344
+
345
+
346
+ def installed_models(root: Path | None = None) -> list[str]:
347
+ """Installed model names, read from Ollama's manifest folders (no server needed).
348
+
349
+ Layout: <dir>/<registry>/<namespace>/<model>/<tag>, where <dir> is ``manifests`` (pulled
350
+ models) or ``manifests-v2`` (newer Ollama; entries are symlinks into ``blobs``, and models
351
+ made with ``ollama create`` live only here). The "library" namespace is left out of the
352
+ name, as ``ollama list`` does.
353
+ """
354
+ base = root or models_dir()
355
+ names: set[str] = set()
356
+ for folder in ("manifests", "manifests-v2"):
357
+ top = base / folder
358
+ if not top.is_dir():
359
+ continue
360
+ for tag_file in top.glob("*/*/*/*"):
361
+ if not (tag_file.is_file() or tag_file.is_symlink()):
362
+ continue
363
+ namespace, model, tag = tag_file.parts[-3], tag_file.parts[-2], tag_file.parts[-1]
364
+ prefix = "" if namespace == "library" else f"{namespace}/"
365
+ names.add(f"{prefix}{model}:{tag}")
366
+ return sorted(names)
367
+
368
+
369
+ # -- curated choices --------------------------------------------------------------------------
370
+
371
+ # Models known to fit Codex's ~64K-token prompt (max context >= 128K) and to support tools,
372
+ # strongest first. Sizes are not hard-coded: each is estimated live for the user's machine.
373
+ CANDIDATES: list[tuple[str, str]] = [
374
+ ("qwen3-coder:30b", "coding specialist"),
375
+ ("devstral:24b", "built for agent-style coding"),
376
+ ("gpt-oss:20b", "strong all-rounder"),
377
+ ("qwen3:4b", "small and capable (thinking model)"),
378
+ ("granite4:3b", "lightest"),
379
+ ]
380
+
381
+
382
+ @dataclass(frozen=True)
383
+ class Choice:
384
+ name: str
385
+ note: str
386
+ estimate: ModelEstimate | None
387
+ fit: str # ok | tight | too_big | unknown (judged on total memory, not momentary free)
388
+ recommended: bool = False
389
+
390
+
391
+ def choices(total_gb: float, estimator: Any = None) -> list[Choice]:
392
+ """Estimate every candidate (in parallel) and recommend the strongest that fits."""
393
+ from concurrent.futures import ThreadPoolExecutor
394
+
395
+ estimate_fn = estimator or registry_estimate
396
+
397
+ def one(item: tuple[str, str]) -> tuple[str, str, ModelEstimate | None]:
398
+ try:
399
+ return item[0], item[1], estimate_fn(item[0])
400
+ except Exception:
401
+ return item[0], item[1], None
402
+
403
+ with ThreadPoolExecutor(max_workers=len(CANDIDATES)) as pool:
404
+ rows = list(pool.map(one, CANDIDATES))
405
+ result: list[Choice] = []
406
+ picked = False
407
+ for name, note, est in rows:
408
+ fit = assess(est.need_gb, total_gb, None).level if est else "unknown"
409
+ recommend = fit == "ok" and not picked
410
+ picked = picked or recommend
411
+ result.append(Choice(name, note, est, fit, recommend))
412
+ if not picked: # nothing fits comfortably: suggest the smallest known one
413
+ sized = [c for c in result if c.estimate is not None]
414
+ if sized:
415
+ smallest = min(sized, key=lambda c: c.estimate.need_gb if c.estimate else 0.0)
416
+ result = [Choice(c.name, c.note, c.estimate, c.fit, c is smallest) for c in result]
417
+ return result
418
+
419
+
420
+ # -- saved estimates and the Codex-ready variant ----------------------------------------------
421
+
422
+
423
+ def estimates_path() -> Path:
424
+ return router_home() / "models.json"
425
+
426
+
427
+ def save_estimate(local_name: str, estimate: ModelEstimate) -> None:
428
+ path = estimates_path()
429
+ try:
430
+ data = json.loads(path.read_text(encoding="utf-8"))
431
+ except (OSError, json.JSONDecodeError):
432
+ data = {}
433
+ data[local_name] = asdict(estimate)
434
+ path.parent.mkdir(parents=True, exist_ok=True)
435
+ path.write_text(json.dumps(data, indent=2), encoding="utf-8")
436
+
437
+
438
+ def load_estimate(local_name: str) -> ModelEstimate | None:
439
+ try:
440
+ data = json.loads(estimates_path().read_text(encoding="utf-8"))
441
+ bare = local_name.removesuffix(":latest")
442
+ entry = data.get(local_name) or data.get(bare) or data.get(f"{bare}:latest")
443
+ return ModelEstimate(**entry) if isinstance(entry, dict) else None
444
+ except (OSError, json.JSONDecodeError, TypeError):
445
+ return None
446
+
447
+
448
+ def agent_variant_name(name: str) -> str:
449
+ """qwen3:4b -> qwen3-4b-agent:latest (same weights, 64K context for Codex)."""
450
+ base = name.removesuffix(":latest").replace(":", "-").replace("/", "-")
451
+ return f"{base}-agent:latest"
452
+
453
+
454
+ def modelfile(name: str, context: int = AGENT_CONTEXT) -> str:
455
+ return f"FROM {name}\nPARAMETER num_ctx {context}\n"
456
+
457
+
458
+ def set_router_model(router_yaml: Path, model: str) -> None:
459
+ """Point ``ollama.model`` in router.yaml at ``model``, keeping comments and layout."""
460
+ text = router_yaml.read_text(encoding="utf-8") if router_yaml.exists() else ""
461
+ lines = text.splitlines()
462
+ start = next((i for i, line in enumerate(lines) if re.match(r"^ollama:\s*(#.*)?$", line)), None)
463
+ entry = f" model: {model} # set by codebaton install-model"
464
+ if start is None:
465
+ lines += ["ollama:", " enabled: true", entry]
466
+ else:
467
+ end = start + 1
468
+ while end < len(lines) and (lines[end].startswith(" ") or not lines[end].strip()):
469
+ end += 1
470
+ for i in range(start + 1, end):
471
+ if re.match(r"^\s+#?\s*model:", lines[i]):
472
+ lines[i] = entry
473
+ break
474
+ else:
475
+ lines.insert(start + 1, entry)
476
+ router_yaml.write_text("\n".join(lines) + "\n", encoding="utf-8")
File without changes
@@ -0,0 +1,14 @@
1
+ """Stub entry point for the future MCP server (budget, handoff, handoff-request tools).
2
+
3
+ Out of scope for v0. Kept so the ``codebaton-mcp`` entry point and package layout are
4
+ stable and the MCP can ship later without restructuring.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import sys
10
+
11
+
12
+ def main() -> None:
13
+ print("codebaton-mcp: the MCP server is not implemented in v0.", file=sys.stderr)
14
+ sys.exit(2)
codebaton/monitor.py ADDED
@@ -0,0 +1,137 @@
1
+ """Live usage monitor: every agent's usage windows, thresholds and reset countdowns.
2
+
3
+ Data sources (no network calls, no tokens):
4
+ - Claude Code: the usage cache, written by the session status line on every refresh and by
5
+ ``codebaton status --refresh``.
6
+ - Codex: the newest ``token_count`` event in ``~/.codex/sessions``.
7
+ A window whose reset time has passed is shown as 0%.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import time
14
+ from dataclasses import asdict, dataclass
15
+ from datetime import datetime
16
+
17
+ from codebaton.config import RouterConfig
18
+ from codebaton.core.usage_cache import UsageCache
19
+ from codebaton.plugins.base import UsageWindow
20
+ from codebaton.plugins.usage.codex_logs import CodexLogsReader
21
+
22
+ WINDOW_LABELS = {"short": "5h", "long": "week"}
23
+ BAR_WIDTH = 20
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class WindowRow:
28
+ provider: str
29
+ window: str # "5h" or "week"
30
+ percent: float
31
+ threshold: float
32
+ resets_at: float | None
33
+ updated_at: float | None # when the provider last reported this number
34
+
35
+
36
+ def _rows(
37
+ provider: str,
38
+ threshold: float,
39
+ windows: dict[str, UsageWindow],
40
+ updated_at: float | None,
41
+ now: float,
42
+ ) -> list[WindowRow]:
43
+ rows = []
44
+ for key in ("short", "long"):
45
+ win = windows.get(key)
46
+ if win is None:
47
+ continue
48
+ expired = win.resets_at is not None and win.resets_at <= now
49
+ rows.append(
50
+ WindowRow(
51
+ provider,
52
+ WINDOW_LABELS[key],
53
+ 0.0 if expired else win.percent,
54
+ threshold,
55
+ None if expired else win.resets_at,
56
+ updated_at,
57
+ )
58
+ )
59
+ return rows
60
+
61
+
62
+ def _parse_ts(value: str) -> float | None:
63
+ try:
64
+ return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
65
+ except ValueError:
66
+ return None
67
+
68
+
69
+ def collect(
70
+ config: RouterConfig,
71
+ cache: UsageCache | None = None,
72
+ codex: CodexLogsReader | None = None,
73
+ now: float | None = None,
74
+ ) -> list[WindowRow]:
75
+ """Usage rows for every configured provider that has reported numbers."""
76
+ now = time.time() if now is None else now
77
+ rows: list[WindowRow] = []
78
+ for provider in config.providers:
79
+ kind = provider.adapter_name
80
+ if kind == "claude_code":
81
+ entry = (cache or UsageCache()).load(provider.name)
82
+ if entry:
83
+ rows += _rows(provider.name, provider.cap_percent, entry[1], entry[0], now)
84
+ elif kind == "codex":
85
+ found = (codex or CodexLogsReader()).windows()
86
+ if found:
87
+ rows += _rows(
88
+ provider.name, provider.cap_percent, found[1], _parse_ts(found[0]), now
89
+ )
90
+ return rows
91
+
92
+
93
+ def _duration(seconds: float) -> str:
94
+ seconds = max(0, int(seconds))
95
+ days, rem = divmod(seconds, 86400)
96
+ hours, rem = divmod(rem, 3600)
97
+ minutes = rem // 60
98
+ if days:
99
+ return f"{days}d {hours}h"
100
+ if hours:
101
+ return f"{hours}h {minutes:02d}m"
102
+ return f"{minutes}m"
103
+
104
+
105
+ def _bar(percent: float, threshold: float) -> str:
106
+ filled = round(min(percent, 100) / 100 * BAR_WIDTH)
107
+ mark = min(BAR_WIDTH - 1, round(threshold / 100 * BAR_WIDTH))
108
+ cells = ["█" if i < filled else "░" for i in range(BAR_WIDTH)]
109
+ if mark >= filled:
110
+ cells[mark] = "│" # where the threshold sits
111
+ return "".join(cells)
112
+
113
+
114
+ def render(rows: list[WindowRow], now: float | None = None) -> str:
115
+ now = time.time() if now is None else now
116
+ if not rows:
117
+ return (
118
+ "No usage reported yet. Open a session with `codebaton`, or run\n"
119
+ "`codebaton status --refresh` for Claude. Codex numbers appear after its first reply."
120
+ )
121
+ lines = [f"{'agent':<13}{'window':<7}{'usage':<{BAR_WIDTH + 2}}{'used':>6} status"]
122
+ for r in rows:
123
+ state = "over threshold" if r.percent >= r.threshold else "ok"
124
+ reset = f"resets in {_duration(r.resets_at - now)}" if r.resets_at else ""
125
+ age = f"updated {_duration(now - r.updated_at)} ago" if r.updated_at else ""
126
+ extra = ", ".join(x for x in (reset, age) if x)
127
+ lines.append(
128
+ f"{r.provider:<13}{r.window:<7}{_bar(r.percent, r.threshold)} {r.percent:>4.0f}% "
129
+ f"{state} (threshold {r.threshold:.0f}%) {extra}"
130
+ )
131
+ lines.append("")
132
+ lines.append("│ marks the threshold. Claude refreshes while a Claude session is open.")
133
+ return "\n".join(lines)
134
+
135
+
136
+ def to_json(rows: list[WindowRow]) -> str:
137
+ return json.dumps([asdict(r) for r in rows], indent=2)
File without changes