coding-agent-cli 0.1.0__py3-none-any.whl → 0.2.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.
- coding_agent_cli/__init__.py +21 -7
- coding_agent_cli/_args.py +28 -8
- coding_agent_cli/_classify.py +194 -103
- coding_agent_cli/_drivers/_common.py +12 -321
- coding_agent_cli/_drivers/agy.py +269 -293
- coding_agent_cli/_drivers/claude.py +413 -268
- coding_agent_cli/_drivers/codex.py +352 -273
- coding_agent_cli/_drivers/pi.py +205 -308
- coding_agent_cli/_platform.py +71 -1
- coding_agent_cli/_transport.py +520 -0
- coding_agent_cli/api.py +74 -74
- coding_agent_cli/driver.py +308 -0
- coding_agent_cli/events.py +50 -9
- coding_agent_cli/registry.py +15 -39
- coding_agent_cli/types.py +45 -5
- coding_agent_cli-0.2.0.dist-info/METADATA +290 -0
- coding_agent_cli-0.2.0.dist-info/RECORD +21 -0
- coding_agent_cli/_drivers/_usage.py +0 -77
- coding_agent_cli/_drivers/codex_rollout.py +0 -439
- coding_agent_cli/_process.py +0 -338
- coding_agent_cli-0.1.0.dist-info/METADATA +0 -217
- coding_agent_cli-0.1.0.dist-info/RECORD +0 -22
- {coding_agent_cli-0.1.0.dist-info → coding_agent_cli-0.2.0.dist-info}/WHEEL +0 -0
- {coding_agent_cli-0.1.0.dist-info → coding_agent_cli-0.2.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -1,330 +1,21 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""Small conversion helpers shared by built-in drivers."""
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
import
|
|
6
|
-
import json
|
|
7
|
-
import logging
|
|
8
|
-
import os
|
|
9
|
-
import shutil
|
|
10
|
-
import time
|
|
11
|
-
from collections.abc import Mapping, Sequence
|
|
12
|
-
from dataclasses import dataclass
|
|
13
|
-
from pathlib import Path
|
|
14
|
-
from typing import Any, Literal
|
|
5
|
+
from typing import Any
|
|
15
6
|
|
|
16
|
-
from .._args import reject_conflicts, reject_transport_flags, reject_unsupported, validate_args
|
|
17
|
-
from .._classify import Facts, classify
|
|
18
|
-
from .._process import ProcessOutcome, run_process
|
|
19
|
-
from ..events import Event, ToolStarted
|
|
20
|
-
from ..registry import EventHandler
|
|
21
|
-
from ..types import Capabilities, Diagnostic, Request, Result, Usage
|
|
22
7
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
_VERIFIED_COMMANDS: dict[str, frozenset[str]] = {
|
|
26
|
-
"claude": frozenset({"bash"}),
|
|
27
|
-
"codex": frozenset({"bash"}),
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
def classify_tool_activity(provider: str, tool_name: str) -> Literal["command", "tool_call"]:
|
|
32
|
-
"""Classify tool activity by exact, case-sensitive provider and tool-name allow-lists."""
|
|
33
|
-
commands = _VERIFIED_COMMANDS.get(provider)
|
|
34
|
-
if commands is not None and tool_name in commands:
|
|
35
|
-
return "command"
|
|
36
|
-
return "tool_call"
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
def tool_started(entity_id: str, provider: str, tool_name: str, tool_input: Any = None) -> ToolStarted:
|
|
40
|
-
return ToolStarted(
|
|
41
|
-
entity_id=entity_id,
|
|
42
|
-
tool=tool_name,
|
|
43
|
-
activity=classify_tool_activity(provider, tool_name),
|
|
44
|
-
input=tool_input,
|
|
45
|
-
)
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
def tool_status(value: Any) -> Literal["completed", "error", "unknown"]:
|
|
49
|
-
if value in ("completed", "error"):
|
|
50
|
-
return value
|
|
51
|
-
if value in ("failed", "failure"):
|
|
52
|
-
return "error"
|
|
53
|
-
return "unknown"
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
def parse_json_object(line: str) -> dict[str, Any] | None:
|
|
57
|
-
"""Return the line's JSON object, or None for non-JSON or non-object lines."""
|
|
58
|
-
try:
|
|
59
|
-
value = json.loads(line)
|
|
60
|
-
except (json.JSONDecodeError, TypeError):
|
|
61
|
-
return None
|
|
62
|
-
return value if isinstance(value, dict) else None
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
def as_int(val: Any) -> int | None:
|
|
66
|
-
if isinstance(val, bool) or not isinstance(val, int) or val < 0:
|
|
8
|
+
def as_int(value: Any) -> int | None:
|
|
9
|
+
if isinstance(value, bool):
|
|
67
10
|
return None
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
def read_and_unlink(path: Path, *, errors: str) -> str:
|
|
72
|
-
"""Return the file's UTF-8 text, or "" when it cannot be read. The file is removed either way."""
|
|
73
|
-
try:
|
|
74
|
-
return path.read_text(encoding="utf-8", errors=errors)
|
|
75
|
-
except OSError:
|
|
76
|
-
return ""
|
|
77
|
-
finally:
|
|
78
|
-
try:
|
|
79
|
-
path.unlink()
|
|
80
|
-
except OSError:
|
|
81
|
-
pass
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
def parse_token_component(usage: dict[str, Any], key: str) -> tuple[int | None, bool]:
|
|
85
|
-
"""Return (value, malformed). A missing or null key is absent, not malformed."""
|
|
86
|
-
if key not in usage:
|
|
87
|
-
return None, False
|
|
88
|
-
val = usage[key]
|
|
89
|
-
if val is None:
|
|
90
|
-
return None, False
|
|
91
|
-
if isinstance(val, bool) or not isinstance(val, int) or val < 0:
|
|
92
|
-
return None, True
|
|
93
|
-
return val, False
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
@dataclass(slots=True, frozen=True)
|
|
97
|
-
class TokenUsage:
|
|
98
|
-
"""Normalized usage.
|
|
99
|
-
|
|
100
|
-
``input`` is raw input plus cache reads and writes, or None when the raw input is absent or malformed.
|
|
101
|
-
|
|
102
|
-
``observed`` is True when any component was present or malformed.
|
|
103
|
-
"""
|
|
104
|
-
|
|
105
|
-
input: int | None
|
|
106
|
-
output: int | None
|
|
107
|
-
cache_read: int | None
|
|
108
|
-
cache_write: int | None
|
|
109
|
-
observed: bool
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
NO_USAGE = TokenUsage(input=None, output=None, cache_read=None, cache_write=None, observed=False)
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
def read_usage(
|
|
116
|
-
usage: dict[str, Any],
|
|
117
|
-
*,
|
|
118
|
-
input_key: str = "input_tokens",
|
|
119
|
-
output_key: str = "output_tokens",
|
|
120
|
-
cache_read_key: str = "cache_read_input_tokens",
|
|
121
|
-
cache_write_key: str = "cache_creation_input_tokens",
|
|
122
|
-
) -> TokenUsage:
|
|
123
|
-
raw_in, raw_in_bad = parse_token_component(usage, input_key)
|
|
124
|
-
cr, cr_bad = parse_token_component(usage, cache_read_key)
|
|
125
|
-
cw, cw_bad = parse_token_component(usage, cache_write_key)
|
|
126
|
-
raw_out, raw_out_bad = parse_token_component(usage, output_key)
|
|
127
|
-
if raw_in_bad or cr_bad or cw_bad or raw_in is None:
|
|
128
|
-
norm_in = None
|
|
129
|
-
else:
|
|
130
|
-
norm_in = raw_in + (cr or 0) + (cw or 0)
|
|
131
|
-
observed = any(v is not None for v in (norm_in, cr, cw, raw_out)) or raw_in_bad or cr_bad or cw_bad or raw_out_bad
|
|
132
|
-
return TokenUsage(input=norm_in, output=raw_out, cache_read=cr, cache_write=cw, observed=observed)
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
class EventBuffer:
|
|
136
|
-
"""Collect the events one parsed line produces, then await the sink once per event in order.
|
|
137
|
-
|
|
138
|
-
The parser stays synchronous. ``flush`` runs after each line, so a failing sink fails the run at that line.
|
|
139
|
-
"""
|
|
140
|
-
|
|
141
|
-
def __init__(self, sink: EventHandler) -> None:
|
|
142
|
-
self._sink = sink
|
|
143
|
-
self._pending: list[Event] = []
|
|
144
|
-
|
|
145
|
-
def emit(self, event: Event) -> None:
|
|
146
|
-
self._pending.append(event)
|
|
147
|
-
|
|
148
|
-
async def flush(self) -> None:
|
|
149
|
-
while self._pending:
|
|
150
|
-
await self._sink(self._pending.pop(0))
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
class Diagnostics:
|
|
154
|
-
"""Keep the first ``limit`` diagnostic lines, plus the first line that matches ``keep`` beyond it."""
|
|
155
|
-
|
|
156
|
-
def __init__(self, limit: int = 50) -> None:
|
|
157
|
-
self.limit = limit
|
|
158
|
-
self.lines: list[str] = []
|
|
159
|
-
self._kept: set[str] = set()
|
|
160
|
-
|
|
161
|
-
def add(self, line: str, *, marks: Sequence[str] = ()) -> None:
|
|
162
|
-
extra = [mark for mark in marks if mark not in self._kept]
|
|
163
|
-
if len(self.lines) < self.limit or extra:
|
|
164
|
-
self.lines.append(line)
|
|
165
|
-
self._kept.update(marks)
|
|
166
|
-
|
|
167
|
-
def text(self) -> str:
|
|
168
|
-
return "\n".join(self.lines).strip()
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
def effective_env(req: Request) -> dict[str, str]:
|
|
172
|
-
return {**os.environ, **req.env}
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
def resolve_executable(req: Request, default: str) -> Path | None:
|
|
176
|
-
"""Resolve ``req.executable`` or ``default`` on the request's effective ``PATH``."""
|
|
177
|
-
found = shutil.which(req.executable or default, path=effective_env(req).get("PATH"))
|
|
178
|
-
return None if found is None else Path(found)
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
def request_failure(req: Request, error: Diagnostic, cancel: asyncio.Event | None = None) -> Result:
|
|
182
|
-
"""A result for a run that never spawned."""
|
|
183
|
-
verdict = classify(Facts(cancelled=cancel is not None and cancel.is_set(), request_error=error))
|
|
184
|
-
return Result(outcome=verdict.outcome, session_id=req.session_id, error=verdict.error)
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
def build_result(facts: Facts, *, model: str | None, usage: Usage) -> Result:
|
|
188
|
-
verdict = classify(facts)
|
|
189
|
-
return Result(
|
|
190
|
-
outcome=verdict.outcome,
|
|
191
|
-
text=facts.text,
|
|
192
|
-
session_id=facts.session_id or None,
|
|
193
|
-
model=model,
|
|
194
|
-
usage=usage,
|
|
195
|
-
returncode=facts.returncode,
|
|
196
|
-
error=verdict.error,
|
|
197
|
-
warnings=verdict.warnings,
|
|
198
|
-
)
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
def process_facts(process: ProcessOutcome, cancel: asyncio.Event) -> Facts:
|
|
202
|
-
return Facts(
|
|
203
|
-
cancelled=cancel.is_set(),
|
|
204
|
-
process_error=process.error_class,
|
|
205
|
-
process_message=process.error,
|
|
206
|
-
returncode=process.returncode,
|
|
207
|
-
)
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
def deadline_for(req: Request) -> float | None:
|
|
211
|
-
return None if req.timeout_s is None else time.monotonic() + req.timeout_s
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
class CliDriver:
|
|
215
|
-
"""Shared preflight and capability probe for the built-in drivers.
|
|
216
|
-
|
|
217
|
-
Subclasses set ``name``, ``executable``, ``owned_flags``, ``portable_flags`` (supported
|
|
218
|
-
portable field to the flags that set it), ``help_args``, and ``help_markers``.
|
|
219
|
-
"""
|
|
220
|
-
|
|
221
|
-
name = ""
|
|
222
|
-
executable = ""
|
|
223
|
-
owned_flags: tuple[str, ...] = ()
|
|
224
|
-
portable_flags: Mapping[str, tuple[str, ...]] = {}
|
|
225
|
-
help_args: tuple[str, ...] = ("--help",)
|
|
226
|
-
help_markers: tuple[str, ...] = ()
|
|
227
|
-
|
|
228
|
-
def __init__(self) -> None:
|
|
229
|
-
self._probe_cache: set[tuple[str, int]] = set()
|
|
230
|
-
self.log = logging.getLogger(f"coding_agent_cli.drivers.{self.name}")
|
|
231
|
-
|
|
232
|
-
def validate(self, req: Request) -> Diagnostic | None:
|
|
233
|
-
"""Driver-specific argument checks. Return a diagnostic to reject the request."""
|
|
234
|
-
return None
|
|
235
|
-
|
|
236
|
-
def preflight(self, req: Request, cancel: asyncio.Event) -> tuple[Path, Path] | Result:
|
|
237
|
-
"""Validate the request and resolve ``(cwd, executable)``, or return the failure result."""
|
|
238
|
-
error = (
|
|
239
|
-
validate_args(req.args)
|
|
240
|
-
or reject_unsupported(req, self.portable_flags)
|
|
241
|
-
or reject_conflicts(req, self.portable_flags)
|
|
242
|
-
or reject_transport_flags(req.args, self.owned_flags)
|
|
243
|
-
or self.validate(req)
|
|
244
|
-
)
|
|
245
|
-
cwd = req.cwd.expanduser().absolute()
|
|
246
|
-
if error is None:
|
|
247
|
-
if not cwd.is_dir():
|
|
248
|
-
error = Diagnostic(code="bad_cwd", message=f"cwd {os.fspath(cwd)!r} is not a directory")
|
|
249
|
-
if error is not None:
|
|
250
|
-
return request_failure(req, error, cancel)
|
|
251
|
-
executable = resolve_executable(req, self.executable)
|
|
252
|
-
if executable is None:
|
|
253
|
-
name = req.executable or self.executable
|
|
254
|
-
verdict = classify(
|
|
255
|
-
Facts(
|
|
256
|
-
cancelled=cancel.is_set(),
|
|
257
|
-
process_error="missing_cli",
|
|
258
|
-
process_message=f"{name!r} was not found on PATH",
|
|
259
|
-
)
|
|
260
|
-
)
|
|
261
|
-
return Result(outcome=verdict.outcome, session_id=req.session_id, error=verdict.error)
|
|
262
|
-
return cwd, executable
|
|
263
|
-
|
|
264
|
-
def portable_argv(self, req: Request) -> list[str]:
|
|
265
|
-
"""Flags for the portable options the request sets, in ``portable_flags`` order."""
|
|
266
|
-
argv: list[str] = []
|
|
267
|
-
for name, flags in self.portable_flags.items():
|
|
268
|
-
value = getattr(req, name)
|
|
269
|
-
if value is not None:
|
|
270
|
-
argv.extend([flags[0], value])
|
|
271
|
-
return argv
|
|
272
|
-
|
|
273
|
-
async def check(self, req: Request, *, refresh: bool = False) -> Capabilities:
|
|
274
|
-
executable = resolve_executable(req, self.executable)
|
|
275
|
-
if executable is None:
|
|
276
|
-
return Capabilities(available=False)
|
|
277
|
-
try:
|
|
278
|
-
key = (os.fspath(executable), executable.stat().st_mtime_ns)
|
|
279
|
-
except OSError:
|
|
280
|
-
return Capabilities(available=False)
|
|
281
|
-
if not refresh and key in self._probe_cache:
|
|
282
|
-
return Capabilities(available=True, executable=executable, structured_streaming=True)
|
|
283
|
-
supported = await self._probe(req, executable)
|
|
284
|
-
if supported:
|
|
285
|
-
self._probe_cache.add(key)
|
|
286
|
-
return Capabilities(available=True, executable=executable, structured_streaming=supported or None)
|
|
287
|
-
|
|
288
|
-
async def _probe(self, req: Request, executable: Path) -> bool:
|
|
289
|
-
lines: list[str] = []
|
|
290
|
-
|
|
291
|
-
async def collect(line: str) -> None:
|
|
292
|
-
lines.append(line)
|
|
293
|
-
|
|
11
|
+
if isinstance(value, int):
|
|
12
|
+
return value
|
|
13
|
+
if isinstance(value, str):
|
|
294
14
|
try:
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
None,
|
|
300
|
-
time.monotonic() + PROBE_TIMEOUT_S,
|
|
301
|
-
None,
|
|
302
|
-
collect,
|
|
303
|
-
)
|
|
304
|
-
except OSError:
|
|
305
|
-
return False
|
|
306
|
-
if outcome.error_class:
|
|
307
|
-
return False
|
|
308
|
-
text = "\n".join(lines)
|
|
309
|
-
return all(marker in text for marker in self.help_markers)
|
|
15
|
+
return int(value)
|
|
16
|
+
except ValueError:
|
|
17
|
+
return None
|
|
18
|
+
return None
|
|
310
19
|
|
|
311
20
|
|
|
312
|
-
__all__ = [
|
|
313
|
-
"NO_USAGE",
|
|
314
|
-
"CliDriver",
|
|
315
|
-
"Diagnostics",
|
|
316
|
-
"EventBuffer",
|
|
317
|
-
"TokenUsage",
|
|
318
|
-
"as_int",
|
|
319
|
-
"build_result",
|
|
320
|
-
"classify_tool_activity",
|
|
321
|
-
"deadline_for",
|
|
322
|
-
"effective_env",
|
|
323
|
-
"parse_json_object",
|
|
324
|
-
"process_facts",
|
|
325
|
-
"read_and_unlink",
|
|
326
|
-
"read_usage",
|
|
327
|
-
"request_failure",
|
|
328
|
-
"resolve_executable",
|
|
329
|
-
"tool_started",
|
|
330
|
-
]
|
|
21
|
+
__all__ = ["as_int"]
|