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,228 @@
|
|
|
1
|
+
"""ProcessRunner protocol + asyncio implementation (Plan 02 §6.1 / T05).
|
|
2
|
+
|
|
3
|
+
Chunked stdout reads (arbitrary lines up to 4 MiB never raise ValueError), stdin fed
|
|
4
|
+
concurrently (broken-pipe safe when the child exits early), rolling 4 KiB stderr tail,
|
|
5
|
+
and full process-group termination on timeout AND cancellation (no orphan leaks).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import contextlib
|
|
12
|
+
import signal
|
|
13
|
+
import time
|
|
14
|
+
from collections.abc import Callable
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Protocol
|
|
17
|
+
|
|
18
|
+
from pydantic import BaseModel
|
|
19
|
+
|
|
20
|
+
STDERR_TAIL_BYTES = 4096
|
|
21
|
+
KILL_GRACE_S = 5.0
|
|
22
|
+
STDOUT_CHUNK_BYTES = 65536
|
|
23
|
+
MAX_LINE_BYTES = 4 * 1024 * 1024
|
|
24
|
+
_SOFT_PIPE_ERRORS = (BrokenPipeError, ConnectionResetError)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ProcResult(BaseModel):
|
|
28
|
+
exit_code: int
|
|
29
|
+
stdout_lines: list[str]
|
|
30
|
+
stderr_tail: str
|
|
31
|
+
timed_out: bool
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ProcessRunner(Protocol):
|
|
35
|
+
supports_inactivity_timeout: bool = False
|
|
36
|
+
|
|
37
|
+
async def run(
|
|
38
|
+
self,
|
|
39
|
+
argv: list[str],
|
|
40
|
+
cwd: Path,
|
|
41
|
+
env: dict[str, str] | None,
|
|
42
|
+
stdin: str | None,
|
|
43
|
+
timeout_s: int,
|
|
44
|
+
on_line: Callable[[str], None],
|
|
45
|
+
inactivity_timeout_s: float | None = None,
|
|
46
|
+
) -> ProcResult: ...
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class AsyncProcessRunner:
|
|
50
|
+
"""Runs one subprocess in its own process group; streams stdout lines to on_line."""
|
|
51
|
+
|
|
52
|
+
supports_inactivity_timeout: bool = True
|
|
53
|
+
|
|
54
|
+
async def run(
|
|
55
|
+
self,
|
|
56
|
+
argv: list[str],
|
|
57
|
+
cwd: Path,
|
|
58
|
+
env: dict[str, str] | None,
|
|
59
|
+
stdin: str | None,
|
|
60
|
+
timeout_s: int,
|
|
61
|
+
on_line: Callable[[str], None],
|
|
62
|
+
inactivity_timeout_s: float | None = None,
|
|
63
|
+
) -> ProcResult:
|
|
64
|
+
proc = await asyncio.create_subprocess_exec(
|
|
65
|
+
*argv,
|
|
66
|
+
cwd=str(cwd),
|
|
67
|
+
env=env,
|
|
68
|
+
stdin=asyncio.subprocess.PIPE if stdin is not None else asyncio.subprocess.DEVNULL,
|
|
69
|
+
stdout=asyncio.subprocess.PIPE,
|
|
70
|
+
stderr=asyncio.subprocess.PIPE,
|
|
71
|
+
start_new_session=True,
|
|
72
|
+
)
|
|
73
|
+
stdout_lines: list[str] = []
|
|
74
|
+
stderr_buf = bytearray()
|
|
75
|
+
timed_out = False
|
|
76
|
+
try:
|
|
77
|
+
await self._run_with_watchdogs(
|
|
78
|
+
proc, stdin, on_line, stdout_lines, stderr_buf, timeout_s, inactivity_timeout_s
|
|
79
|
+
)
|
|
80
|
+
except TimeoutError:
|
|
81
|
+
timed_out = True
|
|
82
|
+
await self._terminate_group(proc)
|
|
83
|
+
except asyncio.CancelledError:
|
|
84
|
+
await self._terminate_group(proc)
|
|
85
|
+
raise
|
|
86
|
+
return ProcResult(
|
|
87
|
+
exit_code=proc.returncode if proc.returncode is not None else -1,
|
|
88
|
+
stdout_lines=stdout_lines,
|
|
89
|
+
stderr_tail=bytes(stderr_buf).decode("utf-8", errors="replace"),
|
|
90
|
+
timed_out=timed_out,
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
async def _run_with_watchdogs(
|
|
94
|
+
self,
|
|
95
|
+
proc: asyncio.subprocess.Process,
|
|
96
|
+
stdin: str | None,
|
|
97
|
+
on_line: Callable[[str], None],
|
|
98
|
+
stdout_lines: list[str],
|
|
99
|
+
stderr_buf: bytearray,
|
|
100
|
+
timeout_s: int,
|
|
101
|
+
inactivity_s: float | None,
|
|
102
|
+
) -> None:
|
|
103
|
+
last_active = [time.monotonic()]
|
|
104
|
+
drive_task = asyncio.ensure_future(
|
|
105
|
+
self._drive(proc, stdin, on_line, stdout_lines, stderr_buf, last_active)
|
|
106
|
+
)
|
|
107
|
+
wall_deadline = time.monotonic() + timeout_s
|
|
108
|
+
try:
|
|
109
|
+
while not drive_task.done():
|
|
110
|
+
now = time.monotonic()
|
|
111
|
+
if now >= wall_deadline:
|
|
112
|
+
raise TimeoutError("wall-clock timeout")
|
|
113
|
+
if inactivity_s and inactivity_s > 0 and (now - last_active[0]) >= inactivity_s:
|
|
114
|
+
msg = b"\n[onechat watchdog: process killed after inactivity timeout]\n"
|
|
115
|
+
stderr_buf.extend(msg)
|
|
116
|
+
raise TimeoutError("inactivity timeout")
|
|
117
|
+
step = 0.5
|
|
118
|
+
if inactivity_s and inactivity_s > 0:
|
|
119
|
+
step = min(step, max(0.05, inactivity_s - (now - last_active[0])))
|
|
120
|
+
with contextlib.suppress(TimeoutError):
|
|
121
|
+
await asyncio.wait_for(asyncio.shield(drive_task), timeout=step)
|
|
122
|
+
await drive_task
|
|
123
|
+
finally:
|
|
124
|
+
if not drive_task.done():
|
|
125
|
+
drive_task.cancel()
|
|
126
|
+
with contextlib.suppress(asyncio.CancelledError, Exception):
|
|
127
|
+
await drive_task
|
|
128
|
+
|
|
129
|
+
async def _drive(
|
|
130
|
+
self,
|
|
131
|
+
proc: asyncio.subprocess.Process,
|
|
132
|
+
stdin: str | None,
|
|
133
|
+
on_line: Callable[[str], None],
|
|
134
|
+
stdout_lines: list[str],
|
|
135
|
+
stderr_buf: bytearray,
|
|
136
|
+
last_active: list[float] | None = None,
|
|
137
|
+
) -> None:
|
|
138
|
+
"""stdin feed, both pumps and proc.wait() run concurrently (no pipe deadlocks)."""
|
|
139
|
+
feed = asyncio.ensure_future(self._feed_stdin(proc, stdin))
|
|
140
|
+
pump_out = asyncio.ensure_future(
|
|
141
|
+
self._pump_lines(proc.stdout, on_line, stdout_lines, last_active)
|
|
142
|
+
)
|
|
143
|
+
pump_err = asyncio.ensure_future(self._pump_stderr(proc.stderr, stderr_buf, last_active))
|
|
144
|
+
results = await asyncio.gather(
|
|
145
|
+
pump_out, pump_err, feed, proc.wait(), return_exceptions=True
|
|
146
|
+
)
|
|
147
|
+
for exc in results[:3]:
|
|
148
|
+
if isinstance(exc, Exception) and not isinstance(exc, _SOFT_PIPE_ERRORS):
|
|
149
|
+
raise exc
|
|
150
|
+
|
|
151
|
+
async def _feed_stdin(self, proc: asyncio.subprocess.Process, stdin_text: str | None) -> None:
|
|
152
|
+
if stdin_text is None or proc.stdin is None:
|
|
153
|
+
return
|
|
154
|
+
try:
|
|
155
|
+
proc.stdin.write(stdin_text.encode("utf-8"))
|
|
156
|
+
await proc.stdin.drain()
|
|
157
|
+
proc.stdin.close()
|
|
158
|
+
except _SOFT_PIPE_ERRORS:
|
|
159
|
+
pass # child exited before reading stdin; the exit code carries the outcome
|
|
160
|
+
|
|
161
|
+
async def _pump_lines(
|
|
162
|
+
self,
|
|
163
|
+
stream: asyncio.StreamReader | None,
|
|
164
|
+
on_line: Callable[[str], None],
|
|
165
|
+
sink: list[str],
|
|
166
|
+
last_active: list[float] | None = None,
|
|
167
|
+
) -> None:
|
|
168
|
+
"""65536-byte chunked reads: split on newlines, cap a single line at 4 MiB."""
|
|
169
|
+
if stream is None:
|
|
170
|
+
return
|
|
171
|
+
buf = b""
|
|
172
|
+
while True:
|
|
173
|
+
chunk = await stream.read(STDOUT_CHUNK_BYTES)
|
|
174
|
+
if not chunk:
|
|
175
|
+
break
|
|
176
|
+
if last_active is not None:
|
|
177
|
+
last_active[0] = time.monotonic()
|
|
178
|
+
buf += chunk
|
|
179
|
+
while b"\n" in buf or len(buf) >= MAX_LINE_BYTES:
|
|
180
|
+
if b"\n" in buf:
|
|
181
|
+
raw, _, buf = buf.partition(b"\n")
|
|
182
|
+
else: # pathological unterminated line: emit capped chunk, keep memory bounded
|
|
183
|
+
raw, buf = buf[:MAX_LINE_BYTES], buf[MAX_LINE_BYTES:]
|
|
184
|
+
line = raw.decode("utf-8", errors="replace").rstrip("\r")
|
|
185
|
+
sink.append(line)
|
|
186
|
+
on_line(line)
|
|
187
|
+
if buf:
|
|
188
|
+
line = buf.decode("utf-8", errors="replace").rstrip("\r")
|
|
189
|
+
sink.append(line)
|
|
190
|
+
on_line(line)
|
|
191
|
+
|
|
192
|
+
async def _pump_stderr(
|
|
193
|
+
self,
|
|
194
|
+
stream: asyncio.StreamReader | None,
|
|
195
|
+
buf: bytearray,
|
|
196
|
+
last_active: list[float] | None = None,
|
|
197
|
+
) -> None:
|
|
198
|
+
while stream is not None:
|
|
199
|
+
raw = await stream.read(1024)
|
|
200
|
+
if not raw:
|
|
201
|
+
break
|
|
202
|
+
if last_active is not None:
|
|
203
|
+
last_active[0] = time.monotonic()
|
|
204
|
+
buf.extend(raw)
|
|
205
|
+
if len(buf) > STDERR_TAIL_BYTES:
|
|
206
|
+
del buf[: len(buf) - STDERR_TAIL_BYTES]
|
|
207
|
+
|
|
208
|
+
async def _terminate_group(self, proc: asyncio.subprocess.Process) -> None:
|
|
209
|
+
import contextlib
|
|
210
|
+
|
|
211
|
+
try:
|
|
212
|
+
import os
|
|
213
|
+
|
|
214
|
+
os.killpg(proc.pid, signal.SIGTERM)
|
|
215
|
+
except (ProcessLookupError, PermissionError, AttributeError):
|
|
216
|
+
with contextlib.suppress(ProcessLookupError):
|
|
217
|
+
proc.terminate()
|
|
218
|
+
try:
|
|
219
|
+
await asyncio.wait_for(proc.wait(), timeout=KILL_GRACE_S)
|
|
220
|
+
except TimeoutError:
|
|
221
|
+
try:
|
|
222
|
+
import os
|
|
223
|
+
|
|
224
|
+
os.killpg(proc.pid, signal.SIGKILL)
|
|
225
|
+
except (ProcessLookupError, PermissionError, AttributeError):
|
|
226
|
+
with contextlib.suppress(ProcessLookupError):
|
|
227
|
+
proc.kill()
|
|
228
|
+
await proc.wait()
|
onechat/gitstate.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Git workspace state (Plan 03 §3 / T11): short status + diff stat for handoff briefs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextlib
|
|
7
|
+
import subprocess
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
MAX_CHARS = 2000
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def git_state(workdir: Path, max_chars: int = MAX_CHARS) -> str:
|
|
14
|
+
"""`git status --short` + `git diff --stat`, truncated. '' when not a git repo."""
|
|
15
|
+
try:
|
|
16
|
+
status = subprocess.run(
|
|
17
|
+
["git", "status", "--short"],
|
|
18
|
+
cwd=str(workdir),
|
|
19
|
+
capture_output=True,
|
|
20
|
+
text=True,
|
|
21
|
+
timeout=10,
|
|
22
|
+
check=False,
|
|
23
|
+
)
|
|
24
|
+
diff = subprocess.run(
|
|
25
|
+
["git", "diff", "--stat"],
|
|
26
|
+
cwd=str(workdir),
|
|
27
|
+
capture_output=True,
|
|
28
|
+
text=True,
|
|
29
|
+
timeout=10,
|
|
30
|
+
check=False,
|
|
31
|
+
)
|
|
32
|
+
except (OSError, subprocess.SubprocessError):
|
|
33
|
+
return ""
|
|
34
|
+
if status.returncode != 0:
|
|
35
|
+
return ""
|
|
36
|
+
parts = [status.stdout.strip()]
|
|
37
|
+
if diff.returncode == 0 and diff.stdout.strip():
|
|
38
|
+
parts.append(diff.stdout.strip())
|
|
39
|
+
text = "\n".join(p for p in parts if p)
|
|
40
|
+
return text[:max_chars]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
async def async_git_state(workdir: Path, max_chars: int = MAX_CHARS) -> str:
|
|
44
|
+
"""Async variant (T11): staged + unstaged diff stat via create_subprocess_exec —
|
|
45
|
+
the event loop never blocks on git. '' immediately when not a git repo."""
|
|
46
|
+
try:
|
|
47
|
+
status = await asyncio.create_subprocess_exec(
|
|
48
|
+
"git",
|
|
49
|
+
"status",
|
|
50
|
+
"--short",
|
|
51
|
+
cwd=str(workdir),
|
|
52
|
+
stdout=asyncio.subprocess.PIPE,
|
|
53
|
+
stderr=asyncio.subprocess.PIPE,
|
|
54
|
+
)
|
|
55
|
+
out, _ = await _communicate_or_kill(status, timeout=10)
|
|
56
|
+
except (TimeoutError, OSError, subprocess.SubprocessError):
|
|
57
|
+
return ""
|
|
58
|
+
if status.returncode != 0:
|
|
59
|
+
return ""
|
|
60
|
+
parts = [out.decode("utf-8", errors="replace").strip()]
|
|
61
|
+
for diff_args in (["git", "diff", "--cached", "--stat"], ["git", "diff", "--stat"]):
|
|
62
|
+
text = await _git_out(diff_args, workdir)
|
|
63
|
+
if text:
|
|
64
|
+
parts.append(text)
|
|
65
|
+
return "\n".join(p for p in parts if p)[:max_chars]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
async def _git_out(args: list[str], workdir: Path) -> str:
|
|
69
|
+
try:
|
|
70
|
+
proc = await asyncio.create_subprocess_exec(
|
|
71
|
+
*args,
|
|
72
|
+
cwd=str(workdir),
|
|
73
|
+
stdout=asyncio.subprocess.PIPE,
|
|
74
|
+
stderr=asyncio.subprocess.PIPE,
|
|
75
|
+
)
|
|
76
|
+
out, _ = await _communicate_or_kill(proc, timeout=10)
|
|
77
|
+
except (TimeoutError, OSError, subprocess.SubprocessError):
|
|
78
|
+
return ""
|
|
79
|
+
return out.decode("utf-8", errors="replace").strip() if proc.returncode == 0 else ""
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
async def _communicate_or_kill(
|
|
83
|
+
proc: asyncio.subprocess.Process, timeout: int
|
|
84
|
+
) -> tuple[bytes, bytes]:
|
|
85
|
+
try:
|
|
86
|
+
return await asyncio.wait_for(proc.communicate(), timeout=timeout)
|
|
87
|
+
except TimeoutError:
|
|
88
|
+
with contextlib.suppress(ProcessLookupError):
|
|
89
|
+
proc.kill()
|
|
90
|
+
await proc.wait()
|
|
91
|
+
raise
|
onechat/handoff.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Handoff briefs (Plan 03 §4 / T11): cross-backend session continuity prompts.
|
|
2
|
+
|
|
3
|
+
Caps: recent_turns and brief_max_chars bound every brief; an oversized summary is
|
|
4
|
+
truncated BEFORE recent turns are dropped; api_messages keeps summary + newest turns
|
|
5
|
+
within the budget. Pure functions.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Awaitable, Callable
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from .config import HandoffConfig
|
|
14
|
+
from .contracts import Message
|
|
15
|
+
|
|
16
|
+
BRIEF_HEADER = (
|
|
17
|
+
"<asf-handoff>\n"
|
|
18
|
+
"You are continuing a conversation started by another assistant. "
|
|
19
|
+
"Continue seamlessly; do not mention the switch.\n"
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _format_turn(t: dict[str, Any], max_chars: int) -> str:
|
|
24
|
+
role = t.get("role", "user")
|
|
25
|
+
text = str(t.get("text", ""))[:max_chars]
|
|
26
|
+
return f"[{role}] {text}"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _turns_block(turns: list[dict[str, Any]], cfg: HandoffConfig) -> str:
|
|
30
|
+
return "\n".join(_format_turn(t, cfg.turn_max_chars) for t in turns)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _bounded_summary(session: dict[str, Any], cfg: HandoffConfig) -> str:
|
|
34
|
+
"""Summary truncated to half the brief budget (T11) — '(none)' when absent."""
|
|
35
|
+
summary = str(session.get("summary") or "")
|
|
36
|
+
if not summary:
|
|
37
|
+
return "(none)"
|
|
38
|
+
return summary[: cfg.brief_max_chars // 2]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def handoff_brief(
|
|
42
|
+
session: dict[str, Any],
|
|
43
|
+
turns: list[dict[str, Any]],
|
|
44
|
+
git: str,
|
|
45
|
+
interrupted: bool,
|
|
46
|
+
cfg: HandoffConfig,
|
|
47
|
+
prompt: str = "",
|
|
48
|
+
) -> str:
|
|
49
|
+
"""Full continuation brief: summary + recent turns + git state + optional note + prompt."""
|
|
50
|
+
recent = _bounded_recent(session, turns, git, cfg)
|
|
51
|
+
summary = _bounded_summary(session, cfg)
|
|
52
|
+
parts = [
|
|
53
|
+
BRIEF_HEADER,
|
|
54
|
+
f"Working directory: {session.get('workdir', '')}\n",
|
|
55
|
+
"Summary of earlier conversation:\n",
|
|
56
|
+
f"{summary}\n",
|
|
57
|
+
"Recent turns, oldest first:\n",
|
|
58
|
+
f"{_turns_block(recent, cfg) or '(none)'}\n",
|
|
59
|
+
"Workspace state:\n",
|
|
60
|
+
f"{git or '(not a git repo)'}\n",
|
|
61
|
+
]
|
|
62
|
+
if interrupted:
|
|
63
|
+
parts.append(
|
|
64
|
+
"The previous assistant was interrupted mid-task. Inspect the workspace "
|
|
65
|
+
"(git status/diff) and finish the task.\n"
|
|
66
|
+
)
|
|
67
|
+
parts.append("</asf-handoff>\n\n")
|
|
68
|
+
parts.append(prompt)
|
|
69
|
+
return "".join(parts)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _bounded_recent(
|
|
73
|
+
session: dict[str, Any],
|
|
74
|
+
turns: list[dict[str, Any]],
|
|
75
|
+
git: str,
|
|
76
|
+
cfg: HandoffConfig,
|
|
77
|
+
) -> list[dict[str, Any]]:
|
|
78
|
+
"""Newest `recent_turns` turns (T11: <= 0 -> []), dropping oldest first over budget."""
|
|
79
|
+
if cfg.recent_turns <= 0:
|
|
80
|
+
return []
|
|
81
|
+
recent = turns[-cfg.recent_turns :]
|
|
82
|
+
while len(recent) > 1 and _brief_size(session, recent, git, cfg) > cfg.brief_max_chars:
|
|
83
|
+
recent = recent[1:]
|
|
84
|
+
return recent
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _brief_size(
|
|
88
|
+
session: dict[str, Any], recent: list[dict[str, Any]], git: str, cfg: HandoffConfig
|
|
89
|
+
) -> int:
|
|
90
|
+
return (
|
|
91
|
+
len(BRIEF_HEADER)
|
|
92
|
+
+ len(_turns_block(recent, cfg))
|
|
93
|
+
+ len(git)
|
|
94
|
+
+ min(len(str(session.get("summary") or "")), cfg.brief_max_chars // 2)
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def delta_brief(missed: list[dict[str, Any]], git: str, cfg: HandoffConfig) -> str:
|
|
99
|
+
"""Turns handled by other backends while this one was away (T11: capped)."""
|
|
100
|
+
bounded = [] if cfg.recent_turns <= 0 else missed[-cfg.recent_turns :]
|
|
101
|
+
block = _turns_block(bounded, cfg)
|
|
102
|
+
if len(block) > cfg.brief_max_chars:
|
|
103
|
+
block = block[-cfg.brief_max_chars :]
|
|
104
|
+
parts = [
|
|
105
|
+
BRIEF_HEADER,
|
|
106
|
+
"Turns handled while you were away, oldest first:\n",
|
|
107
|
+
f"{block or '(none)'}\n",
|
|
108
|
+
"Workspace state:\n",
|
|
109
|
+
f"{git or '(not a git repo)'}\n",
|
|
110
|
+
"</asf-handoff>\n\n",
|
|
111
|
+
]
|
|
112
|
+
return "".join(parts)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _summary_upto(session: dict[str, Any]) -> int:
|
|
116
|
+
"""Last turn idx included in the summary. DB default 0 with no summary means 'none yet'
|
|
117
|
+
(turns start at idx 0), expressed as -1 so nothing is skipped."""
|
|
118
|
+
raw = session.get("summary_upto")
|
|
119
|
+
if not session.get("summary") and (raw is None or int(raw) == 0):
|
|
120
|
+
return -1
|
|
121
|
+
return int(raw if raw is not None else -1)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def api_messages(
|
|
125
|
+
session: dict[str, Any],
|
|
126
|
+
turns: list[dict[str, Any]],
|
|
127
|
+
prompt: str,
|
|
128
|
+
cfg: HandoffConfig,
|
|
129
|
+
) -> list[Message]:
|
|
130
|
+
"""OpenAI-style history (T11): summary + turns AFTER summary_upto, newest-first kept
|
|
131
|
+
within brief_max_chars; the current prompt is always the final user message."""
|
|
132
|
+
upto = _summary_upto(session)
|
|
133
|
+
budget = max(cfg.brief_max_chars - len(prompt) - 50, 500)
|
|
134
|
+
history: list[Message] = []
|
|
135
|
+
if session.get("summary"):
|
|
136
|
+
header = f"Summary of earlier conversation:\n{_bounded_summary(session, cfg)}"
|
|
137
|
+
history.append(Message(role="system", content=header))
|
|
138
|
+
body = [t for t in turns if int(t.get("idx", 0)) > upto]
|
|
139
|
+
body_budget = budget - (len(history[0].content) if history else 0)
|
|
140
|
+
chosen: list[dict[str, Any]] = []
|
|
141
|
+
used = 0
|
|
142
|
+
for t in reversed(body):
|
|
143
|
+
cost = min(len(str(t.get("text", ""))), cfg.turn_max_chars)
|
|
144
|
+
if used + cost > body_budget and chosen:
|
|
145
|
+
break
|
|
146
|
+
chosen.append(t)
|
|
147
|
+
used += cost
|
|
148
|
+
chosen.reverse()
|
|
149
|
+
for t in chosen:
|
|
150
|
+
role = "assistant" if t.get("role") == "assistant" else "user"
|
|
151
|
+
history.append(Message(role=role, content=str(t.get("text", ""))[: cfg.turn_max_chars]))
|
|
152
|
+
history.append(Message(role="user", content=prompt))
|
|
153
|
+
return history
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
async def maybe_compact(
|
|
157
|
+
session: dict[str, Any],
|
|
158
|
+
turns: list[dict[str, Any]],
|
|
159
|
+
cfg: HandoffConfig,
|
|
160
|
+
summarize: Callable[[str], Awaitable[str]],
|
|
161
|
+
) -> tuple[str, int] | None:
|
|
162
|
+
"""Summarize old turns past the threshold; return (new summary, last summarized idx)."""
|
|
163
|
+
upto = _summary_upto(session)
|
|
164
|
+
if cfg.recent_turns <= 0:
|
|
165
|
+
keep_from = int(turns[-1]["idx"]) + 1 if turns else 0
|
|
166
|
+
elif len(turns) > cfg.recent_turns:
|
|
167
|
+
keep_from = int(turns[-cfg.recent_turns]["idx"])
|
|
168
|
+
else:
|
|
169
|
+
keep_from = 0
|
|
170
|
+
old = [t for t in turns if upto < int(t.get("idx", 0)) < keep_from]
|
|
171
|
+
total_chars = sum(len(str(t.get("text", ""))) for t in old)
|
|
172
|
+
if total_chars <= cfg.compact_threshold_chars:
|
|
173
|
+
return None
|
|
174
|
+
previous = str(session.get("summary") or "")
|
|
175
|
+
summary = await summarize(previous + "\n" + _turns_block(old, cfg))
|
|
176
|
+
return summary, int(keep_from) - 1
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# agy profile — new-turn stream shape verified via captured result event; --mode auto not in
|
|
2
|
+
# help (docs/compat.md §1) so auto list is minimal: --sandbox only.
|
|
3
|
+
name: agy
|
|
4
|
+
binary: agy
|
|
5
|
+
new: ["-p", "{prompt}", "--output-format", "stream-json", "--model", "{model}", "{auto}"]
|
|
6
|
+
resume: ["-p", "{prompt}", "--conversation", "{session_id}", "--output-format", "stream-json", "--model", "{model}", "{auto}"]
|
|
7
|
+
auto: ["--dangerously-skip-permissions", "--mode", "accept-edits"]
|
|
8
|
+
prompt_via: argv
|
|
9
|
+
parser: agy_stream_json
|
|
10
|
+
quota_patterns: ["usage limit", "http 429", "rate limit", "quota"]
|
|
11
|
+
auth_patterns: ["Eligibility check failed", "/login", "401 unauthorized", "unauthorized"]
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# autoclaw profile — drives desktop AutoClaw IDE via ai-driver CDP bridge (port 9226)
|
|
2
|
+
name: autoclaw
|
|
3
|
+
binary: ai-driver
|
|
4
|
+
new: ["run", "--driver", "autoclaw", "-m", "{model}", "--json", "-w", ".", "{prompt}"]
|
|
5
|
+
resume: ["run", "--driver", "autoclaw", "-m", "{model}", "--session", "{session_id}", "--json", "-w", ".", "{prompt}"]
|
|
6
|
+
auto: []
|
|
7
|
+
prompt_via: argv
|
|
8
|
+
parser: claude_stream_json
|
|
9
|
+
quota_patterns: ["quota", "insufficient", "credits exhausted", "no longer available", "limit reach", "limit reached"]
|
|
10
|
+
auth_patterns: ["login", "unauthorized", "auth"]
|
|
11
|
+
unavailable_patterns: ["connection refused", "not running", "cannot connect", "no output", "remote debugging", "cdp"]
|
|
12
|
+
share_cooldown: true
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# claude profile — flags verified-local from `claude --help` (docs/compat.md §1, 2026-11-02).
|
|
2
|
+
# resume flag exists in help; end-to-end resume behavior unverified (OAuth expired at capture).
|
|
3
|
+
name: claude
|
|
4
|
+
binary: claude
|
|
5
|
+
new: ["-p", "{prompt}", "--output-format", "stream-json", "--verbose", "--model", "{model}", "{auto}"]
|
|
6
|
+
resume: ["-p", "{prompt}", "--resume", "{session_id}", "--output-format", "stream-json", "--verbose", "--model", "{model}", "{auto}"]
|
|
7
|
+
auto: ["--permission-mode", "bypassPermissions"]
|
|
8
|
+
prompt_via: argv
|
|
9
|
+
parser: claude_stream_json
|
|
10
|
+
quota_patterns: ["usage limit", "rate limit", "http 429", "insufficient_quota"]
|
|
11
|
+
auth_patterns: ["authentication_failed", "Failed to authenticate", "not logged in", "401 unauthorized"]
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# codex profile — `codex exec --json` verified via captured event stream; resume syntax from
|
|
2
|
+
# plan, not verified tonight (docs/compat.md §1 marks it unverified).
|
|
3
|
+
# Plan 09 K2: PIN the codex binary per deployment — the exec --json event enum drifts
|
|
4
|
+
# between releases (--full-auto was REMOVED; collab_tool_call was ADDED).
|
|
5
|
+
# After upgrades: re-run scripts/capture_cli.py + tests/router/test_parsers.py.
|
|
6
|
+
name: codex
|
|
7
|
+
binary: codex
|
|
8
|
+
new: ["exec", "--json", "-m", "{model}", "{auto}", "{prompt}"]
|
|
9
|
+
resume: ["exec", "{auto}", "resume", "--json", "-m", "{model}", "{session_id}", "{prompt}"]
|
|
10
|
+
auto: ["--sandbox", "workspace-write", "--skip-git-repo-check"]
|
|
11
|
+
prompt_via: argv
|
|
12
|
+
parser: codex_jsonl
|
|
13
|
+
quota_patterns: ["usage limit", "rate limit", "http 429", "insufficient_quota"]
|
|
14
|
+
auth_patterns: ["not logged in", "401 unauthorized", "unauthorized"]
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# gemini profile — flags verified-local from `gemini --help` (--resume/--session-id/--session-file,
|
|
2
|
+
# --approval-mode/--yolo). Turn-level behavior unverified (interactive login at capture).
|
|
3
|
+
name: gemini
|
|
4
|
+
binary: gemini
|
|
5
|
+
new: ["-p", "{prompt}", "-o", "stream-json", "-m", "{model}", "{auto}"]
|
|
6
|
+
resume: ["-p", "{prompt}", "--resume", "{session_id}", "-o", "stream-json", "-m", "{model}", "{auto}"]
|
|
7
|
+
auto: ["--approval-mode", "yolo"]
|
|
8
|
+
prompt_via: argv
|
|
9
|
+
parser: gemini_stream_json
|
|
10
|
+
quota_patterns: ["quota", "http 429", "rate limit", "RESOURCE_EXHAUSTED"]
|
|
11
|
+
auth_patterns: ["not authenticated", "login required", "not logged in", "401 unauthorized"]
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# opencode profile — `opencode run --format json` event stream captured live (step_start/error);
|
|
2
|
+
# --session/--continue/--model verified-local from help. Free models: openrouter/<id>:free.
|
|
3
|
+
name: opencode
|
|
4
|
+
binary: opencode
|
|
5
|
+
new: ["run", "{prompt}", "--format", "json", "-m", "{model}", "{auto}"]
|
|
6
|
+
resume: ["run", "{prompt}", "--session", "{session_id}", "--format", "json", "-m", "{model}", "{auto}"]
|
|
7
|
+
auto: ["--auto"]
|
|
8
|
+
prompt_via: argv
|
|
9
|
+
parser: opencode_json
|
|
10
|
+
quota_patterns: ["http 429", "rate limit", "quota", "insufficient credit", "limit reach", "limit reached"]
|
|
11
|
+
auth_patterns: ["provider.auth", "401 unauthorized", "unauthorized", "Access denied"]
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# qoder profile — drives desktop Qoder IDE via ai-driver CDP bridge (port 9223)
|
|
2
|
+
name: qoder
|
|
3
|
+
binary: ai-driver
|
|
4
|
+
new: ["run", "--driver", "qoder", "-m", "{model}", "--json", "-w", ".", "{prompt}"]
|
|
5
|
+
resume: ["run", "--driver", "qoder", "-m", "{model}", "--session", "{session_id}", "--json", "-w", ".", "{prompt}"]
|
|
6
|
+
auto: []
|
|
7
|
+
prompt_via: argv
|
|
8
|
+
parser: claude_stream_json
|
|
9
|
+
quota_patterns: ["quota", "no longer available", "limit reach", "limit reached"]
|
|
10
|
+
auth_patterns: ["login", "unauthorized"]
|
|
11
|
+
unavailable_patterns: ["connection refused", "not running", "cannot connect", "no output", "remote debugging", "cdp"]
|
|
12
|
+
share_cooldown: true
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# qwen profile — qwen is Claude-Code-like (result/error_during_execution schema captured);
|
|
2
|
+
# flags verified-local from `qwen --help` (--resume/--continue/--session-id/--approval-mode/--yolo).
|
|
3
|
+
name: qwen
|
|
4
|
+
binary: qwen
|
|
5
|
+
new: ["-p", "{prompt}", "-o", "stream-json", "-m", "{model}", "{auto}"]
|
|
6
|
+
resume: ["-p", "{prompt}", "--resume", "{session_id}", "-o", "stream-json", "-m", "{model}", "{auto}"]
|
|
7
|
+
auto: ["--approval-mode", "yolo"]
|
|
8
|
+
prompt_via: argv
|
|
9
|
+
parser: qwen_stream_json
|
|
10
|
+
quota_patterns: ["quota", "http 429", "rate limit"]
|
|
11
|
+
auth_patterns: ["No auth type", "not logged in", "401 unauthorized", "unauthorized"]
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# workbuddy profile — drives desktop WorkBuddy AI via Electron CDP bridge with fullAccess/bypassPermissions
|
|
2
|
+
name: workbuddy
|
|
3
|
+
binary: workbuddy
|
|
4
|
+
new: ["-p", "{prompt}", "--output-format", "stream-json", "--verbose", "--model", "{model}", "{auto}"]
|
|
5
|
+
resume: ["-p", "{prompt}", "--resume", "{session_id}", "--output-format", "stream-json", "--verbose", "--model", "{model}", "{auto}"]
|
|
6
|
+
auto: ["--permission-mode", "bypassPermissions", "-y"]
|
|
7
|
+
prompt_via: argv
|
|
8
|
+
parser: claude_stream_json
|
|
9
|
+
quota_patterns: ["usage limit", "rate limit", "http 429", "insufficient_quota", "insufficient credit", "limit reach", "limit reached"]
|
|
10
|
+
auth_patterns: ["authentication_failed", "Failed to authenticate", "not logged in", "401 unauthorized", "Authentication required"]
|
|
11
|
+
unavailable_patterns: ["connection refused", "not running", "cannot connect", "no output", "remote debugging", "cdp"]
|
|
12
|
+
share_cooldown: true
|
|
13
|
+
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# zcode profile — drives desktop ZCode IDE via ai-driver CDP bridge (port 9224)
|
|
2
|
+
name: zcode
|
|
3
|
+
binary: ai-driver
|
|
4
|
+
new: ["run", "--driver", "zcode", "-m", "{model}", "--json", "-w", ".", "{prompt}"]
|
|
5
|
+
resume: ["run", "--driver", "zcode", "-m", "{model}", "--session", "{session_id}", "--json", "-w", ".", "{prompt}"]
|
|
6
|
+
auto: []
|
|
7
|
+
prompt_via: argv
|
|
8
|
+
parser: claude_stream_json
|
|
9
|
+
quota_patterns: ["quota", "insufficient", "credits exhausted", "no longer available", "limit reach", "limit reached"]
|
|
10
|
+
auth_patterns: ["login", "unauthorized", "auth"]
|
|
11
|
+
unavailable_patterns: ["connection refused", "not running", "cannot connect", "no output", "remote debugging", "cdp"]
|
|
12
|
+
share_cooldown: true
|