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.
- codebaton/__init__.py +8 -0
- codebaton/cli.py +918 -0
- codebaton/config.py +316 -0
- codebaton/core/__init__.py +0 -0
- codebaton/core/audit.py +42 -0
- codebaton/core/budget.py +117 -0
- codebaton/core/handoff.py +251 -0
- codebaton/core/model_routing.py +205 -0
- codebaton/core/policy.py +98 -0
- codebaton/core/router.py +279 -0
- codebaton/core/usage_cache.py +102 -0
- codebaton/discovery.py +79 -0
- codebaton/hooks.py +275 -0
- codebaton/launcher.py +236 -0
- codebaton/local_models.py +476 -0
- codebaton/mcp/__init__.py +0 -0
- codebaton/mcp/server.py +14 -0
- codebaton/monitor.py +137 -0
- codebaton/plugins/__init__.py +0 -0
- codebaton/plugins/base.py +112 -0
- codebaton/plugins/executors/__init__.py +0 -0
- codebaton/plugins/executors/local.py +99 -0
- codebaton/plugins/providers/__init__.py +0 -0
- codebaton/plugins/providers/_common.py +29 -0
- codebaton/plugins/providers/claude_code.py +135 -0
- codebaton/plugins/providers/codex.py +101 -0
- codebaton/plugins/registry.py +77 -0
- codebaton/plugins/usage/__init__.py +0 -0
- codebaton/plugins/usage/cached.py +52 -0
- codebaton/plugins/usage/codex_logs.py +120 -0
- codebaton/plugins/usage/manual.py +49 -0
- codebaton/py.typed +0 -0
- codebaton/report.py +130 -0
- codebaton-0.1.0.dist-info/METADATA +305 -0
- codebaton-0.1.0.dist-info/RECORD +38 -0
- codebaton-0.1.0.dist-info/WHEEL +4 -0
- codebaton-0.1.0.dist-info/entry_points.txt +3 -0
- codebaton-0.1.0.dist-info/licenses/LICENSE +21 -0
codebaton/cli.py
ADDED
|
@@ -0,0 +1,918 @@
|
|
|
1
|
+
"""codebaton CLI: start (default: open an agent with routing), init, run, status."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
import time
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Annotated
|
|
10
|
+
|
|
11
|
+
import typer
|
|
12
|
+
import yaml
|
|
13
|
+
|
|
14
|
+
from codebaton import monitor, report
|
|
15
|
+
from codebaton.config import (
|
|
16
|
+
MODEL_ROUTING_FILE,
|
|
17
|
+
ROUTER_FILE,
|
|
18
|
+
STATE_DIR,
|
|
19
|
+
TIER_ORDER,
|
|
20
|
+
ConfigError,
|
|
21
|
+
RouterConfig,
|
|
22
|
+
apply_org_policy,
|
|
23
|
+
default_model_routing,
|
|
24
|
+
load_model_routing,
|
|
25
|
+
load_org_policy,
|
|
26
|
+
load_router_config,
|
|
27
|
+
)
|
|
28
|
+
from codebaton.core.audit import AuditLog
|
|
29
|
+
from codebaton.core.budget import BudgetManager, ProviderUsage
|
|
30
|
+
from codebaton.core.handoff import HandoffStore
|
|
31
|
+
from codebaton.core.model_routing import HaikuClassifier, native_model
|
|
32
|
+
from codebaton.core.policy import terminal_confirm
|
|
33
|
+
from codebaton.core.router import Orchestrator, select_provider
|
|
34
|
+
from codebaton.core.usage_cache import UsageCache
|
|
35
|
+
from codebaton.discovery import codex_tiers, discover_codex_models
|
|
36
|
+
from codebaton.hooks import SessionState, save_session
|
|
37
|
+
from codebaton.launcher import (
|
|
38
|
+
MenuOption,
|
|
39
|
+
build_menu,
|
|
40
|
+
detect_ollama,
|
|
41
|
+
launch_argv,
|
|
42
|
+
next_agent,
|
|
43
|
+
session_prompt,
|
|
44
|
+
)
|
|
45
|
+
from codebaton.local_models import (
|
|
46
|
+
RECOMMENDED_MODEL,
|
|
47
|
+
Assessment,
|
|
48
|
+
ModelEstimate,
|
|
49
|
+
agent_variant_name,
|
|
50
|
+
assess,
|
|
51
|
+
choices,
|
|
52
|
+
free_memory_gb,
|
|
53
|
+
load_estimate,
|
|
54
|
+
modelfile,
|
|
55
|
+
ollama_running,
|
|
56
|
+
registry_estimate,
|
|
57
|
+
rough_estimate,
|
|
58
|
+
save_estimate,
|
|
59
|
+
set_router_model,
|
|
60
|
+
start_ollama_server,
|
|
61
|
+
stop_ollama_server,
|
|
62
|
+
total_memory_gb,
|
|
63
|
+
)
|
|
64
|
+
from codebaton.plugins.base import RunContext, Task
|
|
65
|
+
from codebaton.plugins.registry import (
|
|
66
|
+
PluginError,
|
|
67
|
+
make_adapter,
|
|
68
|
+
make_executor,
|
|
69
|
+
make_usage_reader,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
HELP = """Use Claude Code, Codex and Ollama as one tool: codebaton opens the real CLI
|
|
73
|
+
and switches agent when one reaches its usage threshold.
|
|
74
|
+
|
|
75
|
+
Everyday use (run inside your project folder):
|
|
76
|
+
|
|
77
|
+
codebaton show usage, then open the recommended agent
|
|
78
|
+
codebaton use claude open Claude Code directly (also: codex, ollama)
|
|
79
|
+
codebaton status usage of each agent vs its threshold
|
|
80
|
+
codebaton watch live usage with reset countdowns (Ctrl+C to stop)
|
|
81
|
+
codebaton report sessions, hours and hand-overs per agent (--json, --csv)
|
|
82
|
+
|
|
83
|
+
\b
|
|
84
|
+
First time in a project? codebaton offers to set it up (same as `init`).
|
|
85
|
+
Unattended one-off task (scripts, overnight)? codebaton run "<task>"
|
|
86
|
+
Settings live in router.yaml. Details: codebaton COMMAND --help"""
|
|
87
|
+
|
|
88
|
+
app = typer.Typer(
|
|
89
|
+
add_completion=False,
|
|
90
|
+
help=HELP,
|
|
91
|
+
rich_markup_mode=None,
|
|
92
|
+
context_settings={"help_option_names": ["-h", "--help"]},
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
AGENT_ALIASES = {
|
|
96
|
+
"claude": "claude_code",
|
|
97
|
+
"claude_code": "claude_code",
|
|
98
|
+
"codex": "codex",
|
|
99
|
+
"ollama": "ollama",
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
ROUTER_TEMPLATE = """\
|
|
103
|
+
# codebaton config. Never put secrets here: keys come from env vars or the OS keychain.
|
|
104
|
+
providers: # preference order: first provider under its cap wins
|
|
105
|
+
- name: claude_code
|
|
106
|
+
cap_percent: 50 # over 50% used (as /usage shows it) -> switch to Codex
|
|
107
|
+
- name: codex
|
|
108
|
+
cap_percent: 50
|
|
109
|
+
profile: per_session # overnight | per_session | strict
|
|
110
|
+
executor: local
|
|
111
|
+
# Extra permissions for unattended `codebaton run` (and Codex web search). Off by
|
|
112
|
+
# default; set to true if you trust the agents in this repo. `strict` ignores them.
|
|
113
|
+
allow_web: false # agents may browse / search the web
|
|
114
|
+
allow_push: false # agents may run `git push`
|
|
115
|
+
allow_all_commands: false # agents may run any shell command (npm, python, ...)
|
|
116
|
+
warn_margin_percent: 5 # this close to a threshold, the agent is asked for a full handoff
|
|
117
|
+
git_checkpoint: true # commit a checkpoint after every agent reply
|
|
118
|
+
ollama: # local model, shown in the agent menu; runs through Codex's agent
|
|
119
|
+
enabled: true
|
|
120
|
+
# model: llama3.2:1b # set by `codebaton install-model`; default: first installed
|
|
121
|
+
# gates: ["uv run pytest -q"] # optional checks after each task; failure retries one tier up
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
GITIGNORE_LINES = [ROUTER_FILE, f"{STATE_DIR}/", ".env"]
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _git_root(path: Path) -> Path | None:
|
|
128
|
+
"""Top folder of the git repository containing ``path``, or None outside git."""
|
|
129
|
+
try:
|
|
130
|
+
out = subprocess.run(
|
|
131
|
+
["git", "rev-parse", "--show-toplevel"],
|
|
132
|
+
cwd=path,
|
|
133
|
+
capture_output=True,
|
|
134
|
+
text=True,
|
|
135
|
+
check=False,
|
|
136
|
+
)
|
|
137
|
+
except OSError: # git not installed
|
|
138
|
+
return None
|
|
139
|
+
return Path(out.stdout.strip()).resolve() if out.returncode == 0 else None
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _repo(repo: Path | None) -> Path:
|
|
143
|
+
"""--repo if given; otherwise the git repo around the current folder (or the folder)."""
|
|
144
|
+
if repo is not None:
|
|
145
|
+
return repo.resolve()
|
|
146
|
+
cwd = Path.cwd().resolve()
|
|
147
|
+
return _git_root(cwd) or cwd
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _ensure_setup(repo: Path) -> None:
|
|
151
|
+
"""First use in a folder: offer to create router.yaml and the shared notes."""
|
|
152
|
+
if (repo / ROUTER_FILE).exists():
|
|
153
|
+
return
|
|
154
|
+
typer.echo(f"{repo} is not set up for codebaton yet.")
|
|
155
|
+
if _git_root(repo) is None:
|
|
156
|
+
typer.secho(
|
|
157
|
+
"Warning: this folder is not a git repository. codebaton saves progress as git\n"
|
|
158
|
+
"commits, so there would be no checkpoints, and its setup files would be created\n"
|
|
159
|
+
"right here. Usually you want to `cd` into a project first (or run `git init`).",
|
|
160
|
+
fg=typer.colors.YELLOW,
|
|
161
|
+
)
|
|
162
|
+
if not typer.confirm("Set up this folder anyway?", default=False):
|
|
163
|
+
raise typer.Exit(0)
|
|
164
|
+
elif not typer.confirm(
|
|
165
|
+
"Set it up now? (creates router.yaml, AGENTS.md, HANDOFF.md)", default=True
|
|
166
|
+
):
|
|
167
|
+
raise typer.Exit(0)
|
|
168
|
+
init(repo=repo)
|
|
169
|
+
typer.echo()
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _load(repo: Path) -> RouterConfig:
|
|
173
|
+
try:
|
|
174
|
+
return _with_org_policy(load_router_config(repo / ROUTER_FILE))
|
|
175
|
+
except ConfigError as exc:
|
|
176
|
+
typer.secho(str(exc), fg=typer.colors.RED, err=True)
|
|
177
|
+
raise typer.Exit(2) from exc
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _with_org_policy(config: RouterConfig) -> RouterConfig:
|
|
181
|
+
"""Enforce the machine-wide organisation policy, if one is installed."""
|
|
182
|
+
found = load_org_policy()
|
|
183
|
+
if found is None:
|
|
184
|
+
return config
|
|
185
|
+
policy, path = found
|
|
186
|
+
config, notes = apply_org_policy(config, policy)
|
|
187
|
+
if notes:
|
|
188
|
+
typer.secho(f"Organisation policy ({path}): {'; '.join(notes)}", fg="cyan", err=True)
|
|
189
|
+
return config
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _budget(repo: Path, config: RouterConfig) -> BudgetManager:
|
|
193
|
+
readers = {p.name: make_usage_reader(p) for p in config.providers}
|
|
194
|
+
return BudgetManager(config.providers, readers, repo / STATE_DIR, usage_cache=UsageCache())
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
RepoOpt = Annotated[
|
|
198
|
+
Path | None, typer.Option("--repo", help="Repository (default: the git repo you are in).")
|
|
199
|
+
]
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _print_version(value: bool) -> None:
|
|
203
|
+
if value:
|
|
204
|
+
from codebaton import __version__
|
|
205
|
+
|
|
206
|
+
typer.echo(f"codebaton {__version__}")
|
|
207
|
+
raise typer.Exit()
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
@app.callback(invoke_without_command=True)
|
|
211
|
+
def _default(
|
|
212
|
+
ctx: typer.Context,
|
|
213
|
+
version: Annotated[
|
|
214
|
+
bool,
|
|
215
|
+
typer.Option(
|
|
216
|
+
"--version", "-V", callback=_print_version, is_eager=True, help="Show version."
|
|
217
|
+
),
|
|
218
|
+
] = False,
|
|
219
|
+
) -> None:
|
|
220
|
+
"""Bare `codebaton` opens an agent session (same as `codebaton start`)."""
|
|
221
|
+
if ctx.invoked_subcommand is None:
|
|
222
|
+
start(task=None, agent=None, model=None, chat=False, repo=None)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _print_usage(usages: list[ProviderUsage]) -> None:
|
|
226
|
+
typer.secho("codebaton", bold=True)
|
|
227
|
+
for u in usages:
|
|
228
|
+
flag = "rate-limited" if u.exhausted else ("ok" if u.under_cap else "over threshold")
|
|
229
|
+
color = typer.colors.GREEN if u.under_cap else typer.colors.YELLOW
|
|
230
|
+
typer.secho(
|
|
231
|
+
f" {u.name:<12} {u.percent:5.1f}% used / {u.cap_percent:.0f}% threshold "
|
|
232
|
+
f"{flag:<15} [{u.note}]",
|
|
233
|
+
fg=color,
|
|
234
|
+
)
|
|
235
|
+
typer.echo()
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _choose(options: list[MenuOption]) -> MenuOption:
|
|
239
|
+
default = next((i for i, o in enumerate(options, 1) if o.recommended), None)
|
|
240
|
+
typer.echo("Which agent?")
|
|
241
|
+
for i, option in enumerate(options, 1):
|
|
242
|
+
mark = " <- recommended" if option.recommended else ""
|
|
243
|
+
color = None if option.available else typer.colors.BRIGHT_BLACK
|
|
244
|
+
typer.secho(f" {i}) {option.label}{mark}", fg=color)
|
|
245
|
+
typer.echo(" q) quit")
|
|
246
|
+
while True:
|
|
247
|
+
raw = typer.prompt("Choose (Enter = recommended)", default=str(default) if default else "q")
|
|
248
|
+
if raw.strip().lower() in {"q", "quit"}:
|
|
249
|
+
raise typer.Exit(0)
|
|
250
|
+
if raw.isdigit() and 1 <= int(raw) <= len(options):
|
|
251
|
+
choice = options[int(raw) - 1]
|
|
252
|
+
if choice.available:
|
|
253
|
+
return choice
|
|
254
|
+
typer.secho("That one is not available (see the note next to it).", fg="yellow")
|
|
255
|
+
else:
|
|
256
|
+
typer.secho(f"Type a number from 1 to {len(options)}, or q.", fg="yellow")
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _session_summary(store: HandoffStore, start_sha: str | None) -> list[str]:
|
|
260
|
+
"""Files changed since the session started (from git, no tokens)."""
|
|
261
|
+
if not start_sha:
|
|
262
|
+
return []
|
|
263
|
+
out = (
|
|
264
|
+
subprocess.run(
|
|
265
|
+
["git", "diff", "--stat", "--stat-width=80", f"{start_sha}..HEAD"],
|
|
266
|
+
cwd=store.repo,
|
|
267
|
+
capture_output=True,
|
|
268
|
+
text=True,
|
|
269
|
+
check=False,
|
|
270
|
+
)
|
|
271
|
+
.stdout.strip()
|
|
272
|
+
.splitlines()
|
|
273
|
+
)
|
|
274
|
+
return out[:-1][:15] if len(out) > 1 else []
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _run_agent(argv: list[str], cwd: Path) -> int:
|
|
278
|
+
"""Hand the terminal to the agent's own CLI and wait until the user exits it."""
|
|
279
|
+
return subprocess.run(argv, cwd=cwd, check=False).returncode
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _head(repo: Path) -> str | None:
|
|
283
|
+
if not (repo / ".git").exists():
|
|
284
|
+
return None
|
|
285
|
+
result = subprocess.run(
|
|
286
|
+
["git", "rev-parse", "HEAD"], cwd=repo, capture_output=True, text=True, check=False
|
|
287
|
+
)
|
|
288
|
+
return result.stdout.strip() or None
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
@app.command()
|
|
292
|
+
def start(
|
|
293
|
+
task: Annotated[
|
|
294
|
+
str | None, typer.Argument(help="Optional first message for the agent.")
|
|
295
|
+
] = None,
|
|
296
|
+
agent: Annotated[
|
|
297
|
+
str | None,
|
|
298
|
+
typer.Option("--agent", "-a", help="Open this agent directly: claude, codex, ollama."),
|
|
299
|
+
] = None,
|
|
300
|
+
model: Annotated[
|
|
301
|
+
str | None,
|
|
302
|
+
typer.Option("--model", "-m", help="Start on a tier: haiku, sonnet or opus."),
|
|
303
|
+
] = None,
|
|
304
|
+
chat: Annotated[
|
|
305
|
+
bool,
|
|
306
|
+
typer.Option("--chat", help="Ollama only: plain chat (answers in seconds, no file edits)."),
|
|
307
|
+
] = False,
|
|
308
|
+
repo: RepoOpt = None,
|
|
309
|
+
) -> None:
|
|
310
|
+
"""Show usage and open the recommended agent's real CLI (the default command)."""
|
|
311
|
+
root = _repo(repo)
|
|
312
|
+
_ensure_setup(root)
|
|
313
|
+
config = _load(root)
|
|
314
|
+
if model and model not in TIER_ORDER:
|
|
315
|
+
typer.secho("--model must be haiku, sonnet or opus.", fg=typer.colors.RED, err=True)
|
|
316
|
+
raise typer.Exit(2)
|
|
317
|
+
try:
|
|
318
|
+
routing = load_model_routing(root / MODEL_ROUTING_FILE)
|
|
319
|
+
budget = _budget(root, config)
|
|
320
|
+
except (ConfigError, PluginError) as exc:
|
|
321
|
+
typer.secho(str(exc), fg=typer.colors.RED, err=True)
|
|
322
|
+
raise typer.Exit(2) from exc
|
|
323
|
+
known = {p.name: p for p in config.providers}
|
|
324
|
+
agent = AGENT_ALIASES.get(agent, agent) if agent else None
|
|
325
|
+
if agent and agent not in {*known, "ollama"}:
|
|
326
|
+
typer.secho(
|
|
327
|
+
f"Unknown agent '{agent}'. Choose from: {', '.join(known)}, ollama.",
|
|
328
|
+
fg=typer.colors.RED,
|
|
329
|
+
err=True,
|
|
330
|
+
)
|
|
331
|
+
raise typer.Exit(2)
|
|
332
|
+
|
|
333
|
+
store = HandoffStore(root)
|
|
334
|
+
audit = AuditLog(root / STATE_DIR / "audit.jsonl")
|
|
335
|
+
ollama = detect_ollama()
|
|
336
|
+
takeover_from: str | None = None
|
|
337
|
+
pick = agent
|
|
338
|
+
while True:
|
|
339
|
+
usages = budget.all_usage()
|
|
340
|
+
_print_usage(usages)
|
|
341
|
+
options = build_menu(usages, config, ollama)
|
|
342
|
+
if pick is not None:
|
|
343
|
+
choice = (
|
|
344
|
+
next(o for o in options if o.key == pick)
|
|
345
|
+
if any(o.key == pick for o in options)
|
|
346
|
+
else None
|
|
347
|
+
)
|
|
348
|
+
if choice is None or not choice.available:
|
|
349
|
+
typer.secho(f"{pick} is not available.", fg=typer.colors.RED, err=True)
|
|
350
|
+
raise typer.Exit(2)
|
|
351
|
+
else:
|
|
352
|
+
choice = _choose(options)
|
|
353
|
+
usage = next((u for u in usages if u.name == choice.key), None)
|
|
354
|
+
if (
|
|
355
|
+
usage
|
|
356
|
+
and not usage.under_cap
|
|
357
|
+
and takeover_from is None
|
|
358
|
+
and not typer.confirm(
|
|
359
|
+
f"{choice.key} is over its threshold ({usage.percent:.0f}% / "
|
|
360
|
+
f"{usage.cap_percent:.0f}%). Use it anyway?",
|
|
361
|
+
default=False,
|
|
362
|
+
)
|
|
363
|
+
):
|
|
364
|
+
raise typer.Exit(0)
|
|
365
|
+
|
|
366
|
+
name = choice.key
|
|
367
|
+
nxt = next_agent(usages, name) if name in known else None
|
|
368
|
+
if name in known:
|
|
369
|
+
save_session(
|
|
370
|
+
root,
|
|
371
|
+
SessionState(
|
|
372
|
+
agent=name,
|
|
373
|
+
cap=known[name].cap_percent,
|
|
374
|
+
warn_margin=config.warn_margin_percent,
|
|
375
|
+
next_agent=nxt,
|
|
376
|
+
git_checkpoint=config.git_checkpoint,
|
|
377
|
+
),
|
|
378
|
+
)
|
|
379
|
+
budget.record_run(name)
|
|
380
|
+
native, effort = (
|
|
381
|
+
native_model(routing, known[name].adapter_name, model)
|
|
382
|
+
if model and name in known
|
|
383
|
+
else ("", None)
|
|
384
|
+
)
|
|
385
|
+
mode = "chat" if chat else (config.ollama.mode if config.ollama else "agent")
|
|
386
|
+
via_codex = name == "ollama" and mode == "agent" and shutil.which("codex") is not None
|
|
387
|
+
server = None
|
|
388
|
+
if name == "ollama":
|
|
389
|
+
local = (config.ollama.model if config.ollama else None) or (
|
|
390
|
+
ollama.models[0] if ollama.models else ""
|
|
391
|
+
)
|
|
392
|
+
if not _memory_check(local, ollama_models_gb().get(local)):
|
|
393
|
+
raise typer.Exit(0)
|
|
394
|
+
save_session(
|
|
395
|
+
root,
|
|
396
|
+
SessionState(
|
|
397
|
+
agent="ollama",
|
|
398
|
+
cap=100,
|
|
399
|
+
warn_margin=0,
|
|
400
|
+
next_agent=None,
|
|
401
|
+
git_checkpoint=config.git_checkpoint,
|
|
402
|
+
),
|
|
403
|
+
)
|
|
404
|
+
server = start_ollama_server(root / STATE_DIR / "ollama.log")
|
|
405
|
+
if server is None and not ollama_running():
|
|
406
|
+
typer.secho(
|
|
407
|
+
"Could not start Ollama. Try: ollama serve", fg=typer.colors.RED, err=True
|
|
408
|
+
)
|
|
409
|
+
raise typer.Exit(1)
|
|
410
|
+
if via_codex:
|
|
411
|
+
typer.secho(
|
|
412
|
+
"Local model via Codex: the first reply takes about a minute, because "
|
|
413
|
+
"Codex sends ~47K tokens of instructions. For instant answers: "
|
|
414
|
+
"codebaton use ollama --chat",
|
|
415
|
+
fg=typer.colors.YELLOW,
|
|
416
|
+
)
|
|
417
|
+
prompt = session_prompt(task, takeover_from) if name != "ollama" or via_codex else ""
|
|
418
|
+
argv = launch_argv(
|
|
419
|
+
name,
|
|
420
|
+
prompt,
|
|
421
|
+
config,
|
|
422
|
+
ollama,
|
|
423
|
+
root,
|
|
424
|
+
model=native,
|
|
425
|
+
reasoning_effort=effort,
|
|
426
|
+
ollama_via_codex=via_codex,
|
|
427
|
+
)
|
|
428
|
+
audit.record(
|
|
429
|
+
"session_start",
|
|
430
|
+
provider=name,
|
|
431
|
+
model=native or "(cli default)",
|
|
432
|
+
takeover_from=takeover_from,
|
|
433
|
+
next_agent=nxt,
|
|
434
|
+
)
|
|
435
|
+
start_sha = _head(root)
|
|
436
|
+
before = store.snapshot()
|
|
437
|
+
store.save_baseline() # checkpoints will leave already-uncommitted work alone
|
|
438
|
+
|
|
439
|
+
where = f" on {native}" if native else ""
|
|
440
|
+
typer.secho(
|
|
441
|
+
f"Opening {name}{where}. Exit it normally (/exit) to come back here.\n",
|
|
442
|
+
fg=typer.colors.GREEN,
|
|
443
|
+
)
|
|
444
|
+
try:
|
|
445
|
+
code = _run_agent(argv, root)
|
|
446
|
+
except FileNotFoundError as exc:
|
|
447
|
+
typer.secho(f"Could not start {argv[0]}: not on PATH.", fg=typer.colors.RED, err=True)
|
|
448
|
+
raise typer.Exit(127) from exc
|
|
449
|
+
except KeyboardInterrupt:
|
|
450
|
+
code = 130
|
|
451
|
+
finally:
|
|
452
|
+
if name == "ollama":
|
|
453
|
+
stop_ollama_server(server) # only stops a server this session started
|
|
454
|
+
audit.record("session_end", provider=name, exit_code=code)
|
|
455
|
+
|
|
456
|
+
# Default behaviour after every session: save a checkpoint (free, no tokens).
|
|
457
|
+
sha = (
|
|
458
|
+
store.checkpoint_turn(f"chore(codebaton): end of {name} session")
|
|
459
|
+
if (config.git_checkpoint)
|
|
460
|
+
else None
|
|
461
|
+
)
|
|
462
|
+
changed = _session_summary(store, start_sha)
|
|
463
|
+
if changed and not store.agent_updated(before)[0] and name != "ollama":
|
|
464
|
+
# Safety net: the agent changed files but never updated HANDOFF.md.
|
|
465
|
+
with store.handoff_path.open("a", encoding="utf-8") as fh:
|
|
466
|
+
fh.write(
|
|
467
|
+
f"\n## Last session ({name}, written by codebaton)\n"
|
|
468
|
+
"Files changed (see git log for details):\n"
|
|
469
|
+
+ "\n".join(f"- {line.strip()}" for line in changed)
|
|
470
|
+
+ "\n"
|
|
471
|
+
)
|
|
472
|
+
sha = store.checkpoint_turn("chore(codebaton): handoff note") or sha
|
|
473
|
+
if sha:
|
|
474
|
+
typer.echo(f"Checkpoint saved: {sha[:12]}")
|
|
475
|
+
|
|
476
|
+
if name not in known:
|
|
477
|
+
break
|
|
478
|
+
after = budget.usage(name)
|
|
479
|
+
over = after.exhausted or not after.under_cap
|
|
480
|
+
nxt = next_agent(budget.all_usage(), name)
|
|
481
|
+
if over and nxt:
|
|
482
|
+
typer.secho(
|
|
483
|
+
f"\n{name} reached its threshold ({after.percent:.0f}% / "
|
|
484
|
+
f"{after.cap_percent:.0f}%).",
|
|
485
|
+
fg=typer.colors.YELLOW,
|
|
486
|
+
)
|
|
487
|
+
if typer.confirm(f"Continue in {nxt}? It will pick up from HANDOFF.md.", default=True):
|
|
488
|
+
audit.record("switch", from_provider=name, to_provider=nxt, percent=after.percent)
|
|
489
|
+
store.append_decision(
|
|
490
|
+
"codebaton",
|
|
491
|
+
f"switched {name} -> {nxt} at {after.percent:.0f}% of {after.cap_percent:.0f}%",
|
|
492
|
+
)
|
|
493
|
+
takeover_from, pick, task = name, nxt, None
|
|
494
|
+
continue
|
|
495
|
+
elif over:
|
|
496
|
+
typer.secho(
|
|
497
|
+
f"{name} is over its threshold and no other agent is available.",
|
|
498
|
+
fg=typer.colors.YELLOW,
|
|
499
|
+
)
|
|
500
|
+
break
|
|
501
|
+
typer.echo("Done. Progress is in HANDOFF.md and git log.")
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
@app.command()
|
|
505
|
+
def use(
|
|
506
|
+
agent: Annotated[str, typer.Argument(help="claude, codex or ollama.")],
|
|
507
|
+
task: Annotated[
|
|
508
|
+
str | None, typer.Argument(help="Optional first message for the agent.")
|
|
509
|
+
] = None,
|
|
510
|
+
model: Annotated[
|
|
511
|
+
str | None,
|
|
512
|
+
typer.Option("--model", "-m", help="Start on a tier: haiku, sonnet or opus."),
|
|
513
|
+
] = None,
|
|
514
|
+
chat: Annotated[
|
|
515
|
+
bool,
|
|
516
|
+
typer.Option("--chat", help="Ollama only: plain chat (answers in seconds, no file edits)."),
|
|
517
|
+
] = False,
|
|
518
|
+
repo: RepoOpt = None,
|
|
519
|
+
) -> None:
|
|
520
|
+
"""Open a specific agent: codebaton use claude | codex | ollama [--chat]."""
|
|
521
|
+
if agent.lower() not in AGENT_ALIASES:
|
|
522
|
+
typer.secho(
|
|
523
|
+
f"Unknown agent '{agent}'. Use: claude, codex or ollama.", fg=typer.colors.RED, err=True
|
|
524
|
+
)
|
|
525
|
+
raise typer.Exit(2)
|
|
526
|
+
start(task=task, agent=AGENT_ALIASES[agent.lower()], model=model, chat=chat, repo=repo)
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
def ollama_models_gb() -> dict[str, float]:
|
|
530
|
+
"""Installed Ollama models and their sizes in GB, from `ollama list`."""
|
|
531
|
+
try:
|
|
532
|
+
out = subprocess.run(
|
|
533
|
+
["ollama", "list"], capture_output=True, text=True, timeout=10, check=False
|
|
534
|
+
).stdout
|
|
535
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
536
|
+
return {}
|
|
537
|
+
sizes: dict[str, float] = {}
|
|
538
|
+
for line in out.splitlines()[1:]:
|
|
539
|
+
parts = line.split()
|
|
540
|
+
if len(parts) >= 4:
|
|
541
|
+
try:
|
|
542
|
+
value = float(parts[2])
|
|
543
|
+
except ValueError:
|
|
544
|
+
continue
|
|
545
|
+
sizes[parts[0]] = value / 1000 if parts[3].upper() == "MB" else value
|
|
546
|
+
return sizes
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def _show_assessment(title: str, estimate: ModelEstimate, verdict: Assessment) -> None:
|
|
550
|
+
color = {"ok": typer.colors.GREEN, "tight": typer.colors.YELLOW, "too_big": typer.colors.RED}[
|
|
551
|
+
verdict.level
|
|
552
|
+
]
|
|
553
|
+
how = "" if estimate.exact else " (rough estimate)"
|
|
554
|
+
typer.echo(f"\n{title}")
|
|
555
|
+
typer.echo(f" model: {estimate.name}")
|
|
556
|
+
if estimate.download_gb:
|
|
557
|
+
typer.echo(f" download size: {estimate.download_gb:.1f} GB")
|
|
558
|
+
typer.echo(
|
|
559
|
+
f" memory needed: ~{verdict.need_gb:.1f} GB while running{how} "
|
|
560
|
+
f"({estimate.context // 1024}K context for Codex)"
|
|
561
|
+
)
|
|
562
|
+
free = f"{verdict.free_gb:.1f} GB" if verdict.free_gb is not None else "unknown"
|
|
563
|
+
typer.echo(f" your Mac: {verdict.total_gb:.0f} GB total, {free} free right now")
|
|
564
|
+
label = {
|
|
565
|
+
"ok": "fits comfortably",
|
|
566
|
+
"tight": "tight: close other apps first",
|
|
567
|
+
"too_big": "too big: your Mac may freeze",
|
|
568
|
+
}[verdict.level]
|
|
569
|
+
typer.secho(f" verdict: {label}", fg=color, bold=True)
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
def _memory_check(local_name: str, size_gb: float | None) -> bool:
|
|
573
|
+
"""Before loading a local model: show the memory picture and ask unless it clearly fits."""
|
|
574
|
+
estimate = load_estimate(local_name) or (
|
|
575
|
+
rough_estimate(local_name, size_gb) if size_gb else None
|
|
576
|
+
)
|
|
577
|
+
if estimate is None:
|
|
578
|
+
return True
|
|
579
|
+
verdict = assess(estimate.need_gb, total_memory_gb(), free_memory_gb())
|
|
580
|
+
if verdict.level == "ok":
|
|
581
|
+
typer.secho(f"Memory check: {verdict.summary()}", fg=typer.colors.GREEN)
|
|
582
|
+
return True
|
|
583
|
+
_show_assessment("Memory check before loading the local model", estimate, verdict)
|
|
584
|
+
return typer.confirm("Load it anyway?", default=False)
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
def _pick_model() -> str:
|
|
588
|
+
"""Show the curated models, judged against this Mac, and let the user choose one."""
|
|
589
|
+
total = total_memory_gb()
|
|
590
|
+
free = free_memory_gb()
|
|
591
|
+
typer.echo("Checking models in the Ollama library (nothing is downloaded yet)...")
|
|
592
|
+
rows = choices(total)
|
|
593
|
+
free_text = f", {free:.1f} GB free right now" if free is not None else ""
|
|
594
|
+
typer.echo(f"\nYour Mac: {total:.0f} GB total{free_text}\n")
|
|
595
|
+
labels = {
|
|
596
|
+
"ok": "fits",
|
|
597
|
+
"tight": "tight",
|
|
598
|
+
"too_big": "too big for this Mac",
|
|
599
|
+
"unknown": "size unknown",
|
|
600
|
+
}
|
|
601
|
+
colors = {
|
|
602
|
+
"ok": typer.colors.GREEN,
|
|
603
|
+
"tight": typer.colors.YELLOW,
|
|
604
|
+
"too_big": typer.colors.RED,
|
|
605
|
+
"unknown": None,
|
|
606
|
+
}
|
|
607
|
+
default = 1
|
|
608
|
+
for i, row in enumerate(rows, 1):
|
|
609
|
+
sizes = (
|
|
610
|
+
f"{row.estimate.download_gb:4.1f} GB download, ~{row.estimate.need_gb:4.1f} GB running"
|
|
611
|
+
if row.estimate
|
|
612
|
+
else "sizes unavailable"
|
|
613
|
+
)
|
|
614
|
+
mark = " <- recommended" if row.recommended else ""
|
|
615
|
+
default = i if row.recommended else default
|
|
616
|
+
typer.secho(
|
|
617
|
+
f" {i}) {row.name:<16} {sizes} {labels[row.fit]:<20} ({row.note}){mark}",
|
|
618
|
+
fg=colors[row.fit],
|
|
619
|
+
)
|
|
620
|
+
typer.echo(" or type any Ollama model name\n")
|
|
621
|
+
raw = str(typer.prompt("Choose", default=str(default))).strip()
|
|
622
|
+
if raw.isdigit() and 1 <= int(raw) <= len(rows):
|
|
623
|
+
return rows[int(raw) - 1].name
|
|
624
|
+
return raw
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
@app.command("install-model")
|
|
628
|
+
def install_model(
|
|
629
|
+
name: Annotated[
|
|
630
|
+
str | None,
|
|
631
|
+
typer.Argument(help="Ollama model to install. Leave out to pick from a list."),
|
|
632
|
+
] = None,
|
|
633
|
+
repo: RepoOpt = None,
|
|
634
|
+
) -> None:
|
|
635
|
+
"""Install a local model safely: shows download size and memory needed, then asks."""
|
|
636
|
+
if shutil.which("ollama") is None:
|
|
637
|
+
typer.secho(
|
|
638
|
+
"Ollama is not installed. Install it with: brew install ollama && "
|
|
639
|
+
"brew services start ollama",
|
|
640
|
+
fg=typer.colors.RED,
|
|
641
|
+
err=True,
|
|
642
|
+
)
|
|
643
|
+
raise typer.Exit(2)
|
|
644
|
+
if name is None:
|
|
645
|
+
name = _pick_model()
|
|
646
|
+
typer.echo(f"Checking {name} in the Ollama library (nothing is downloaded yet)...")
|
|
647
|
+
try:
|
|
648
|
+
estimate = registry_estimate(name)
|
|
649
|
+
except Exception as exc:
|
|
650
|
+
typer.secho(f"Could not look up {name}: {exc}", fg=typer.colors.RED, err=True)
|
|
651
|
+
raise typer.Exit(2) from exc
|
|
652
|
+
if estimate.max_context is not None and estimate.max_context < estimate.context:
|
|
653
|
+
typer.secho(
|
|
654
|
+
f"{name} supports at most {estimate.max_context:,} tokens of context, but Codex "
|
|
655
|
+
f"needs about {estimate.context:,}. It would not work as a coding agent here. "
|
|
656
|
+
f"Try {RECOMMENDED_MODEL}.",
|
|
657
|
+
fg=typer.colors.RED,
|
|
658
|
+
err=True,
|
|
659
|
+
)
|
|
660
|
+
raise typer.Exit(2)
|
|
661
|
+
verdict = assess(estimate.need_gb, total_memory_gb(), free_memory_gb())
|
|
662
|
+
_show_assessment("Before installing", estimate, verdict)
|
|
663
|
+
if not typer.confirm(
|
|
664
|
+
f"\nDownload {name} ({estimate.download_gb:.1f} GB) now?",
|
|
665
|
+
default=verdict.level != "too_big",
|
|
666
|
+
):
|
|
667
|
+
typer.echo("Nothing was downloaded.")
|
|
668
|
+
raise typer.Exit(0)
|
|
669
|
+
|
|
670
|
+
server = start_ollama_server(_repo(repo) / STATE_DIR / "ollama.log")
|
|
671
|
+
try:
|
|
672
|
+
_pull_and_prepare(name, estimate, _repo(repo))
|
|
673
|
+
finally:
|
|
674
|
+
stop_ollama_server(server)
|
|
675
|
+
|
|
676
|
+
|
|
677
|
+
def _pull_and_prepare(name: str, estimate: ModelEstimate, root: Path) -> None:
|
|
678
|
+
if subprocess.run(["ollama", "pull", name], check=False).returncode != 0:
|
|
679
|
+
typer.secho(
|
|
680
|
+
"Download failed; run the command again to resume.", fg=typer.colors.RED, err=True
|
|
681
|
+
)
|
|
682
|
+
raise typer.Exit(1)
|
|
683
|
+
variant = agent_variant_name(name)
|
|
684
|
+
state = root / STATE_DIR
|
|
685
|
+
state.mkdir(parents=True, exist_ok=True)
|
|
686
|
+
spec = state / "Modelfile.agent"
|
|
687
|
+
spec.write_text(modelfile(name, estimate.context), encoding="utf-8")
|
|
688
|
+
created = subprocess.run(
|
|
689
|
+
["ollama", "create", variant, "-f", str(spec)], capture_output=True, text=True, check=False
|
|
690
|
+
)
|
|
691
|
+
if created.returncode != 0:
|
|
692
|
+
typer.secho(
|
|
693
|
+
f"Could not create {variant}: {created.stderr[-300:]}", fg=typer.colors.RED, err=True
|
|
694
|
+
)
|
|
695
|
+
raise typer.Exit(1)
|
|
696
|
+
save_estimate(variant, estimate)
|
|
697
|
+
save_estimate(name, estimate)
|
|
698
|
+
if (root / ROUTER_FILE).exists():
|
|
699
|
+
set_router_model(root / ROUTER_FILE, variant)
|
|
700
|
+
typer.echo(f"router.yaml now uses {variant} for Ollama.")
|
|
701
|
+
typer.secho(
|
|
702
|
+
f"\nInstalled. Try it with: codebaton use ollama ({variant}: "
|
|
703
|
+
f"{name} with a {estimate.context // 1024}K context, no extra disk)",
|
|
704
|
+
fg=typer.colors.GREEN,
|
|
705
|
+
)
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
@app.command("help")
|
|
709
|
+
def help_(ctx: typer.Context) -> None:
|
|
710
|
+
"""Show this help."""
|
|
711
|
+
typer.echo(ctx.parent.get_help() if ctx.parent else HELP)
|
|
712
|
+
|
|
713
|
+
|
|
714
|
+
@app.command()
|
|
715
|
+
def init(repo: RepoOpt = None) -> None:
|
|
716
|
+
"""One-time setup of a project (codebaton also offers this on first use)."""
|
|
717
|
+
root = _repo(repo)
|
|
718
|
+
created = HandoffStore(root).init_files()
|
|
719
|
+
if not (root / ROUTER_FILE).exists():
|
|
720
|
+
(root / ROUTER_FILE).write_text(ROUTER_TEMPLATE, encoding="utf-8")
|
|
721
|
+
created.append(ROUTER_FILE)
|
|
722
|
+
if not (root / MODEL_ROUTING_FILE).exists():
|
|
723
|
+
routing = default_model_routing().model_dump(mode="json")
|
|
724
|
+
models = discover_codex_models()
|
|
725
|
+
routing["provider_tiers"]["codex"] = codex_tiers(models)
|
|
726
|
+
header = "# Model tier routing. Rule: when in doubt, go up a tier, never down.\n"
|
|
727
|
+
if models:
|
|
728
|
+
header += (
|
|
729
|
+
"# Codex models found for this account (from ~/.codex/models_cache.json):\n# "
|
|
730
|
+
+ ", ".join(models.slugs)
|
|
731
|
+
+ "\n# Codex tiers: top = opus, medium = sonnet, light = haiku. Edit freely.\n"
|
|
732
|
+
)
|
|
733
|
+
else:
|
|
734
|
+
header += "# Codex models not found; empty model = Codex CLI default.\n"
|
|
735
|
+
(root / MODEL_ROUTING_FILE).write_text(
|
|
736
|
+
header + yaml.safe_dump(routing, sort_keys=False), encoding="utf-8"
|
|
737
|
+
)
|
|
738
|
+
created.append(MODEL_ROUTING_FILE)
|
|
739
|
+
gitignore = root / ".gitignore"
|
|
740
|
+
existing = gitignore.read_text(encoding="utf-8").splitlines() if gitignore.exists() else []
|
|
741
|
+
missing = [line for line in GITIGNORE_LINES if line not in existing]
|
|
742
|
+
if missing:
|
|
743
|
+
with gitignore.open("a", encoding="utf-8") as fh:
|
|
744
|
+
if existing and existing[-1].strip():
|
|
745
|
+
fh.write("\n")
|
|
746
|
+
fh.write("# codebaton\n" + "\n".join(missing) + "\n")
|
|
747
|
+
typer.echo("Created: " + ", ".join(created) if created else "Everything already exists.")
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
@app.command()
|
|
751
|
+
def run(
|
|
752
|
+
task: Annotated[str, typer.Argument(help="Plain-English coding task.")],
|
|
753
|
+
model: Annotated[
|
|
754
|
+
str | None, typer.Option("--model", help="Pin tier: haiku|sonnet|opus.")
|
|
755
|
+
] = None,
|
|
756
|
+
task_type: Annotated[
|
|
757
|
+
str | None, typer.Option("--type", help="Task type, e.g. write_tests.")
|
|
758
|
+
] = None,
|
|
759
|
+
path: Annotated[list[str] | None, typer.Option("--path", help="File the task touches.")] = None,
|
|
760
|
+
repo: RepoOpt = None,
|
|
761
|
+
) -> None:
|
|
762
|
+
"""Autopilot: give one task to the best agent and run it unattended."""
|
|
763
|
+
root = _repo(repo)
|
|
764
|
+
config = _load(root)
|
|
765
|
+
try:
|
|
766
|
+
routing = load_model_routing(root / MODEL_ROUTING_FILE)
|
|
767
|
+
executor = make_executor(config.executor)
|
|
768
|
+
adapters = {p.name: make_adapter(p, executor) for p in config.providers}
|
|
769
|
+
budget = _budget(root, config)
|
|
770
|
+
except (ConfigError, PluginError) as exc:
|
|
771
|
+
typer.secho(str(exc), fg=typer.colors.RED, err=True)
|
|
772
|
+
raise typer.Exit(2) from exc
|
|
773
|
+
orchestrator = Orchestrator(
|
|
774
|
+
repo=root,
|
|
775
|
+
config=config,
|
|
776
|
+
routing=routing,
|
|
777
|
+
budget=budget,
|
|
778
|
+
adapters=adapters,
|
|
779
|
+
audit=AuditLog(root / STATE_DIR / "audit.jsonl"),
|
|
780
|
+
executor=executor,
|
|
781
|
+
confirm=terminal_confirm,
|
|
782
|
+
classifier=HaikuClassifier(executor, root),
|
|
783
|
+
)
|
|
784
|
+
try:
|
|
785
|
+
outcome = orchestrator.run(task, override=model, task_type=task_type, paths=path)
|
|
786
|
+
except ValueError as exc:
|
|
787
|
+
typer.secho(str(exc), fg=typer.colors.RED, err=True)
|
|
788
|
+
raise typer.Exit(2) from exc
|
|
789
|
+
color = typer.colors.GREEN if outcome.status == "ok" else typer.colors.YELLOW
|
|
790
|
+
typer.secho(outcome.message, fg=color)
|
|
791
|
+
if outcome.attempts:
|
|
792
|
+
typer.echo("Attempts: " + " -> ".join(outcome.attempts))
|
|
793
|
+
if outcome.commit:
|
|
794
|
+
typer.echo(f"Checkpoint: {outcome.commit[:12]}")
|
|
795
|
+
raise typer.Exit(0 if outcome.status == "ok" else 1)
|
|
796
|
+
|
|
797
|
+
|
|
798
|
+
@app.command()
|
|
799
|
+
def status(
|
|
800
|
+
repo: RepoOpt = None,
|
|
801
|
+
refresh: Annotated[
|
|
802
|
+
bool,
|
|
803
|
+
typer.Option("--refresh", help="Make one tiny Claude Haiku call to fetch real usage."),
|
|
804
|
+
] = False,
|
|
805
|
+
) -> None:
|
|
806
|
+
"""Usage of each agent vs its threshold, and which one would open next."""
|
|
807
|
+
root = _repo(repo)
|
|
808
|
+
config = _load(root)
|
|
809
|
+
if refresh:
|
|
810
|
+
_refresh_claude_usage(root, config)
|
|
811
|
+
try:
|
|
812
|
+
usages = _budget(root, config).all_usage()
|
|
813
|
+
except PluginError as exc:
|
|
814
|
+
typer.secho(str(exc), fg=typer.colors.RED, err=True)
|
|
815
|
+
raise typer.Exit(2) from exc
|
|
816
|
+
chosen = select_provider(usages, set())
|
|
817
|
+
typer.echo(f"{'provider':<14}{'used':>8}{'cap':>8} {'source':<12}note")
|
|
818
|
+
for u in usages:
|
|
819
|
+
mark = " <- next" if chosen and u.name == chosen.name else ""
|
|
820
|
+
typer.echo(
|
|
821
|
+
f"{u.name:<14}{u.percent:>7.1f}%{u.cap_percent:>7.0f}% {u.source:<12}{u.note}{mark}"
|
|
822
|
+
)
|
|
823
|
+
typer.echo(f"Next: {chosen.name if chosen else 'none (all providers at or over cap)'}")
|
|
824
|
+
|
|
825
|
+
|
|
826
|
+
@app.command()
|
|
827
|
+
def watch(
|
|
828
|
+
interval: Annotated[
|
|
829
|
+
int, typer.Option("--interval", "-n", min=2, help="Seconds between refreshes.")
|
|
830
|
+
] = 10,
|
|
831
|
+
once: Annotated[bool, typer.Option("--once", help="Print once and exit.")] = False,
|
|
832
|
+
as_json: Annotated[
|
|
833
|
+
bool, typer.Option("--json", help="Machine-readable output (implies --once).")
|
|
834
|
+
] = False,
|
|
835
|
+
repo: RepoOpt = None,
|
|
836
|
+
) -> None:
|
|
837
|
+
"""Live usage of every agent: bars, thresholds and when each window resets."""
|
|
838
|
+
root = _repo(repo)
|
|
839
|
+
# Works in any folder: without router.yaml, the default thresholds are shown.
|
|
840
|
+
if (root / ROUTER_FILE).exists():
|
|
841
|
+
config = _load(root)
|
|
842
|
+
else:
|
|
843
|
+
try:
|
|
844
|
+
config = _with_org_policy(_default_config())
|
|
845
|
+
except ConfigError as exc:
|
|
846
|
+
typer.secho(str(exc), fg=typer.colors.RED, err=True)
|
|
847
|
+
raise typer.Exit(2) from exc
|
|
848
|
+
if as_json:
|
|
849
|
+
typer.echo(monitor.to_json(monitor.collect(config)))
|
|
850
|
+
return
|
|
851
|
+
try:
|
|
852
|
+
while True:
|
|
853
|
+
screen = monitor.render(monitor.collect(config))
|
|
854
|
+
if once:
|
|
855
|
+
typer.echo(screen)
|
|
856
|
+
return
|
|
857
|
+
stamp = time.strftime("%H:%M:%S")
|
|
858
|
+
typer.echo(f"\033[2J\033[Hcodebaton watch · {stamp} · Ctrl+C to stop\n\n{screen}")
|
|
859
|
+
time.sleep(interval)
|
|
860
|
+
except KeyboardInterrupt:
|
|
861
|
+
typer.echo()
|
|
862
|
+
|
|
863
|
+
|
|
864
|
+
@app.command("report")
|
|
865
|
+
def report_(
|
|
866
|
+
since: Annotated[str, typer.Option("--since", help="Period: 24h, 7d, 4w or all.")] = "7d",
|
|
867
|
+
as_json: Annotated[bool, typer.Option("--json", help="JSON output.")] = False,
|
|
868
|
+
as_csv: Annotated[bool, typer.Option("--csv", help="CSV output (one row per agent).")] = False,
|
|
869
|
+
repo: RepoOpt = None,
|
|
870
|
+
) -> None:
|
|
871
|
+
"""Usage report for this repository from its audit log."""
|
|
872
|
+
root = _repo(repo)
|
|
873
|
+
try:
|
|
874
|
+
cutoff = report.parse_since(since, time.time())
|
|
875
|
+
except ValueError as exc:
|
|
876
|
+
typer.secho(f"--since: {exc}", fg=typer.colors.RED, err=True)
|
|
877
|
+
raise typer.Exit(2) from exc
|
|
878
|
+
label = "all time" if since == "all" else f"last {since}"
|
|
879
|
+
entries = AuditLog(root / STATE_DIR / "audit.jsonl").read()
|
|
880
|
+
result = report.summarize(entries, cutoff, label)
|
|
881
|
+
if as_json:
|
|
882
|
+
typer.echo(report.to_json(result))
|
|
883
|
+
elif as_csv:
|
|
884
|
+
typer.echo(report.to_csv(result), nl=False)
|
|
885
|
+
else:
|
|
886
|
+
typer.echo(report.render(result))
|
|
887
|
+
|
|
888
|
+
|
|
889
|
+
def _default_config() -> RouterConfig:
|
|
890
|
+
return RouterConfig.model_validate(yaml.safe_load(ROUTER_TEMPLATE))
|
|
891
|
+
|
|
892
|
+
|
|
893
|
+
def _refresh_claude_usage(root: Path, config: RouterConfig) -> None:
|
|
894
|
+
"""Claude reports usage with each reply; ask for a one-word reply to get fresh numbers."""
|
|
895
|
+
budget = _budget(root, config)
|
|
896
|
+
executor = make_executor(config.executor)
|
|
897
|
+
for provider in config.providers:
|
|
898
|
+
if provider.adapter_name != "claude_code":
|
|
899
|
+
continue
|
|
900
|
+
adapter = make_adapter(provider, executor)
|
|
901
|
+
context = RunContext(
|
|
902
|
+
"Reply with just: ok", "haiku", None, ["--permission-mode", "dontAsk"], 120
|
|
903
|
+
)
|
|
904
|
+
result = adapter.run(Task("usage probe", root), context)
|
|
905
|
+
budget.record_usage(provider.name, result.usage)
|
|
906
|
+
if not result.usage:
|
|
907
|
+
typer.secho(
|
|
908
|
+
f"{provider.name}: no usage reported ({result.detail[-200:]})",
|
|
909
|
+
fg=typer.colors.YELLOW,
|
|
910
|
+
)
|
|
911
|
+
|
|
912
|
+
|
|
913
|
+
def main() -> None:
|
|
914
|
+
app()
|
|
915
|
+
|
|
916
|
+
|
|
917
|
+
if __name__ == "__main__":
|
|
918
|
+
main()
|