claude-code-router 0.1.1__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.
- ccr/__init__.py +0 -0
- ccr/__main__.py +4 -0
- ccr/cli.py +595 -0
- ccr/config.py +518 -0
- ccr/detect/__init__.py +123 -0
- ccr/doctor.py +208 -0
- ccr/entry.py +23 -0
- ccr/evaluate/__init__.py +13 -0
- ccr/evaluate/classify.py +335 -0
- ccr/evaluate/llm.py +182 -0
- ccr/evaluate/locate.py +359 -0
- ccr/evaluate/risk.py +285 -0
- ccr/evaluate/text.py +190 -0
- ccr/graph/__init__.py +15 -0
- ccr/graph/build.py +475 -0
- ccr/graph/db.py +88 -0
- ccr/graph/files.py +169 -0
- ccr/graph/git.py +90 -0
- ccr/graph/parse.py +510 -0
- ccr/graph/query.py +359 -0
- ccr/graph/resolve.py +256 -0
- ccr/headless.py +363 -0
- ccr/history/__init__.py +172 -0
- ccr/history/calibrate.py +161 -0
- ccr/history/dashboard.py +374 -0
- ccr/history/feedback.py +91 -0
- ccr/history/learn.py +184 -0
- ccr/history/prompts.py +120 -0
- ccr/history/redact.py +45 -0
- ccr/history/savings.py +187 -0
- ccr/history/shadow.py +114 -0
- ccr/history/stats.py +172 -0
- ccr/history/tune.py +80 -0
- ccr/history/why.py +186 -0
- ccr/hooks/__init__.py +134 -0
- ccr/hooks/bg.py +68 -0
- ccr/hooks/common.py +159 -0
- ccr/hooks/prompt.py +322 -0
- ccr/hooks/session_start.py +91 -0
- ccr/hooks/stop.py +52 -0
- ccr/hooks/tasks.py +170 -0
- ccr/install/__init__.py +388 -0
- ccr/install/agents.py +200 -0
- ccr/install/command.py +159 -0
- ccr/install/settings.py +175 -0
- ccr/memory/__init__.py +87 -0
- ccr/memory/signals.py +210 -0
- ccr/memory/sources.py +422 -0
- ccr/report.py +40 -0
- ccr/route/__init__.py +527 -0
- ccr/route/budget.py +166 -0
- ccr/statusline.py +143 -0
- ccr/transcript.py +98 -0
- claude_code_router-0.1.1.dist-info/METADATA +291 -0
- claude_code_router-0.1.1.dist-info/RECORD +58 -0
- claude_code_router-0.1.1.dist-info/WHEEL +4 -0
- claude_code_router-0.1.1.dist-info/entry_points.txt +2 -0
- claude_code_router-0.1.1.dist-info/licenses/LICENSE +21 -0
ccr/route/budget.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""Budget pressure from weekly subscription usage.
|
|
2
|
+
|
|
3
|
+
Primary source: `.ccr/local/state.json` written by `ccr statusline` (Claude Code passes
|
|
4
|
+
`rate_limits.seven_day.used_percentage` to status line commands). Fallback hook point: a
|
|
5
|
+
callable `(root, cfg, now) -> (used_pct | None, detail)`; the default sums token usage from
|
|
6
|
+
`.ccr/history.jsonl` (last 7 days) plus the current transcript, against
|
|
7
|
+
`budget.weekly_token_limit` when configured.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import time
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from datetime import datetime
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
WEEK_S = 7 * 86400
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class Budget:
|
|
23
|
+
used_pct: float | None = None
|
|
24
|
+
source: str = "none" # statusline | tokens | custom | none
|
|
25
|
+
pressure: bool = False
|
|
26
|
+
soft_limit_pct: float = 80.0
|
|
27
|
+
detail: str = "no usage data"
|
|
28
|
+
age_s: int | None = None
|
|
29
|
+
five_hour_pct: float | None = None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def state_path(root: str | Path) -> Path:
|
|
33
|
+
return Path(root) / ".ccr" / "local" / "state.json"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _epoch(v) -> float | None:
|
|
37
|
+
if isinstance(v, bool):
|
|
38
|
+
return None
|
|
39
|
+
if isinstance(v, (int, float)):
|
|
40
|
+
return float(v) / 1000.0 if v > 1e12 else float(v) # accept ms
|
|
41
|
+
if isinstance(v, str) and v.strip():
|
|
42
|
+
try:
|
|
43
|
+
return datetime.fromisoformat(v.strip().replace("Z", "+00:00")).timestamp()
|
|
44
|
+
except ValueError:
|
|
45
|
+
try:
|
|
46
|
+
return float(v)
|
|
47
|
+
except ValueError:
|
|
48
|
+
return None
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _pct(v) -> float | None:
|
|
53
|
+
if isinstance(v, bool) or not isinstance(v, (int, float)):
|
|
54
|
+
return None
|
|
55
|
+
return max(0.0, min(100.0, float(v)))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def read_statusline_usage(root: str | Path, cfg, now: float) -> tuple[float | None, str,
|
|
59
|
+
int | None,
|
|
60
|
+
float | None]:
|
|
61
|
+
"""(weekly used %, detail, age seconds, five-hour %) from the statusline state file."""
|
|
62
|
+
p = state_path(root)
|
|
63
|
+
try:
|
|
64
|
+
data = json.loads(p.read_text(encoding="utf-8"))
|
|
65
|
+
mtime = os.path.getmtime(p)
|
|
66
|
+
except FileNotFoundError:
|
|
67
|
+
return None, "statusline state missing", None, None
|
|
68
|
+
except (OSError, ValueError) as e:
|
|
69
|
+
return None, f"statusline state unreadable ({e.__class__.__name__})", None, None
|
|
70
|
+
if not isinstance(data, dict):
|
|
71
|
+
return None, "statusline state malformed", None, None
|
|
72
|
+
rl = data.get("rate_limits") if isinstance(data.get("rate_limits"), dict) else {}
|
|
73
|
+
week = rl.get("seven_day") if isinstance(rl.get("seven_day"), dict) else {}
|
|
74
|
+
five = rl.get("five_hour") if isinstance(rl.get("five_hour"), dict) else {}
|
|
75
|
+
pct = _pct(week.get("used_percentage"))
|
|
76
|
+
five_pct = _pct(five.get("used_percentage"))
|
|
77
|
+
ts = _epoch(data.get("ts")) or mtime
|
|
78
|
+
age = max(0, int(now - ts))
|
|
79
|
+
if pct is None:
|
|
80
|
+
return None, "statusline state has no seven_day usage", age, five_pct
|
|
81
|
+
max_age = float(cfg["budget"]["state_max_age_hours"]) * 3600
|
|
82
|
+
if age > max_age:
|
|
83
|
+
return None, f"statusline state is stale ({age // 3600}h old)", age, five_pct
|
|
84
|
+
resets = _epoch(week.get("resets_at"))
|
|
85
|
+
if resets is not None and resets <= now:
|
|
86
|
+
return 0.0, "weekly window reset since last statusline update", age, five_pct
|
|
87
|
+
return pct, f"weekly usage {pct:.0f}% (statusline, {_age(age)} old)", age, five_pct
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def transcript_tokens(path: str | Path) -> int:
|
|
91
|
+
"""Input + output + cache-creation tokens, counted once per assistant message."""
|
|
92
|
+
from ccr.transcript import read_usage
|
|
93
|
+
return read_usage(path, complete_only=False).tokens
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def token_fallback(root: str | Path, cfg, now: float,
|
|
97
|
+
transcript_path: str | Path | None = None) -> tuple[float | None, str]:
|
|
98
|
+
limit = cfg["budget"].get("weekly_token_limit")
|
|
99
|
+
if not limit:
|
|
100
|
+
return None, "no weekly_token_limit configured for the token fallback"
|
|
101
|
+
from ccr import history
|
|
102
|
+
session = None
|
|
103
|
+
tokens = 0
|
|
104
|
+
if transcript_path:
|
|
105
|
+
session = Path(transcript_path).stem
|
|
106
|
+
tokens += transcript_tokens(transcript_path)
|
|
107
|
+
for r in history.read(root, window_days=7, now=now):
|
|
108
|
+
if session and r.get("session") == session:
|
|
109
|
+
continue
|
|
110
|
+
t = r.get("tokens")
|
|
111
|
+
if isinstance(t, int) and not isinstance(t, bool):
|
|
112
|
+
tokens += t
|
|
113
|
+
pct = min(100.0, 100.0 * tokens / float(limit))
|
|
114
|
+
return pct, f"~{pct:.0f}% of weekly_token_limit ({_kfmt(tokens)}/{_kfmt(limit)} tokens, " \
|
|
115
|
+
f"history + transcript)"
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def budget_pressure(root: str | Path, cfg, now: float | None = None, fallback=None,
|
|
119
|
+
transcript_path: str | Path | None = None) -> Budget:
|
|
120
|
+
"""Read weekly usage and decide whether budget pressure applies. Never raises."""
|
|
121
|
+
now = time.time() if now is None else now
|
|
122
|
+
soft = float(cfg["budget"]["soft_limit_pct"])
|
|
123
|
+
b = Budget(soft_limit_pct=soft)
|
|
124
|
+
try:
|
|
125
|
+
pct, detail, age, five = read_statusline_usage(root, cfg, now)
|
|
126
|
+
except Exception as e: # pragma: no cover - defensive
|
|
127
|
+
pct, detail, age, five = None, f"statusline state error: {e}", None, None
|
|
128
|
+
b.age_s, b.five_hour_pct = age, five
|
|
129
|
+
if pct is not None:
|
|
130
|
+
b.used_pct, b.source, b.detail = pct, "statusline", detail
|
|
131
|
+
else:
|
|
132
|
+
why = detail
|
|
133
|
+
try:
|
|
134
|
+
if fallback is not None:
|
|
135
|
+
fpct, fdetail = fallback(root, cfg, now)
|
|
136
|
+
src = "custom"
|
|
137
|
+
else:
|
|
138
|
+
fpct, fdetail = token_fallback(root, cfg, now, transcript_path)
|
|
139
|
+
src = "tokens"
|
|
140
|
+
except Exception as e:
|
|
141
|
+
fpct, fdetail, src = None, f"fallback failed: {e}", "none"
|
|
142
|
+
if fpct is not None:
|
|
143
|
+
b.used_pct, b.source, b.detail = float(fpct), src, f"{fdetail} [{why}]"
|
|
144
|
+
else:
|
|
145
|
+
b.detail = f"{why}; {fdetail}"
|
|
146
|
+
if b.used_pct is not None:
|
|
147
|
+
b.pressure = b.used_pct >= soft
|
|
148
|
+
b.detail += (f" >= soft limit {soft:.0f}%" if b.pressure
|
|
149
|
+
else f" < soft limit {soft:.0f}%")
|
|
150
|
+
return b
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _age(s: int) -> str:
|
|
154
|
+
if s < 120:
|
|
155
|
+
return f"{s}s"
|
|
156
|
+
if s < 7200:
|
|
157
|
+
return f"{s // 60}m"
|
|
158
|
+
return f"{s // 3600}h"
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _kfmt(n: float) -> str:
|
|
162
|
+
n = float(n)
|
|
163
|
+
for unit, div in (("M", 1e6), ("k", 1e3)):
|
|
164
|
+
if n >= div:
|
|
165
|
+
return f"{n / div:.1f}{unit}"
|
|
166
|
+
return f"{int(n)}"
|
ccr/statusline.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""`ccr statusline [--wrap "<command>"]`: Claude Code status line relay.
|
|
2
|
+
|
|
3
|
+
Reads the status line JSON on stdin and atomically writes .ccr/local/state.json:
|
|
4
|
+
{"ts", "model": {"id", "display_name"}, "effort", "rate_limits", "session_id",
|
|
5
|
+
"sessions": {session_id: {"model", "effort", "ts"}}} (newest 16 sessions)
|
|
6
|
+
which the prompt hook (main model for /model advice) and budget pressure (weekly usage) read.
|
|
7
|
+
|
|
8
|
+
Prints a short line (`ccr T2 sonnet/medium · 5h 24% · 7d 41%`), or with --wrap runs the
|
|
9
|
+
user's own status line command with the same stdin and prints its output unchanged.
|
|
10
|
+
Fails open: errors print nothing (or just the wrapped output) and exit 0.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import logging
|
|
15
|
+
import os
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
import time
|
|
19
|
+
|
|
20
|
+
MAX_SESSIONS = 16
|
|
21
|
+
WRAP_TIMEOUT_S = 5.0
|
|
22
|
+
|
|
23
|
+
log = logging.getLogger("ccr.statusline")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _shell_argv(cmd: str) -> list[str] | None:
|
|
27
|
+
"""How Claude Code would run a status line command: sh -c (POSIX), Git Bash or
|
|
28
|
+
PowerShell (Windows)."""
|
|
29
|
+
if os.name != "nt":
|
|
30
|
+
return ["/bin/sh", "-c", cmd]
|
|
31
|
+
from ccr.install.command import git_bash
|
|
32
|
+
bash = git_bash()
|
|
33
|
+
if bash:
|
|
34
|
+
return [bash, "-c", cmd]
|
|
35
|
+
return ["powershell", "-NoProfile", "-Command", cmd]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def run_wrapped(cmd: str, raw: bytes) -> str:
|
|
39
|
+
argv = _shell_argv(cmd)
|
|
40
|
+
try:
|
|
41
|
+
r = subprocess.run(argv, input=raw, capture_output=True, timeout=WRAP_TIMEOUT_S)
|
|
42
|
+
except (OSError, subprocess.SubprocessError):
|
|
43
|
+
return ""
|
|
44
|
+
return r.stdout.decode("utf-8", errors="replace")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _pct(v) -> float | None:
|
|
48
|
+
return float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def record(data: dict, environ=None) -> tuple[object, dict | None]:
|
|
52
|
+
"""Write state.json; returns (root, written state) or (None, None)."""
|
|
53
|
+
from ccr.hooks.common import effort_level, find_root, read_json, write_json_atomic
|
|
54
|
+
root = find_root(data, environ)
|
|
55
|
+
if root is None:
|
|
56
|
+
return None, None
|
|
57
|
+
model = data.get("model") if isinstance(data.get("model"), dict) else {}
|
|
58
|
+
p = root / ".ccr" / "local" / "state.json"
|
|
59
|
+
prev = read_json(p)
|
|
60
|
+
now = time.time()
|
|
61
|
+
state = {"ts": now,
|
|
62
|
+
"model": {"id": model.get("id"), "display_name": model.get("display_name")},
|
|
63
|
+
"effort": effort_level(data.get("effort")),
|
|
64
|
+
"rate_limits": data.get("rate_limits") if isinstance(data.get("rate_limits"),
|
|
65
|
+
dict) else
|
|
66
|
+
prev.get("rate_limits") if isinstance(prev.get("rate_limits"), dict) else {},
|
|
67
|
+
"session_id": data.get("session_id"),
|
|
68
|
+
"version": data.get("version")}
|
|
69
|
+
sessions = prev.get("sessions") if isinstance(prev.get("sessions"), dict) else {}
|
|
70
|
+
sid = data.get("session_id")
|
|
71
|
+
if not model.get("id") and isinstance(prev.get("model"), dict) and \
|
|
72
|
+
prev.get("session_id") == sid:
|
|
73
|
+
state["model"] = prev["model"] # partial payload: keep what we knew
|
|
74
|
+
state["effort"] = state["effort"] or prev.get("effort")
|
|
75
|
+
if isinstance(sid, str) and sid:
|
|
76
|
+
old = sessions.get(sid) if isinstance(sessions.get(sid), dict) else {}
|
|
77
|
+
sessions[sid] = {"model": model.get("id") or old.get("model"),
|
|
78
|
+
"effort": state["effort"] or old.get("effort"), "ts": now}
|
|
79
|
+
if len(sessions) > MAX_SESSIONS:
|
|
80
|
+
keep = sorted(sessions.items(), key=lambda kv: -float((kv[1] or {}).get("ts") or 0))
|
|
81
|
+
sessions = dict(keep[:MAX_SESSIONS])
|
|
82
|
+
state["sessions"] = sessions
|
|
83
|
+
write_json_atomic(p, state)
|
|
84
|
+
return root, state
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def line(root, state: dict) -> str:
|
|
88
|
+
from ccr.hooks.common import load_session, model_alias
|
|
89
|
+
parts = ["ccr"]
|
|
90
|
+
sid = state.get("session_id")
|
|
91
|
+
pend = load_session(root, sid).get("pending") if sid else None
|
|
92
|
+
if isinstance(pend, dict) and pend.get("tier"):
|
|
93
|
+
parts.append(f"{pend['tier']} {pend.get('model')}/{pend.get('effort')}")
|
|
94
|
+
else:
|
|
95
|
+
alias = model_alias(state["model"].get("id"))
|
|
96
|
+
if alias:
|
|
97
|
+
parts.append(alias + (f"/{state['effort']}" if state.get("effort") else ""))
|
|
98
|
+
rl = state.get("rate_limits") or {}
|
|
99
|
+
for key, label in (("five_hour", "5h"), ("seven_day", "7d")):
|
|
100
|
+
w = rl.get(key) if isinstance(rl.get(key), dict) else {}
|
|
101
|
+
v = _pct(w.get("used_percentage"))
|
|
102
|
+
if v is not None:
|
|
103
|
+
parts.append(f"{label} {v:.0f}%")
|
|
104
|
+
return " · ".join(parts)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def main(args: list[str], *, stdin=None, stdout=None, environ=None) -> int:
|
|
108
|
+
out = stdout if stdout is not None else sys.stdout
|
|
109
|
+
wrap = None
|
|
110
|
+
if "--wrap" in args:
|
|
111
|
+
i = args.index("--wrap")
|
|
112
|
+
wrap = args[i + 1] if i + 1 < len(args) else None
|
|
113
|
+
text = ""
|
|
114
|
+
try:
|
|
115
|
+
src = stdin if stdin is not None else sys.stdin.buffer
|
|
116
|
+
raw = src.read(4 * 1024 * 1024)
|
|
117
|
+
if isinstance(raw, str):
|
|
118
|
+
raw = raw.encode("utf-8")
|
|
119
|
+
except Exception:
|
|
120
|
+
log.debug("statusline: stdin unreadable", exc_info=True)
|
|
121
|
+
raw = b""
|
|
122
|
+
try:
|
|
123
|
+
if wrap:
|
|
124
|
+
text = run_wrapped(wrap, raw)
|
|
125
|
+
except Exception:
|
|
126
|
+
log.debug("statusline: wrapped command failed", exc_info=True)
|
|
127
|
+
text = ""
|
|
128
|
+
try:
|
|
129
|
+
from ccr.hooks.common import parse_stdin
|
|
130
|
+
data = parse_stdin(raw)
|
|
131
|
+
if data is not None:
|
|
132
|
+
root, state = record(data, environ)
|
|
133
|
+
if not wrap and root is not None:
|
|
134
|
+
text = line(root, state)
|
|
135
|
+
except Exception:
|
|
136
|
+
log.debug("statusline: record/line failed", exc_info=True)
|
|
137
|
+
if text:
|
|
138
|
+
try:
|
|
139
|
+
out.write(text if text.endswith("\n") else text + "\n")
|
|
140
|
+
out.flush()
|
|
141
|
+
except Exception:
|
|
142
|
+
log.debug("statusline: write failed", exc_info=True)
|
|
143
|
+
return 0
|
ccr/transcript.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Token usage from Claude Code transcript JSONL files (stdlib only; safe for hooks).
|
|
2
|
+
|
|
3
|
+
Claude Code writes one line per content block of an assistant message, each repeating the
|
|
4
|
+
message's `usage`, so usage is counted once per `message.id` (last line wins). Reads can be
|
|
5
|
+
incremental: pass the byte offset returned by the previous call (only complete lines are
|
|
6
|
+
consumed). Message text is never returned.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
|
|
14
|
+
TOKEN_KEYS = ("input_tokens", "output_tokens", "cache_creation_input_tokens")
|
|
15
|
+
MAX_CHUNK = 64 * 1024 * 1024
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class Usage:
|
|
20
|
+
tokens: int = 0 # input + output + cache-creation tokens
|
|
21
|
+
cache_read: int = 0
|
|
22
|
+
messages: int = 0 # distinct assistant messages
|
|
23
|
+
tool_errors: int = 0 # tool results flagged is_error
|
|
24
|
+
model: str | None = None # model of the last assistant message
|
|
25
|
+
offset: int = 0 # byte offset after the last complete line read
|
|
26
|
+
models: dict[str, int] = field(default_factory=dict)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _int(v) -> int:
|
|
30
|
+
return v if isinstance(v, int) and not isinstance(v, bool) and v > 0 else 0
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _scan_line(raw: bytes, u: Usage):
|
|
34
|
+
"""Count tool errors on one transcript line into `u`. Returns (message id or None,
|
|
35
|
+
tokens, cache_read, model) for an assistant message with usage, else None."""
|
|
36
|
+
try:
|
|
37
|
+
obj = json.loads(raw)
|
|
38
|
+
except ValueError:
|
|
39
|
+
return None
|
|
40
|
+
msg = obj.get("message") if isinstance(obj, dict) else None
|
|
41
|
+
if not isinstance(msg, dict):
|
|
42
|
+
return None
|
|
43
|
+
content = msg.get("content")
|
|
44
|
+
if isinstance(content, list):
|
|
45
|
+
u.tool_errors += sum(1 for block in content
|
|
46
|
+
if isinstance(block, dict) and block.get("type") == "tool_result"
|
|
47
|
+
and block.get("is_error") is True)
|
|
48
|
+
usage = msg.get("usage")
|
|
49
|
+
if obj.get("type") != "assistant" or not isinstance(usage, dict):
|
|
50
|
+
return None
|
|
51
|
+
mid = msg.get("id")
|
|
52
|
+
model = msg.get("model") if isinstance(msg.get("model"), str) else None
|
|
53
|
+
return (mid if isinstance(mid, str) else None, sum(_int(usage.get(k)) for k in TOKEN_KEYS),
|
|
54
|
+
_int(usage.get("cache_read_input_tokens")), model)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def read_usage(path: str | os.PathLike, offset: int = 0, seen: set | None = None,
|
|
58
|
+
complete_only: bool = True) -> Usage:
|
|
59
|
+
"""Usage in `path` after byte `offset`. `seen` (message ids already counted by an earlier
|
|
60
|
+
incremental call) is updated in place so a message split across reads counts once.
|
|
61
|
+
With `complete_only` a trailing line without newline is left for the next call."""
|
|
62
|
+
u = Usage(offset=offset)
|
|
63
|
+
seen = set() if seen is None else seen
|
|
64
|
+
per_msg: dict[str, tuple[int, int, str | None]] = {}
|
|
65
|
+
try:
|
|
66
|
+
with open(path, "rb") as f:
|
|
67
|
+
f.seek(offset)
|
|
68
|
+
data = f.read(MAX_CHUNK)
|
|
69
|
+
except (OSError, TypeError, ValueError):
|
|
70
|
+
return u
|
|
71
|
+
end = data.rfind(b"\n") if complete_only else len(data) - 1
|
|
72
|
+
if end < 0:
|
|
73
|
+
return u
|
|
74
|
+
u.offset = offset + end + 1
|
|
75
|
+
anon = 0
|
|
76
|
+
for raw in data[: end + 1].splitlines():
|
|
77
|
+
if b'"usage"' not in raw and b'"is_error"' not in raw:
|
|
78
|
+
continue
|
|
79
|
+
entry = _scan_line(raw, u)
|
|
80
|
+
if entry is None:
|
|
81
|
+
continue
|
|
82
|
+
mid, tokens, cache_read, model = entry
|
|
83
|
+
if mid is None:
|
|
84
|
+
anon += 1
|
|
85
|
+
mid = f"_anon{offset}_{anon}"
|
|
86
|
+
per_msg[mid] = (tokens, cache_read, model)
|
|
87
|
+
if model and not model.startswith("<"):
|
|
88
|
+
u.model = model
|
|
89
|
+
for mid, (tokens, cache_read, model) in per_msg.items():
|
|
90
|
+
if mid in seen:
|
|
91
|
+
continue
|
|
92
|
+
seen.add(mid)
|
|
93
|
+
u.tokens += tokens
|
|
94
|
+
u.cache_read += cache_read
|
|
95
|
+
u.messages += 1
|
|
96
|
+
if model and not model.startswith("<"):
|
|
97
|
+
u.models[model] = u.models.get(model, 0) + 1
|
|
98
|
+
return u
|