onechat-cli 0.1.1__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.
- onechat/__init__.py +46 -0
- onechat/benchmark.py +253 -0
- onechat/cli.py +252 -0
- onechat/cli_doctor.py +272 -0
- onechat/cli_repl.py +116 -0
- onechat/config.py +311 -0
- onechat/contracts.py +142 -0
- onechat/defaults.yaml +47 -0
- onechat/executors/__init__.py +19 -0
- onechat/executors/api.py +254 -0
- onechat/executors/cli.py +211 -0
- onechat/executors/parser_cc.py +129 -0
- onechat/executors/parser_formats.py +81 -0
- onechat/executors/parser_tool_streams.py +218 -0
- onechat/executors/parsers.py +52 -0
- onechat/executors/process.py +228 -0
- onechat/gitstate.py +91 -0
- onechat/handoff.py +176 -0
- onechat/profiles/agy.yaml +11 -0
- onechat/profiles/autoclaw.yaml +12 -0
- onechat/profiles/claude.yaml +11 -0
- onechat/profiles/codex.yaml +14 -0
- onechat/profiles/gemini.yaml +11 -0
- onechat/profiles/opencode.yaml +11 -0
- onechat/profiles/qoder.yaml +12 -0
- onechat/profiles/qwen.yaml +11 -0
- onechat/profiles/workbuddy.yaml +13 -0
- onechat/profiles/zcode.yaml +12 -0
- onechat/quota.py +287 -0
- onechat/redact.py +58 -0
- onechat/router.py +299 -0
- onechat/router_helpers.py +288 -0
- onechat/scoring.py +241 -0
- onechat/sdk.py +210 -0
- onechat/selector.py +294 -0
- onechat/store.py +298 -0
- onechat_cli-0.1.1.dist-info/METADATA +201 -0
- onechat_cli-0.1.1.dist-info/RECORD +40 -0
- onechat_cli-0.1.1.dist-info/WHEEL +4 -0
- onechat_cli-0.1.1.dist-info/entry_points.txt +3 -0
onechat/contracts.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Router contracts (Plan 02 §2): executor specs, turn request/result, executor protocol."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from enum import IntEnum, StrEnum
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Literal, Protocol
|
|
9
|
+
|
|
10
|
+
from pydantic import BaseModel, Field, model_validator
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Tier(IntEnum):
|
|
14
|
+
LOW = 1
|
|
15
|
+
MEDIUM = 2
|
|
16
|
+
HIGH = 3
|
|
17
|
+
MAX = 4
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class CostClass(StrEnum):
|
|
21
|
+
FREE = "free"
|
|
22
|
+
SUBSCRIPTION = "subscription"
|
|
23
|
+
PAID = "paid"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Capability(StrEnum):
|
|
27
|
+
CHAT = "chat"
|
|
28
|
+
CODE = "code" # edits files / runs commands in workdir
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Stop(StrEnum):
|
|
32
|
+
DONE = "done"
|
|
33
|
+
QUOTA = "quota"
|
|
34
|
+
AUTH = "auth"
|
|
35
|
+
ERROR = "error"
|
|
36
|
+
TIMEOUT = "timeout"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Limits(BaseModel):
|
|
40
|
+
rpm: int | None = Field(default=None, gt=0)
|
|
41
|
+
rpd: int | None = Field(default=None, gt=0)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class ExecutorSpec(BaseModel):
|
|
45
|
+
"""One backend instance. Validators enforce cli/api shape differences."""
|
|
46
|
+
|
|
47
|
+
id: str
|
|
48
|
+
kind: Literal["cli", "api"]
|
|
49
|
+
profile: str | None = None
|
|
50
|
+
model: str
|
|
51
|
+
model_key: str | None = None
|
|
52
|
+
scores: dict[str, float] = Field(default_factory=dict)
|
|
53
|
+
tier: Tier
|
|
54
|
+
capabilities: frozenset[Capability] = Field(default_factory=frozenset)
|
|
55
|
+
cost: CostClass
|
|
56
|
+
family: str
|
|
57
|
+
env: dict[str, str] = Field(default_factory=dict)
|
|
58
|
+
base_url: str | None = None
|
|
59
|
+
api_key_env: str | None = None
|
|
60
|
+
limits: Limits = Field(default_factory=Limits)
|
|
61
|
+
priority: int = 100
|
|
62
|
+
enabled: bool = True
|
|
63
|
+
input_cost_per_m: float | None = None # USD per 1M input tokens (paid accounting)
|
|
64
|
+
output_cost_per_m: float | None = None # USD per 1M output tokens
|
|
65
|
+
stream_usage: bool = True # send stream_options={"include_usage": True} (T08/D14)
|
|
66
|
+
|
|
67
|
+
@model_validator(mode="after")
|
|
68
|
+
def _validate_shape(self) -> ExecutorSpec:
|
|
69
|
+
if self.kind == "cli" and not self.profile:
|
|
70
|
+
raise ValueError("cli executor requires a profile")
|
|
71
|
+
if self.kind == "cli" and not self.capabilities:
|
|
72
|
+
raise ValueError("cli executor requires at least one capability")
|
|
73
|
+
if self.kind == "api":
|
|
74
|
+
if not self.base_url or not self.api_key_env:
|
|
75
|
+
raise ValueError("api executor requires base_url and api_key_env")
|
|
76
|
+
if self.capabilities != frozenset({Capability.CHAT}):
|
|
77
|
+
raise ValueError("api executor capabilities must be exactly {CHAT}")
|
|
78
|
+
return self
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class Message(BaseModel):
|
|
82
|
+
role: Literal["system", "user", "assistant"]
|
|
83
|
+
content: str
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class Usage(BaseModel):
|
|
87
|
+
input_tokens: int = 0
|
|
88
|
+
output_tokens: int = 0
|
|
89
|
+
cost_usd: float | None = None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class Event(BaseModel):
|
|
93
|
+
kind: Literal["text", "tool", "status"]
|
|
94
|
+
text: str
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class TurnRequest(BaseModel):
|
|
98
|
+
prompt: str
|
|
99
|
+
workdir: Path
|
|
100
|
+
native_session_id: str | None = None
|
|
101
|
+
messages: list[Message] | None = None
|
|
102
|
+
timeout_s: int = Field(default=1800, gt=0)
|
|
103
|
+
inactivity_timeout_s: int | None = Field(default=None, ge=0)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class TurnResult(BaseModel):
|
|
107
|
+
stop: Stop
|
|
108
|
+
text: str = ""
|
|
109
|
+
native_session_id: str | None = None
|
|
110
|
+
usage: Usage = Field(default_factory=Usage)
|
|
111
|
+
retry_after_s: int | None = None
|
|
112
|
+
error: str | None = None
|
|
113
|
+
duration_s: float = 0.0
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
OnEvent = Callable[[Event], None]
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class Executor(Protocol):
|
|
120
|
+
spec: ExecutorSpec
|
|
121
|
+
|
|
122
|
+
def available(self) -> bool: ...
|
|
123
|
+
|
|
124
|
+
async def run(self, req: TurnRequest, on_event: OnEvent | None = None) -> TurnResult: ...
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class Reply(BaseModel):
|
|
128
|
+
text: str
|
|
129
|
+
executor_id: str
|
|
130
|
+
stop: Stop
|
|
131
|
+
switched_from: list[str]
|
|
132
|
+
turn_idx: int
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class NoExecutorAvailable(Exception):
|
|
136
|
+
def __init__(self, retry_at: float | None = None) -> None:
|
|
137
|
+
self.retry_at = retry_at
|
|
138
|
+
super().__init__("no executor available")
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class SessionBusy(Exception):
|
|
142
|
+
pass
|
onechat/defaults.yaml
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# Package defaults for onechat. User config (~/.onechat/config.yaml) overrides by executor id.
|
|
2
|
+
db_path: ~/.onechat/onechat.db
|
|
3
|
+
executors: []
|
|
4
|
+
handoff:
|
|
5
|
+
recent_turns: 6
|
|
6
|
+
turn_max_chars: 4000
|
|
7
|
+
brief_max_chars: 24000
|
|
8
|
+
compact_threshold_chars: 30000
|
|
9
|
+
cooldown:
|
|
10
|
+
min_requests: 1
|
|
11
|
+
failure_rate: 0.5
|
|
12
|
+
window_s: 60
|
|
13
|
+
quota_cooldown_s: 7200
|
|
14
|
+
timeout_cooldown_s: 7200
|
|
15
|
+
error_cooldown_s: 14400
|
|
16
|
+
auth_cooldown_s: 86400
|
|
17
|
+
share_profile_cooldown: true
|
|
18
|
+
tier_policy:
|
|
19
|
+
min_tier: 2
|
|
20
|
+
max_tier: 2
|
|
21
|
+
by_task_kind:
|
|
22
|
+
summarize: 2
|
|
23
|
+
research: 2
|
|
24
|
+
digest: 2
|
|
25
|
+
fix: 2
|
|
26
|
+
test: 2
|
|
27
|
+
code: 2
|
|
28
|
+
plan: 2
|
|
29
|
+
spec: 2
|
|
30
|
+
review: 2
|
|
31
|
+
chat_default: 2
|
|
32
|
+
high_keywords: [deepswe, automationbench]
|
|
33
|
+
escalate_every: 0
|
|
34
|
+
cost_order: [free, subscription, paid]
|
|
35
|
+
allow_paid: false
|
|
36
|
+
roles:
|
|
37
|
+
builder: codex
|
|
38
|
+
reviewer: claude
|
|
39
|
+
auditor: codex
|
|
40
|
+
benchmark:
|
|
41
|
+
enabled: false
|
|
42
|
+
interval_s: 1800
|
|
43
|
+
max_latency_s: 15.0
|
|
44
|
+
timeout_s: 20.0
|
|
45
|
+
promote_roles: [builder, code]
|
|
46
|
+
selection_mode: order
|
|
47
|
+
targets: []
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Executor factory (Plan 02 §6): build_executor(spec, profiles) — a plain function."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from ..config import CliProfile
|
|
6
|
+
from ..contracts import Executor, ExecutorSpec
|
|
7
|
+
from .api import ApiExecutor
|
|
8
|
+
from .cli import CliExecutor
|
|
9
|
+
|
|
10
|
+
__all__ = ["build_executor"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def build_executor(spec: ExecutorSpec, profiles: dict[str, CliProfile]) -> Executor:
|
|
14
|
+
"""Build the right executor for a spec. Unknown cli profile is a config error (raise)."""
|
|
15
|
+
if spec.kind == "api":
|
|
16
|
+
return ApiExecutor(spec)
|
|
17
|
+
if spec.profile not in profiles:
|
|
18
|
+
raise KeyError(f"unknown profile {spec.profile!r} for executor {spec.id!r}")
|
|
19
|
+
return CliExecutor(spec, profiles[spec.profile])
|
onechat/executors/api.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""ApiExecutor (Plan 02 §6.3 / T08): OpenAI-compatible API backends via the openai SDK.
|
|
2
|
+
|
|
3
|
+
Async end-to-end; the client cache is keyed by (running loop, key hash) so per-call
|
|
4
|
+
asyncio.run loops and rotated env keys always get a live client. One wall-clock
|
|
5
|
+
asyncio.timeout covers create + stream consumption; EVERY exception becomes a value.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import contextlib
|
|
12
|
+
import email.utils
|
|
13
|
+
import hashlib
|
|
14
|
+
import math
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
import time
|
|
18
|
+
import weakref
|
|
19
|
+
from collections.abc import Callable
|
|
20
|
+
from datetime import UTC, datetime
|
|
21
|
+
|
|
22
|
+
import openai
|
|
23
|
+
|
|
24
|
+
from ..contracts import Event, ExecutorSpec, OnEvent, Stop, TurnRequest, TurnResult
|
|
25
|
+
from ..quota import parse_retry_after
|
|
26
|
+
from ..redact import make_redactor, redact
|
|
27
|
+
|
|
28
|
+
_GROQ_DURATION_RE = re.compile(r"(\d+(?:\.\d+)?)(h|ms|m|s)") # longest unit first: ms before m
|
|
29
|
+
_UNIT_SECONDS = {"h": 3600.0, "m": 60.0, "s": 1.0, "ms": 0.001}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def default_openai_factory(spec: ExecutorSpec) -> object:
|
|
33
|
+
# A missing key must not explode at construction: available() reports that honestly.
|
|
34
|
+
# The placeholder makes any accidental call fail closed with an auth error.
|
|
35
|
+
key = os.environ.get(spec.api_key_env or "", "") or "unavailable"
|
|
36
|
+
return openai.AsyncOpenAI(base_url=spec.base_url, api_key=key, max_retries=0)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _groq_duration_seconds(raw: str) -> float | None:
|
|
40
|
+
"""Groq-style durations: '1m2.5s', '250ms', '1h30m'. None when no unit pairs match."""
|
|
41
|
+
total = 0.0
|
|
42
|
+
matched = False
|
|
43
|
+
for number, unit in _GROQ_DURATION_RE.findall(raw):
|
|
44
|
+
total += float(number) * _UNIT_SECONDS[unit]
|
|
45
|
+
matched = True
|
|
46
|
+
return total if matched else None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _duration_header_seconds(raw: str) -> float | None:
|
|
50
|
+
"""Retry-after header value: plain float, Groq duration, or an HTTP-date."""
|
|
51
|
+
text = raw.strip()
|
|
52
|
+
try:
|
|
53
|
+
return float(text)
|
|
54
|
+
except ValueError:
|
|
55
|
+
pass
|
|
56
|
+
groq = _groq_duration_seconds(text)
|
|
57
|
+
if groq is not None:
|
|
58
|
+
return groq
|
|
59
|
+
try:
|
|
60
|
+
when = email.utils.parsedate_to_datetime(text)
|
|
61
|
+
except (TypeError, ValueError):
|
|
62
|
+
return None
|
|
63
|
+
if when.tzinfo is None:
|
|
64
|
+
when = when.replace(tzinfo=UTC)
|
|
65
|
+
delta = (when - datetime.now(UTC)).total_seconds()
|
|
66
|
+
return delta if delta >= 0 else None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class ApiExecutor:
|
|
70
|
+
"""One OpenAI-compatible API backend. run() never raises for backend problems."""
|
|
71
|
+
|
|
72
|
+
def __init__(
|
|
73
|
+
self,
|
|
74
|
+
spec: ExecutorSpec,
|
|
75
|
+
client_factory: Callable[[ExecutorSpec], object] = default_openai_factory,
|
|
76
|
+
) -> None:
|
|
77
|
+
self.spec = spec
|
|
78
|
+
self._client_factory = client_factory
|
|
79
|
+
self._client: object | None = None
|
|
80
|
+
self._loop_ref: weakref.ref | None = None
|
|
81
|
+
self._key_hash: str = ""
|
|
82
|
+
self._redact = (
|
|
83
|
+
make_redactor([spec.api_key_env]) if spec.api_key_env else redact
|
|
84
|
+
) # Plan 02 §9: mask the configured key value in every error text
|
|
85
|
+
|
|
86
|
+
def available(self) -> bool:
|
|
87
|
+
return bool(os.environ.get(self.spec.api_key_env or ""))
|
|
88
|
+
|
|
89
|
+
def _client_for_loop(self) -> object:
|
|
90
|
+
"""Fresh client per (live loop, key hash): async clients bind to one loop (T08).
|
|
91
|
+
The loop is held by weakref identity — id() alone can alias a freed loop."""
|
|
92
|
+
old_ref = self._loop_ref
|
|
93
|
+
try:
|
|
94
|
+
loop = asyncio.get_running_loop()
|
|
95
|
+
new_ref: weakref.ref | None = weakref.ref(loop)
|
|
96
|
+
except RuntimeError:
|
|
97
|
+
loop, new_ref = None, None
|
|
98
|
+
same_loop = loop is not None and old_ref is not None and old_ref() is loop
|
|
99
|
+
key_hash = self._current_key_hash()
|
|
100
|
+
if self._client is None or not same_loop or self._key_hash != key_hash:
|
|
101
|
+
self._client = self._client_factory(self.spec)
|
|
102
|
+
self._loop_ref = new_ref
|
|
103
|
+
self._key_hash = key_hash
|
|
104
|
+
return self._client
|
|
105
|
+
|
|
106
|
+
def _current_key_hash(self) -> str:
|
|
107
|
+
key = os.environ.get(self.spec.api_key_env or "") or ""
|
|
108
|
+
return hashlib.sha1(key.encode("utf-8")).hexdigest()
|
|
109
|
+
|
|
110
|
+
async def run(self, req: TurnRequest, on_event: OnEvent | None = None) -> TurnResult:
|
|
111
|
+
start = time.monotonic()
|
|
112
|
+
try:
|
|
113
|
+
async with asyncio.timeout(req.timeout_s): # wall clock over create+consume
|
|
114
|
+
stream = await self._create_with_fallback(req)
|
|
115
|
+
return await self._consume(stream, on_event, start, req)
|
|
116
|
+
except openai.RateLimitError as exc:
|
|
117
|
+
return self._quota(exc, start)
|
|
118
|
+
except (openai.AuthenticationError, openai.PermissionDeniedError) as exc:
|
|
119
|
+
return self._auth(exc, start)
|
|
120
|
+
except openai.APITimeoutError as exc:
|
|
121
|
+
return self._timeout(exc, start)
|
|
122
|
+
except openai.APIError as exc:
|
|
123
|
+
return self._error(exc, start)
|
|
124
|
+
except TimeoutError:
|
|
125
|
+
return self._timeout(RuntimeError("wall clock timeout"), start)
|
|
126
|
+
except Exception as exc: # noqa: BLE001 - Plan 02 §2: run() never raises
|
|
127
|
+
return self._error(exc, start)
|
|
128
|
+
|
|
129
|
+
def _request_kwargs(self, req: TurnRequest, with_stream_options: bool) -> dict[str, object]:
|
|
130
|
+
self._client_for_loop() # ensure the loop-live client exists before creating
|
|
131
|
+
kwargs: dict[str, object] = {
|
|
132
|
+
"model": self.spec.model,
|
|
133
|
+
"messages": self._messages(req),
|
|
134
|
+
"stream": True,
|
|
135
|
+
"timeout": req.timeout_s,
|
|
136
|
+
}
|
|
137
|
+
if with_stream_options and self.spec.stream_usage:
|
|
138
|
+
kwargs["stream_options"] = {"include_usage": True}
|
|
139
|
+
return kwargs
|
|
140
|
+
|
|
141
|
+
async def _create_with_fallback(self, req: TurnRequest) -> object:
|
|
142
|
+
"""Create the stream; a 400 with stream_options gets ONE clean retry without."""
|
|
143
|
+
client = self._client_for_loop()
|
|
144
|
+
completions = client.chat.completions # type: ignore[attr-defined]
|
|
145
|
+
try:
|
|
146
|
+
return await completions.create(**self._request_kwargs(req, True)) # type: ignore[attr-defined]
|
|
147
|
+
except openai.BadRequestError:
|
|
148
|
+
if not self.spec.stream_usage:
|
|
149
|
+
raise
|
|
150
|
+
retry_kwargs = self._request_kwargs(req, False)
|
|
151
|
+
return await completions.create(**retry_kwargs) # type: ignore[attr-defined]
|
|
152
|
+
|
|
153
|
+
def _messages(self, req: TurnRequest) -> list[dict[str, str]]:
|
|
154
|
+
if req.messages:
|
|
155
|
+
return [m.model_dump() for m in req.messages]
|
|
156
|
+
return [{"role": "user", "content": req.prompt}]
|
|
157
|
+
|
|
158
|
+
async def _consume(
|
|
159
|
+
self, stream: object, on_event: OnEvent | None, start: float, req: TurnRequest
|
|
160
|
+
) -> TurnResult:
|
|
161
|
+
texts: list[str] = []
|
|
162
|
+
input_tokens = output_tokens = 0
|
|
163
|
+
cost_usd: float | None = None
|
|
164
|
+
async for chunk in stream: # type: ignore[union-attr]
|
|
165
|
+
choices = getattr(chunk, "choices", None) or []
|
|
166
|
+
if choices:
|
|
167
|
+
delta_obj = getattr(choices[0], "delta", None)
|
|
168
|
+
delta = getattr(delta_obj, "content", None) if delta_obj is not None else None
|
|
169
|
+
if delta:
|
|
170
|
+
texts.append(delta)
|
|
171
|
+
if on_event:
|
|
172
|
+
with contextlib.suppress(Exception):
|
|
173
|
+
on_event(Event(kind="text", text=delta))
|
|
174
|
+
usage = getattr(chunk, "usage", None)
|
|
175
|
+
if usage is not None:
|
|
176
|
+
input_tokens = int(getattr(usage, "prompt_tokens", 0) or 0)
|
|
177
|
+
output_tokens = int(getattr(usage, "completion_tokens", 0) or 0)
|
|
178
|
+
cost_usd = getattr(usage, "cost", None)
|
|
179
|
+
text = "".join(texts)
|
|
180
|
+
if not text:
|
|
181
|
+
return self._error(RuntimeError("empty stream: no content chunks"), start)
|
|
182
|
+
return TurnResult(
|
|
183
|
+
stop=Stop.DONE,
|
|
184
|
+
text=text,
|
|
185
|
+
usage=self._usage(input_tokens, output_tokens, cost_usd),
|
|
186
|
+
duration_s=_elapsed(start),
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
def _usage(self, input_tokens: int, output_tokens: int, cost_usd: float | None):
|
|
190
|
+
from ..contracts import Usage
|
|
191
|
+
|
|
192
|
+
if cost_usd is None and (
|
|
193
|
+
self.spec.input_cost_per_m is not None or self.spec.output_cost_per_m is not None
|
|
194
|
+
):
|
|
195
|
+
cost_usd = self._priced_cost(input_tokens, output_tokens)
|
|
196
|
+
return Usage(input_tokens=input_tokens, output_tokens=output_tokens, cost_usd=cost_usd)
|
|
197
|
+
|
|
198
|
+
def _priced_cost(self, input_tokens: int, output_tokens: int) -> float:
|
|
199
|
+
in_rate = self.spec.input_cost_per_m or 0.0
|
|
200
|
+
out_rate = self.spec.output_cost_per_m or 0.0
|
|
201
|
+
return input_tokens / 1e6 * in_rate + output_tokens / 1e6 * out_rate
|
|
202
|
+
|
|
203
|
+
async def aclose(self) -> None:
|
|
204
|
+
client = self._client
|
|
205
|
+
self._client = None
|
|
206
|
+
if client is not None and hasattr(client, "close"):
|
|
207
|
+
with contextlib.suppress(Exception):
|
|
208
|
+
res = client.close() # type: ignore[attr-defined]
|
|
209
|
+
if asyncio.iscoroutine(res):
|
|
210
|
+
await res
|
|
211
|
+
|
|
212
|
+
def _quota(self, exc: Exception, start: float) -> TurnResult:
|
|
213
|
+
headers = getattr(getattr(exc, "response", None), "headers", {}) or {}
|
|
214
|
+
retry_after = self._retry_after(headers) or parse_retry_after(str(exc), _utc_now())
|
|
215
|
+
return TurnResult(
|
|
216
|
+
stop=Stop.QUOTA,
|
|
217
|
+
error=self._redact(str(exc)),
|
|
218
|
+
retry_after_s=retry_after,
|
|
219
|
+
duration_s=_elapsed(start),
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
def _retry_after(self, headers: object) -> int | None:
|
|
223
|
+
get = headers.get if hasattr(headers, "get") else (lambda _name: None)
|
|
224
|
+
for name in ("retry-after", "x-ratelimit-reset-requests"):
|
|
225
|
+
raw = get(name)
|
|
226
|
+
if not raw:
|
|
227
|
+
continue
|
|
228
|
+
seconds = _duration_header_seconds(str(raw))
|
|
229
|
+
if seconds is not None:
|
|
230
|
+
return max(1, math.ceil(seconds))
|
|
231
|
+
return None
|
|
232
|
+
|
|
233
|
+
def _auth(self, exc: Exception, start: float, text: str = "") -> TurnResult:
|
|
234
|
+
return TurnResult(
|
|
235
|
+
stop=Stop.AUTH, text=text, error=self._redact(str(exc)), duration_s=_elapsed(start)
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
def _timeout(self, exc: Exception, start: float, text: str = "") -> TurnResult:
|
|
239
|
+
return TurnResult(
|
|
240
|
+
stop=Stop.TIMEOUT, text=text, error=self._redact(str(exc)), duration_s=_elapsed(start)
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
def _error(self, exc: Exception, start: float, text: str = "") -> TurnResult:
|
|
244
|
+
return TurnResult(
|
|
245
|
+
stop=Stop.ERROR, text=text, error=self._redact(str(exc)), duration_s=_elapsed(start)
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _elapsed(start: float) -> float:
|
|
250
|
+
return max(time.monotonic() - start, 1e-6)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _utc_now():
|
|
254
|
+
return datetime.now(UTC)
|
onechat/executors/cli.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
"""CliExecutor (Plan 02 §6.2 / T07): profile-driven argv templates + incremental sink.
|
|
2
|
+
|
|
3
|
+
Classification order (T07): TIMEOUT first; exit 0 without parsed.error is DONE when the
|
|
4
|
+
turn produced text or tool events; quota/auth patterns match ONLY on non-zero exit or
|
|
5
|
+
parsed.error. Every parse/classify exception becomes an ERROR TurnResult (Rule 8).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import contextlib
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import shutil
|
|
14
|
+
import time
|
|
15
|
+
from datetime import UTC, datetime
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from ..config import CliProfile
|
|
19
|
+
from ..contracts import ExecutorSpec, OnEvent, Stop, TurnRequest, TurnResult
|
|
20
|
+
from ..quota import parse_retry_after
|
|
21
|
+
from ..redact import make_redactor
|
|
22
|
+
from ..selector import is_high_effort_benchmark
|
|
23
|
+
from .parsers import StreamParser
|
|
24
|
+
from .process import ProcessRunner, ProcResult
|
|
25
|
+
|
|
26
|
+
_PLACEHOLDER_RE = re.compile(r"\{(model|prompt|session_id)\}")
|
|
27
|
+
_QUOTA_RE = re.compile(
|
|
28
|
+
r"\b(?:limit reach(?:ed)?|quota(?: exceeded)?|rate limit(?: exceeded)?|"
|
|
29
|
+
r"http\s*429|status[:\s]*429|\b429\b)\b",
|
|
30
|
+
re.I,
|
|
31
|
+
)
|
|
32
|
+
_STDIN_SWITCH_CHARS = 32768
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _effort_flags(profile: CliProfile, prompt: str) -> list[str]:
|
|
36
|
+
effort = "high" if is_high_effort_benchmark(prompt) else "medium"
|
|
37
|
+
bin_name = Path(profile.binary).name.lower()
|
|
38
|
+
if profile.name == "codex" or bin_name == "codex":
|
|
39
|
+
return ["-c", f'model_reasoning_effort="{effort}"']
|
|
40
|
+
if profile.name in ("claude", "agy") or bin_name in ("claude", "agy"):
|
|
41
|
+
return ["--effort", effort]
|
|
42
|
+
return []
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def build_argv(
|
|
46
|
+
profile: CliProfile, spec: ExecutorSpec, req: TurnRequest
|
|
47
|
+
) -> tuple[list[str], str | None]:
|
|
48
|
+
"""Expand the new/resume template in ONE pass (values are never re-expanded).
|
|
49
|
+
A flag-looking prompt in a positional slot gets a '--' separator (T07)."""
|
|
50
|
+
template = profile.resume if req.native_session_id else profile.new
|
|
51
|
+
values = {"model": spec.model, "session_id": req.native_session_id or "", "prompt": req.prompt}
|
|
52
|
+
via_stdin = profile.prompt_via == "stdin"
|
|
53
|
+
flag_like = req.prompt.startswith("-")
|
|
54
|
+
effort_args = _effort_flags(profile, req.prompt)
|
|
55
|
+
has_effort = any(
|
|
56
|
+
"model_reasoning_effort" in a or "--effort" in a for a in (*template, *profile.auto)
|
|
57
|
+
)
|
|
58
|
+
argv: list[str] = []
|
|
59
|
+
for element in template:
|
|
60
|
+
if element == "{auto}":
|
|
61
|
+
argv.extend(profile.auto)
|
|
62
|
+
if effort_args and not has_effort:
|
|
63
|
+
argv.extend(effort_args)
|
|
64
|
+
continue
|
|
65
|
+
if element == "{prompt}":
|
|
66
|
+
if via_stdin:
|
|
67
|
+
continue # prompt rides stdin
|
|
68
|
+
if flag_like and _prompt_is_positional(argv):
|
|
69
|
+
argv.append("--")
|
|
70
|
+
argv.append(_PLACEHOLDER_RE.sub(lambda m: values[m.group(1)], element))
|
|
71
|
+
return argv, req.prompt if via_stdin else None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _prompt_is_positional(argv: list[str]) -> bool:
|
|
75
|
+
"""True unless the previous element is a short value flag like -p/-m/-o."""
|
|
76
|
+
if not argv:
|
|
77
|
+
return True
|
|
78
|
+
prev = argv[-1]
|
|
79
|
+
return not (len(prev) == 2 and prev.startswith("-") and not prev.startswith("--"))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _elapsed(start: float) -> float:
|
|
83
|
+
return max(time.monotonic() - start, 1e-6)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _utc_now():
|
|
87
|
+
return datetime.now(UTC)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class CliExecutor:
|
|
91
|
+
"""One CLI backend instance. run() never raises for backend problems."""
|
|
92
|
+
|
|
93
|
+
def __init__(
|
|
94
|
+
self,
|
|
95
|
+
spec: ExecutorSpec,
|
|
96
|
+
profile: CliProfile,
|
|
97
|
+
runner: ProcessRunner | None = None,
|
|
98
|
+
which: callable = shutil.which, # type: ignore[assignment]
|
|
99
|
+
) -> None:
|
|
100
|
+
self.spec = spec
|
|
101
|
+
self.profile = profile
|
|
102
|
+
self._runner: ProcessRunner = runner or _default_runner()
|
|
103
|
+
self._which = which
|
|
104
|
+
self._redact = make_redactor(
|
|
105
|
+
list(self.spec.env.keys()), extra_values=self.spec.env.values()
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
def available(self) -> bool:
|
|
109
|
+
return self._which(self.profile.binary) is not None
|
|
110
|
+
|
|
111
|
+
async def run(self, req: TurnRequest, on_event: OnEvent | None = None) -> TurnResult:
|
|
112
|
+
start = time.monotonic()
|
|
113
|
+
try:
|
|
114
|
+
stream = StreamParser(self.profile.parser) # unknown parser: honest ERROR (T07)
|
|
115
|
+
template_argv, stdin_prompt = build_argv(self.profile, self.spec, req)
|
|
116
|
+
argv = [self.profile.binary, *template_argv]
|
|
117
|
+
env = dict(os.environ)
|
|
118
|
+
env.update(self.spec.env)
|
|
119
|
+
kwargs = {}
|
|
120
|
+
if getattr(self._runner, "supports_inactivity_timeout", False):
|
|
121
|
+
kwargs["inactivity_timeout_s"] = req.inactivity_timeout_s
|
|
122
|
+
proc = await self._runner.run(
|
|
123
|
+
argv,
|
|
124
|
+
Path(req.workdir),
|
|
125
|
+
env,
|
|
126
|
+
stdin_prompt,
|
|
127
|
+
req.timeout_s,
|
|
128
|
+
on_line=self._line_sink(stream, on_event),
|
|
129
|
+
**kwargs,
|
|
130
|
+
)
|
|
131
|
+
parsed = stream.finalize()
|
|
132
|
+
|
|
133
|
+
return self._classify(proc, parsed, _elapsed(start))
|
|
134
|
+
except Exception as exc: # noqa: BLE001 - boundary: backend problems are values
|
|
135
|
+
return TurnResult(
|
|
136
|
+
stop=Stop.ERROR,
|
|
137
|
+
error=self._redact(f"{type(exc).__name__}: {exc}"),
|
|
138
|
+
duration_s=_elapsed(start),
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
def _line_sink(self, stream: StreamParser, on_event: OnEvent | None) -> callable: # type: ignore[annotation]
|
|
142
|
+
def sink(line: str) -> None:
|
|
143
|
+
if on_event is not None:
|
|
144
|
+
for event in stream.feed(line): # O(N): each line parsed exactly once (T07)
|
|
145
|
+
with contextlib.suppress(Exception):
|
|
146
|
+
on_event(event)
|
|
147
|
+
else:
|
|
148
|
+
stream.feed(line)
|
|
149
|
+
|
|
150
|
+
return sink
|
|
151
|
+
|
|
152
|
+
def _classify(self, proc: ProcResult, parsed, duration: float) -> TurnResult:
|
|
153
|
+
"""Order per T07: timeout -> healthy exit -> quota/auth (failure text only)."""
|
|
154
|
+
if proc.timed_out:
|
|
155
|
+
detail = self._redact(
|
|
156
|
+
" ".join(p for p in (parsed.error, proc.stderr_tail) if p).strip()
|
|
157
|
+
)
|
|
158
|
+
return TurnResult(
|
|
159
|
+
stop=Stop.TIMEOUT,
|
|
160
|
+
text=parsed.text,
|
|
161
|
+
error=detail,
|
|
162
|
+
native_session_id=parsed.session_id,
|
|
163
|
+
usage=parsed.usage,
|
|
164
|
+
duration_s=duration,
|
|
165
|
+
)
|
|
166
|
+
if proc.exit_code == 0 and parsed.error is None:
|
|
167
|
+
healthy = bool(parsed.text) or any(e.kind == "tool" for e in parsed.events)
|
|
168
|
+
if healthy:
|
|
169
|
+
return TurnResult(
|
|
170
|
+
stop=Stop.DONE,
|
|
171
|
+
text=parsed.text,
|
|
172
|
+
native_session_id=parsed.session_id,
|
|
173
|
+
usage=parsed.usage,
|
|
174
|
+
duration_s=duration,
|
|
175
|
+
)
|
|
176
|
+
return TurnResult(
|
|
177
|
+
stop=Stop.ERROR,
|
|
178
|
+
text=parsed.text,
|
|
179
|
+
error=self._redact("no output"),
|
|
180
|
+
native_session_id=parsed.session_id,
|
|
181
|
+
usage=parsed.usage,
|
|
182
|
+
duration_s=duration,
|
|
183
|
+
)
|
|
184
|
+
return self._classify_failure(proc, parsed, duration)
|
|
185
|
+
|
|
186
|
+
def _classify_failure(self, proc: ProcResult, parsed, duration: float) -> TurnResult:
|
|
187
|
+
error_text = " ".join(p for p in (parsed.error, proc.stderr_tail) if p).strip()
|
|
188
|
+
lowered = error_text.lower()
|
|
189
|
+
native = parsed.session_id
|
|
190
|
+
base = dict(
|
|
191
|
+
text=parsed.text, native_session_id=native, usage=parsed.usage, duration_s=duration
|
|
192
|
+
)
|
|
193
|
+
is_quota = any(p.lower() in lowered for p in self.profile.quota_patterns) or bool(
|
|
194
|
+
_QUOTA_RE.search(lowered)
|
|
195
|
+
)
|
|
196
|
+
if is_quota:
|
|
197
|
+
return TurnResult(
|
|
198
|
+
stop=Stop.QUOTA,
|
|
199
|
+
error=self._redact(error_text),
|
|
200
|
+
retry_after_s=parse_retry_after(error_text, _utc_now()),
|
|
201
|
+
**base,
|
|
202
|
+
)
|
|
203
|
+
if any(p.lower() in lowered for p in self.profile.auth_patterns):
|
|
204
|
+
return TurnResult(stop=Stop.AUTH, error=self._redact(error_text), **base)
|
|
205
|
+
return TurnResult(stop=Stop.ERROR, error=self._redact(error_text or "no output"), **base)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _default_runner() -> ProcessRunner:
|
|
209
|
+
from .process import AsyncProcessRunner
|
|
210
|
+
|
|
211
|
+
return AsyncProcessRunner()
|