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,112 @@
|
|
|
1
|
+
"""Plug-in interfaces. Every outer layer sits behind one of these Protocols.
|
|
2
|
+
|
|
3
|
+
New providers, usage readers, executors or notifiers implement a Protocol and are named
|
|
4
|
+
in router.yaml (built-in name or ``module:Class``); the core never changes.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from enum import StrEnum
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Protocol, runtime_checkable
|
|
14
|
+
|
|
15
|
+
# Receives one human-readable progress line (e.g. "Write index.html") while an agent works.
|
|
16
|
+
ProgressCallback = Callable[[str], None]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class RunStatus(StrEnum):
|
|
20
|
+
OK = "ok"
|
|
21
|
+
RATE_LIMITED = "rate_limited"
|
|
22
|
+
ERROR = "error"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class ExecResult:
|
|
27
|
+
returncode: int
|
|
28
|
+
stdout: str
|
|
29
|
+
stderr: str
|
|
30
|
+
timed_out: bool = False
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class Task:
|
|
35
|
+
text: str
|
|
36
|
+
repo: Path
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class UsageWindow:
|
|
41
|
+
"""One provider-reported usage window, e.g. Claude's five_hour or Codex's primary."""
|
|
42
|
+
|
|
43
|
+
percent: float
|
|
44
|
+
resets_at: float | None = None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class RunContext:
|
|
49
|
+
"""Everything an adapter needs besides the task itself."""
|
|
50
|
+
|
|
51
|
+
prompt: str
|
|
52
|
+
model: str
|
|
53
|
+
reasoning_effort: str | None
|
|
54
|
+
permission_args: list[str]
|
|
55
|
+
timeout_seconds: int
|
|
56
|
+
resume_session: str | None = None # continue this conversation instead of a new one
|
|
57
|
+
on_progress: ProgressCallback | None = None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True)
|
|
61
|
+
class RunResult:
|
|
62
|
+
status: RunStatus
|
|
63
|
+
output: str
|
|
64
|
+
detail: str = ""
|
|
65
|
+
argv: list[str] = field(default_factory=list)
|
|
66
|
+
session_id: str | None = None # pass back as resume_session to continue
|
|
67
|
+
# Usage the provider reported with this reply, keyed "short" (5 h) / "long" (weekly).
|
|
68
|
+
usage: dict[str, UsageWindow] = field(default_factory=dict)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(frozen=True)
|
|
72
|
+
class UsageReading:
|
|
73
|
+
"""Percent of the provider's budget used in the current window.
|
|
74
|
+
|
|
75
|
+
``percent`` is None when the reader cannot tell; the budget manager then falls
|
|
76
|
+
back to the manual counter and says so.
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
percent: float | None
|
|
80
|
+
source: str
|
|
81
|
+
note: str = ""
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@runtime_checkable
|
|
85
|
+
class Executor(Protocol):
|
|
86
|
+
"""Where an agent process runs (local process now; Docker sandbox later)."""
|
|
87
|
+
|
|
88
|
+
def run(
|
|
89
|
+
self,
|
|
90
|
+
argv: list[str],
|
|
91
|
+
cwd: Path,
|
|
92
|
+
timeout_seconds: int,
|
|
93
|
+
stdin: str | None = None,
|
|
94
|
+
on_line: Callable[[str], None] | None = None,
|
|
95
|
+
) -> ExecResult: ...
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@runtime_checkable
|
|
99
|
+
class ProviderAdapter(Protocol):
|
|
100
|
+
name: str
|
|
101
|
+
|
|
102
|
+
def run(self, task: Task, context: RunContext) -> RunResult: ...
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@runtime_checkable
|
|
106
|
+
class UsageReader(Protocol):
|
|
107
|
+
def used(self, window_hours: float) -> UsageReading: ...
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@runtime_checkable
|
|
111
|
+
class Notifier(Protocol):
|
|
112
|
+
def send(self, alert: str) -> None: ...
|
|
File without changes
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Run an agent as a local child process, rooted in the repo directory."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import subprocess
|
|
7
|
+
import threading
|
|
8
|
+
from collections.abc import Callable
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from codebaton.plugins.base import ExecResult
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class LocalExecutor:
|
|
15
|
+
def run(
|
|
16
|
+
self,
|
|
17
|
+
argv: list[str],
|
|
18
|
+
cwd: Path,
|
|
19
|
+
timeout_seconds: int,
|
|
20
|
+
stdin: str | None = None,
|
|
21
|
+
on_line: Callable[[str], None] | None = None,
|
|
22
|
+
) -> ExecResult:
|
|
23
|
+
if on_line is None:
|
|
24
|
+
return self._run_captured(argv, cwd, timeout_seconds, stdin)
|
|
25
|
+
return self._run_streaming(argv, cwd, timeout_seconds, stdin, on_line)
|
|
26
|
+
|
|
27
|
+
def _run_captured(
|
|
28
|
+
self, argv: list[str], cwd: Path, timeout_seconds: int, stdin: str | None
|
|
29
|
+
) -> ExecResult:
|
|
30
|
+
try:
|
|
31
|
+
proc = subprocess.run(
|
|
32
|
+
argv,
|
|
33
|
+
cwd=cwd,
|
|
34
|
+
input=stdin,
|
|
35
|
+
capture_output=True,
|
|
36
|
+
text=True,
|
|
37
|
+
timeout=timeout_seconds,
|
|
38
|
+
check=False,
|
|
39
|
+
)
|
|
40
|
+
except FileNotFoundError:
|
|
41
|
+
return ExecResult(127, "", f"executable not found: {argv[0]}")
|
|
42
|
+
except subprocess.TimeoutExpired as exc:
|
|
43
|
+
out = exc.stdout if isinstance(exc.stdout, str) else ""
|
|
44
|
+
err = exc.stderr if isinstance(exc.stderr, str) else ""
|
|
45
|
+
return ExecResult(124, out, err, timed_out=True)
|
|
46
|
+
return ExecResult(proc.returncode, proc.stdout, proc.stderr)
|
|
47
|
+
|
|
48
|
+
def _run_streaming(
|
|
49
|
+
self,
|
|
50
|
+
argv: list[str],
|
|
51
|
+
cwd: Path,
|
|
52
|
+
timeout_seconds: int,
|
|
53
|
+
stdin: str | None,
|
|
54
|
+
on_line: Callable[[str], None],
|
|
55
|
+
) -> ExecResult:
|
|
56
|
+
"""Like _run_captured, but hands each stdout line to ``on_line`` as it arrives."""
|
|
57
|
+
try:
|
|
58
|
+
proc = subprocess.Popen(
|
|
59
|
+
argv,
|
|
60
|
+
cwd=cwd,
|
|
61
|
+
stdin=subprocess.PIPE,
|
|
62
|
+
stdout=subprocess.PIPE,
|
|
63
|
+
stderr=subprocess.PIPE,
|
|
64
|
+
text=True,
|
|
65
|
+
bufsize=1,
|
|
66
|
+
)
|
|
67
|
+
except FileNotFoundError:
|
|
68
|
+
return ExecResult(127, "", f"executable not found: {argv[0]}")
|
|
69
|
+
timed_out = threading.Event()
|
|
70
|
+
|
|
71
|
+
def kill() -> None:
|
|
72
|
+
timed_out.set()
|
|
73
|
+
proc.kill()
|
|
74
|
+
|
|
75
|
+
timer = threading.Timer(timeout_seconds, kill)
|
|
76
|
+
timer.start()
|
|
77
|
+
err_chunks: list[str] = []
|
|
78
|
+
err_thread = threading.Thread(
|
|
79
|
+
target=lambda: err_chunks.append(proc.stderr.read() if proc.stderr else ""),
|
|
80
|
+
daemon=True,
|
|
81
|
+
)
|
|
82
|
+
err_thread.start()
|
|
83
|
+
out_lines: list[str] = []
|
|
84
|
+
try:
|
|
85
|
+
if proc.stdin:
|
|
86
|
+
proc.stdin.write(stdin or "")
|
|
87
|
+
proc.stdin.close()
|
|
88
|
+
assert proc.stdout is not None # noqa: S101 - set by PIPE above
|
|
89
|
+
for line in proc.stdout:
|
|
90
|
+
out_lines.append(line)
|
|
91
|
+
# A display bug must never kill the agent run.
|
|
92
|
+
with contextlib.suppress(Exception):
|
|
93
|
+
on_line(line.rstrip("\n"))
|
|
94
|
+
proc.wait()
|
|
95
|
+
finally:
|
|
96
|
+
timer.cancel()
|
|
97
|
+
err_thread.join(timeout=5)
|
|
98
|
+
code = 124 if timed_out.is_set() else proc.returncode
|
|
99
|
+
return ExecResult(code, "".join(out_lines), "".join(err_chunks), timed_out.is_set())
|
|
File without changes
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Helpers shared by provider adapters."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
from codebaton.plugins.base import ExecResult, RunStatus
|
|
8
|
+
|
|
9
|
+
# Phrases the official CLIs print when a subscription window or API rate limit is hit.
|
|
10
|
+
# Matching is deliberately broad: a false positive only causes a failover, which is safe.
|
|
11
|
+
RATE_LIMIT_PATTERNS = re.compile(
|
|
12
|
+
r"(rate[ _-]?limit|usage limit|limit reached|too many requests|\b429\b|"
|
|
13
|
+
r"quota exceeded|out of credits|rate_limit_reached)",
|
|
14
|
+
re.IGNORECASE,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def classify(result: ExecResult, *, rate_limited_hint: bool = False) -> RunStatus:
|
|
19
|
+
if rate_limited_hint:
|
|
20
|
+
return RunStatus.RATE_LIMITED
|
|
21
|
+
if result.returncode == 0 and not result.timed_out:
|
|
22
|
+
return RunStatus.OK
|
|
23
|
+
if RATE_LIMIT_PATTERNS.search(result.stdout) or RATE_LIMIT_PATTERNS.search(result.stderr):
|
|
24
|
+
return RunStatus.RATE_LIMITED
|
|
25
|
+
return RunStatus.ERROR
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def tail(text: str, limit: int = 2000) -> str:
|
|
29
|
+
return text if len(text) <= limit else "..." + text[-limit:]
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""Claude Code adapter: ``claude -p`` headless mode with streaming JSON output.
|
|
2
|
+
|
|
3
|
+
Flags verified against ``claude --help`` (Claude Code 2.1.334):
|
|
4
|
+
``-p/--print``, ``--output-format stream-json`` (requires ``--verbose`` with ``-p``),
|
|
5
|
+
``--model <alias|name>``, ``-r/--resume <session id>``,
|
|
6
|
+
``--permission-mode {acceptEdits,auto,bypassPermissions,manual,dontAsk,plan}``,
|
|
7
|
+
``--allowedTools``, ``--disallowedTools``. The prompt is sent on stdin.
|
|
8
|
+
|
|
9
|
+
Events used (one JSON object per line):
|
|
10
|
+
- ``{"type": "assistant", "message": {"content": [{"type": "text"|"tool_use", ...}]}}``
|
|
11
|
+
- ``{"type": "rate_limit_event", "rate_limit_info": {... "unifiedWindows": {...}}}``:
|
|
12
|
+
real account usage, see ``core/usage_cache.py``.
|
|
13
|
+
- ``{"type": "result", "is_error": bool, "result": str, "session_id": str, ...}``
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from codebaton.core.usage_cache import claude_windows_from_event
|
|
22
|
+
from codebaton.plugins.base import (
|
|
23
|
+
Executor,
|
|
24
|
+
ProgressCallback,
|
|
25
|
+
RunContext,
|
|
26
|
+
RunResult,
|
|
27
|
+
RunStatus,
|
|
28
|
+
Task,
|
|
29
|
+
UsageWindow,
|
|
30
|
+
)
|
|
31
|
+
from codebaton.plugins.providers._common import RATE_LIMIT_PATTERNS, classify, tail
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ClaudeCodeAdapter:
|
|
35
|
+
name = "claude_code"
|
|
36
|
+
binary = "claude"
|
|
37
|
+
|
|
38
|
+
def __init__(self, executor: Executor) -> None:
|
|
39
|
+
self.executor = executor
|
|
40
|
+
|
|
41
|
+
def build_argv(self, context: RunContext) -> list[str]:
|
|
42
|
+
argv = [self.binary, "-p", "--output-format", "stream-json", "--verbose"]
|
|
43
|
+
if context.resume_session:
|
|
44
|
+
argv += ["--resume", context.resume_session]
|
|
45
|
+
if context.model:
|
|
46
|
+
argv += ["--model", context.model]
|
|
47
|
+
return [*argv, *context.permission_args]
|
|
48
|
+
|
|
49
|
+
def run(self, task: Task, context: RunContext) -> RunResult:
|
|
50
|
+
argv = self.build_argv(context)
|
|
51
|
+
state = _StreamState(context.on_progress, str(task.repo))
|
|
52
|
+
result = self.executor.run(
|
|
53
|
+
argv,
|
|
54
|
+
task.repo,
|
|
55
|
+
context.timeout_seconds,
|
|
56
|
+
stdin=context.prompt,
|
|
57
|
+
on_line=state.feed if context.on_progress else None,
|
|
58
|
+
)
|
|
59
|
+
if not context.on_progress: # not streamed: parse the captured output now
|
|
60
|
+
for line in result.stdout.splitlines():
|
|
61
|
+
state.feed(line)
|
|
62
|
+
|
|
63
|
+
hint = state.rejected
|
|
64
|
+
if state.final is not None:
|
|
65
|
+
output = str(state.final.get("result", ""))
|
|
66
|
+
if state.final.get("is_error") and RATE_LIMIT_PATTERNS.search(output):
|
|
67
|
+
hint = True
|
|
68
|
+
elif state.final.get("is_error") and result.returncode == 0 and not hint:
|
|
69
|
+
return RunResult(
|
|
70
|
+
RunStatus.ERROR,
|
|
71
|
+
output,
|
|
72
|
+
"agent reported is_error",
|
|
73
|
+
argv,
|
|
74
|
+
state.session_id,
|
|
75
|
+
state.usage,
|
|
76
|
+
)
|
|
77
|
+
else:
|
|
78
|
+
output = state.last_text or tail(result.stdout)
|
|
79
|
+
status = classify(result, rate_limited_hint=hint)
|
|
80
|
+
return RunResult(status, output, tail(result.stderr), argv, state.session_id, state.usage)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class _StreamState:
|
|
84
|
+
def __init__(self, on_progress: ProgressCallback | None, repo: str = "") -> None:
|
|
85
|
+
self.on_progress = on_progress
|
|
86
|
+
self.repo = repo.rstrip("/") + "/" if repo else ""
|
|
87
|
+
self.final: dict[str, Any] | None = None
|
|
88
|
+
self.session_id: str | None = None
|
|
89
|
+
self.usage: dict[str, UsageWindow] = {}
|
|
90
|
+
self.last_text = ""
|
|
91
|
+
self.rejected = False
|
|
92
|
+
|
|
93
|
+
def _say(self, line: str) -> None:
|
|
94
|
+
if self.on_progress:
|
|
95
|
+
self.on_progress(line)
|
|
96
|
+
|
|
97
|
+
def feed(self, line: str) -> None:
|
|
98
|
+
try:
|
|
99
|
+
event = json.loads(line)
|
|
100
|
+
except json.JSONDecodeError:
|
|
101
|
+
return
|
|
102
|
+
if not isinstance(event, dict):
|
|
103
|
+
return
|
|
104
|
+
kind = event.get("type")
|
|
105
|
+
if isinstance(event.get("session_id"), str):
|
|
106
|
+
self.session_id = event["session_id"]
|
|
107
|
+
if kind == "rate_limit_event":
|
|
108
|
+
info = event.get("rate_limit_info")
|
|
109
|
+
self.usage = claude_windows_from_event(info) or self.usage
|
|
110
|
+
if isinstance(info, dict) and info.get("status") == "rejected":
|
|
111
|
+
self.rejected = True
|
|
112
|
+
elif kind == "assistant":
|
|
113
|
+
message = event.get("message")
|
|
114
|
+
content = message.get("content") if isinstance(message, dict) else None
|
|
115
|
+
for block in content if isinstance(content, list) else []:
|
|
116
|
+
if not isinstance(block, dict):
|
|
117
|
+
continue
|
|
118
|
+
if block.get("type") == "text" and block.get("text"):
|
|
119
|
+
self.last_text = str(block["text"])
|
|
120
|
+
elif block.get("type") == "tool_use":
|
|
121
|
+
self._say(
|
|
122
|
+
_describe_tool(block).replace(self.repo, "")
|
|
123
|
+
if self.repo
|
|
124
|
+
else _describe_tool(block)
|
|
125
|
+
)
|
|
126
|
+
elif kind == "result":
|
|
127
|
+
self.final = event
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _describe_tool(block: dict[str, Any]) -> str:
|
|
131
|
+
name = str(block.get("name", "tool"))
|
|
132
|
+
args = block.get("input") if isinstance(block.get("input"), dict) else {}
|
|
133
|
+
assert isinstance(args, dict) # noqa: S101 - narrowed above
|
|
134
|
+
target = args.get("file_path") or args.get("command") or args.get("pattern") or args.get("url")
|
|
135
|
+
return f"{name} {str(target)[:100]}" if target else name
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Codex CLI adapter: ``codex exec`` non-interactive mode.
|
|
2
|
+
|
|
3
|
+
Verified against codex-cli 0.173.0:
|
|
4
|
+
- ``codex exec [OPTIONS] -`` and ``codex exec resume <SESSION_ID> -`` (``-`` = prompt on
|
|
5
|
+
stdin). ``resume`` does not accept ``-s``/``-C``, so permissions are passed as ``-c``
|
|
6
|
+
config overrides (``sandbox_mode``, ``approval_policy``, ...) which both forms accept,
|
|
7
|
+
and the working directory is set by running the process in the repo.
|
|
8
|
+
- ``--json`` prints JSONL events: ``{"type": "thread.started", "thread_id": ...}``,
|
|
9
|
+
``{"type": "item.completed", "item": {"type": "agent_message", "text": ...}}``,
|
|
10
|
+
``{"type": "turn.completed", "usage": {...tokens...}}``. Account usage percentages are
|
|
11
|
+
not in this stream; they are read from Codex's session logs (``usage/codex_logs.py``).
|
|
12
|
+
- ``-m/--model`` and ``-c model_reasoning_effort="..."``.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from codebaton.plugins.base import Executor, ProgressCallback, RunContext, RunResult, Task
|
|
21
|
+
from codebaton.plugins.providers._common import classify, tail
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class CodexAdapter:
|
|
25
|
+
name = "codex"
|
|
26
|
+
binary = "codex"
|
|
27
|
+
|
|
28
|
+
def __init__(self, executor: Executor) -> None:
|
|
29
|
+
self.executor = executor
|
|
30
|
+
|
|
31
|
+
def build_argv(self, task: Task, context: RunContext) -> list[str]:
|
|
32
|
+
argv = [self.binary, "exec"]
|
|
33
|
+
if context.resume_session:
|
|
34
|
+
argv += ["resume", context.resume_session]
|
|
35
|
+
argv += ["--json", "--skip-git-repo-check"]
|
|
36
|
+
if context.model:
|
|
37
|
+
argv += ["-m", context.model]
|
|
38
|
+
if context.reasoning_effort:
|
|
39
|
+
argv += ["-c", f'model_reasoning_effort="{context.reasoning_effort}"']
|
|
40
|
+
return [*argv, *context.permission_args, "-"]
|
|
41
|
+
|
|
42
|
+
def run(self, task: Task, context: RunContext) -> RunResult:
|
|
43
|
+
argv = self.build_argv(task, context)
|
|
44
|
+
state = _EventState(context.on_progress)
|
|
45
|
+
result = self.executor.run(
|
|
46
|
+
argv,
|
|
47
|
+
task.repo,
|
|
48
|
+
context.timeout_seconds,
|
|
49
|
+
stdin=context.prompt,
|
|
50
|
+
on_line=state.feed if context.on_progress else None,
|
|
51
|
+
)
|
|
52
|
+
if not context.on_progress:
|
|
53
|
+
for line in result.stdout.splitlines():
|
|
54
|
+
state.feed(line)
|
|
55
|
+
status = classify(result, rate_limited_hint=state.limited)
|
|
56
|
+
return RunResult(
|
|
57
|
+
status,
|
|
58
|
+
state.last_message or tail(result.stdout),
|
|
59
|
+
tail(result.stderr),
|
|
60
|
+
argv,
|
|
61
|
+
state.thread_id,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class _EventState:
|
|
66
|
+
def __init__(self, on_progress: ProgressCallback | None) -> None:
|
|
67
|
+
self.on_progress = on_progress
|
|
68
|
+
self.last_message = ""
|
|
69
|
+
self.thread_id: str | None = None
|
|
70
|
+
self.limited = False
|
|
71
|
+
|
|
72
|
+
def feed(self, line: str) -> None:
|
|
73
|
+
try:
|
|
74
|
+
event = json.loads(line)
|
|
75
|
+
except json.JSONDecodeError:
|
|
76
|
+
return
|
|
77
|
+
if not isinstance(event, dict):
|
|
78
|
+
return
|
|
79
|
+
if isinstance(event.get("thread_id"), str):
|
|
80
|
+
self.thread_id = event["thread_id"]
|
|
81
|
+
blob = json.dumps(event)
|
|
82
|
+
if '"rate_limit_reached_type": "' in blob: # non-null value means the limit hit
|
|
83
|
+
self.limited = True
|
|
84
|
+
msg: Any = event.get("item") or event.get("msg") or event.get("payload") or {}
|
|
85
|
+
if not isinstance(msg, dict):
|
|
86
|
+
return
|
|
87
|
+
kind = msg.get("type")
|
|
88
|
+
text = msg.get("message") or msg.get("text") or msg.get("last_agent_message")
|
|
89
|
+
if kind in {"agent_message", None} and isinstance(text, str) and text:
|
|
90
|
+
self.last_message = text
|
|
91
|
+
elif self.on_progress and event.get("type") == "item.completed":
|
|
92
|
+
if kind == "command_execution" and msg.get("command"):
|
|
93
|
+
self.on_progress(f"$ {str(msg['command'])[:100]}")
|
|
94
|
+
elif kind == "file_change":
|
|
95
|
+
changes = msg.get("changes") or []
|
|
96
|
+
paths = [c.get("path") for c in changes if isinstance(c, dict)]
|
|
97
|
+
self.on_progress("edit " + ", ".join(str(p) for p in paths if p)[:100])
|
|
98
|
+
elif kind == "web_search":
|
|
99
|
+
self.on_progress(f"search {str(msg.get('query', ''))[:100]}")
|
|
100
|
+
if kind == "error" and "limit" in str(msg.get("message", "")).lower():
|
|
101
|
+
self.limited = True
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Resolve plug-ins named in config: a built-in short name or ``package.module:Class``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from codebaton.config import ProviderConfig
|
|
10
|
+
from codebaton.core.usage_cache import UsageCache
|
|
11
|
+
from codebaton.plugins.base import Executor, ProviderAdapter, UsageReader
|
|
12
|
+
from codebaton.plugins.executors.local import LocalExecutor
|
|
13
|
+
from codebaton.plugins.providers.claude_code import ClaudeCodeAdapter
|
|
14
|
+
from codebaton.plugins.providers.codex import CodexAdapter
|
|
15
|
+
from codebaton.plugins.usage.cached import CachedUsageReader
|
|
16
|
+
from codebaton.plugins.usage.codex_logs import CodexLogsReader
|
|
17
|
+
|
|
18
|
+
PROVIDERS: dict[str, type[Any]] = {"claude_code": ClaudeCodeAdapter, "codex": CodexAdapter}
|
|
19
|
+
EXECUTORS: dict[str, type[Any]] = {"local": LocalExecutor}
|
|
20
|
+
DEFAULT_READER = {"claude_code": "reported", "codex": "codex_logs"}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class PluginError(LookupError):
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _import(spec: str) -> type[Any]:
|
|
28
|
+
module_name, _, attr = spec.partition(":")
|
|
29
|
+
if not module_name or not attr:
|
|
30
|
+
raise PluginError(f"plug-in '{spec}' must be a built-in name or 'module:Class'")
|
|
31
|
+
try:
|
|
32
|
+
obj = getattr(importlib.import_module(module_name), attr)
|
|
33
|
+
except (ImportError, AttributeError) as exc:
|
|
34
|
+
raise PluginError(f"cannot load plug-in '{spec}': {exc}") from exc
|
|
35
|
+
if not isinstance(obj, type):
|
|
36
|
+
raise PluginError(f"plug-in '{spec}' is not a class")
|
|
37
|
+
return obj
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def make_executor(name: str) -> Executor:
|
|
41
|
+
cls = EXECUTORS.get(name) or _import(name)
|
|
42
|
+
executor = cls()
|
|
43
|
+
if not isinstance(executor, Executor):
|
|
44
|
+
raise PluginError(f"executor '{name}' does not implement Executor")
|
|
45
|
+
return executor
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def make_adapter(provider: ProviderConfig, executor: Executor) -> ProviderAdapter:
|
|
49
|
+
name = provider.adapter_name
|
|
50
|
+
cls = PROVIDERS.get(name) or _import(name)
|
|
51
|
+
adapter = cls(executor)
|
|
52
|
+
if not isinstance(adapter, ProviderAdapter):
|
|
53
|
+
raise PluginError(f"provider '{name}' does not implement ProviderAdapter")
|
|
54
|
+
return adapter
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def make_usage_reader(provider: ProviderConfig) -> UsageReader | None:
|
|
58
|
+
"""Return the configured reader, or None if the provider has no known reader."""
|
|
59
|
+
usage = provider.usage
|
|
60
|
+
name = usage.reader or DEFAULT_READER.get(provider.adapter_name)
|
|
61
|
+
if name is None:
|
|
62
|
+
return None
|
|
63
|
+
path = Path(usage.path).expanduser() if usage.path else None
|
|
64
|
+
reader: object
|
|
65
|
+
if name == "reported":
|
|
66
|
+
# Real percentages the provider reported with its last reply (see usage_cache.py).
|
|
67
|
+
cache = UsageCache(path) if path else UsageCache()
|
|
68
|
+
reader = CachedUsageReader(provider.name, cache, window=usage.window)
|
|
69
|
+
elif name == "codex_logs":
|
|
70
|
+
reader = CodexLogsReader(path=path, window=usage.window)
|
|
71
|
+
elif name == "manual":
|
|
72
|
+
return None # the budget manager owns the manual counter
|
|
73
|
+
else:
|
|
74
|
+
reader = _import(name)()
|
|
75
|
+
if not isinstance(reader, UsageReader):
|
|
76
|
+
raise PluginError(f"usage reader '{name}' does not implement UsageReader")
|
|
77
|
+
return reader
|
|
File without changes
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Usage reader backed by the per-user usage cache (real provider-reported percentages).
|
|
2
|
+
|
|
3
|
+
Used for Claude Code: its replies carry the account's five-hour and weekly utilization, which
|
|
4
|
+
the router stores after every call. Until the first call there is nothing cached, and the
|
|
5
|
+
budget manager falls back to the manual counter (``codebaton status --refresh`` makes one
|
|
6
|
+
tiny call to fetch real numbers).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import time
|
|
12
|
+
from collections.abc import Callable
|
|
13
|
+
from typing import Literal
|
|
14
|
+
|
|
15
|
+
from codebaton.core.usage_cache import UsageCache
|
|
16
|
+
from codebaton.plugins.base import UsageReading
|
|
17
|
+
|
|
18
|
+
Window = Literal["short", "long", "max"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class CachedUsageReader:
|
|
22
|
+
def __init__(
|
|
23
|
+
self,
|
|
24
|
+
provider: str,
|
|
25
|
+
cache: UsageCache | None = None,
|
|
26
|
+
window: Window = "max",
|
|
27
|
+
now: Callable[[], float] = time.time,
|
|
28
|
+
) -> None:
|
|
29
|
+
self.provider = provider
|
|
30
|
+
self.cache = cache or UsageCache()
|
|
31
|
+
self.window = window
|
|
32
|
+
self.now = now
|
|
33
|
+
|
|
34
|
+
def used(self, window_hours: float) -> UsageReading:
|
|
35
|
+
entry = self.cache.load(self.provider)
|
|
36
|
+
if entry is None or not entry[1]:
|
|
37
|
+
return UsageReading(None, "reported", "no usage reported yet (updates after a reply)")
|
|
38
|
+
_, windows = entry
|
|
39
|
+
now = self.now()
|
|
40
|
+
values = {
|
|
41
|
+
k: (0.0 if w.resets_at is not None and w.resets_at <= now else w.percent)
|
|
42
|
+
for k, w in windows.items()
|
|
43
|
+
}
|
|
44
|
+
if self.window == "max":
|
|
45
|
+
percent = max(values.values())
|
|
46
|
+
elif self.window in values:
|
|
47
|
+
percent = values[self.window]
|
|
48
|
+
else:
|
|
49
|
+
return UsageReading(None, "reported", f"no {self.window} window reported")
|
|
50
|
+
names = {"short": "5h", "long": "week"}
|
|
51
|
+
detail = ", ".join(f"{names.get(k, k)} {v:.0f}%" for k, v in sorted(values.items()))
|
|
52
|
+
return UsageReading(percent, "reported", detail)
|