readthrough 0.4.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.
Files changed (73) hide show
  1. readthrough/__init__.py +8 -0
  2. readthrough/__main__.py +3 -0
  3. readthrough/agents.py +344 -0
  4. readthrough/analyze.py +537 -0
  5. readthrough/assets/SKILL.md +86 -0
  6. readthrough/assets/defaults.toml +143 -0
  7. readthrough/assets/profile-reference.md +133 -0
  8. readthrough/assets/vendor/README.md +22 -0
  9. readthrough/assets/vendor/cose-base.js +3214 -0
  10. readthrough/assets/vendor/cytoscape-fcose.js +1549 -0
  11. readthrough/assets/vendor/cytoscape.min.js +31 -0
  12. readthrough/assets/vendor/layout-base.js +5230 -0
  13. readthrough/assets/vendor/licenses/cose-base-LICENSE +21 -0
  14. readthrough/assets/vendor/licenses/cytoscape-LICENSE +19 -0
  15. readthrough/assets/vendor/licenses/cytoscape-fcose-LICENSE +19 -0
  16. readthrough/assets/vendor/licenses/dompurify-LICENSE +202 -0
  17. readthrough/assets/vendor/licenses/layout-base-LICENSE +21 -0
  18. readthrough/assets/vendor/licenses/lucide-LICENSE +15 -0
  19. readthrough/assets/vendor/licenses/marked-LICENSE +44 -0
  20. readthrough/assets/vendor/lucide-icons.js +36 -0
  21. readthrough/assets/vendor/marked.umd.js +82 -0
  22. readthrough/assets/vendor/purify.min.js +7 -0
  23. readthrough/assets/web/dashboard.css +202 -0
  24. readthrough/assets/web/dashboard.html +48 -0
  25. readthrough/assets/web/dashboard.js +937 -0
  26. readthrough/assets/web/setup.css +57 -0
  27. readthrough/assets/web/setup.html +28 -0
  28. readthrough/assets/web/setup.js +342 -0
  29. readthrough/assets/web/theme.css +36 -0
  30. readthrough/assistants.py +699 -0
  31. readthrough/brief.py +145 -0
  32. readthrough/build.py +616 -0
  33. readthrough/ci.py +107 -0
  34. readthrough/cli.py +958 -0
  35. readthrough/config.py +533 -0
  36. readthrough/contract.py +394 -0
  37. readthrough/engine.py +230 -0
  38. readthrough/faults.py +92 -0
  39. readthrough/files.py +110 -0
  40. readthrough/forges/__init__.py +614 -0
  41. readthrough/forges/azure_devops.py +658 -0
  42. readthrough/forges/forgejo.py +300 -0
  43. readthrough/forges/github.py +487 -0
  44. readthrough/forges/gitlab.py +335 -0
  45. readthrough/ledger.py +61 -0
  46. readthrough/limits.py +26 -0
  47. readthrough/logs.py +169 -0
  48. readthrough/membership.py +76 -0
  49. readthrough/model.py +177 -0
  50. readthrough/onboard.py +551 -0
  51. readthrough/onboard_model.py +319 -0
  52. readthrough/process.py +169 -0
  53. readthrough/profile.py +699 -0
  54. readthrough/py.typed +0 -0
  55. readthrough/registry.py +157 -0
  56. readthrough/review.py +394 -0
  57. readthrough/rules.py +111 -0
  58. readthrough/runtimes/__init__.py +297 -0
  59. readthrough/runtimes/anthropic.py +278 -0
  60. readthrough/runtimes/copilot.py +313 -0
  61. readthrough/runtimes/openai.py +307 -0
  62. readthrough/serve.py +817 -0
  63. readthrough/study.py +327 -0
  64. readthrough/system.py +205 -0
  65. readthrough/terminals.py +168 -0
  66. readthrough/tuning.py +266 -0
  67. readthrough/usage.py +169 -0
  68. readthrough/web_setup.py +635 -0
  69. readthrough-0.4.0.dist-info/METADATA +123 -0
  70. readthrough-0.4.0.dist-info/RECORD +73 -0
  71. readthrough-0.4.0.dist-info/WHEEL +4 -0
  72. readthrough-0.4.0.dist-info/entry_points.txt +2 -0
  73. readthrough-0.4.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,168 @@
