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/core/router.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"""Router: pick the highest-preference provider still under cap, run it, fail over on rate limits.
|
|
2
|
+
|
|
3
|
+
On every switch the handoff is written first, so the next agent can resume.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import shlex
|
|
9
|
+
from collections.abc import Mapping
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Literal
|
|
13
|
+
|
|
14
|
+
from codebaton.config import TIER_ORDER, ModelRoutingConfig, RouterConfig, Tier
|
|
15
|
+
from codebaton.core.audit import AuditLog
|
|
16
|
+
from codebaton.core.budget import BudgetManager, ProviderUsage
|
|
17
|
+
from codebaton.core.handoff import HandoffStore, Snapshot
|
|
18
|
+
from codebaton.core.model_routing import (
|
|
19
|
+
Classifier,
|
|
20
|
+
TierDecision,
|
|
21
|
+
decide_tier,
|
|
22
|
+
native_model,
|
|
23
|
+
next_tier,
|
|
24
|
+
)
|
|
25
|
+
from codebaton.core.policy import (
|
|
26
|
+
Confirm,
|
|
27
|
+
compile_flags,
|
|
28
|
+
needs_attempt_approval,
|
|
29
|
+
needs_session_approval,
|
|
30
|
+
)
|
|
31
|
+
from codebaton.plugins.base import (
|
|
32
|
+
Executor,
|
|
33
|
+
ProviderAdapter,
|
|
34
|
+
RunContext,
|
|
35
|
+
RunResult,
|
|
36
|
+
RunStatus,
|
|
37
|
+
Task,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
OutcomeStatus = Literal["ok", "no_provider", "error", "denied", "gates_failed"]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def select_provider(usages: list[ProviderUsage], exclude: set[str]) -> ProviderUsage | None:
|
|
44
|
+
"""First provider in preference order that is under its cap and not excluded."""
|
|
45
|
+
for usage in usages:
|
|
46
|
+
if usage.name not in exclude and usage.under_cap:
|
|
47
|
+
return usage
|
|
48
|
+
return None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class RunOutcome:
|
|
53
|
+
status: OutcomeStatus
|
|
54
|
+
message: str
|
|
55
|
+
provider: str | None = None
|
|
56
|
+
tier: Tier | None = None
|
|
57
|
+
attempts: list[str] = field(default_factory=list)
|
|
58
|
+
commit: str | None = None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class Orchestrator:
|
|
62
|
+
def __init__(
|
|
63
|
+
self,
|
|
64
|
+
repo: Path,
|
|
65
|
+
config: RouterConfig,
|
|
66
|
+
routing: ModelRoutingConfig,
|
|
67
|
+
budget: BudgetManager,
|
|
68
|
+
adapters: Mapping[str, ProviderAdapter],
|
|
69
|
+
audit: AuditLog,
|
|
70
|
+
executor: Executor,
|
|
71
|
+
confirm: Confirm,
|
|
72
|
+
classifier: Classifier | None = None,
|
|
73
|
+
) -> None:
|
|
74
|
+
self.repo = repo
|
|
75
|
+
self.config = config
|
|
76
|
+
self.routing = routing
|
|
77
|
+
self.budget = budget
|
|
78
|
+
self.adapters = adapters
|
|
79
|
+
self.audit = audit
|
|
80
|
+
self.executor = executor
|
|
81
|
+
self.confirm = confirm
|
|
82
|
+
self.classifier = classifier
|
|
83
|
+
self.handoff = HandoffStore(repo)
|
|
84
|
+
self._providers = {p.name: p for p in config.providers}
|
|
85
|
+
|
|
86
|
+
# -- helpers ---------------------------------------------------------------------------
|
|
87
|
+
|
|
88
|
+
def _checkpoint(self, message: str) -> str | None:
|
|
89
|
+
if not self.config.git_checkpoint:
|
|
90
|
+
return None
|
|
91
|
+
sha = self.handoff.git_checkpoint(message)
|
|
92
|
+
self.audit.record("checkpoint", message=message, commit=sha)
|
|
93
|
+
return sha
|
|
94
|
+
|
|
95
|
+
def _router_handoff(self, task: str, before: Snapshot, done: str, next_step: str) -> None:
|
|
96
|
+
"""Write the handoff ourselves if the agent did not, and log the decision."""
|
|
97
|
+
handoff_done, decision_done = self.handoff.agent_updated(before)
|
|
98
|
+
if not handoff_done:
|
|
99
|
+
self.handoff.write_handoff(
|
|
100
|
+
goal=task,
|
|
101
|
+
done=[done],
|
|
102
|
+
next_steps=[next_step],
|
|
103
|
+
questions=["Check the working tree / last checkpoint for partial changes."],
|
|
104
|
+
)
|
|
105
|
+
self.audit.record("handoff_written_by_router", reason=done)
|
|
106
|
+
if not decision_done:
|
|
107
|
+
self.handoff.append_decision("codebaton", done)
|
|
108
|
+
|
|
109
|
+
def _run_gates(self) -> tuple[bool, str]:
|
|
110
|
+
for command in self.config.gates:
|
|
111
|
+
result = self.executor.run(shlex.split(command), self.repo, 1800)
|
|
112
|
+
if result.returncode != 0:
|
|
113
|
+
return False, command
|
|
114
|
+
return True, ""
|
|
115
|
+
|
|
116
|
+
# -- main flow -------------------------------------------------------------------------
|
|
117
|
+
|
|
118
|
+
def run(
|
|
119
|
+
self,
|
|
120
|
+
task_text: str,
|
|
121
|
+
*,
|
|
122
|
+
override: str | None = None,
|
|
123
|
+
task_type: str | None = None,
|
|
124
|
+
paths: list[str] | None = None,
|
|
125
|
+
) -> RunOutcome:
|
|
126
|
+
decision: TierDecision = decide_tier(
|
|
127
|
+
task_text,
|
|
128
|
+
self.routing,
|
|
129
|
+
override=override,
|
|
130
|
+
task_type=task_type,
|
|
131
|
+
paths=paths,
|
|
132
|
+
classifier=self.classifier,
|
|
133
|
+
)
|
|
134
|
+
self.audit.record(
|
|
135
|
+
"tier_decision",
|
|
136
|
+
task=task_text,
|
|
137
|
+
tier=decision.tier,
|
|
138
|
+
reason=decision.reason,
|
|
139
|
+
task_type=decision.task_type,
|
|
140
|
+
confidence=decision.confidence,
|
|
141
|
+
)
|
|
142
|
+
profile = self.config.profile
|
|
143
|
+
if needs_session_approval(profile):
|
|
144
|
+
approved = self.confirm(f"Run task with codebaton (profile {profile})?")
|
|
145
|
+
self.audit.record("approval", scope="session", approved=approved)
|
|
146
|
+
if not approved:
|
|
147
|
+
return RunOutcome("denied", "Session not approved; nothing ran.")
|
|
148
|
+
|
|
149
|
+
tier: Tier = decision.tier
|
|
150
|
+
tier_retry_used = False
|
|
151
|
+
rate_limited: set[str] = set()
|
|
152
|
+
attempts: list[str] = []
|
|
153
|
+
|
|
154
|
+
while True:
|
|
155
|
+
usages = self.budget.all_usage()
|
|
156
|
+
choice = select_provider(usages, rate_limited)
|
|
157
|
+
self.audit.record(
|
|
158
|
+
"route",
|
|
159
|
+
usage={
|
|
160
|
+
u.name: {
|
|
161
|
+
"percent": round(u.percent, 1),
|
|
162
|
+
"cap": u.cap_percent,
|
|
163
|
+
"source": u.source,
|
|
164
|
+
"exhausted": u.exhausted,
|
|
165
|
+
}
|
|
166
|
+
for u in usages
|
|
167
|
+
},
|
|
168
|
+
chosen=choice.name if choice else None,
|
|
169
|
+
skipped=[u.name for u in usages if choice is None or u.name != choice.name],
|
|
170
|
+
tier=tier,
|
|
171
|
+
)
|
|
172
|
+
if choice is None:
|
|
173
|
+
msg = "No provider is under its cap; task not run."
|
|
174
|
+
if attempts:
|
|
175
|
+
msg = f"All providers exhausted after: {', '.join(attempts)}."
|
|
176
|
+
self.audit.record("no_provider", attempts=attempts)
|
|
177
|
+
return RunOutcome("no_provider", msg, tier=tier, attempts=attempts)
|
|
178
|
+
|
|
179
|
+
name = choice.name
|
|
180
|
+
if needs_attempt_approval(profile):
|
|
181
|
+
approved = self.confirm(f"Run '{name}' ({tier}) on this task?")
|
|
182
|
+
self.audit.record("approval", scope="attempt", provider=name, approved=approved)
|
|
183
|
+
if not approved:
|
|
184
|
+
return RunOutcome(
|
|
185
|
+
"denied", f"Attempt on {name} not approved.", name, tier, attempts
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
provider = self._providers[name]
|
|
189
|
+
model, effort = native_model(self.routing, provider.adapter_name, tier)
|
|
190
|
+
context = RunContext(
|
|
191
|
+
prompt=self.handoff.build_prompt(task_text, name),
|
|
192
|
+
model=model,
|
|
193
|
+
reasoning_effort=effort,
|
|
194
|
+
permission_args=compile_flags(
|
|
195
|
+
profile,
|
|
196
|
+
provider.adapter_name,
|
|
197
|
+
self.config.allowed_commands,
|
|
198
|
+
allow_web=self.config.allow_web,
|
|
199
|
+
allow_push=self.config.allow_push,
|
|
200
|
+
allow_all_commands=self.config.allow_all_commands,
|
|
201
|
+
),
|
|
202
|
+
timeout_seconds=provider.timeout_seconds,
|
|
203
|
+
)
|
|
204
|
+
before = self.handoff.snapshot()
|
|
205
|
+
self.budget.record_run(name)
|
|
206
|
+
attempts.append(f"{name}:{tier}")
|
|
207
|
+
result: RunResult = self.adapters[name].run(Task(task_text, self.repo), context)
|
|
208
|
+
self.budget.record_usage(name, result.usage)
|
|
209
|
+
self.audit.record(
|
|
210
|
+
"provider_call",
|
|
211
|
+
provider=name,
|
|
212
|
+
model=model or "(cli default)",
|
|
213
|
+
reasoning_effort=effort,
|
|
214
|
+
status=result.status.value,
|
|
215
|
+
argv=result.argv,
|
|
216
|
+
detail=result.detail[-500:],
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
if result.status is RunStatus.RATE_LIMITED:
|
|
220
|
+
until = self.budget.mark_exhausted(name)
|
|
221
|
+
rate_limited.add(name)
|
|
222
|
+
self.audit.record("rate_limited", provider=name, exhausted_until=until)
|
|
223
|
+
self._router_handoff(
|
|
224
|
+
task_text,
|
|
225
|
+
before,
|
|
226
|
+
done=f"{name} hit a rate limit mid-task; switching provider.",
|
|
227
|
+
next_step=f"Resume and finish the task: {task_text}",
|
|
228
|
+
)
|
|
229
|
+
self._checkpoint(f"chore(codebaton): checkpoint, {name} rate-limited")
|
|
230
|
+
continue
|
|
231
|
+
|
|
232
|
+
if result.status is RunStatus.ERROR:
|
|
233
|
+
self._router_handoff(
|
|
234
|
+
task_text,
|
|
235
|
+
before,
|
|
236
|
+
done=f"{name} failed: {result.detail[-200:] or 'non-zero exit'}",
|
|
237
|
+
next_step=f"Investigate the failure, then retry: {task_text}",
|
|
238
|
+
)
|
|
239
|
+
sha = self._checkpoint(f"chore(codebaton): checkpoint, {name} failed")
|
|
240
|
+
return RunOutcome(
|
|
241
|
+
"error", f"{name} failed; see audit log.", name, tier, attempts, sha
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
# OK
|
|
245
|
+
handoff_done, decision_done = self.handoff.agent_updated(before)
|
|
246
|
+
if not (handoff_done and decision_done):
|
|
247
|
+
self.audit.record(
|
|
248
|
+
"agent_skipped_handoff",
|
|
249
|
+
provider=name,
|
|
250
|
+
handoff=handoff_done,
|
|
251
|
+
decisions=decision_done,
|
|
252
|
+
)
|
|
253
|
+
self._router_handoff(
|
|
254
|
+
task_text,
|
|
255
|
+
before,
|
|
256
|
+
done=f"{name} completed the task (agent did not update HANDOFF.md): "
|
|
257
|
+
f"{result.output[-300:]}",
|
|
258
|
+
next_step="Review the change and pick the next task.",
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
gates_ok, failed = self._run_gates()
|
|
262
|
+
if not gates_ok:
|
|
263
|
+
self.audit.record("gate_failed", provider=name, tier=tier, command=failed)
|
|
264
|
+
up = next_tier(tier)
|
|
265
|
+
if up is not None and not tier_retry_used:
|
|
266
|
+
self._checkpoint(f"chore(codebaton): checkpoint, gates failed on {tier}")
|
|
267
|
+
self.audit.record("tier_retry", from_tier=tier, to_tier=up)
|
|
268
|
+
tier, tier_retry_used = up, True
|
|
269
|
+
continue
|
|
270
|
+
sha = self._checkpoint(f"chore(codebaton): {name} ({tier}), gates failed")
|
|
271
|
+
return RunOutcome(
|
|
272
|
+
"gates_failed", f"Gate failed: {failed}", name, tier, attempts, sha
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
sha = self._checkpoint(f"chore(codebaton): {name} ({tier}): {task_text[:60]}")
|
|
276
|
+
return RunOutcome("ok", f"Done by {name} ({tier}).", name, tier, attempts, sha)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
__all__ = ["TIER_ORDER", "Orchestrator", "RunOutcome", "select_provider"]
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Per-user cache of provider-reported usage percentages.
|
|
2
|
+
|
|
3
|
+
Usage is account-wide (not per repo), so the cache lives in ``~/.codebaton/``
|
|
4
|
+
(override with ``CODEBATON_HOME``). Adapters return the usage a provider reports with
|
|
5
|
+
each reply; the router saves it here and usage readers read it back.
|
|
6
|
+
|
|
7
|
+
Claude Code reports usage in its ``-p --output-format stream-json`` output as a
|
|
8
|
+
``rate_limit_event`` whose ``rate_limit_info.unifiedWindows`` holds ``five_hour`` and
|
|
9
|
+
``seven_day`` entries with ``utilization`` (0..1) and ``resetsAt`` (epoch seconds). Verified
|
|
10
|
+
against Claude Code 2.1.334. These are the same numbers ``/usage`` shows.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import time
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from codebaton.plugins.base import UsageWindow
|
|
21
|
+
|
|
22
|
+
LEGACY_HOME = ".agent_router" # name before the project was renamed to codebaton
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def router_home() -> Path:
|
|
26
|
+
if "CODEBATON_HOME" in os.environ:
|
|
27
|
+
return Path(os.environ["CODEBATON_HOME"])
|
|
28
|
+
home = Path.home() / ".codebaton"
|
|
29
|
+
legacy = Path.home() / LEGACY_HOME
|
|
30
|
+
if not home.exists() and legacy.is_dir():
|
|
31
|
+
try:
|
|
32
|
+
legacy.rename(home) # one-time move of the usage cache and model estimates
|
|
33
|
+
except OSError:
|
|
34
|
+
return legacy
|
|
35
|
+
return home
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def default_cache_path() -> Path:
|
|
39
|
+
return router_home() / "usage_cache.json"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class UsageCache:
|
|
43
|
+
def __init__(self, path: Path | None = None) -> None:
|
|
44
|
+
self.path = path or default_cache_path()
|
|
45
|
+
|
|
46
|
+
def _load(self) -> dict[str, dict[str, object]]:
|
|
47
|
+
try:
|
|
48
|
+
data = json.loads(self.path.read_text(encoding="utf-8"))
|
|
49
|
+
except (OSError, json.JSONDecodeError):
|
|
50
|
+
return {}
|
|
51
|
+
return data if isinstance(data, dict) else {}
|
|
52
|
+
|
|
53
|
+
def save(self, provider: str, windows: dict[str, UsageWindow]) -> None:
|
|
54
|
+
if not windows:
|
|
55
|
+
return
|
|
56
|
+
data = self._load()
|
|
57
|
+
data[provider] = {
|
|
58
|
+
"updated_at": time.time(),
|
|
59
|
+
"windows": {
|
|
60
|
+
k: {"percent": w.percent, "resets_at": w.resets_at} for k, w in windows.items()
|
|
61
|
+
},
|
|
62
|
+
}
|
|
63
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
64
|
+
self.path.write_text(json.dumps(data, indent=2), encoding="utf-8")
|
|
65
|
+
|
|
66
|
+
def load(self, provider: str) -> tuple[float, dict[str, UsageWindow]] | None:
|
|
67
|
+
"""Return (updated_at, windows) for a provider, or None if never recorded."""
|
|
68
|
+
entry = self._load().get(provider)
|
|
69
|
+
if not isinstance(entry, dict):
|
|
70
|
+
return None
|
|
71
|
+
raw = entry.get("windows")
|
|
72
|
+
if not isinstance(raw, dict):
|
|
73
|
+
return None
|
|
74
|
+
windows: dict[str, UsageWindow] = {}
|
|
75
|
+
for key, value in raw.items():
|
|
76
|
+
if isinstance(value, dict) and isinstance(value.get("percent"), int | float):
|
|
77
|
+
resets = value.get("resets_at")
|
|
78
|
+
windows[key] = UsageWindow(
|
|
79
|
+
float(value["percent"]),
|
|
80
|
+
float(resets) if isinstance(resets, int | float) else None,
|
|
81
|
+
)
|
|
82
|
+
updated = entry.get("updated_at")
|
|
83
|
+
return (float(updated) if isinstance(updated, int | float) else 0.0), windows
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def claude_windows_from_event(info: object) -> dict[str, UsageWindow]:
|
|
87
|
+
"""Parse ``rate_limit_info`` from a Claude ``rate_limit_event`` into usage windows."""
|
|
88
|
+
if not isinstance(info, dict):
|
|
89
|
+
return {}
|
|
90
|
+
unified = info.get("unifiedWindows")
|
|
91
|
+
if not isinstance(unified, dict):
|
|
92
|
+
return {}
|
|
93
|
+
out: dict[str, UsageWindow] = {}
|
|
94
|
+
for src, dst in (("five_hour", "short"), ("seven_day", "long")):
|
|
95
|
+
win = unified.get(src)
|
|
96
|
+
if isinstance(win, dict) and isinstance(win.get("utilization"), int | float):
|
|
97
|
+
resets = win.get("resetsAt")
|
|
98
|
+
out[dst] = UsageWindow(
|
|
99
|
+
round(float(win["utilization"]) * 100, 1),
|
|
100
|
+
float(resets) if isinstance(resets, int | float) else None,
|
|
101
|
+
)
|
|
102
|
+
return out
|
codebaton/discovery.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Discover the Codex models available to this account, for ``codebaton init``.
|
|
2
|
+
|
|
3
|
+
The Codex CLI caches the account's model list in ``~/.codex/models_cache.json``
|
|
4
|
+
(``models[].slug``, ``visibility``, ``priority``, ``supported_reasoning_levels[].effort``).
|
|
5
|
+
That file does not say which model is "smallest", so the tier -> model mapping is the
|
|
6
|
+
user's choice (decision D-018), checked against what the account actually has. A chosen
|
|
7
|
+
model the account lacks falls back to the highest-priority listed model (go up, never
|
|
8
|
+
down). The result is written to model_routing.yaml, where the user can edit it.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
DEFAULT_CACHE = Path.home() / ".codex" / "models_cache.json"
|
|
18
|
+
|
|
19
|
+
# Codex tier keys mirror Claude's: top = opus, medium = sonnet, light = haiku.
|
|
20
|
+
PREFERRED_CODEX_MODELS: dict[str, str] = {
|
|
21
|
+
"top": "gpt-6.2-astra", # complex coding, architecture, difficult debugging
|
|
22
|
+
"medium": "gpt-6.2-sol", # everyday coding, features, refactoring
|
|
23
|
+
"light": "gpt-6-luna", # small edits, repetitive tasks, cheap automation
|
|
24
|
+
}
|
|
25
|
+
TIER_EFFORT: dict[str, str] = {"light": "low", "medium": "medium", "top": "high"}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class CodexModels:
|
|
30
|
+
slugs: list[str] # visible models, highest priority first
|
|
31
|
+
efforts: dict[str, list[str]]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def discover_codex_models(cache: Path = DEFAULT_CACHE) -> CodexModels | None:
|
|
35
|
+
try:
|
|
36
|
+
data = json.loads(cache.read_text(encoding="utf-8"))
|
|
37
|
+
except (OSError, json.JSONDecodeError):
|
|
38
|
+
return None
|
|
39
|
+
models = data.get("models") if isinstance(data, dict) else None
|
|
40
|
+
if not isinstance(models, list):
|
|
41
|
+
return None
|
|
42
|
+
visible = [
|
|
43
|
+
m
|
|
44
|
+
for m in models
|
|
45
|
+
if isinstance(m, dict) and m.get("slug") and m.get("visibility", "list") == "list"
|
|
46
|
+
]
|
|
47
|
+
visible.sort(key=lambda m: m.get("priority", 1_000))
|
|
48
|
+
if not visible:
|
|
49
|
+
return None
|
|
50
|
+
efforts = {
|
|
51
|
+
m["slug"]: [
|
|
52
|
+
lvl["effort"]
|
|
53
|
+
for lvl in m.get("supported_reasoning_levels", [])
|
|
54
|
+
if isinstance(lvl, dict) and "effort" in lvl
|
|
55
|
+
]
|
|
56
|
+
for m in visible
|
|
57
|
+
}
|
|
58
|
+
return CodexModels([m["slug"] for m in visible], efforts)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def codex_tiers(models: CodexModels | None) -> dict[str, dict[str, str]]:
|
|
62
|
+
if models is None:
|
|
63
|
+
# Empty model = let the Codex CLI use its own configured default.
|
|
64
|
+
return {
|
|
65
|
+
"light": {"model": "", "reasoning_effort": "low"},
|
|
66
|
+
"medium": {"model": "", "reasoning_effort": "medium"},
|
|
67
|
+
"top": {"model": "", "reasoning_effort": "high"},
|
|
68
|
+
}
|
|
69
|
+
fallback = models.slugs[0]
|
|
70
|
+
tiers: dict[str, dict[str, str]] = {}
|
|
71
|
+
for tier, effort_wanted in TIER_EFFORT.items():
|
|
72
|
+
preferred = PREFERRED_CODEX_MODELS[tier]
|
|
73
|
+
# Use the chosen model only if this account actually has it; otherwise go up to the
|
|
74
|
+
# highest-priority model rather than guessing a smaller one.
|
|
75
|
+
model = preferred if preferred in models.slugs else fallback
|
|
76
|
+
supported = models.efforts.get(model) or ["low", "medium", "high"]
|
|
77
|
+
effort = effort_wanted if effort_wanted in supported else supported[-1]
|
|
78
|
+
tiers[tier] = {"model": model, "reasoning_effort": effort}
|
|
79
|
+
return tiers
|