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/hooks.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
"""Hooks the router installs into a native agent session (for that session only).
|
|
2
|
+
|
|
3
|
+
The router opens the real Claude Code / Codex CLI and stays out of the conversation. These
|
|
4
|
+
small commands run inside the session, so routing still works:
|
|
5
|
+
|
|
6
|
+
``statusline`` (Claude Code ``statusLine``)
|
|
7
|
+
Claude pipes session JSON on stdin, including ``rate_limits.five_hour`` /
|
|
8
|
+
``rate_limits.seven_day`` with ``used_percentage`` (0-100) and ``resets_at`` (Unix epoch
|
|
9
|
+
seconds); verified against Claude Code 2.1.334. We save it to the usage cache and print
|
|
10
|
+
one line: usage vs threshold and what happens next.
|
|
11
|
+
|
|
12
|
+
``claude-stop`` (Claude Code ``Stop`` hook, after every reply)
|
|
13
|
+
Git checkpoint if files changed. Near the threshold, once per session, returns
|
|
14
|
+
``{"decision": "block", "reason": ...}`` so Claude brings HANDOFF.md up to date before
|
|
15
|
+
stopping (guarded by ``stop_hook_active`` so it cannot loop). Over the threshold, adds a
|
|
16
|
+
``systemMessage`` telling the user to /exit and continue in the next agent.
|
|
17
|
+
|
|
18
|
+
``codex-notify`` (Codex ``notify`` program, after every turn; JSON is the last argv item)
|
|
19
|
+
Git checkpoint, then reads Codex's usage from its logs and, near/over the threshold,
|
|
20
|
+
shows a desktop notification (Codex has no way to inject text into its own UI).
|
|
21
|
+
|
|
22
|
+
Each command reads ``.codebaton/session.json``, written by the router when it opens the
|
|
23
|
+
session, so hooks stay fast (no config parsing) and know the agent, threshold and next agent.
|
|
24
|
+
Hooks must never break the agent's session: every failure is swallowed.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import json
|
|
30
|
+
import subprocess
|
|
31
|
+
import sys
|
|
32
|
+
from dataclasses import asdict, dataclass
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
from typing import Any
|
|
35
|
+
|
|
36
|
+
from codebaton.core.audit import AuditLog
|
|
37
|
+
from codebaton.core.handoff import HandoffStore
|
|
38
|
+
from codebaton.core.usage_cache import UsageCache
|
|
39
|
+
from codebaton.plugins.base import UsageWindow
|
|
40
|
+
from codebaton.plugins.usage.cached import CachedUsageReader
|
|
41
|
+
from codebaton.plugins.usage.codex_logs import CodexLogsReader
|
|
42
|
+
|
|
43
|
+
SESSION_FILE = "session.json"
|
|
44
|
+
LABELS = {"claude_code": "Claude", "codex": "Codex", "ollama": "Ollama"}
|
|
45
|
+
|
|
46
|
+
WRAP_UP_REASON = (
|
|
47
|
+
"codebaton: you are close to your usage threshold and another agent may take over "
|
|
48
|
+
"after this. Before stopping, bring HANDOFF.md fully up to date (## Goal, ## Done, "
|
|
49
|
+
"## Next, ## Open questions) so a different agent can continue without asking, and "
|
|
50
|
+
"append one line to decisions.log. Then stop."
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class SessionState:
|
|
56
|
+
agent: str
|
|
57
|
+
cap: float
|
|
58
|
+
warn_margin: float
|
|
59
|
+
next_agent: str | None
|
|
60
|
+
git_checkpoint: bool = True
|
|
61
|
+
warned: bool = False # handoff already requested this session
|
|
62
|
+
over_notified: bool = False # "over threshold" already announced (Codex)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def label(name: str | None) -> str:
|
|
66
|
+
return LABELS.get(name or "", name or "none")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def session_path(repo: Path) -> Path:
|
|
70
|
+
return repo / ".codebaton" / SESSION_FILE
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def save_session(repo: Path, state: SessionState) -> None:
|
|
74
|
+
path = session_path(repo)
|
|
75
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
76
|
+
path.write_text(json.dumps(asdict(state)), encoding="utf-8")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def load_session(repo: Path) -> SessionState | None:
|
|
80
|
+
try:
|
|
81
|
+
data = json.loads(session_path(repo).read_text(encoding="utf-8"))
|
|
82
|
+
return SessionState(**data)
|
|
83
|
+
except (OSError, ValueError, TypeError):
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
# -- status line ------------------------------------------------------------------------------
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _windows_from_statusline(data: dict[str, Any]) -> dict[str, UsageWindow]:
|
|
91
|
+
limits = data.get("rate_limits")
|
|
92
|
+
if not isinstance(limits, dict):
|
|
93
|
+
return {}
|
|
94
|
+
out: dict[str, UsageWindow] = {}
|
|
95
|
+
for src, dst in (("five_hour", "short"), ("seven_day", "long")):
|
|
96
|
+
win = limits.get(src)
|
|
97
|
+
if isinstance(win, dict) and isinstance(win.get("used_percentage"), int | float):
|
|
98
|
+
resets = win.get("resets_at")
|
|
99
|
+
out[dst] = UsageWindow(
|
|
100
|
+
float(win["used_percentage"]),
|
|
101
|
+
float(resets) if isinstance(resets, int | float) else None,
|
|
102
|
+
)
|
|
103
|
+
return out
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def statusline(repo: Path, raw: str, cache: UsageCache | None = None) -> str:
|
|
107
|
+
state = load_session(repo)
|
|
108
|
+
if state is None:
|
|
109
|
+
return "codebaton"
|
|
110
|
+
try:
|
|
111
|
+
data = json.loads(raw) if raw.strip() else {}
|
|
112
|
+
except json.JSONDecodeError:
|
|
113
|
+
data = {}
|
|
114
|
+
windows = _windows_from_statusline(data if isinstance(data, dict) else {})
|
|
115
|
+
cache = cache or UsageCache()
|
|
116
|
+
if windows:
|
|
117
|
+
cached = cache.load(state.agent)
|
|
118
|
+
if cached is None or cached[1] != windows: # avoid rewriting on every refresh
|
|
119
|
+
cache.save(state.agent, windows)
|
|
120
|
+
if not windows:
|
|
121
|
+
return f"baton · {label(state.agent)} usage n/a / {state.cap:.0f}%"
|
|
122
|
+
five = windows.get("short")
|
|
123
|
+
week = windows.get("long")
|
|
124
|
+
percent = max(w.percent for w in windows.values())
|
|
125
|
+
parts = [f"baton · {label(state.agent)}"]
|
|
126
|
+
if five:
|
|
127
|
+
parts.append(f"5h {five.percent:.0f}%")
|
|
128
|
+
if week:
|
|
129
|
+
parts.append(f"wk {week.percent:.0f}%")
|
|
130
|
+
text = " · ".join(parts) + f" / {state.cap:.0f}%"
|
|
131
|
+
if percent >= state.cap:
|
|
132
|
+
target = label(state.next_agent) if state.next_agent else "the next agent"
|
|
133
|
+
text += f" · ⚠ over threshold: /exit to continue in {target}"
|
|
134
|
+
elif percent >= state.cap - state.warn_margin:
|
|
135
|
+
text += " · near threshold"
|
|
136
|
+
elif state.next_agent:
|
|
137
|
+
text += f" · next: {label(state.next_agent)}"
|
|
138
|
+
return text
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
# -- Claude Stop hook -----------------------------------------------------------------------
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def claude_stop(repo: Path, raw: str, cache: UsageCache | None = None) -> dict[str, Any]:
|
|
145
|
+
state = load_session(repo)
|
|
146
|
+
if state is None:
|
|
147
|
+
return {}
|
|
148
|
+
try:
|
|
149
|
+
data = json.loads(raw) if raw.strip() else {}
|
|
150
|
+
except json.JSONDecodeError:
|
|
151
|
+
data = {}
|
|
152
|
+
audit = AuditLog(repo / ".codebaton" / "audit.jsonl")
|
|
153
|
+
if state.git_checkpoint:
|
|
154
|
+
sha = HandoffStore(repo).checkpoint_turn(f"chore(codebaton): checkpoint ({state.agent})")
|
|
155
|
+
if sha:
|
|
156
|
+
audit.record("checkpoint", provider=state.agent, commit=sha)
|
|
157
|
+
reading = CachedUsageReader(state.agent, cache or UsageCache()).used(5)
|
|
158
|
+
if reading.percent is None:
|
|
159
|
+
return {}
|
|
160
|
+
out: dict[str, Any] = {}
|
|
161
|
+
already_continuing = isinstance(data, dict) and bool(data.get("stop_hook_active"))
|
|
162
|
+
if (
|
|
163
|
+
reading.percent >= state.cap - state.warn_margin
|
|
164
|
+
and not state.warned
|
|
165
|
+
and not already_continuing
|
|
166
|
+
):
|
|
167
|
+
state.warned = True
|
|
168
|
+
save_session(repo, state)
|
|
169
|
+
audit.record("wrap_up", provider=state.agent, percent=reading.percent)
|
|
170
|
+
out = {"decision": "block", "reason": WRAP_UP_REASON}
|
|
171
|
+
if reading.percent >= state.cap:
|
|
172
|
+
target = label(state.next_agent) if state.next_agent else "another agent"
|
|
173
|
+
out["systemMessage"] = (
|
|
174
|
+
f"codebaton: {label(state.agent)} is at {reading.percent:.0f}% of its "
|
|
175
|
+
f"{state.cap:.0f}% threshold. Type /exit to continue in {target}."
|
|
176
|
+
)
|
|
177
|
+
return out
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
# -- Codex notify -----------------------------------------------------------------------------
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def desktop_notify(message: str) -> None:
|
|
184
|
+
"""Best-effort macOS notification; silently does nothing elsewhere."""
|
|
185
|
+
if sys.platform != "darwin":
|
|
186
|
+
return
|
|
187
|
+
subprocess.run(
|
|
188
|
+
[
|
|
189
|
+
"osascript",
|
|
190
|
+
"-e",
|
|
191
|
+
"on run argv",
|
|
192
|
+
"-e",
|
|
193
|
+
'display notification (item 1 of argv) with title "codebaton"',
|
|
194
|
+
"-e",
|
|
195
|
+
"end run",
|
|
196
|
+
message,
|
|
197
|
+
],
|
|
198
|
+
capture_output=True,
|
|
199
|
+
check=False,
|
|
200
|
+
timeout=5,
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def codex_notify(
|
|
205
|
+
repo: Path,
|
|
206
|
+
payload: str,
|
|
207
|
+
reader: CodexLogsReader | None = None,
|
|
208
|
+
notify: Any = desktop_notify,
|
|
209
|
+
) -> None:
|
|
210
|
+
state = load_session(repo)
|
|
211
|
+
if state is None:
|
|
212
|
+
return
|
|
213
|
+
try:
|
|
214
|
+
event = json.loads(payload) if payload.strip() else {}
|
|
215
|
+
except json.JSONDecodeError:
|
|
216
|
+
event = {}
|
|
217
|
+
if isinstance(event, dict) and event.get("type") not in {None, "agent-turn-complete"}:
|
|
218
|
+
return
|
|
219
|
+
audit = AuditLog(repo / ".codebaton" / "audit.jsonl")
|
|
220
|
+
if state.git_checkpoint:
|
|
221
|
+
sha = HandoffStore(repo).checkpoint_turn(f"chore(codebaton): checkpoint ({state.agent})")
|
|
222
|
+
if sha:
|
|
223
|
+
audit.record("checkpoint", provider=state.agent, commit=sha)
|
|
224
|
+
if state.agent == "ollama":
|
|
225
|
+
return # local model: no usage limits to watch
|
|
226
|
+
reading = (reader or CodexLogsReader()).used(5)
|
|
227
|
+
if reading.percent is None:
|
|
228
|
+
return
|
|
229
|
+
target = label(state.next_agent) if state.next_agent else "another agent"
|
|
230
|
+
if reading.percent >= state.cap and not state.over_notified:
|
|
231
|
+
state.over_notified = state.warned = True
|
|
232
|
+
save_session(repo, state)
|
|
233
|
+
notify(
|
|
234
|
+
f"Codex is at {reading.percent:.0f}% of its {state.cap:.0f}% threshold. Ask it to "
|
|
235
|
+
f"update HANDOFF.md, then /exit to continue in {target}."
|
|
236
|
+
)
|
|
237
|
+
elif reading.percent >= state.cap - state.warn_margin and not state.warned:
|
|
238
|
+
state.warned = True
|
|
239
|
+
save_session(repo, state)
|
|
240
|
+
notify(
|
|
241
|
+
f"Codex is near its threshold ({reading.percent:.0f}% / {state.cap:.0f}%). "
|
|
242
|
+
"Good moment to ask it to update HANDOFF.md."
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
# -- entry point --------------------------------------------------------------------------------
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def main(argv: list[str] | None = None) -> int:
|
|
250
|
+
args = list(sys.argv[1:] if argv is None else argv)
|
|
251
|
+
if len(args) < 2:
|
|
252
|
+
print(
|
|
253
|
+
"usage: python -m codebaton.hooks <statusline|claude-stop|codex-notify> <repo>",
|
|
254
|
+
file=sys.stderr,
|
|
255
|
+
)
|
|
256
|
+
return 2
|
|
257
|
+
command, repo = args[0], Path(args[1])
|
|
258
|
+
try:
|
|
259
|
+
if command == "statusline":
|
|
260
|
+
print(statusline(repo, sys.stdin.read()))
|
|
261
|
+
elif command == "claude-stop":
|
|
262
|
+
out = claude_stop(repo, sys.stdin.read())
|
|
263
|
+
if out:
|
|
264
|
+
print(json.dumps(out))
|
|
265
|
+
elif command == "codex-notify":
|
|
266
|
+
codex_notify(repo, args[2] if len(args) > 2 else "")
|
|
267
|
+
else:
|
|
268
|
+
return 2
|
|
269
|
+
except Exception: # a hook must never break the agent session
|
|
270
|
+
return 0
|
|
271
|
+
return 0
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
if __name__ == "__main__":
|
|
275
|
+
sys.exit(main())
|
codebaton/launcher.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"""Open the real agent CLI with routing attached (the default ``codebaton`` command).
|
|
2
|
+
|
|
3
|
+
The router never sits between you and the agent: it shows usage, picks (or lets you pick)
|
|
4
|
+
an agent, then hands the terminal to that agent's own interactive CLI, so every native
|
|
5
|
+
feature works at native speed. Routing comes from hooks added for that session only:
|
|
6
|
+
|
|
7
|
+
- Claude Code: ``claude --settings <json>`` adds a ``statusLine`` (live usage vs threshold)
|
|
8
|
+
and a ``Stop`` hook (checkpoint, handoff request, threshold warning). ``--append-system-prompt``
|
|
9
|
+
points Claude at AGENTS.md / HANDOFF.md, which Codex reads natively. Verified flags:
|
|
10
|
+
``--settings <file-or-json>``, ``--append-system-prompt``, ``--model``, ``[prompt]``
|
|
11
|
+
(Claude Code 2.1.334). The user's own settings files are not modified.
|
|
12
|
+
- Codex: ``-c notify=[...]`` runs our hook after every turn (``notify`` must be a list;
|
|
13
|
+
verified with codex 0.173.0), plus ``-C``, ``-m``, ``-c model_reasoning_effort``,
|
|
14
|
+
``--search`` and ``[PROMPT]``.
|
|
15
|
+
- Ollama: a local model driven by the Codex CLI's own agent (``codex --oss --local-provider
|
|
16
|
+
ollama -m <model>``, flags verified with codex 0.173.0), so it can read, edit and run code
|
|
17
|
+
like the cloud agents, with the same checkpoint hook. Without Codex installed, falls back to
|
|
18
|
+
``ollama run <model>``, a plain chat.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import json
|
|
24
|
+
import shlex
|
|
25
|
+
import shutil
|
|
26
|
+
import sys
|
|
27
|
+
from collections.abc import Callable
|
|
28
|
+
from dataclasses import dataclass
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
|
|
31
|
+
from codebaton.config import RouterConfig
|
|
32
|
+
from codebaton.core.budget import ProviderUsage
|
|
33
|
+
|
|
34
|
+
INTERACTIVE_BINARIES = {"claude_code": "claude", "codex": "codex"}
|
|
35
|
+
|
|
36
|
+
CLAUDE_CONVENTIONS = (
|
|
37
|
+
"This repository uses shared notes for a multi-agent workflow (managed by codebaton): "
|
|
38
|
+
"AGENTS.md holds the goal and conventions, HANDOFF.md the current state (Goal, Done, Next, "
|
|
39
|
+
"Open questions). Read them before substantial work. After work that changes files, update "
|
|
40
|
+
"HANDOFF.md's Done/Next in a line or two and keep the file short (under ~60 lines; move "
|
|
41
|
+
"old detail to decisions.log); plain questions need no update. Do not make git "
|
|
42
|
+
"commits yourself: codebaton saves a checkpoint after every reply."
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class MenuOption:
|
|
48
|
+
key: str # provider name, or "ollama"
|
|
49
|
+
label: str
|
|
50
|
+
available: bool # binary installed (and, for ollama, a model exists)
|
|
51
|
+
recommended: bool = False
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class OllamaInfo:
|
|
56
|
+
installed: bool
|
|
57
|
+
models: list[str]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def detect_ollama(which: Callable[[str], str | None] | None = None) -> OllamaInfo:
|
|
61
|
+
"""Is Ollama installed, and which models are on disk (works while the server is off)."""
|
|
62
|
+
from codebaton.local_models import installed_models
|
|
63
|
+
|
|
64
|
+
which = which or shutil.which
|
|
65
|
+
if which("ollama") is None:
|
|
66
|
+
return OllamaInfo(False, [])
|
|
67
|
+
return OllamaInfo(True, installed_models())
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def build_menu(
|
|
71
|
+
usages: list[ProviderUsage],
|
|
72
|
+
config: RouterConfig,
|
|
73
|
+
ollama: OllamaInfo,
|
|
74
|
+
which: Callable[[str], str | None] | None = None,
|
|
75
|
+
exclude: set[str] | None = None,
|
|
76
|
+
) -> list[MenuOption]:
|
|
77
|
+
which = which or shutil.which
|
|
78
|
+
exclude = exclude or set()
|
|
79
|
+
options: list[MenuOption] = []
|
|
80
|
+
recommended_set = False
|
|
81
|
+
for u in usages:
|
|
82
|
+
binary = INTERACTIVE_BINARIES.get(u.name, u.name)
|
|
83
|
+
installed = which(binary) is not None
|
|
84
|
+
if u.exhausted:
|
|
85
|
+
state = "rate-limited"
|
|
86
|
+
elif u.under_cap:
|
|
87
|
+
state = "under threshold"
|
|
88
|
+
else:
|
|
89
|
+
state = "over threshold"
|
|
90
|
+
label = (
|
|
91
|
+
f"{u.name:<12} {u.percent:5.1f}% used / {u.cap_percent:.0f}% threshold, {state}"
|
|
92
|
+
f" [{u.note}]"
|
|
93
|
+
)
|
|
94
|
+
if not installed:
|
|
95
|
+
label += f" [not installed: '{binary}' not on PATH]"
|
|
96
|
+
recommend = installed and u.under_cap and not recommended_set and u.name not in exclude
|
|
97
|
+
recommended_set = recommended_set or recommend
|
|
98
|
+
options.append(MenuOption(u.name, label, installed, recommend))
|
|
99
|
+
if config.ollama is not None and config.ollama.enabled:
|
|
100
|
+
model = config.ollama.model or (ollama.models[0] if ollama.models else None)
|
|
101
|
+
if not ollama.installed:
|
|
102
|
+
label, ok = "ollama [not installed: 'ollama' not on PATH]", False
|
|
103
|
+
elif model is None:
|
|
104
|
+
label, ok = "ollama [no local model yet: run 'codebaton install-model']", False
|
|
105
|
+
elif not _downloaded(model, ollama.models):
|
|
106
|
+
label, ok = (
|
|
107
|
+
f"ollama [{model} not installed: run 'codebaton install-model']",
|
|
108
|
+
False,
|
|
109
|
+
)
|
|
110
|
+
elif config.ollama.mode == "chat":
|
|
111
|
+
label, ok = (
|
|
112
|
+
f"ollama local model {model}, chat (answers in seconds, no edits)",
|
|
113
|
+
True,
|
|
114
|
+
)
|
|
115
|
+
elif which("codex") is not None:
|
|
116
|
+
label, ok = (
|
|
117
|
+
f"ollama local model {model} via Codex (edits code; first reply ~1 min)",
|
|
118
|
+
True,
|
|
119
|
+
)
|
|
120
|
+
else:
|
|
121
|
+
label, ok = f"ollama local model {model}, free (chat only: install codex)", True
|
|
122
|
+
recommend = ok and not recommended_set
|
|
123
|
+
options.append(MenuOption("ollama", label, ok, recommend))
|
|
124
|
+
return options
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _downloaded(model: str, models: list[str]) -> bool:
|
|
128
|
+
"""`ollama list` shows "name:tag"; a bare name means ":latest"."""
|
|
129
|
+
wanted = model if ":" in model else f"{model}:latest"
|
|
130
|
+
return wanted in models or model in models
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def next_agent(
|
|
134
|
+
usages: list[ProviderUsage],
|
|
135
|
+
current: str,
|
|
136
|
+
which: Callable[[str], str | None] | None = None,
|
|
137
|
+
) -> str | None:
|
|
138
|
+
"""First other installed agent under its threshold, in router.yaml order."""
|
|
139
|
+
which = which or shutil.which
|
|
140
|
+
for u in usages:
|
|
141
|
+
if u.name == current or not u.under_cap:
|
|
142
|
+
continue
|
|
143
|
+
if which(INTERACTIVE_BINARIES.get(u.name, u.name)) is not None:
|
|
144
|
+
return u.name
|
|
145
|
+
return None
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def session_prompt(task: str | None, takeover_from: str | None) -> str:
|
|
149
|
+
"""First message for a session. Empty for a fresh start, so the CLI opens instantly."""
|
|
150
|
+
if takeover_from:
|
|
151
|
+
text = (
|
|
152
|
+
f"You are taking over this project from {takeover_from}, which reached its usage "
|
|
153
|
+
"threshold. Read HANDOFF.md (and AGENTS.md if present) and continue where it left "
|
|
154
|
+
"off. Start with a two-line summary of where things stand."
|
|
155
|
+
)
|
|
156
|
+
return f"{text} Then: {task}" if task else text
|
|
157
|
+
return task or ""
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def hook_command(python: str, *args: str) -> str:
|
|
161
|
+
return " ".join(shlex.quote(a) for a in [python, "-m", "codebaton.hooks", *args])
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def claude_settings(repo: Path, python: str) -> dict[str, object]:
|
|
165
|
+
return {
|
|
166
|
+
"statusLine": {"type": "command", "command": hook_command(python, "statusline", str(repo))},
|
|
167
|
+
"hooks": {
|
|
168
|
+
"Stop": [
|
|
169
|
+
{
|
|
170
|
+
"hooks": [
|
|
171
|
+
{
|
|
172
|
+
"type": "command",
|
|
173
|
+
"command": hook_command(python, "claude-stop", str(repo)),
|
|
174
|
+
}
|
|
175
|
+
]
|
|
176
|
+
}
|
|
177
|
+
]
|
|
178
|
+
},
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def launch_argv(
|
|
183
|
+
key: str,
|
|
184
|
+
prompt: str,
|
|
185
|
+
config: RouterConfig,
|
|
186
|
+
ollama: OllamaInfo,
|
|
187
|
+
repo: Path,
|
|
188
|
+
*,
|
|
189
|
+
model: str = "",
|
|
190
|
+
reasoning_effort: str | None = None,
|
|
191
|
+
python: str = sys.executable,
|
|
192
|
+
ollama_via_codex: bool = False,
|
|
193
|
+
) -> list[str]:
|
|
194
|
+
if key == "claude_code":
|
|
195
|
+
argv = [
|
|
196
|
+
"claude",
|
|
197
|
+
"--settings",
|
|
198
|
+
json.dumps(claude_settings(repo, python)),
|
|
199
|
+
"--append-system-prompt",
|
|
200
|
+
CLAUDE_CONVENTIONS,
|
|
201
|
+
]
|
|
202
|
+
if model:
|
|
203
|
+
argv += ["--model", model]
|
|
204
|
+
return [*argv, prompt] if prompt else argv
|
|
205
|
+
if key == "codex":
|
|
206
|
+
argv = ["codex", "-C", str(repo)]
|
|
207
|
+
if config.allow_web:
|
|
208
|
+
argv.append("--search")
|
|
209
|
+
if model:
|
|
210
|
+
argv += ["-m", model]
|
|
211
|
+
if reasoning_effort:
|
|
212
|
+
argv += ["-c", f'model_reasoning_effort="{reasoning_effort}"']
|
|
213
|
+
notify = [python, "-m", "codebaton.hooks", "codex-notify", str(repo)]
|
|
214
|
+
argv += ["-c", f"notify={json.dumps(notify)}"] # a JSON string list is valid TOML
|
|
215
|
+
return [*argv, prompt] if prompt else argv
|
|
216
|
+
if key == "ollama":
|
|
217
|
+
chosen = (config.ollama.model if config.ollama else None) or (
|
|
218
|
+
ollama.models[0] if ollama.models else ""
|
|
219
|
+
)
|
|
220
|
+
if not ollama_via_codex:
|
|
221
|
+
return ["ollama", "run", chosen]
|
|
222
|
+
notify = [python, "-m", "codebaton.hooks", "codex-notify", str(repo)]
|
|
223
|
+
argv = [
|
|
224
|
+
"codex",
|
|
225
|
+
"--oss",
|
|
226
|
+
"--local-provider",
|
|
227
|
+
"ollama",
|
|
228
|
+
"-m",
|
|
229
|
+
chosen,
|
|
230
|
+
"-C",
|
|
231
|
+
str(repo),
|
|
232
|
+
"-c",
|
|
233
|
+
f"notify={json.dumps(notify)}",
|
|
234
|
+
]
|
|
235
|
+
return [*argv, prompt] if prompt else argv
|
|
236
|
+
raise ValueError(f"no interactive launcher for '{key}'")
|