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
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""claude-code-like stream family (T06): claude, qwen, gemini + gemini-native extras.
|
|
2
|
+
|
|
3
|
+
Shapes: type=assistant (content blocks) / type=result (final text+usage) as captured in
|
|
4
|
+
tests/fixtures/cli/; gemini-native type=message / type=stats handled too (no live fixture
|
|
5
|
+
yet — compat.md §1 marks gemini turn-level shapes unverified).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from ..contracts import Event, Usage
|
|
11
|
+
from .parser_formats import Parsed, _cc_usage, _dict_or, _safe_int, _safe_json, _tool_target
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class CCFamily:
|
|
15
|
+
"""claude-code-like result family: claude, qwen, gemini (+ gemini-native extras)."""
|
|
16
|
+
|
|
17
|
+
def __init__(self) -> None:
|
|
18
|
+
self.texts: list[str] = []
|
|
19
|
+
self.events: list[Event] = []
|
|
20
|
+
self.session_id: str | None = None
|
|
21
|
+
self.usage = Usage()
|
|
22
|
+
self.error: str | None = None
|
|
23
|
+
|
|
24
|
+
def feed(self, line: str) -> list[Event]:
|
|
25
|
+
data = _safe_json(line)
|
|
26
|
+
if data is None:
|
|
27
|
+
return []
|
|
28
|
+
before = len(self.events)
|
|
29
|
+
self._dispatch(data)
|
|
30
|
+
return self.events[before:]
|
|
31
|
+
|
|
32
|
+
def _dispatch(self, data: dict) -> None:
|
|
33
|
+
session = data.get("session_id")
|
|
34
|
+
if session and self.session_id is None:
|
|
35
|
+
self.session_id = str(session)
|
|
36
|
+
kind = data.get("type")
|
|
37
|
+
if kind == "assistant":
|
|
38
|
+
self._assistant(data)
|
|
39
|
+
elif kind == "result":
|
|
40
|
+
self._result(data)
|
|
41
|
+
elif kind == "message": # gemini-native stream shape
|
|
42
|
+
self._message(data)
|
|
43
|
+
elif kind == "stats": # gemini-native usage shape
|
|
44
|
+
self._stats(data)
|
|
45
|
+
|
|
46
|
+
def _add_text(self, text: str) -> None:
|
|
47
|
+
self.texts.append(text)
|
|
48
|
+
self.events.append(Event(kind="text", text=text))
|
|
49
|
+
|
|
50
|
+
def _assistant(self, data: dict) -> None:
|
|
51
|
+
content = _dict_or(data.get("message")).get("content")
|
|
52
|
+
if isinstance(content, str):
|
|
53
|
+
self._add_text(content)
|
|
54
|
+
return
|
|
55
|
+
for block in content if isinstance(content, list) else []:
|
|
56
|
+
if not isinstance(block, dict):
|
|
57
|
+
continue
|
|
58
|
+
if block.get("type") == "text" and block.get("text"):
|
|
59
|
+
self._add_text(str(block["text"]))
|
|
60
|
+
elif block.get("type") == "tool_use":
|
|
61
|
+
summary = f"tool: {block.get('name', 'unknown')}{_tool_target(block.get('input'))}"
|
|
62
|
+
self.events.append(Event(kind="tool", text=summary))
|
|
63
|
+
|
|
64
|
+
def _message(self, data: dict) -> None:
|
|
65
|
+
if data.get("role") == "user":
|
|
66
|
+
return
|
|
67
|
+
content = (
|
|
68
|
+
data.get("content")
|
|
69
|
+
if "content" in data
|
|
70
|
+
else _dict_or(data.get("message")).get("content")
|
|
71
|
+
)
|
|
72
|
+
if isinstance(content, str):
|
|
73
|
+
self._add_text(content)
|
|
74
|
+
return
|
|
75
|
+
for part in content if isinstance(content, list) else []:
|
|
76
|
+
text = part.get("text") if isinstance(part, dict) else part
|
|
77
|
+
if isinstance(text, str) and text:
|
|
78
|
+
self._add_text(text)
|
|
79
|
+
|
|
80
|
+
def _stats(self, data: dict) -> None:
|
|
81
|
+
usage = data.get("usage") if isinstance(data.get("usage"), dict) else data
|
|
82
|
+
self.usage = Usage(
|
|
83
|
+
input_tokens=_safe_int(usage.get("input_tokens")),
|
|
84
|
+
output_tokens=_safe_int(usage.get("output_tokens")),
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
def _result(self, data: dict) -> None:
|
|
88
|
+
stats = data.get("stats")
|
|
89
|
+
if isinstance(stats, dict):
|
|
90
|
+
self._stats(stats)
|
|
91
|
+
else:
|
|
92
|
+
self.usage = _cc_usage(data)
|
|
93
|
+
if data.get("is_error") or data.get("subtype") == "error_during_execution":
|
|
94
|
+
self._result_error(data)
|
|
95
|
+
return
|
|
96
|
+
result_text = str(data.get("result") or "")
|
|
97
|
+
if not result_text:
|
|
98
|
+
return
|
|
99
|
+
joined = "\n".join(t for t in self.texts if t)
|
|
100
|
+
if not self.texts or (result_text != self.texts[-1] and result_text != joined):
|
|
101
|
+
self._add_text(result_text)
|
|
102
|
+
|
|
103
|
+
def _result_error(self, data: dict) -> None:
|
|
104
|
+
err = data.get("error")
|
|
105
|
+
errors = data.get("errors")
|
|
106
|
+
if isinstance(err, dict):
|
|
107
|
+
msg = str(err.get("message") or "")
|
|
108
|
+
elif err:
|
|
109
|
+
msg = str(err)
|
|
110
|
+
elif data.get("result"):
|
|
111
|
+
msg = str(data["result"])
|
|
112
|
+
elif isinstance(errors, list) and errors:
|
|
113
|
+
msg = "; ".join(str(e) for e in errors)
|
|
114
|
+
else:
|
|
115
|
+
msg = self.texts[-1] if self.texts else "error"
|
|
116
|
+
self.error = msg
|
|
117
|
+
self.texts.clear()
|
|
118
|
+
|
|
119
|
+
def finalize(self) -> Parsed:
|
|
120
|
+
out = Parsed(
|
|
121
|
+
text="\n".join(t for t in self.texts if t),
|
|
122
|
+
session_id=self.session_id,
|
|
123
|
+
usage=self.usage,
|
|
124
|
+
error=self.error,
|
|
125
|
+
events=self.events,
|
|
126
|
+
)
|
|
127
|
+
if out.text == "" and out.error is None and not any(e.kind == "tool" for e in out.events):
|
|
128
|
+
out.error = "no assistant text in stream"
|
|
129
|
+
return out
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Shared parser plumbing (T06): Parsed model, tolerant JSON/typing helpers, registry.
|
|
2
|
+
|
|
3
|
+
Handler classes live next to their stream families: ``parser_cc.py`` (claude-code-like),
|
|
4
|
+
``parser_tool_streams.py`` (codex / agy / opencode). Wrong-typed nested fields are a
|
|
5
|
+
no-op, never a crash (garbage lines are ignored, Plan 02 §5).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from pydantic import BaseModel, Field
|
|
14
|
+
|
|
15
|
+
from ..contracts import Event, Usage
|
|
16
|
+
from ..redact import redact
|
|
17
|
+
|
|
18
|
+
__all__ = ["Parsed", "_safe_json", "_safe_int", "_dict_or", "_tool_target", "_cc_usage", "redact"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Parsed(BaseModel):
|
|
22
|
+
text: str = ""
|
|
23
|
+
session_id: str | None = None
|
|
24
|
+
usage: Usage = Field(default_factory=Usage)
|
|
25
|
+
error: str | None = None
|
|
26
|
+
events: list[Event] = Field(default_factory=list)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _safe_json(line: str) -> dict | None:
|
|
30
|
+
stripped = line.strip()
|
|
31
|
+
if not stripped.startswith("{"):
|
|
32
|
+
return None
|
|
33
|
+
try:
|
|
34
|
+
data = json.loads(stripped)
|
|
35
|
+
except json.JSONDecodeError:
|
|
36
|
+
return None
|
|
37
|
+
return data if isinstance(data, dict) else None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _dict_or(value: Any) -> dict:
|
|
41
|
+
return value if isinstance(value, dict) else {}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _safe_int(value: Any) -> int:
|
|
45
|
+
if isinstance(value, bool) or value is None:
|
|
46
|
+
return 0
|
|
47
|
+
if isinstance(value, (int, float)):
|
|
48
|
+
return int(value)
|
|
49
|
+
if isinstance(value, str):
|
|
50
|
+
try:
|
|
51
|
+
return int(float(value))
|
|
52
|
+
except ValueError:
|
|
53
|
+
return 0
|
|
54
|
+
return 0
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _tool_target(tool_input: object) -> str:
|
|
58
|
+
"""First recognizable target field of a tool_use input (Plan 02 §5 example)."""
|
|
59
|
+
if not isinstance(tool_input, dict):
|
|
60
|
+
return ""
|
|
61
|
+
for key in ("file_path", "path", "notebook", "url", "command", "pattern"):
|
|
62
|
+
value = tool_input.get(key)
|
|
63
|
+
if isinstance(value, str) and value:
|
|
64
|
+
return f" {redact(value)}"
|
|
65
|
+
return ""
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _cc_usage(data: dict) -> Usage:
|
|
69
|
+
"""input_tokens includes cache writes/reads (T06) — they are billed input too."""
|
|
70
|
+
usage = _dict_or(data.get("usage"))
|
|
71
|
+
|
|
72
|
+
def _int(key: str) -> int:
|
|
73
|
+
return _safe_int(usage.get(key))
|
|
74
|
+
|
|
75
|
+
input_tokens = _int("input_tokens") + _int("cache_creation_input_tokens")
|
|
76
|
+
input_tokens += _int("cache_read_input_tokens")
|
|
77
|
+
return Usage(
|
|
78
|
+
input_tokens=input_tokens,
|
|
79
|
+
output_tokens=_int("output_tokens"),
|
|
80
|
+
cost_usd=data.get("total_cost_usd"),
|
|
81
|
+
)
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""Tool-centric stream families (T06): codex exec --json, agy result, opencode json."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from ..contracts import Event, Usage
|
|
6
|
+
from ..redact import redact
|
|
7
|
+
from .parser_formats import Parsed, _dict_or, _safe_int, _safe_json, _tool_target
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class CodexFamily:
|
|
11
|
+
"""codex exec --json (Plan 09 K2, exec_events.rs). Usage accumulates per turn."""
|
|
12
|
+
|
|
13
|
+
def __init__(self) -> None:
|
|
14
|
+
self.texts: list[str] = []
|
|
15
|
+
self.events: list[Event] = []
|
|
16
|
+
self.errors: list[str] = []
|
|
17
|
+
self.session_id: str | None = None
|
|
18
|
+
self._input = 0
|
|
19
|
+
self._output = 0
|
|
20
|
+
|
|
21
|
+
def feed(self, line: str) -> list[Event]:
|
|
22
|
+
data = _safe_json(line)
|
|
23
|
+
if data is None:
|
|
24
|
+
return []
|
|
25
|
+
before = len(self.events)
|
|
26
|
+
self._dispatch(data)
|
|
27
|
+
return self.events[before:]
|
|
28
|
+
|
|
29
|
+
def _dispatch(self, data: dict) -> None:
|
|
30
|
+
kind = data.get("type")
|
|
31
|
+
if kind == "thread.started" and data.get("thread_id"):
|
|
32
|
+
self.session_id = str(data["thread_id"])
|
|
33
|
+
elif kind == "item.completed":
|
|
34
|
+
self._item(data)
|
|
35
|
+
elif kind == "error":
|
|
36
|
+
self.errors.append(str(data.get("message") or data.get("error") or "stream error"))
|
|
37
|
+
elif kind == "turn.failed":
|
|
38
|
+
self._turn_failed(data)
|
|
39
|
+
elif kind == "turn.completed":
|
|
40
|
+
usage = _dict_or(data.get("usage"))
|
|
41
|
+
self._input += _safe_int(usage.get("input_tokens"))
|
|
42
|
+
self._output += _safe_int(usage.get("output_tokens"))
|
|
43
|
+
|
|
44
|
+
def _turn_failed(self, data: dict) -> None:
|
|
45
|
+
err = data.get("error") or {}
|
|
46
|
+
message = err.get("message") if isinstance(err, dict) else err
|
|
47
|
+
self.errors.append(str(message or "turn failed"))
|
|
48
|
+
|
|
49
|
+
def _item(self, data: dict) -> None:
|
|
50
|
+
item = data.get("item")
|
|
51
|
+
payload = _dict_or(_dict_or(item).get("details")) or _dict_or(item)
|
|
52
|
+
item_type = str(payload.get("type") or _dict_or(item).get("type") or "")
|
|
53
|
+
if item_type == "agent_message":
|
|
54
|
+
text = payload.get("text") or payload.get("message") or ""
|
|
55
|
+
if text:
|
|
56
|
+
self.texts.append(str(text))
|
|
57
|
+
self.events.append(Event(kind="text", text=str(text)))
|
|
58
|
+
elif item_type == "command_execution":
|
|
59
|
+
self._command(payload)
|
|
60
|
+
elif item_type in ("mcp_tool_call", "collab_tool_call"):
|
|
61
|
+
label = item_type.replace("_tool_call", "")
|
|
62
|
+
self.events.append(
|
|
63
|
+
Event(kind="tool", text=f"tool: {label} {payload.get('server') or ''}".strip())
|
|
64
|
+
)
|
|
65
|
+
elif item_type == "file_change":
|
|
66
|
+
changes = payload.get("changes") or []
|
|
67
|
+
first = ""
|
|
68
|
+
if changes and isinstance(changes[0], dict):
|
|
69
|
+
first = str(changes[0].get("path") or "")
|
|
70
|
+
text = f"tool: file_change {redact(first)}".strip()
|
|
71
|
+
self.events.append(Event(kind="tool", text=text))
|
|
72
|
+
elif item_type in ("todo_list", "web_search"):
|
|
73
|
+
self.events.append(Event(kind="tool", text=f"tool: {item_type}"))
|
|
74
|
+
elif item_type == "error":
|
|
75
|
+
self.errors.append(str(payload.get("message") or "item error"))
|
|
76
|
+
|
|
77
|
+
def _command(self, payload: dict) -> None:
|
|
78
|
+
if str(payload.get("status") or "") == "declined": # healthy: policy said no
|
|
79
|
+
self.events.append(Event(kind="tool", text="tool: command (declined)"))
|
|
80
|
+
else:
|
|
81
|
+
target = _tool_target({"command": payload.get("command")})
|
|
82
|
+
self.events.append(Event(kind="tool", text=f"tool: command{target}"))
|
|
83
|
+
|
|
84
|
+
def finalize(self) -> Parsed:
|
|
85
|
+
out = Parsed(
|
|
86
|
+
text="\n".join(self.texts),
|
|
87
|
+
session_id=self.session_id,
|
|
88
|
+
usage=Usage(input_tokens=self._input, output_tokens=self._output),
|
|
89
|
+
error="; ".join(self.errors) or None,
|
|
90
|
+
events=self.events,
|
|
91
|
+
)
|
|
92
|
+
if out.text == "" and out.error is None and not any(e.kind == "tool" for e in out.events):
|
|
93
|
+
out.error = "no agent message in stream" # a declined-only turn DID work
|
|
94
|
+
return out
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class AgyFamily:
|
|
98
|
+
"""agy: {event: result, result: {conversation_id, status, response, error, usage}}."""
|
|
99
|
+
|
|
100
|
+
def __init__(self) -> None:
|
|
101
|
+
self.text: str = ""
|
|
102
|
+
self.events: list[Event] = []
|
|
103
|
+
self.session_id: str | None = None
|
|
104
|
+
self.usage = Usage()
|
|
105
|
+
self.error: str | None = None
|
|
106
|
+
|
|
107
|
+
def feed(self, line: str) -> list[Event]:
|
|
108
|
+
data = _safe_json(line)
|
|
109
|
+
if data is None or data.get("event") != "result":
|
|
110
|
+
return []
|
|
111
|
+
before = len(self.events)
|
|
112
|
+
result = _dict_or(data.get("result"))
|
|
113
|
+
self.session_id = result.get("conversation_id") or None
|
|
114
|
+
self.text = str(result.get("response") or "")
|
|
115
|
+
if self.text:
|
|
116
|
+
self.events.append(Event(kind="text", text=self.text))
|
|
117
|
+
if result.get("status") == "ERROR" or result.get("error"):
|
|
118
|
+
self.error = str(result.get("error") or "agy error")
|
|
119
|
+
usage = _dict_or(result.get("usage"))
|
|
120
|
+
self.usage = Usage(
|
|
121
|
+
input_tokens=_safe_int(usage.get("input_tokens")),
|
|
122
|
+
output_tokens=_safe_int(usage.get("output_tokens")),
|
|
123
|
+
)
|
|
124
|
+
return self.events[before:]
|
|
125
|
+
|
|
126
|
+
def finalize(self) -> Parsed:
|
|
127
|
+
out = Parsed(
|
|
128
|
+
text=self.text,
|
|
129
|
+
session_id=self.session_id,
|
|
130
|
+
usage=self.usage,
|
|
131
|
+
error=self.error,
|
|
132
|
+
events=self.events,
|
|
133
|
+
)
|
|
134
|
+
if out.text == "" and out.error is None:
|
|
135
|
+
out.error = "no agy result event"
|
|
136
|
+
return out
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class OpencodeFamily:
|
|
140
|
+
"""opencode run --format json: text/tool/error events; usage SUMS across step_finish."""
|
|
141
|
+
|
|
142
|
+
def __init__(self) -> None:
|
|
143
|
+
self.texts: list[str] = []
|
|
144
|
+
self.events: list[Event] = []
|
|
145
|
+
self.errors: list[str] = []
|
|
146
|
+
self._retry_errors: list[str] = []
|
|
147
|
+
self.session_id: str | None = None
|
|
148
|
+
self._input = 0
|
|
149
|
+
self._output = 0
|
|
150
|
+
self._cost: float | None = None
|
|
151
|
+
|
|
152
|
+
def feed(self, line: str) -> list[Event]:
|
|
153
|
+
data = _safe_json(line)
|
|
154
|
+
if data is None:
|
|
155
|
+
return []
|
|
156
|
+
before = len(self.events)
|
|
157
|
+
self._dispatch(data)
|
|
158
|
+
return self.events[before:]
|
|
159
|
+
|
|
160
|
+
def _dispatch(self, data: dict) -> None:
|
|
161
|
+
session = data.get("sessionID")
|
|
162
|
+
if session and self.session_id is None:
|
|
163
|
+
self.session_id = str(session)
|
|
164
|
+
kind = data.get("type")
|
|
165
|
+
part = _dict_or(data.get("part"))
|
|
166
|
+
if kind == "text" and part.get("text"):
|
|
167
|
+
self.texts.append(str(part["text"]))
|
|
168
|
+
self.events.append(Event(kind="text", text=str(part["text"])))
|
|
169
|
+
elif kind in ("step_finish", "step-finish") or part.get("type") == "step-finish":
|
|
170
|
+
self._tokens(_dict_or(part.get("tokens")))
|
|
171
|
+
elif kind == "tool" and part.get("tool"):
|
|
172
|
+
self._tool(part)
|
|
173
|
+
elif kind == "retry":
|
|
174
|
+
self._record_retry(data.get("error"))
|
|
175
|
+
elif kind == "error" or data.get("error"):
|
|
176
|
+
self._error(data.get("error"))
|
|
177
|
+
|
|
178
|
+
def _tool(self, part: dict) -> None:
|
|
179
|
+
title = part.get("title") if isinstance(part.get("title"), str) else ""
|
|
180
|
+
self.events.append(
|
|
181
|
+
Event(kind="tool", text=f"tool: {part.get('tool')} {redact(title)}".strip())
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
def _tokens(self, tokens: dict) -> None:
|
|
185
|
+
self._input += _safe_int(tokens.get("input"))
|
|
186
|
+
self._output += _safe_int(tokens.get("output"))
|
|
187
|
+
cost = tokens.get("cost")
|
|
188
|
+
if isinstance(cost, (int, float)):
|
|
189
|
+
self._cost = (self._cost or 0.0) + float(cost)
|
|
190
|
+
|
|
191
|
+
def _extract_err_text(self, err: object) -> str:
|
|
192
|
+
if isinstance(err, str):
|
|
193
|
+
return err or "opencode error"
|
|
194
|
+
info = _dict_or(err)
|
|
195
|
+
body = str(_dict_or(info.get("response")).get("body") or "")
|
|
196
|
+
return str(info.get("message") or body or "opencode error")
|
|
197
|
+
|
|
198
|
+
def _error(self, err: object) -> None:
|
|
199
|
+
self.errors.append(self._extract_err_text(err))
|
|
200
|
+
|
|
201
|
+
def _record_retry(self, err: object) -> None:
|
|
202
|
+
self._retry_errors.append(self._extract_err_text(err))
|
|
203
|
+
|
|
204
|
+
def finalize(self) -> Parsed:
|
|
205
|
+
errs = list(self.errors)
|
|
206
|
+
has_progress = bool(self.texts or any(e.kind == "tool" for e in self.events))
|
|
207
|
+
if not has_progress and self._retry_errors:
|
|
208
|
+
errs.extend(self._retry_errors)
|
|
209
|
+
out = Parsed(
|
|
210
|
+
text="\n".join(self.texts),
|
|
211
|
+
session_id=self.session_id,
|
|
212
|
+
usage=Usage(input_tokens=self._input, output_tokens=self._output, cost_usd=self._cost),
|
|
213
|
+
error="; ".join(errs) or None,
|
|
214
|
+
events=self.events,
|
|
215
|
+
)
|
|
216
|
+
if out.text == "" and out.error is None:
|
|
217
|
+
out.error = "no text part in opencode stream"
|
|
218
|
+
return out
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Output parsers (Plan 02 §5 / T06): incremental ``StreamParser`` + batch ``parse``.
|
|
2
|
+
|
|
3
|
+
Field shapes come from the real captured fixtures in tests/fixtures/cli/ (Plan 01).
|
|
4
|
+
``feed()`` parses each line exactly once (O(N), fixes the O(n^2) sink) and returns that
|
|
5
|
+
line's new events; the batch ``parse()`` is StreamParser fed with all lines, so
|
|
6
|
+
incremental and batch results match exactly by construction.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Iterable
|
|
12
|
+
|
|
13
|
+
from ..contracts import Event
|
|
14
|
+
from .parser_cc import CCFamily
|
|
15
|
+
from .parser_formats import Parsed
|
|
16
|
+
from .parser_tool_streams import AgyFamily, CodexFamily, OpencodeFamily
|
|
17
|
+
|
|
18
|
+
__all__ = ["Parsed", "StreamParser", "PARSERS", "parse"]
|
|
19
|
+
|
|
20
|
+
PARSERS: dict[str, type] = { # name -> handler class (registry validated by config load)
|
|
21
|
+
"claude_stream_json": CCFamily,
|
|
22
|
+
"codex_jsonl": CodexFamily,
|
|
23
|
+
"gemini_stream_json": CCFamily,
|
|
24
|
+
"agy_stream_json": AgyFamily,
|
|
25
|
+
"opencode_json": OpencodeFamily,
|
|
26
|
+
"qwen_stream_json": CCFamily,
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class StreamParser:
|
|
31
|
+
"""Incremental parser for one turn's output stream (T06/T07)."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, parser_name: str) -> None:
|
|
34
|
+
handler = PARSERS.get(parser_name)
|
|
35
|
+
if handler is None:
|
|
36
|
+
raise KeyError(f"unknown parser: {parser_name} (known: {sorted(PARSERS)})")
|
|
37
|
+
self._handler = handler()
|
|
38
|
+
|
|
39
|
+
def feed(self, line: str) -> list[Event]:
|
|
40
|
+
"""Parse one line; returns the NEW events it produced."""
|
|
41
|
+
return self._handler.feed(line)
|
|
42
|
+
|
|
43
|
+
def finalize(self) -> Parsed:
|
|
44
|
+
return self._handler.finalize()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def parse(parser_name: str, lines: Iterable[str]) -> Parsed:
|
|
48
|
+
"""Batch parse: fresh StreamParser over all lines (identical to incremental)."""
|
|
49
|
+
stream = StreamParser(parser_name) # unknown names are a programming error (raise)
|
|
50
|
+
for line in lines:
|
|
51
|
+
stream.feed(line)
|
|
52
|
+
return stream.finalize()
|