1
+ """Terminal launchers: how a deep-review session gets its own window.
2
+
3
+ Each launcher turns a command (argv, working directory, title) into a ``Spawn``: the process to start and
4
+ how. ``terminal = "auto"`` in ``config.toml`` tries the platform's launchers in order and uses the first
5
+ one that is installed; naming one (``terminal = "wt"``) uses it even when something else is available.
6
+ Options go in ``[terminals.<name>]`` and are validated against the launcher's options dataclass.
7
+
8
+ Only the Windows launchers are exercised on the author's machine. The macOS and Linux ones are the
9
+ invocations those terminals document; if one misbehaves, ``readthrough review N --here`` runs the
10
+ session in the current terminal instead.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import shlex
16
+ import shutil
17
+ import subprocess
18
+ import sys
19
+ from collections.abc import Callable, Mapping
20
+ from dataclasses import dataclass, field
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ from readthrough.registry import NoOptions, Registry, RegistryError
25
+
26
+ AUTO = "auto"
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Command:
31
+ """What to run: the program and its arguments, where, and a window title."""
32
+
33
+ argv: list[str]
34
+ cwd: Path
35
+ title: str
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class Spawn:
40
+ """What to start to get that command into a new window."""
41
+
42
+ argv: list[str]
43
+ cwd: Path | None = None
44
+ creationflags: int = 0
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class Launcher:
49
+ """``program`` must be on PATH for the launcher to count as available; None means nothing extra is needed.
50
+
51
+ ``spawn`` gets the program's path, the command, and the launcher's validated options object.
52
+ """
53
+
54
+ program: str | None
55
+ spawn: Callable[[str, Command, Any], Spawn]
56
+ platforms: tuple[str, ...]
57
+
58
+ def path(self) -> str | None:
59
+ return "" if self.program is None else shutil.which(self.program)
60
+
61
+ def available(self) -> bool:
62
+ return sys.platform in self.platforms and self.path() is not None
63
+
64
+
65
+ TERMINALS: Registry[Launcher] = Registry("terminal")
66
+
67
+ # Tried in this order by "auto", filtered to the current platform.
68
+ AUTO_ORDER = ("wt", "console", "terminal-app", "x-terminal-emulator", "gnome-terminal")
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class WindowsTerminalOptions:
73
+ profile: str = "" # a Windows Terminal profile name; empty means the default profile
74
+ window: str = "new" # "new" opens a window; "0" (or another id) adds a tab to that window
75
+ extra_args: list[str] = field(default_factory=list) # passed to `wt new-tab` as they are
76
+
77
+
78
+ def _wt(path: str, command: Command, options: WindowsTerminalOptions) -> Spawn:
79
+ tab = ["new-tab", "--title", command.title, "-d", str(command.cwd)]
80
+ if options.profile:
81
+ tab += ["-p", options.profile]
82
+ tab += options.extra_args
83
+ # Windows Terminal treats a bare `;` as a command separator.
84
+ return Spawn([path, "-w", options.window, *tab, *(a.replace(";", r"\;") for a in command.argv)])
85
+
86
+
87
+ TERMINALS.add("wt", "Windows Terminal, a new window or tab", options=WindowsTerminalOptions)(
88
+ Launcher("wt", _wt, ("win32",))
89
+ )
90
+
91
+
92
+ def _console(path: str, command: Command, options: NoOptions) -> Spawn:
93
+ return Spawn(command.argv, cwd=command.cwd, creationflags=getattr(subprocess, "CREATE_NEW_CONSOLE", 0))
94
+
95
+
96
+ TERMINALS.add("console", "a plain Windows console window")(Launcher(None, _console, ("win32",)))
97
+
98
+
99
+ def _applescript_str(text: str) -> str:
100
+ return '"' + text.replace("\\", "\\\\").replace('"', '\\"') + '"'
101
+
102
+
103
+ def _terminal_app(path: str, command: Command, options: NoOptions) -> Spawn:
104
+ script = f"cd {shlex.quote(str(command.cwd))} && {shlex.join(command.argv)}"
105
+ applescript = f'tell application "Terminal" to do script {_applescript_str(script)}'
106
+ return Spawn([path, "-e", applescript, "-e", 'tell application "Terminal" to activate'])
107
+
108
+
109
+ TERMINALS.add("terminal-app", "macOS Terminal.app, through osascript")(
110
+ Launcher("osascript", _terminal_app, ("darwin",))
111
+ )
112
+
113
+
114
+ def _dash_dash(path: str, command: Command, options: NoOptions) -> Spawn:
115
+ return Spawn([path, "--", *command.argv], cwd=command.cwd)
116
+
117
+
118
+ def _dash_e(path: str, command: Command, options: NoOptions) -> Spawn:
119
+ return Spawn([path, "-e", shlex.join(command.argv)], cwd=command.cwd)
120
+
121
+
122
+ TERMINALS.add("x-terminal-emulator", "the Debian/Ubuntu default terminal (update-alternatives)")(
123
+ Launcher("x-terminal-emulator", _dash_e, ("linux",))
124
+ )
125
+ TERMINALS.add("gnome-terminal", "GNOME Terminal")(Launcher("gnome-terminal", _dash_dash, ("linux",)))
126
+
127
+
128
+ def choose(name: str = AUTO) -> tuple[str, Launcher]:
129
+ """The launcher to use: the named one, or the first available one for this platform."""
130
+ if name != AUTO:
131
+ launcher = TERMINALS.get(name).impl
132
+ if sys.platform not in launcher.platforms:
133
+ raise RegistryError(f"terminal {name!r} is for {', '.join(launcher.platforms)}, not {sys.platform}")
134
+ if launcher.path() is None:
135
+ raise RegistryError(f"terminal {name!r} needs `{launcher.program}` on PATH")
136
+ return name, launcher
137
+ for candidate in AUTO_ORDER:
138
+ launcher = TERMINALS.get(candidate).impl
139
+ if launcher.available():
140
+ return candidate, launcher
141
+ raise RegistryError("No terminal emulator found. Run `readthrough review N --here` instead.")
142
+
143
+
144
+ def launch(command: Command, *, terminal: str = AUTO, options: Mapping[str, object] | None = None) -> str:
145
+ """Open ``command`` in a new terminal window. Returns the launcher's name.
146
+
147
+ ``options`` maps launcher names to their validated options objects (``Settings.terminal_options``).
148
+ """
149
+ name, launcher = choose(terminal)
150
+ spawn = plan(name, launcher, command, options)
151
+ subprocess.Popen(spawn.argv, cwd=spawn.cwd, creationflags=spawn.creationflags)
152
+ return name
153
+
154
+
155
+ def plan(name: str, launcher: Launcher, command: Command, options: Mapping[str, object] | None = None) -> Spawn:
156
+ """The process a launcher would start. Separate from ``launch`` so tests can check it without spawning."""
157
+ opts = (options or {}).get(name) or TERMINALS.defaults_for(name)
158
+ return launcher.spawn(launcher.path() or "", command, opts)
159
+
160
+
161
+ def describe(terminal: str = AUTO) -> str:
162
+ """For `doctor`: which launcher would be used, or why none can be."""
163
+ try:
164
+ name, launcher = choose(terminal)
165
+ except RegistryError as exc:
166
+ return str(exc)
167
+ where = launcher.path() or "built in"
168
+ return f"{name} ({where})" + (", chosen automatically" if terminal == AUTO else "")
readthrough/tuning.py ADDED
@@ -0,0 +1,266 @@
1
+ """Tunable settings: typed, range-checked, documented in one place.
2
+
3
+ The defaults and their explanations live in ``assets/defaults.toml``, the single source of truth. Your
4
+ ``config.toml`` overrides them under ``[tuning.<section>]``, and some sections can be overridden per repo.
5
+ The dataclasses here only declare each setting's type and allowed range; a test checks they match the file.
6
+
7
+ Values that define file formats or protocols (CI state names, ledger statuses, the URL scheme, schema
8
+ versions) and security limits (see ``limits.py``) are deliberately not tunable.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import difflib
14
+ import tomllib
15
+ from dataclasses import dataclass, field, fields, replace
16
+ from functools import cache
17
+ from importlib.resources import files
18
+ from typing import TYPE_CHECKING, Any, get_type_hints
19
+
20
+ if TYPE_CHECKING:
21
+ from _typeshed import DataclassInstance
22
+
23
+
24
+ def _r(low: float | None = None, high: float | None = None) -> Any:
25
+ """Declare a field's allowed range."""
26
+ return field(metadata={"range": (low, high)})
27
+
28
+
29
+ def _choice(*options: str) -> Any:
30
+ return field(metadata={"choices": options})
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class ForgeTuning:
35
+ timeout_seconds: float = _r(5, 3600)
36
+ retries: int = _r(0, 10)
37
+ retry_backoff_seconds: float = _r(0, 300)
38
+ retry_max_backoff_seconds: float = _r(0, 3600)
39
+ rate_limit_wait_seconds: float = _r(1, 3600)
40
+ concurrency: int = _r(1, 32)
41
+ pr_page_size: int = _r(1, 100)
42
+ max_files_per_pr: int = _r(100, 3000)
43
+ max_checks_per_pr: int = _r(100, 5000)
44
+ max_review_threads_per_pr: int = _r(100, 5000)
45
+ max_tree_files: int = _r(1000, 1_000_000)
46
+ max_assembled_diff_files: int = _r(1, 3000)
47
+ diff_cache_days: float = _r(0, 3650)
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class GitTuning:
52
+ timeout_seconds: float = _r(10, 7200)
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class ServerTuning:
57
+ watch_seconds: float = _r(0.5, 300)
58
+ keepalive_seconds: float = _r(1, 300)
59
+ start_stagger_seconds: float = _r(0, 3600)
60
+ refresh_jitter: float = _r(0, 0.5)
61
+ retry_after_failure_minutes: list[float] = _r(0.1, 1440) # noqa: RUF009 - _r declares bounds, not a default
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class PlanningTuning:
66
+ estimate_base_minutes: float = _r(0, 120)
67
+ estimate_minutes_per_source_line: float = _r(0, 10)
68
+ estimate_minutes_per_test_line: float = _r(0, 10)
69
+ estimate_minutes_per_other_line: float = _r(0, 10)
70
+ estimate_minutes_per_extra_layer: float = _r(0, 120)
71
+ estimate_max_minutes: int = _r(5, 1440)
72
+ priority_base: float = _r(-1000, 1000)
73
+ priority_age_cap_days: float = _r(0, 3650)
74
+ priority_review_requested: float = _r(-1000, 1000)
75
+ priority_re_review: float = _r(-1000, 1000)
76
+ priority_quick_minutes: int = _r(0, 1440)
77
+ priority_quick_bonus: float = _r(-1000, 1000)
78
+ priority_short_minutes: int = _r(0, 1440)
79
+ priority_short_bonus: float = _r(-1000, 1000)
80
+ priority_closes_issue: float = _r(-1000, 1000)
81
+ priority_approved: float = _r(-1000, 1000)
82
+ priority_ci_passing: float = _r(-1000, 1000)
83
+ priority_ci_failing_on_main: float = _r(-1000, 1000)
84
+ priority_ci_failing_optional: float = _r(-1000, 1000)
85
+ priority_ci_not_run: float = _r(-1000, 1000)
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class OnboardingTuning:
90
+ min_coverage: float = _r(0, 1)
91
+ drift_coverage: float = _r(0, 1)
92
+ merged_sample: int = _r(10, 100)
93
+ facts_cache_minutes: float = _r(0, 1440)
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class FreshnessTuning:
98
+ stale_live_hours: float = _r(0.1, 720)
99
+ stale_snapshot_hours: float = _r(0.1, 720)
100
+ doctor_build_hours: float = _r(0.1, 720)
101
+
102
+
103
+ @dataclass(frozen=True)
104
+ class PayloadTuning:
105
+ description_chars: int = _r(100, 1_000_000)
106
+ description_html_chars: int = _r(100, 2_000_000)
107
+ thread_comment_chars: int = _r(50, 100_000)
108
+ thread_comment_html_chars: int = _r(50, 200_000)
109
+ line_heuristic_code_chars: int = _r(20, 2000)
110
+
111
+
112
+ @dataclass(frozen=True)
113
+ class StudyTuning:
114
+ turn_timeout_seconds: float = _r(30, 7200)
115
+ max_tool_output_chars: int = _r(1000, 1_000_000)
116
+ onboarding_turn_timeout_seconds: float = _r(30, 7200)
117
+ onboarding_tool_output_chars: int = _r(1000, 1_000_000)
118
+ onboarding_doc_excerpt_chars: int = _r(500, 200_000)
119
+
120
+
121
+ @dataclass(frozen=True)
122
+ class SessionsTuning:
123
+ scan_seconds: float = _r(0.5, 3600)
124
+ first_message_bytes: int = _r(4096, 50_000_000)
125
+
126
+
127
+ @dataclass(frozen=True)
128
+ class AuthorsTuning:
129
+ membership_cache_days: float = _r(0, 365)
130
+
131
+
132
+ @dataclass(frozen=True)
133
+ class LoggingTuning:
134
+ level: str = _choice("debug", "info", "warning", "error")
135
+ format: str = _choice("text", "json")
136
+ file_max_kb: int = _r(16, 1_000_000)
137
+ file_backups: int = _r(0, 100)
138
+
139
+
140
+ @dataclass(frozen=True)
141
+ class Tuning:
142
+ forge: ForgeTuning
143
+ git: GitTuning
144
+ server: ServerTuning
145
+ planning: PlanningTuning
146
+ onboarding: OnboardingTuning
147
+ freshness: FreshnessTuning
148
+ payload: PayloadTuning
149
+ study: StudyTuning
150
+ sessions: SessionsTuning
151
+ authors: AuthorsTuning
152
+ logging: LoggingTuning
153
+
154
+
155
+ # Sections that make sense per repo. The rest apply to the whole process (the server, logging, GitHub limits).
156
+ REPO_SECTIONS = ("planning", "onboarding", "freshness", "payload", "study", "authors")
157
+
158
+
159
+ class TuningError(ValueError):
160
+ pass
161
+
162
+
163
+ @cache
164
+ def defaults_text() -> str:
165
+ return files("readthrough").joinpath("assets/defaults.toml").read_text(encoding="utf-8")
166
+
167
+
168
+ @cache
169
+ def _defaults_raw() -> dict[str, dict[str, Any]]:
170
+ return tomllib.loads(defaults_text())
171
+
172
+
173
+ def _section_types() -> dict[str, type[DataclassInstance]]:
174
+ return {f.name: get_type_hints(Tuning)[f.name] for f in fields(Tuning)}
175
+
176
+
177
+ def _suggest(name: str, options: Any) -> str:
178
+ close = difflib.get_close_matches(name, list(options), n=1)
179
+ return f" (did you mean {close[0]!r}?)" if close else ""
180
+
181
+
182
+ def _coerce(where: str, f: Any, hint: Any, value: Any) -> Any:
183
+ low, high = f.metadata.get("range", (None, None))
184
+ choices = f.metadata.get("choices")
185
+ origin = getattr(hint, "__origin__", None)
186
+ if origin is list:
187
+ if not isinstance(value, list) or not value:
188
+ raise TuningError(f"{where} must be a non-empty list of numbers")
189
+ return [_coerce(f"{where}[{i}]", f, float, v) for i, v in enumerate(value)]
190
+ if hint is bool or isinstance(value, bool):
191
+ raise TuningError(f"{where} must be a number, not {value!r}")
192
+ if hint is int:
193
+ if not isinstance(value, int):
194
+ raise TuningError(f"{where} must be a whole number, not {value!r}")
195
+ elif hint is float:
196
+ if not isinstance(value, int | float):
197
+ raise TuningError(f"{where} must be a number, not {value!r}")
198
+ value = float(value)
199
+ elif hint is str:
200
+ if not isinstance(value, str):
201
+ raise TuningError(f"{where} must be text, not {value!r}")
202
+ value = value.lower()
203
+ if choices and value not in choices:
204
+ raise TuningError(f"{where} must be one of {', '.join(choices)}, not {value!r}")
205
+ return value
206
+ if (low is not None and value < low) or (high is not None and value > high):
207
+ raise TuningError(f"{where} must be between {low:g} and {high:g}, not {value!r}")
208
+ return value
209
+
210
+
211
+ def _build_section(cls: type[DataclassInstance], raw: dict[str, Any], where: str) -> Any:
212
+ hints = get_type_hints(cls)
213
+ known = {f.name: f for f in fields(cls)}
214
+ for key in raw:
215
+ if key not in known:
216
+ raise TuningError(f"Unknown setting {where}.{key}{_suggest(key, known)}")
217
+ return cls(**{k: _coerce(f"{where}.{k}", f, hints[k], raw[k]) for k, f in known.items()})
218
+
219
+
220
+ def _check_overrides(raw: Any, where: str, allowed: tuple[str, ...]) -> dict[str, dict[str, Any]]:
221
+ if raw is None:
222
+ return {}
223
+ if not isinstance(raw, dict):
224
+ raise TuningError(f"{where} must be a table")
225
+ for section, values in raw.items():
226
+ if section not in allowed:
227
+ hint = _suggest(section, allowed)
228
+ extra = "" if section not in _section_types() else " (that section can't be set per repo)"
229
+ raise TuningError(f"Unknown section {where}.{section}{hint}{extra}")
230
+ if not isinstance(values, dict):
231
+ raise TuningError(f"{where}.{section} must be a table")
232
+ return raw
233
+
234
+
235
+ def load_tuning(overrides: Any = None, *, repo_overrides: Any = None, where: str = "tuning") -> Tuning:
236
+ """Defaults, then the global ``[tuning]`` table, then a repo's own ``tuning`` table."""
237
+ sections = _section_types()
238
+ glob = _check_overrides(overrides, where, tuple(sections))
239
+ per_repo = _check_overrides(repo_overrides, f"{where} (repo)", REPO_SECTIONS)
240
+ built = {}
241
+ for name, cls in sections.items():
242
+ raw = {**_defaults_raw()[name], **glob.get(name, {}), **per_repo.get(name, {})}
243
+ built[name] = _build_section(cls, raw, f"{where}.{name}")
244
+ return Tuning(**built)
245
+
246
+
247
+ @cache
248
+ def default_tuning() -> Tuning:
249
+ return load_tuning()
250
+
251
+
252
+ def with_section(tuning: Tuning, **sections: Any) -> Tuning:
253
+ """A copy with whole sections replaced (for tests)."""
254
+ return replace(tuning, **sections)
255
+
256
+
257
+ def changed_from_defaults(tuning: Tuning) -> dict[str, dict[str, Any]]:
258
+ """Settings that differ from the defaults, for `readthrough config`."""
259
+ base = default_tuning()
260
+ out: dict[str, dict[str, Any]] = {}
261
+ for f in fields(Tuning):
262
+ mine, theirs = getattr(tuning, f.name), getattr(base, f.name)
263
+ diff = {g.name: getattr(mine, g.name) for g in fields(mine) if getattr(mine, g.name) != getattr(theirs, g.name)}
264
+ if diff:
265
+ out[f.name] = diff
266
+ return out
readthrough/usage.py ADDED
@@ -0,0 +1,169 @@
1
+ """The usage ledger: what each model call cost, in the units the provider actually reports.
2
+
3
+ Every call a study assistant or the onboarding drafter makes to a model is appended here, one line per
4
+ call, keyed by the provider's call id so a replayed event never counts twice. The units are kept apart
5
+ and never converted into each other: tokens are tokens; ``multiplier`` is Copilot's premium-request
6
+ multiplier (not money); ``nano_aiu`` is Copilot's AI-credit consumption, which says nothing about whether
7
+ the call fell inside a plan's allowance; ``usd`` appears only when a price table priced it, and names the
8
+ table. A quantity the provider didn't report is absent, never zero.
9
+
10
+ ``billed_to`` says whose account the call went to: ``copilot:<login>`` for GitHub Copilot through a
11
+ sign-in, ``copilot:org/<org>`` when an organization is billed, or ``<provider>:<host>`` for a model
12
+ provider of your own. ``purpose`` is what the call was for (``study``, ``draft``) and ``ref`` what it was
13
+ about (a PR number, or ``onboarding``). The study log doesn't repeat any of this; its entries name the
14
+ ledger ids they came from.
15
+
16
+ The ledger lives in the repo's data directory (``usage.jsonl``), next to the study logs.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import datetime as dt
22
+ import json
23
+ import threading
24
+ from collections import Counter
25
+ from pathlib import Path
26
+ from typing import Any
27
+
28
+ from readthrough.config import Config
29
+
30
+ PURPOSES = ("study", "draft", "review")
31
+ _lock = threading.Lock()
32
+
33
+
34
+ def ledger_path(cfg: Config) -> Path:
35
+ return cfg.repo_dir / "usage.jsonl"
36
+
37
+
38
+ def load(cfg: Config) -> list[dict[str, Any]]:
39
+ path = ledger_path(cfg)
40
+ if not path.exists():
41
+ return []
42
+ entries = []
43
+ for line in path.read_text(encoding="utf-8").splitlines():
44
+ if line.strip():
45
+ try:
46
+ entries.append(json.loads(line))
47
+ except ValueError:
48
+ continue # a torn final line from a crash
49
+ return entries
50
+
51
+
52
+ def record(
53
+ cfg: Config,
54
+ *,
55
+ call_id: str,
56
+ purpose: str,
57
+ ref: str,
58
+ model: str,
59
+ billed_to: str,
60
+ by: str,
61
+ tokens: dict[str, int] | None = None,
62
+ multiplier: float | None = None,
63
+ nano_aiu: float | None = None,
64
+ usd: float | None = None,
65
+ price_table: str | None = None,
66
+ via: str = "local",
67
+ ) -> dict[str, Any] | None:
68
+ """Append one model call. Returns the entry, or None when ``call_id`` was already recorded."""
69
+ if purpose not in PURPOSES:
70
+ raise ValueError(f"purpose must be one of {', '.join(PURPOSES)}")
71
+ if usd is not None and not price_table:
72
+ raise ValueError("a dollar amount must name the price table that produced it")
73
+ entry: dict[str, Any] = {
74
+ "id": call_id,
75
+ "ts": dt.datetime.now(dt.UTC).isoformat(timespec="seconds"),
76
+ "purpose": purpose,
77
+ "ref": ref,
78
+ "model": model,
79
+ "billed_to": billed_to,
80
+ "by": by,
81
+ "via": via,
82
+ }
83
+ if tokens:
84
+ entry["tokens"] = {k: int(v) for k, v in tokens.items() if v is not None}
85
+ measured = {"multiplier": multiplier, "nano_aiu": nano_aiu, "usd": usd, "price_table": price_table}
86
+ entry.update({k: v for k, v in measured.items() if v is not None})
87
+ with _lock:
88
+ if any(e.get("id") == call_id for e in load(cfg)):
89
+ return None
90
+ path = ledger_path(cfg)
91
+ path.parent.mkdir(parents=True, exist_ok=True)
92
+ with path.open("a", encoding="utf-8") as handle:
93
+ handle.write(json.dumps(entry) + "\n")
94
+ return entry
95
+
96
+
97
+ def from_sdk_usage(data: Any) -> dict[str, Any]:
98
+ """The ledger fields an ``assistant.usage`` event from the Copilot SDK carries, in the ledger's names.
99
+
100
+ Only what the event reports: a BYOK call has no ``nano_aiu`` and a Copilot call no dollar price, and
101
+ the SDK's ``cost`` is the premium-request multiplier, recorded as such.
102
+ """
103
+ tokens = {
104
+ name: getattr(data, attr, None)
105
+ for name, attr in (
106
+ ("input", "input_tokens"),
107
+ ("output", "output_tokens"),
108
+ ("cache_read", "cache_read_tokens"),
109
+ ("cache_write", "cache_write_tokens"),
110
+ ("reasoning", "reasoning_tokens"),
111
+ )
112
+ }
113
+ copilot_usage = getattr(data, "copilot_usage", None)
114
+ byok = bool(getattr(data, "is_byok", False))
115
+ return {
116
+ "call_id": getattr(data, "api_call_id", None) or getattr(data, "provider_call_id", None),
117
+ "model": getattr(data, "model", None) or "?",
118
+ "tokens": {k: v for k, v in tokens.items() if v is not None},
119
+ # The premium-request multiplier is Copilot's unit; a provider of your own has none, and the runtime
120
+ # sends 0 for it, which would read as "free".
121
+ "multiplier": None if byok else getattr(data, "cost", None),
122
+ "nano_aiu": getattr(copilot_usage, "total_nano_aiu", None) if copilot_usage is not None else None,
123
+ "is_byok": byok,
124
+ }
125
+
126
+
127
+ def summarize(entries: list[dict[str, Any]], *, since: dt.datetime | None = None) -> dict[str, Any]:
128
+ """Totals per purpose and per payer, in each unit separately. Calls that reported no tokens are counted
129
+ but add nothing; the summary says how many such calls there were, so a low total isn't read as cheap."""
130
+ picked = [e for e in entries if since is None or dt.datetime.fromisoformat(e["ts"]) >= since]
131
+ tokens: Counter[str] = Counter()
132
+ nano_aiu = 0.0
133
+ usd = 0.0
134
+ priced = unpriced = 0
135
+ for e in picked:
136
+ for k, v in (e.get("tokens") or {}).items():
137
+ tokens[k] += v
138
+ if "nano_aiu" in e:
139
+ nano_aiu += e["nano_aiu"]
140
+ if "usd" in e:
141
+ usd += e["usd"]
142
+ priced += 1
143
+ elif "nano_aiu" not in e:
144
+ unpriced += 1
145
+ return {
146
+ "calls": len(picked),
147
+ "tokens": dict(tokens),
148
+ "nano_aiu": nano_aiu if any("nano_aiu" in e for e in picked) else None,
149
+ "usd": usd if priced else None,
150
+ "unpriced_calls": unpriced,
151
+ "by_purpose": dict(Counter(e["purpose"] for e in picked)),
152
+ "by_payer": dict(Counter(e["billed_to"] for e in picked)),
153
+ "by_model": dict(Counter(e["model"] for e in picked)),
154
+ }
155
+
156
+
157
+ def describe(summary: dict[str, Any]) -> str:
158
+ """One line for `doctor` and the brief, honest about what wasn't measured."""
159
+ if not summary["calls"]:
160
+ return "no model calls recorded"
161
+ t = summary["tokens"]
162
+ parts = [f"{summary['calls']} model calls", f"{t.get('input', 0) + t.get('output', 0):,} tokens"]
163
+ if summary["nano_aiu"] is not None:
164
+ parts.append(f"{summary['nano_aiu'] / 1e9:.2f} AIU")
165
+ if summary["usd"] is not None:
166
+ parts.append(f"${summary['usd']:.2f}")
167
+ if summary["unpriced_calls"]:
168
+ parts.append(f"{summary['unpriced_calls']} calls with no price reported")
169
+ return ", ".join(parts)