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
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Read Codex usage from its local session logs.
|
|
2
|
+
|
|
3
|
+
Location: ``~/.codex/sessions/YYYY/MM/DD/rollout-<timestamp>-<id>.jsonl`` (override with
|
|
4
|
+
``usage.path``). Each ``{"type": "event_msg", "payload": {"type": "token_count", ...}}``
|
|
5
|
+
line carries ``payload.rate_limits.primary`` (short window, e.g. 300 min) and
|
|
6
|
+
``.secondary`` (weekly, 10080 min), each with ``used_percent`` and ``resets_at`` (epoch s).
|
|
7
|
+
These are the server's own numbers, so no estimation is needed. The newest event wins;
|
|
8
|
+
a window whose ``resets_at`` has passed counts as 0%.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import time
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, Literal
|
|
18
|
+
|
|
19
|
+
from codebaton.plugins.base import UsageReading, UsageWindow
|
|
20
|
+
|
|
21
|
+
DEFAULT_PATH = Path.home() / ".codex" / "sessions"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class CodexLogsReader:
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
path: Path | None = None,
|
|
28
|
+
window: Literal["short", "long", "max"] = "max",
|
|
29
|
+
now: Callable[[], float] = time.time,
|
|
30
|
+
max_files: int = 20,
|
|
31
|
+
) -> None:
|
|
32
|
+
self.path = path or DEFAULT_PATH
|
|
33
|
+
self.window = window
|
|
34
|
+
self.now = now
|
|
35
|
+
self.max_files = max_files
|
|
36
|
+
|
|
37
|
+
def _latest(self) -> tuple[str, dict[str, Any]] | None:
|
|
38
|
+
if not self.path.exists():
|
|
39
|
+
return None
|
|
40
|
+
files = sorted(
|
|
41
|
+
self.path.rglob("rollout-*.jsonl"), key=lambda p: p.stat().st_mtime, reverse=True
|
|
42
|
+
)
|
|
43
|
+
latest: tuple[str, dict[str, Any]] | None = None
|
|
44
|
+
for file in files[: self.max_files]:
|
|
45
|
+
found = _last_rate_limits(file)
|
|
46
|
+
if found and (latest is None or found[0] > latest[0]):
|
|
47
|
+
latest = found
|
|
48
|
+
return latest
|
|
49
|
+
|
|
50
|
+
def windows(self) -> tuple[str, dict[str, UsageWindow]] | None:
|
|
51
|
+
"""(timestamp of the event, {"short"/"long": window}) from the newest Codex log."""
|
|
52
|
+
latest = self._latest()
|
|
53
|
+
if latest is None:
|
|
54
|
+
return None
|
|
55
|
+
out: dict[str, UsageWindow] = {}
|
|
56
|
+
for src, key in (("primary", "short"), ("secondary", "long")):
|
|
57
|
+
win = latest[1].get(src)
|
|
58
|
+
if not isinstance(win, dict) or win.get("used_percent") is None:
|
|
59
|
+
continue
|
|
60
|
+
resets = win.get("resets_at")
|
|
61
|
+
out[key] = UsageWindow(
|
|
62
|
+
float(win["used_percent"]),
|
|
63
|
+
float(resets) if isinstance(resets, int | float) else None,
|
|
64
|
+
)
|
|
65
|
+
return latest[0], out
|
|
66
|
+
|
|
67
|
+
def used(self, window_hours: float) -> UsageReading:
|
|
68
|
+
# window_hours is unused: Codex reports its own windows.
|
|
69
|
+
if not self.path.exists():
|
|
70
|
+
return UsageReading(None, "codex_logs", f"no Codex session logs at {self.path}")
|
|
71
|
+
latest = self._latest()
|
|
72
|
+
if latest is None:
|
|
73
|
+
return UsageReading(None, "codex_logs", "no rate_limits events in recent sessions")
|
|
74
|
+
limits = latest[1]
|
|
75
|
+
now = self.now()
|
|
76
|
+
values: dict[str, float] = {}
|
|
77
|
+
for src, key in (("primary", "short"), ("secondary", "long")):
|
|
78
|
+
win = limits.get(src)
|
|
79
|
+
if not isinstance(win, dict) or win.get("used_percent") is None:
|
|
80
|
+
continue
|
|
81
|
+
resets = win.get("resets_at")
|
|
82
|
+
expired = isinstance(resets, int | float) and resets <= now
|
|
83
|
+
values[key] = 0.0 if expired else float(win["used_percent"])
|
|
84
|
+
if not values:
|
|
85
|
+
return UsageReading(None, "codex_logs", "rate_limits event had no used_percent")
|
|
86
|
+
if self.window == "max":
|
|
87
|
+
percent = max(values.values())
|
|
88
|
+
elif self.window in values:
|
|
89
|
+
percent = values[self.window]
|
|
90
|
+
else:
|
|
91
|
+
return UsageReading(None, "codex_logs", f"no {self.window} window in logs")
|
|
92
|
+
names = {"short": "5h", "long": "week"}
|
|
93
|
+
detail = ", ".join(f"{names[k]} {v:.0f}%" for k, v in values.items())
|
|
94
|
+
return UsageReading(percent, "codex_logs", detail)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _last_rate_limits(file: Path) -> tuple[str, dict[str, Any]] | None:
|
|
98
|
+
result: tuple[str, dict[str, Any]] | None = None
|
|
99
|
+
try:
|
|
100
|
+
with file.open(encoding="utf-8") as fh:
|
|
101
|
+
for line in fh:
|
|
102
|
+
if '"rate_limits"' not in line:
|
|
103
|
+
continue
|
|
104
|
+
try:
|
|
105
|
+
event = json.loads(line)
|
|
106
|
+
except json.JSONDecodeError:
|
|
107
|
+
continue
|
|
108
|
+
payload = event.get("payload") if isinstance(event, dict) else None
|
|
109
|
+
if not isinstance(payload, dict) or payload.get("type") != "token_count":
|
|
110
|
+
continue
|
|
111
|
+
limits = payload.get("rate_limits")
|
|
112
|
+
# Some events carry an empty rate_limits block; only keep ones with numbers.
|
|
113
|
+
if isinstance(limits, dict) and any(
|
|
114
|
+
isinstance(limits.get(k), dict) and limits[k].get("used_percent") is not None
|
|
115
|
+
for k in ("primary", "secondary")
|
|
116
|
+
):
|
|
117
|
+
result = (str(event.get("timestamp", "")), limits)
|
|
118
|
+
except OSError:
|
|
119
|
+
return None
|
|
120
|
+
return result
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Manual budget counter: the fallback when a provider's logs cannot be read.
|
|
2
|
+
|
|
3
|
+
Counts runs the router itself started per provider, in a rolling window, and reports
|
|
4
|
+
``runs / runs_per_window`` as percent. Stored in ``.codebaton/manual_budget.json``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import time
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from codebaton.plugins.base import UsageReading
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ManualCounter:
|
|
18
|
+
def __init__(
|
|
19
|
+
self,
|
|
20
|
+
state_file: Path,
|
|
21
|
+
provider: str,
|
|
22
|
+
runs_per_window: int,
|
|
23
|
+
now: Callable[[], float] = time.time,
|
|
24
|
+
) -> None:
|
|
25
|
+
self.state_file = state_file
|
|
26
|
+
self.provider = provider
|
|
27
|
+
self.runs_per_window = max(1, runs_per_window)
|
|
28
|
+
self.now = now
|
|
29
|
+
|
|
30
|
+
def _load(self) -> dict[str, list[float]]:
|
|
31
|
+
try:
|
|
32
|
+
data = json.loads(self.state_file.read_text(encoding="utf-8"))
|
|
33
|
+
except (OSError, json.JSONDecodeError):
|
|
34
|
+
return {}
|
|
35
|
+
return data if isinstance(data, dict) else {}
|
|
36
|
+
|
|
37
|
+
def record_run(self) -> None:
|
|
38
|
+
data = self._load()
|
|
39
|
+
data.setdefault(self.provider, []).append(self.now())
|
|
40
|
+
self.state_file.parent.mkdir(parents=True, exist_ok=True)
|
|
41
|
+
self.state_file.write_text(json.dumps(data), encoding="utf-8")
|
|
42
|
+
|
|
43
|
+
def used(self, window_hours: float) -> UsageReading:
|
|
44
|
+
cutoff = self.now() - window_hours * 3600
|
|
45
|
+
runs = [t for t in self._load().get(self.provider, []) if t >= cutoff]
|
|
46
|
+
percent = min(100.0, 100.0 * len(runs) / self.runs_per_window)
|
|
47
|
+
return UsageReading(
|
|
48
|
+
percent, "manual", f"{len(runs)}/{self.runs_per_window} runs in {window_hours:g}h"
|
|
49
|
+
)
|
codebaton/py.typed
ADDED
|
File without changes
|
codebaton/report.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Usage report from the audit log: sessions, time, checkpoints and hand-overs per agent.
|
|
2
|
+
|
|
3
|
+
Everything comes from ``.codebaton/audit.jsonl`` in a repository, so a team can collect
|
|
4
|
+
the JSON or CSV output from many repositories without any server.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import csv
|
|
10
|
+
import io
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
from dataclasses import asdict, dataclass, field
|
|
14
|
+
from datetime import datetime
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
_SINCE = re.compile(r"^(\d+)([hdw])$")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class AgentStats:
|
|
22
|
+
agent: str
|
|
23
|
+
sessions: int = 0
|
|
24
|
+
minutes: float = 0.0
|
|
25
|
+
checkpoints: int = 0
|
|
26
|
+
handed_over: int = 0 # switches away from this agent at its threshold
|
|
27
|
+
took_over: int = 0 # switches to this agent
|
|
28
|
+
rate_limited: int = 0
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class Report:
|
|
33
|
+
since: str
|
|
34
|
+
first_event: str | None
|
|
35
|
+
last_event: str | None
|
|
36
|
+
agents: list[AgentStats] = field(default_factory=list)
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def switches(self) -> int:
|
|
40
|
+
return sum(a.handed_over for a in self.agents)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def parse_since(value: str, now: float) -> float | None:
|
|
44
|
+
"""'24h', '7d', '4w' -> epoch seconds; 'all' -> None."""
|
|
45
|
+
if value == "all":
|
|
46
|
+
return None
|
|
47
|
+
match = _SINCE.match(value)
|
|
48
|
+
if not match:
|
|
49
|
+
raise ValueError("use a number with h, d or w (e.g. 24h, 7d, 4w) or 'all'")
|
|
50
|
+
amount, unit = int(match.group(1)), match.group(2)
|
|
51
|
+
return now - amount * {"h": 3600, "d": 86400, "w": 604800}[unit]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _ts(entry: dict[str, Any]) -> float | None:
|
|
55
|
+
try:
|
|
56
|
+
return datetime.fromisoformat(str(entry.get("ts"))).timestamp()
|
|
57
|
+
except ValueError:
|
|
58
|
+
return None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def summarize(entries: list[dict[str, Any]], since: float | None, label: str) -> Report:
|
|
62
|
+
stats: dict[str, AgentStats] = {}
|
|
63
|
+
open_sessions: dict[str, float] = {}
|
|
64
|
+
kept: list[dict[str, Any]] = []
|
|
65
|
+
|
|
66
|
+
def agent(name: Any) -> AgentStats:
|
|
67
|
+
key = str(name or "unknown")
|
|
68
|
+
return stats.setdefault(key, AgentStats(key))
|
|
69
|
+
|
|
70
|
+
for entry in entries:
|
|
71
|
+
ts = _ts(entry)
|
|
72
|
+
if ts is None or (since is not None and ts < since):
|
|
73
|
+
continue
|
|
74
|
+
kept.append(entry)
|
|
75
|
+
event = entry.get("event")
|
|
76
|
+
provider = entry.get("provider")
|
|
77
|
+
if event == "session_start":
|
|
78
|
+
agent(provider).sessions += 1
|
|
79
|
+
open_sessions[str(provider)] = ts
|
|
80
|
+
elif event == "session_end":
|
|
81
|
+
started = open_sessions.pop(str(provider), None)
|
|
82
|
+
if started is not None:
|
|
83
|
+
agent(provider).minutes += (ts - started) / 60
|
|
84
|
+
elif event == "checkpoint":
|
|
85
|
+
agent(provider).checkpoints += 1
|
|
86
|
+
elif event == "switch":
|
|
87
|
+
agent(entry.get("from_provider")).handed_over += 1
|
|
88
|
+
agent(entry.get("to_provider")).took_over += 1
|
|
89
|
+
elif event == "rate_limited":
|
|
90
|
+
agent(provider).rate_limited += 1
|
|
91
|
+
return Report(
|
|
92
|
+
label,
|
|
93
|
+
str(kept[0]["ts"]) if kept else None,
|
|
94
|
+
str(kept[-1]["ts"]) if kept else None,
|
|
95
|
+
sorted(stats.values(), key=lambda a: (-a.sessions, a.agent)),
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def render(report: Report) -> str:
|
|
100
|
+
if not report.agents:
|
|
101
|
+
return f"No codebaton activity recorded ({report.since})."
|
|
102
|
+
lines = [
|
|
103
|
+
f"codebaton report · {report.since} · {report.first_event} → {report.last_event}",
|
|
104
|
+
"",
|
|
105
|
+
f"{'agent':<13}{'sessions':>9}{'hours':>8}{'checkpoints':>13}"
|
|
106
|
+
f"{'handed over':>13}{'took over':>11}{'rate-limited':>14}",
|
|
107
|
+
]
|
|
108
|
+
for a in report.agents:
|
|
109
|
+
lines.append(
|
|
110
|
+
f"{a.agent:<13}{a.sessions:>9}{a.minutes / 60:>8.1f}{a.checkpoints:>13}"
|
|
111
|
+
f"{a.handed_over:>13}{a.took_over:>11}{a.rate_limited:>14}"
|
|
112
|
+
)
|
|
113
|
+
lines += ["", f"Hand-overs at a threshold: {report.switches}"]
|
|
114
|
+
return "\n".join(lines)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def to_json(report: Report) -> str:
|
|
118
|
+
data = asdict(report)
|
|
119
|
+
data["switches"] = report.switches
|
|
120
|
+
return json.dumps(data, indent=2)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def to_csv(report: Report) -> str:
|
|
124
|
+
out = io.StringIO()
|
|
125
|
+
names = list(AgentStats.__dataclass_fields__)
|
|
126
|
+
writer = csv.DictWriter(out, fieldnames=names)
|
|
127
|
+
writer.writeheader()
|
|
128
|
+
for a in report.agents:
|
|
129
|
+
writer.writerow(asdict(a))
|
|
130
|
+
return out.getvalue()
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: codebaton
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Keep coding when an AI agent hits its usage limit: opens the real Claude Code, Codex or a local Ollama model, shows usage against your threshold, and hands work over with shared notes and git checkpoints.
|
|
5
|
+
Keywords: claude-code,codex,ollama,ai-agents,coding-agent,cli,rate-limit,failover
|
|
6
|
+
Author: aaajjjj
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Environment :: Console
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: MacOS
|
|
13
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Software Development
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Dist: typer>=0.12
|
|
21
|
+
Requires-Dist: pydantic>=2.6
|
|
22
|
+
Requires-Dist: pyyaml>=6.0
|
|
23
|
+
Requires-Python: >=3.11
|
|
24
|
+
Project-URL: Homepage, https://github.com/aaajjjj/codebaton
|
|
25
|
+
Project-URL: Documentation, https://github.com/aaajjjj/codebaton#readme
|
|
26
|
+
Project-URL: Changelog, https://github.com/aaajjjj/codebaton/blob/main/CHANGELOG.md
|
|
27
|
+
Project-URL: Issues, https://github.com/aaajjjj/codebaton/issues
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# codebaton
|
|
31
|
+
|
|
32
|
+
**See your Claude Code and Codex limits live, and never lose your thread when one runs out.
|
|
33
|
+
No proxy, no API keys: your own subscriptions, the official CLIs.**
|
|
34
|
+
|
|
35
|
+
[](https://github.com/aaajjjj/codebaton/actions/workflows/ci.yml)
|
|
36
|
+
[](https://pypi.org/project/codebaton/)
|
|
37
|
+
[](https://pypi.org/project/codebaton/)
|
|
38
|
+
[](https://github.com/aaajjjj/codebaton/blob/main/LICENSE)
|
|
39
|
+
|
|
40
|
+
You're deep in a task with Claude Code and it says you've used most of your 5-hour limit.
|
|
41
|
+
codebaton sees that coming. It shows each agent's usage against a threshold you choose,
|
|
42
|
+
opens the agent that still has room, and passes the baton: the next agent picks up where the
|
|
43
|
+
last one stopped, using shared notes and git checkpoints.
|
|
44
|
+
|
|
45
|
+
```text
|
|
46
|
+
$ codebaton watch
|
|
47
|
+
agent window usage used status
|
|
48
|
+
claude_code 5h ██████████████│░░░░░ 71% over threshold (threshold 70%) resets in 1h 12m
|
|
49
|
+
claude_code week ████░░░░░░░░░░│░░░░░ 22% ok (threshold 70%) resets in 3d 2h
|
|
50
|
+
codex 5h █░░░░░░░░░│░░░░░░░░░ 6% ok (threshold 50%) resets in 4h 40m
|
|
51
|
+
codex week ░░░░░░░░░░│░░░░░░░░░ 2% ok (threshold 50%) resets in 5d 18h
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
- **No proxy, no API keys.** Your traffic goes straight from the official `claude` and
|
|
55
|
+
`codex` CLIs to their providers, on the subscriptions you already pay for. Nothing sits in
|
|
56
|
+
between, and nothing breaks the providers' terms the way relay proxies can.
|
|
57
|
+
- **Native, not a wrapper.** You get the real CLI, with full speed and every feature.
|
|
58
|
+
codebaton adds a status line and hooks for that session only and never touches your own
|
|
59
|
+
settings.
|
|
60
|
+
- **Real usage numbers.** These are the same percentages `/usage` shows, not token guesses.
|
|
61
|
+
- **Hand-over without a lost thread.** `HANDOFF.md` and `AGENTS.md` carry the goal and
|
|
62
|
+
progress between agents. A git checkpoint is saved after every reply.
|
|
63
|
+
- **Local fallback.** An optional free [Ollama](https://ollama.com) model runs on your
|
|
64
|
+
machine, with a memory check before anything is installed or loaded.
|
|
65
|
+
- **Your logins stay yours.** codebaton never reads, stores or sends credentials. Each CLI
|
|
66
|
+
uses its own sign-in.
|
|
67
|
+
- **Ready for teams.** An organisation policy file locks permissions and approved agents on
|
|
68
|
+
every machine, and `codebaton report` exports usage and hand-overs as JSON or CSV.
|
|
69
|
+
|
|
70
|
+
> Status: **alpha** (0.x). Tested on macOS with Claude Code and Codex CLI. Linux should work;
|
|
71
|
+
> Windows is untested.
|
|
72
|
+
|
|
73
|
+
## How it works
|
|
74
|
+
|
|
75
|
+

|
|
78
|
+
|
|
79
|
+
1. You run `codebaton` in a project.
|
|
80
|
+
2. It reads each agent's usage and recommends the first one under its threshold.
|
|
81
|
+
3. It opens that agent's **real CLI** in your terminal, with session-only hooks attached.
|
|
82
|
+
4. After every reply, a hook saves a git checkpoint and checks usage. Near the threshold the
|
|
83
|
+
agent is asked to update `HANDOFF.md`; over it, you're offered the next agent, which
|
|
84
|
+
starts by reading that file.
|
|
85
|
+
|
|
86
|
+
More detail: [docs/architecture.md](https://github.com/aaajjjj/codebaton/blob/main/docs/architecture.md). Design decisions:
|
|
87
|
+
[docs/decisions.md](https://github.com/aaajjjj/codebaton/blob/main/docs/decisions.md).
|
|
88
|
+
|
|
89
|
+
## Requirements
|
|
90
|
+
|
|
91
|
+
- Python 3.11+
|
|
92
|
+
- At least one agent CLI, installed and signed in:
|
|
93
|
+
[Claude Code](https://code.claude.com/docs) (`claude`) and/or
|
|
94
|
+
[Codex CLI](https://github.com/openai/codex) (`codex`, then `codex login`)
|
|
95
|
+
- git (progress is saved as commits)
|
|
96
|
+
- Optional: [Ollama](https://ollama.com) for a free local model
|
|
97
|
+
|
|
98
|
+
## Install
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
pipx install codebaton # or: uv tool install codebaton
|
|
102
|
+
# or: pip install codebaton
|
|
103
|
+
codebaton --version
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## Quick start
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
cd your-project # any git repository
|
|
110
|
+
codebaton # first run offers to set the project up
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
```text
|
|
114
|
+
claude_code 27.0% used / 50% threshold ok [week 18%, 5h 27%]
|
|
115
|
+
codex 2.0% used / 50% threshold ok [5h 2%, week 0%]
|
|
116
|
+
|
|
117
|
+
Which agent?
|
|
118
|
+
1) claude_code 27.0% used / 50% threshold, under threshold <- recommended
|
|
119
|
+
2) codex 2.0% used / 50% threshold, under threshold
|
|
120
|
+
3) ollama local model llama3.2:1b, chat (answers in seconds, no edits)
|
|
121
|
+
q) quit
|
|
122
|
+
Choose (Enter = recommended):
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Press Enter and you're in the real Claude Code. Work as usual. When you `/exit` above the
|
|
126
|
+
threshold, codebaton asks **"Continue in codex?"**, and Codex starts by reading
|
|
127
|
+
`HANDOFF.md`.
|
|
128
|
+
|
|
129
|
+
## Everyday commands
|
|
130
|
+
|
|
131
|
+
| Command | What it does |
|
|
132
|
+
|---|---|
|
|
133
|
+
| `codebaton` | Show usage, then open the recommended agent |
|
|
134
|
+
| `codebaton use claude` / `codex` / `ollama` | Open a specific agent |
|
|
135
|
+
| `codebaton use claude "fix the login bug"` | Open it with a first message |
|
|
136
|
+
| `codebaton watch` | Live usage bars with reset countdowns for every agent (`--json` for scripts and menu-bar widgets) |
|
|
137
|
+
| `codebaton status [--refresh]` | Usage vs thresholds (`--refresh` makes one tiny Claude call for fresh numbers) |
|
|
138
|
+
| `codebaton report [--since 7d]` | Sessions, hours, checkpoints and hand-overs per agent (`--json`, `--csv`) |
|
|
139
|
+
| `codebaton install-model` | Pick and install a local model: shows its size and the memory it needs, then asks first |
|
|
140
|
+
| `codebaton use ollama --chat` | Local model as a plain chat: answers in seconds, can't edit files |
|
|
141
|
+
| `codebaton run "<task>"` | One task, unattended (scripts, overnight), with model tiers and automatic failover |
|
|
142
|
+
| `codebaton help` | Everyday commands with examples |
|
|
143
|
+
|
|
144
|
+
Options: `--model haiku|sonnet|opus` starts on a tier (Codex uses its matching model);
|
|
145
|
+
`--repo DIR` works on another folder. Inside a session, the agent's own `/model` works as
|
|
146
|
+
usual.
|
|
147
|
+
|
|
148
|
+
## What codebaton adds to a session
|
|
149
|
+
|
|
150
|
+
| | Claude Code | Codex |
|
|
151
|
+
|---|---|---|
|
|
152
|
+
| Live usage | status line: `baton · Claude · 5h 31% · wk 18% / 50% · next: Codex` | Codex's own `/status` |
|
|
153
|
+
| After every reply | git checkpoint if files changed | git checkpoint if files changed |
|
|
154
|
+
| Near the threshold | Claude is asked once to update `HANDOFF.md` | desktop notification |
|
|
155
|
+
| Over the threshold | "Type /exit to continue in Codex" | desktop notification |
|
|
156
|
+
|
|
157
|
+
## Configuration
|
|
158
|
+
|
|
159
|
+
The first run creates these files in your project:
|
|
160
|
+
|
|
161
|
+
| File | Purpose | Commit it? |
|
|
162
|
+
|---|---|---|
|
|
163
|
+
| `router.yaml` | agent order, thresholds, permissions | no (added to `.gitignore`) |
|
|
164
|
+
| `model_routing.yaml` | which tasks go to haiku / sonnet / opus tiers | yes |
|
|
165
|
+
| `AGENTS.md` | project goal and conventions for every agent | yes |
|
|
166
|
+
| `HANDOFF.md` | current state: goal, done, next, open questions | yes |
|
|
167
|
+
| `decisions.log` | one line per decision | yes |
|
|
168
|
+
|
|
169
|
+
```yaml
|
|
170
|
+
# router.yaml
|
|
171
|
+
providers: # preference order: the first one under its threshold wins
|
|
172
|
+
- name: claude_code
|
|
173
|
+
cap_percent: 50 # above 50% used (as /usage shows it), move to the next agent
|
|
174
|
+
- name: codex
|
|
175
|
+
cap_percent: 50
|
|
176
|
+
profile: per_session # overnight | per_session | strict
|
|
177
|
+
warn_margin_percent: 5 # this close to a threshold, ask the agent for a full handoff
|
|
178
|
+
git_checkpoint: true # commit a checkpoint after every agent reply
|
|
179
|
+
allow_web: false # let agents browse / search the web
|
|
180
|
+
allow_push: false # let agents run `git push`
|
|
181
|
+
allow_all_commands: false
|
|
182
|
+
ollama:
|
|
183
|
+
enabled: true
|
|
184
|
+
mode: agent # agent (edits code via Codex) | chat (fast, no edits)
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
The full reference is [examples/router.example.yaml](https://github.com/aaajjjj/codebaton/blob/main/examples/router.example.yaml).
|
|
188
|
+
|
|
189
|
+
**How usage is measured.** Claude reports its 5-hour and weekly usage with every reply.
|
|
190
|
+
Codex writes the same figures to its local session logs. The higher of the two windows
|
|
191
|
+
counts. A rate-limit error marks an agent as exhausted until its window resets.
|
|
192
|
+
|
|
193
|
+
## For teams and organisations
|
|
194
|
+
|
|
195
|
+
**Organisation policy.** IT can deploy one file to every machine (for example with MDM).
|
|
196
|
+
Projects can't loosen it. codebaton reads `$CODEBATON_POLICY` if set, otherwise
|
|
197
|
+
`/etc/codebaton/policy.yaml`:
|
|
198
|
+
|
|
199
|
+
```yaml
|
|
200
|
+
# /etc/codebaton/policy.yaml
|
|
201
|
+
minimum_profile: per_session # projects may be stricter, never looser
|
|
202
|
+
deny: [push, all_commands] # switches no project can turn on (also: web)
|
|
203
|
+
allowed_agents: [claude_code, codex] # e.g. no local models
|
|
204
|
+
require_checkpoints: true
|
|
205
|
+
max_cap_percent: 80 # keep headroom: hand over by 80% at the latest
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Whenever the policy changes a project's settings, codebaton says what it enforced.
|
|
209
|
+
|
|
210
|
+
**Reporting.** `codebaton report --since 30d --json` summarises each repository's audit log
|
|
211
|
+
(`.codebaton/audit.jsonl`): sessions, hours, checkpoints, hand-overs and rate limits per
|
|
212
|
+
agent. Collect the JSON or CSV from many repositories with no server involved.
|
|
213
|
+
|
|
214
|
+
**Why it suits companies:** no proxy and no extra credentials, so no new vendor sees your
|
|
215
|
+
code; the official CLIs keep their own permission prompts and sandboxes; and every routing
|
|
216
|
+
decision is logged locally.
|
|
217
|
+
|
|
218
|
+
## Local models (Ollama)
|
|
219
|
+
|
|
220
|
+
```bash
|
|
221
|
+
codebaton install-model # choose from models that suit your machine's memory
|
|
222
|
+
codebaton use ollama --chat # instant answers, no file edits
|
|
223
|
+
codebaton use ollama # coding agent via Codex's harness (can edit files)
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
Be realistic about speed. Agent mode sends Codex's ~47K-token instructions to the model, so
|
|
227
|
+
on a laptop the **first** reply takes about a minute even with a 1B model. Replies after
|
|
228
|
+
that take seconds. Small models also make mistakes as agents. Chat mode is the quick way to
|
|
229
|
+
confirm local models work. Ollama is started only when you choose it and stopped when you
|
|
230
|
+
exit.
|
|
231
|
+
|
|
232
|
+
## Safety and privacy
|
|
233
|
+
|
|
234
|
+
- **Credentials:** never read or stored. `router.yaml` refuses keys that look like secrets.
|
|
235
|
+
- **Commits:** a checkpoint commits only the files created or changed during the agent's
|
|
236
|
+
turn. Work you already had uncommitted, or staged, when the session opened is left alone,
|
|
237
|
+
unless the agent edits that same file. Checkpoint commits are named
|
|
238
|
+
`chore(codebaton): ...`, hooks such as pre-commit still run, and
|
|
239
|
+
`git_checkpoint: false` turns them off. Unattended `codebaton run` owns the repo and
|
|
240
|
+
commits everything.
|
|
241
|
+
- **Permissions:** in interactive sessions each CLI keeps its own permission prompts. The
|
|
242
|
+
`allow_*` switches mainly affect unattended `codebaton run`, and they're off by
|
|
243
|
+
default.
|
|
244
|
+
- **Outside git:** codebaton warns before setting up a folder that isn't a git repository.
|
|
245
|
+
|
|
246
|
+
Report vulnerabilities privately: see [SECURITY.md](https://github.com/aaajjjj/codebaton/blob/main/SECURITY.md).
|
|
247
|
+
|
|
248
|
+
## Roadmap
|
|
249
|
+
|
|
250
|
+
- [x] **v0.1:** native Claude Code / Codex sessions with usage routing, handoff notes, git
|
|
251
|
+
checkpoints, local models with memory checks
|
|
252
|
+
- [ ] **Milestone 2:** quality gates (tests, lint and an LLM judge after each task; a low
|
|
253
|
+
score moves to a stronger model) and a shared style contract
|
|
254
|
+
- [ ] **Milestone 3:** MCP server, so any MCP client can ask for usage, handoffs and
|
|
255
|
+
checkpoints
|
|
256
|
+
- [ ] A lighter local harness, so small local models can edit code in seconds
|
|
257
|
+
- [x] Live usage monitor (`watch`), team report (`report`), organisation policy
|
|
258
|
+
- [ ] More agents (e.g. Gemini CLI) through the provider plug-in interface
|
|
259
|
+
- [ ] Menu-bar widget and Linux desktop notifications
|
|
260
|
+
|
|
261
|
+
Ideas and votes are welcome in [Issues](https://github.com/aaajjjj/codebaton/issues).
|
|
262
|
+
|
|
263
|
+
## FAQ
|
|
264
|
+
|
|
265
|
+
**Is this a proxy? Does it see my prompts?**
|
|
266
|
+
No. Your terminal talks directly to the agent CLI. codebaton only launches it, reads usage
|
|
267
|
+
numbers and saves checkpoints.
|
|
268
|
+
|
|
269
|
+
**Why not an MCP server?**
|
|
270
|
+
An MCP server runs inside one agent, so it can't switch you to a different agent. The CLI
|
|
271
|
+
does the switching. An MCP server for usage and handoff tools is on the roadmap.
|
|
272
|
+
|
|
273
|
+
**How is this different from claude-code-router or other model proxies?**
|
|
274
|
+
Those send your requests through a proxy to other models or API keys. codebaton never
|
|
275
|
+
touches the traffic: it runs the official CLIs on your own subscriptions, watches the usage
|
|
276
|
+
they report, and hands the work over with shared notes and git checkpoints.
|
|
277
|
+
|
|
278
|
+
**Do I need both Claude Code and Codex?**
|
|
279
|
+
No. With one agent you still get the status line, checkpoints and handoff notes. With Ollama
|
|
280
|
+
you also get a free local fallback.
|
|
281
|
+
|
|
282
|
+
## Contributing
|
|
283
|
+
|
|
284
|
+
Contributions are welcome. Start with [CONTRIBUTING.md](https://github.com/aaajjjj/codebaton/blob/main/CONTRIBUTING.md).
|
|
285
|
+
|
|
286
|
+
```bash
|
|
287
|
+
git clone https://github.com/aaajjjj/codebaton.git
|
|
288
|
+
cd codebaton
|
|
289
|
+
uv sync
|
|
290
|
+
scripts/check.sh # format, lint, type-check and tests, as CI runs them
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
Commit messages follow [Conventional Commits](https://www.conventionalcommits.org)
|
|
294
|
+
(`feat:`, `fix:`, `docs:`, ...). Releases and the changelog are generated from them: see
|
|
295
|
+
[docs/releasing.md](https://github.com/aaajjjj/codebaton/blob/main/docs/releasing.md).
|
|
296
|
+
|
|
297
|
+
## Disclaimer
|
|
298
|
+
|
|
299
|
+
codebaton is an independent project. It isn't affiliated with or endorsed by Anthropic,
|
|
300
|
+
OpenAI or Ollama. Claude, Claude Code, Codex and Ollama are trademarks of their respective
|
|
301
|
+
owners. You're responsible for following each provider's terms of use.
|
|
302
|
+
|
|
303
|
+
## License
|
|
304
|
+
|
|
305
|
+
[MIT](https://github.com/aaajjjj/codebaton/blob/main/LICENSE)
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
codebaton/__init__.py,sha256=rqSWoZlpVk0q8fKmxvrr5CgL7HvEm4GBop9h8uOlUPY,308
|
|
2
|
+
codebaton/cli.py,sha256=Gh4diD7yWMAnMdzQLoIBhHvRF93aDVEpipXqHTg6oMM,34415
|
|
3
|
+
codebaton/config.py,sha256=xdp3WVeViqrsV5A5b93fCae1q15x3iL_HgQg5aYZRRc,12103
|
|
4
|
+
codebaton/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
codebaton/core/audit.py,sha256=1xuLl8QZ9kwjB5t5JxDNz1i86naylmsdki0uXCG9gRc,1451
|
|
6
|
+
codebaton/core/budget.py,sha256=4yxSq-VNnoSfOYOM9JwKWtatVu2iLNWnYLBlZXbxIZ0,4393
|
|
7
|
+
codebaton/core/handoff.py,sha256=tvRFgTKFVlKcszXLFULa64brPn877BxLmXz9r7pMM3E,9677
|
|
8
|
+
codebaton/core/model_routing.py,sha256=6OpAwGosW6qPf3PeCRVLyJmpHfWvJTceShuHDTxkeJ8,7621
|
|
9
|
+
codebaton/core/policy.py,sha256=s8k77zHmYPTV0btNfHG4_ZFY4gUZTWpi3o_gtEcXDFk,3885
|
|
10
|
+
codebaton/core/router.py,sha256=qfzHtS-K7aWgFtWUc1nC-DSGHlqAvoXct0z7CjkkSG0,10661
|
|
11
|
+
codebaton/core/usage_cache.py,sha256=dLwk_ds67pslKmgxcA3vrTnHs33kkAvxNTKbhB4NaJw,3917
|
|
12
|
+
codebaton/discovery.py,sha256=vKVi9KEIKIihxjRSaoif_3Y3HtDyZ_eboq_AwHHMqoI,3250
|
|
13
|
+
codebaton/hooks.py,sha256=_2Q0dCGgJmS_ng6nQtN5UNuG7QRMwXffRrC4-GtrLiE,10264
|
|
14
|
+
codebaton/launcher.py,sha256=ZbYcCOI9fto3yKchNE3ExG84Ff2qGwkNcUPCkfASfz4,8960
|
|
15
|
+
codebaton/local_models.py,sha256=bwkifXumAnvBSADNdS-nfLvjZblgOBjzqzMJb2jyc_4,17074
|
|
16
|
+
codebaton/mcp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
17
|
+
codebaton/mcp/server.py,sha256=cPchbioiErKl4wERdEXtWptjsjxX4JkqGTDFWtRcjvA,408
|
|
18
|
+
codebaton/monitor.py,sha256=KXcz_7X3tM6dgNzHMv-aYz_UHOneGd6juw1945dS8hY,4565
|
|
19
|
+
codebaton/plugins/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
20
|
+
codebaton/plugins/base.py,sha256=lz-WOzElBIa1xqY3xJSmEBToe-kEX5U6-KvjzhsY4rU,2812
|
|
21
|
+
codebaton/plugins/executors/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
22
|
+
codebaton/plugins/executors/local.py,sha256=W8h1Q5Q-yf8dUrljljIKHtMc8KZ5PL1vXJWImoC-OpY,3350
|
|
23
|
+
codebaton/plugins/providers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
24
|
+
codebaton/plugins/providers/_common.py,sha256=xmQptXXs0WB2ZToowdr8aIN42nVnQCmPUAA9CoZ6-sA,1023
|
|
25
|
+
codebaton/plugins/providers/claude_code.py,sha256=TbI3ftTOVi6AN1JduF4qLCpojs_eGjd1QWOZbnX4MbA,5332
|
|
26
|
+
codebaton/plugins/providers/codex.py,sha256=HXMGUpHV_7QCTN2zC1VMtbOMus3jIMC3gNrs_48MdM0,4233
|
|
27
|
+
codebaton/plugins/registry.py,sha256=68I2V-IHuI7ZwO3gDPXYGbwfMOKM2DvkzcESMSGjA0I,3065
|
|
28
|
+
codebaton/plugins/usage/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
29
|
+
codebaton/plugins/usage/cached.py,sha256=-iAGWQgKvZ9BQY3cqMSn_jGdU4zuRROD2N6UDtcz8MA,1906
|
|
30
|
+
codebaton/plugins/usage/codex_logs.py,sha256=iJmsEIyd1Bw3069Egp2nr1fVQr9FE52krhmGnPao8G8,5006
|
|
31
|
+
codebaton/plugins/usage/manual.py,sha256=UHHYAA8-0vG2CGwIAUxBjvl0neYaWF3mIjDAZVCh0lU,1681
|
|
32
|
+
codebaton/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
33
|
+
codebaton/report.py,sha256=9L5nYpMD7ZMfiTBR-_BWrHfTBxLcZT_bsrrlrXIwI0I,4135
|
|
34
|
+
codebaton-0.1.0.dist-info/licenses/LICENSE,sha256=0kbbZZYKPcPzribucd1KHdQ16l8kwt5SzV54yyLYYQ4,1079
|
|
35
|
+
codebaton-0.1.0.dist-info/WHEEL,sha256=wfHFB5CQ4yOA68LQ_ISeFjKJGxj2GfVzMH9QxkYgrCw,81
|
|
36
|
+
codebaton-0.1.0.dist-info/entry_points.txt,sha256=tFyeYWgAFLmXAIOKbJJQTDOGqA7ls4fvMfczuwnfuf0,50
|
|
37
|
+
codebaton-0.1.0.dist-info/METADATA,sha256=iP7MFd9KqRADYksAxjRzXIzheqOsutL07H9d0xfe0gA,14875
|
|
38
|
+
codebaton-0.1.0.dist-info/RECORD,,
|