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 ADDED
@@ -0,0 +1,46 @@
1
+ """onechat: one chat session surviving AI backend switches."""
2
+
3
+ from .contracts import (
4
+ Capability,
5
+ CostClass,
6
+ Event,
7
+ ExecutorSpec,
8
+ Message,
9
+ Stop,
10
+ Tier,
11
+ TurnRequest,
12
+ TurnResult,
13
+ Usage,
14
+ )
15
+ from .executors.process import AsyncProcessRunner, ProcessRunner, ProcResult
16
+ from .redact import redact
17
+ from .router import NoExecutorAvailable, Reply, Router, SessionBusy
18
+ from .sdk import AsfClient, OneChatClient, Session
19
+ from .selector import Need
20
+ from .store import Store
21
+
22
+ __all__ = [
23
+ "AsfClient",
24
+ "AsyncProcessRunner",
25
+ "Capability",
26
+ "CostClass",
27
+ "Event",
28
+ "ExecutorSpec",
29
+ "Message",
30
+ "Need",
31
+ "NoExecutorAvailable",
32
+ "OneChatClient",
33
+ "ProcessRunner",
34
+ "ProcResult",
35
+ "Reply",
36
+ "Router",
37
+ "Session",
38
+ "SessionBusy",
39
+ "Stop",
40
+ "Store",
41
+ "Tier",
42
+ "TurnRequest",
43
+ "TurnResult",
44
+ "Usage",
45
+ "redact",
46
+ ]
onechat/benchmark.py ADDED
@@ -0,0 +1,253 @@
1
+ """Benchmark watchdog runner (T43): latency/health checks and dynamic circuit overrides."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import time
8
+ import urllib.error
9
+ import urllib.request
10
+ from collections.abc import Callable
11
+ from concurrent.futures import ThreadPoolExecutor
12
+ from typing import Any
13
+
14
+ from pydantic import BaseModel, Field
15
+
16
+ from .config import BenchmarkConfig, BenchmarkTarget
17
+ from .redact import redact
18
+ from .store import Store
19
+
20
+ ProbeFn = Callable[[str, float], tuple[bool, float, str]]
21
+ _NON_RETRY_HTTP_RE = re.compile(r"\bHTTP (?:401|403|429)\b")
22
+
23
+
24
+ class BenchmarkResult(BaseModel):
25
+ executor_id: str
26
+ model: str
27
+ status: str # "healthy" | "slow" | "error"
28
+ latency_s: float | None = None
29
+ enabled_override: int | None = None # 1 = healthy, 0 = slow/error
30
+ priority_override: int | None = None
31
+ detail: str = "OK"
32
+
33
+
34
+ class BenchmarkReport(BaseModel):
35
+ timestamp: float = Field(default_factory=time.time)
36
+ results: list[BenchmarkResult] = Field(default_factory=list)
37
+ promoted_roles: dict[str, str] = Field(default_factory=dict)
38
+
39
+
40
+ def http_probe(
41
+ model: str,
42
+ timeout_s: float,
43
+ endpoint: str = "http://127.0.0.1:8789",
44
+ ) -> tuple[bool, float, str]:
45
+ """Lightweight HTTP POST probe directly to the local Gemini proxy endpoint."""
46
+ clean_model = model.split("/")[-1]
47
+ url = f"{endpoint}/v1beta/models/{clean_model}:generateContent"
48
+ payload = json.dumps(
49
+ {
50
+ "contents": [{"parts": [{"text": "ping"}]}],
51
+ "generationConfig": {"maxOutputTokens": 8},
52
+ }
53
+ ).encode("utf-8")
54
+ headers = {
55
+ "Content-Type": "application/json",
56
+ "x-rotator-ttfb-timeout-ms": str(int(timeout_s * 1000)),
57
+ "x-rotator-max-attempts": "2",
58
+ }
59
+ req = urllib.request.Request(url, data=payload, headers=headers)
60
+ t0 = time.monotonic()
61
+ try:
62
+ with urllib.request.urlopen(req, timeout=timeout_s) as resp:
63
+ raw = resp.read().decode("utf-8", errors="replace")
64
+ dt = time.monotonic() - t0
65
+ data = json.loads(raw)
66
+ if not isinstance(data, dict) or not data.get("candidates"):
67
+ return False, dt, "invalid response: missing candidates"
68
+ return True, dt, "OK"
69
+ except urllib.error.HTTPError as err:
70
+ dt = time.monotonic() - t0
71
+ try:
72
+ body = err.read().decode("utf-8", errors="replace")
73
+ except Exception:
74
+ body = ""
75
+ short_body = body.replace("\n", " ").strip()[:140]
76
+ detail = f"HTTP {err.code}: {err.reason}" + (f" - {short_body}" if short_body else "")
77
+ return False, dt, detail
78
+ except Exception as exc:
79
+ return False, time.monotonic() - t0, str(exc)
80
+
81
+
82
+ def _is_non_retryable_error(detail: str) -> bool:
83
+ """Check if error is definitive quota / plan / billing / auth exhaustion (non-retryable)."""
84
+ if _NON_RETRY_HTTP_RE.search(detail):
85
+ return True
86
+ lowered = detail.lower()
87
+ markers = ("quota", "usage limit", "resource_exhausted", "billing", "perday", "daily")
88
+ return any(m in lowered for m in markers)
89
+
90
+
91
+ def _eval_target(
92
+ target: BenchmarkTarget,
93
+ ok: bool,
94
+ dt: float,
95
+ detail: str,
96
+ max_latency_s: float,
97
+ ) -> BenchmarkResult:
98
+ if ok and dt <= max_latency_s:
99
+ return BenchmarkResult(
100
+ executor_id=target.executor_id,
101
+ model=target.model,
102
+ status="healthy",
103
+ latency_s=round(dt, 3),
104
+ enabled_override=1,
105
+ priority_override=target.promoted_priority,
106
+ detail="OK",
107
+ )
108
+ if ok:
109
+ return BenchmarkResult(
110
+ executor_id=target.executor_id,
111
+ model=target.model,
112
+ status="slow",
113
+ latency_s=round(dt, 3),
114
+ enabled_override=0,
115
+ priority_override=None,
116
+ detail=f"latency {dt:.2f}s > {max_latency_s}s",
117
+ )
118
+ return BenchmarkResult(
119
+ executor_id=target.executor_id,
120
+ model=target.model,
121
+ status="error",
122
+ latency_s=round(dt, 3) if dt > 0 else None,
123
+ enabled_override=0,
124
+ priority_override=None,
125
+ detail=redact(detail),
126
+ )
127
+
128
+
129
+ def _rank_results(results: list[BenchmarkResult], mode: str) -> None:
130
+ if mode != "fastest":
131
+ return
132
+ healthy = [r for r in results if r.status == "healthy"]
133
+ healthy.sort(key=lambda r: r.latency_s if r.latency_s is not None else 999.0)
134
+ for idx, r in enumerate(healthy):
135
+ r.priority_override = idx
136
+
137
+
138
+ def _probe_target(
139
+ target: BenchmarkTarget,
140
+ config: BenchmarkConfig,
141
+ probe: ProbeFn,
142
+ available_fn: Callable[[str], bool] | None = None,
143
+ ) -> BenchmarkResult:
144
+ if available_fn is not None and not available_fn(target.executor_id):
145
+ return BenchmarkResult(
146
+ executor_id=target.executor_id,
147
+ model=target.model,
148
+ status="error",
149
+ latency_s=None,
150
+ enabled_override=0,
151
+ priority_override=None,
152
+ detail="executor unavailable (binary missing)",
153
+ )
154
+ ok, dt, detail = probe(target.model, config.timeout_s)
155
+ is_retryable = (not ok and not _is_non_retryable_error(detail)) or (
156
+ ok and dt > config.max_latency_s
157
+ )
158
+ if is_retryable:
159
+ ok, dt, detail = probe(target.model, config.timeout_s)
160
+ return _eval_target(target, ok, dt, detail, config.max_latency_s)
161
+
162
+
163
+ def run_benchmark(
164
+ config: BenchmarkConfig,
165
+ store: Store,
166
+ probe_fn: ProbeFn | None = None,
167
+ available_fn: Callable[[str], bool] | None = None,
168
+ ) -> BenchmarkReport:
169
+ """Execute latency probe for all targets, persist overrides in SQLite, and return report."""
170
+ probe = probe_fn or (lambda m, t: http_probe(m, t, endpoint=config.endpoint))
171
+ with ThreadPoolExecutor(max_workers=max(1, len(config.targets))) as pool:
172
+ results = list(
173
+ pool.map(lambda t: _probe_target(t, config, probe, available_fn), config.targets)
174
+ )
175
+ _rank_results(results, config.selection_mode)
176
+
177
+ for r in results:
178
+ store.set_executor_override(
179
+ executor_id=r.executor_id,
180
+ status=r.status,
181
+ enabled_override=r.enabled_override,
182
+ priority_override=r.priority_override,
183
+ latency_s=r.latency_s,
184
+ detail=r.detail,
185
+ )
186
+
187
+ healthy = [r for r in results if r.status == "healthy" and r.priority_override is not None]
188
+ healthy.sort(key=lambda r: r.priority_override if r.priority_override is not None else 999)
189
+
190
+ promoted_roles: dict[str, str] = {}
191
+ if healthy:
192
+ top_executor = healthy[0].executor_id
193
+ for role in config.promote_roles:
194
+ promoted_roles[role] = top_executor
195
+
196
+ return BenchmarkReport(
197
+ timestamp=time.time(),
198
+ results=results,
199
+ promoted_roles=promoted_roles,
200
+ )
201
+
202
+
203
+ def run_client_benchmark(client: Any) -> BenchmarkReport:
204
+ """Run benchmark using a configured AsfClient and its executor availability."""
205
+ return run_benchmark(
206
+ client.config.benchmark,
207
+ client.store,
208
+ available_fn=lambda eid: bool(
209
+ (ex := client.executors.get(eid)) is not None and ex.available()
210
+ ),
211
+ )
212
+
213
+
214
+ def print_benchmark_status(
215
+ overrides: dict[str, Any],
216
+ json_output: bool,
217
+ echo: Callable[[str], None],
218
+ ) -> None:
219
+ if json_output:
220
+ echo(json.dumps(overrides, ensure_ascii=False))
221
+ return
222
+ if not overrides:
223
+ echo("no benchmark overrides recorded")
224
+ return
225
+ echo("executor_id\tstatus\tlatency\tpriority\toverride")
226
+ for eid, rec in sorted(overrides.items()):
227
+ lat = f"{rec.get('latency_s'):.2f}s" if rec.get("latency_s") is not None else "-"
228
+ prio = str(
229
+ rec.get("priority_override") if rec.get("priority_override") is not None else "-"
230
+ )
231
+ en = "enabled" if rec.get("enabled_override") == 1 else "circuited-out"
232
+ echo(f"{eid}\t{rec.get('status')}\t{lat}\t{prio}\t{en}")
233
+
234
+
235
+ def print_benchmark_report(
236
+ report: BenchmarkReport,
237
+ json_output: bool,
238
+ echo: Callable[[str], None],
239
+ ) -> None:
240
+ if json_output:
241
+ echo(json.dumps(report.model_dump(), ensure_ascii=False))
242
+ return
243
+ ts_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(report.timestamp))
244
+ echo(f"[{ts_str}] Benchmark completed:")
245
+ for r in report.results:
246
+ lat = f"{r.latency_s:.2f}s" if r.latency_s is not None else "-"
247
+ prio = str(r.priority_override if r.priority_override is not None else "-")
248
+ echo(
249
+ f"[{r.status.upper()}] {r.executor_id} ({r.model}): "
250
+ f"latency={lat} priority={prio} detail={r.detail}"
251
+ )
252
+ if report.promoted_roles:
253
+ echo(f"promoted roles: {report.promoted_roles}")
onechat/cli.py ADDED
@@ -0,0 +1,252 @@
1
+ """onechat CLI: run, sessions, executors, doctor, chat."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sys
7
+ import threading
8
+ import time
9
+ from collections.abc import Callable
10
+ from pathlib import Path
11
+
12
+ import typer
13
+
14
+ from .cli_repl import SLASH_COMMANDS, handle_slash, run_chat_turn
15
+ from .contracts import Event, Tier
16
+ from .sdk import AsfClient
17
+
18
+ app = typer.Typer(
19
+ help="onechat: one chat session surviving AI backend switches", no_args_is_help=True
20
+ )
21
+ executors_app = typer.Typer(help="executor pool management", no_args_is_help=True)
22
+ sessions_app = typer.Typer(help="session inspection", no_args_is_help=True)
23
+ app.add_typer(executors_app, name="executors")
24
+ app.add_typer(sessions_app, name="sessions")
25
+
26
+ _RUN_WORKDIR_OPT = typer.Option(None, "--workdir", help="working directory")
27
+ _CHAT_WORKDIR_OPT = typer.Option(Path("."), "--workdir")
28
+ _CONFIG_OPT = typer.Option(None, "--config")
29
+ _SKILL_OPT = typer.Option(None, "--skill", help="required skill(s)")
30
+
31
+
32
+ def _client(config_path: Path | None = None) -> AsfClient:
33
+ return AsfClient(config_path=config_path)
34
+
35
+
36
+ def _run_progress_logger(quiet: bool) -> tuple[Callable[[Event], None], Callable[[], None]]:
37
+ if quiet:
38
+ return lambda _e: None, lambda: None
39
+ start = time.monotonic()
40
+ stop_ev = threading.Event()
41
+
42
+ def on_event(ev: Event) -> None:
43
+ if ev.kind in ("status", "tool"):
44
+ sys.stderr.write(f"[onechat] {ev.text}\n")
45
+ sys.stderr.flush()
46
+
47
+ def heartbeat() -> None:
48
+ while not stop_ev.wait(15.0):
49
+ elapsed = int(time.monotonic() - start)
50
+ sys.stderr.write(f"[onechat] working... ({elapsed}s elapsed)\n")
51
+ sys.stderr.flush()
52
+
53
+ th = threading.Thread(target=heartbeat, daemon=True)
54
+ th.start()
55
+
56
+ def stop() -> None:
57
+ stop_ev.set()
58
+ th.join(timeout=0.5)
59
+
60
+ return on_event, stop
61
+
62
+
63
+ @app.command()
64
+ def run(
65
+ prompt: str,
66
+ session: str | None = typer.Option(None, "--session", help="session id"),
67
+ tier: str = typer.Option("auto", "--tier"),
68
+ executor: str | None = typer.Option(None, "--executor"),
69
+ role: str | None = typer.Option(None, "--role"),
70
+ model: str | None = typer.Option(None, "--model"),
71
+ skill: list[str] | None = _SKILL_OPT,
72
+ json_output: bool = typer.Option(False, "--json"),
73
+ workdir: Path | None = _RUN_WORKDIR_OPT,
74
+ config_path: Path | None = _CONFIG_OPT,
75
+ timeout: int | None = typer.Option(None, "--timeout", help="timeout in seconds"),
76
+ no_fallback: bool = typer.Option(False, "--no-fallback", help="disable fallback"),
77
+ quiet: bool = typer.Option(False, "--quiet", "-q", help="suppress stderr progress"),
78
+ ) -> None:
79
+ """One turn in a (new or existing) session; prints reply or JSON."""
80
+ client = _client(config_path)
81
+ target = str(workdir.resolve()) if workdir is not None else str(Path.cwd())
82
+ on_event, stop_heartbeat = _run_progress_logger(quiet)
83
+ try:
84
+ reply = client.session(workdir=target, session_id=session).ask_sync(
85
+ prompt,
86
+ tier=tier,
87
+ executor=executor,
88
+ role=role,
89
+ model=model,
90
+ skills=skill,
91
+ allow_fallback=not no_fallback,
92
+ timeout_s=timeout,
93
+ on_event=on_event,
94
+ )
95
+ finally:
96
+ stop_heartbeat()
97
+ typer.echo(json.dumps(reply.model_dump(), ensure_ascii=False) if json_output else reply.text)
98
+
99
+
100
+ @sessions_app.command("list")
101
+ def sessions_list(config_path: Path | None = _CONFIG_OPT) -> None:
102
+ for row in _client(config_path).store.list_sessions():
103
+ typer.echo(f"{row['id']} {row.get('title') or ''} {row.get('workdir')}")
104
+
105
+
106
+ @sessions_app.command("show")
107
+ def sessions_show(session_id: str, config_path: Path | None = _CONFIG_OPT) -> None:
108
+ for turn in _client(config_path).store.turns(session_id):
109
+ typer.echo(f"{turn['idx']} {turn['role']} ({turn['executor_id']})\n{turn['text'][:2000]}")
110
+
111
+
112
+ @sessions_app.command("export")
113
+ def sessions_export(
114
+ session_id: str,
115
+ fmt: str = typer.Option("md", "--format", help="md|jsonl"),
116
+ config_path: Path | None = _CONFIG_OPT,
117
+ ) -> None:
118
+ from .cli_doctor import export_session
119
+
120
+ export_session(_client(config_path), session_id, fmt, typer.echo)
121
+
122
+
123
+ @executors_app.command("list")
124
+ def executors_list(config_path: Path | None = _CONFIG_OPT) -> None:
125
+ from .cli_doctor import print_executors_table
126
+
127
+ print_executors_table(_client(config_path), typer.echo)
128
+
129
+
130
+ @executors_app.command("test")
131
+ def executors_test(executor_id: str, config_path: Path | None = _CONFIG_OPT) -> None:
132
+ """Live one-turn ping."""
133
+ reply = (
134
+ _client(config_path)
135
+ .session(workdir=str(Path.cwd()))
136
+ .ask_sync("Reply with the word PONG", executor=executor_id, allow_fallback=False)
137
+ )
138
+ typer.echo(f"{reply.executor_id}: {reply.stop} {reply.text[:100]}")
139
+
140
+
141
+ @executors_app.command("cooldown")
142
+ def executors_cooldown(
143
+ executor_id: str, seconds: int, config_path: Path | None = _CONFIG_OPT
144
+ ) -> None:
145
+ _client(config_path).store.set_cooldown(executor_id, time.time() + seconds, 1, "manual")
146
+ typer.echo(f"cooldown set: {executor_id} for {seconds}s")
147
+
148
+
149
+ @executors_app.command("clear")
150
+ def executors_clear(
151
+ executor_id: str | None = typer.Argument(None),
152
+ all_cooldowns: bool = typer.Option(False, "--all", help="clear all cooldowns"),
153
+ config_path: Path | None = _CONFIG_OPT,
154
+ ) -> None:
155
+ store = _client(config_path).store
156
+ if all_cooldowns or executor_id is None:
157
+ store.clear_cooldown(None)
158
+ typer.echo("cleared all cooldowns")
159
+ else:
160
+ store.clear_cooldown(executor_id)
161
+ typer.echo(f"cooldown cleared: {executor_id}")
162
+
163
+
164
+ @app.command()
165
+ def doctor(config_path: Path | None = _CONFIG_OPT) -> None:
166
+ """CLIs + versions vs docs/compat.md, key envs present, DB writable."""
167
+ from .cli_doctor import run_doctor
168
+
169
+ run_doctor(_client(config_path), typer.echo)
170
+
171
+
172
+ @app.command()
173
+ def explain(
174
+ prompt: str,
175
+ role: str | None = typer.Option(None, "--role"),
176
+ tier: str = typer.Option("auto", "--tier"),
177
+ skill: list[str] | None = _SKILL_OPT,
178
+ capability: str = typer.Option("auto", "--capability"),
179
+ workdir: Path | None = _RUN_WORKDIR_OPT,
180
+ json_output: bool = typer.Option(False, "--json"),
181
+ config_path: Path | None = _CONFIG_OPT,
182
+ ) -> None:
183
+ """Explain candidate selection and skill detection without calling LLMs."""
184
+ from .cli_doctor import explain_routing
185
+
186
+ explain_routing(
187
+ _client(config_path),
188
+ prompt,
189
+ role,
190
+ tier,
191
+ workdir,
192
+ json_output,
193
+ typer.echo,
194
+ skill,
195
+ capability,
196
+ )
197
+
198
+
199
+ @app.command()
200
+ def benchmark(
201
+ status_only: bool = typer.Option(False, "--status", help="show latest circuit status"),
202
+ json_output: bool = typer.Option(False, "--json", help="output JSON"),
203
+ config_path: Path | None = _CONFIG_OPT,
204
+ ) -> None:
205
+ """Run model health & latency benchmark, or inspect active circuit status."""
206
+ from .benchmark import print_benchmark_report, print_benchmark_status, run_client_benchmark
207
+
208
+ client = _client(config_path)
209
+ if status_only:
210
+ print_benchmark_status(client.store.get_executor_overrides(), json_output, typer.echo)
211
+ else:
212
+ print_benchmark_report(run_client_benchmark(client), json_output, typer.echo)
213
+
214
+
215
+ @app.command()
216
+ def chat(
217
+ session: str | None = typer.Option(None, "--session"),
218
+ tier: str = typer.Option("auto", "--tier"),
219
+ executor: str | None = typer.Option(None, "--executor"),
220
+ code: bool | None = typer.Option(None, "--code/--no-code"),
221
+ workdir: Path = _CHAT_WORKDIR_OPT,
222
+ config_path: Path | None = _CONFIG_OPT,
223
+ ) -> None:
224
+ """REPL: one conversation over many backends. /exit to leave."""
225
+ client = AsfClient(config_path=config_path)
226
+ capability = "code" if (code if code is not None else (workdir / ".git").exists()) else "chat"
227
+ sess = client.session(workdir=str(workdir), session_id=session)
228
+ current_tier: str | Tier = tier
229
+ current_executor: str | None = executor
230
+ last_executor: str | None = None
231
+ typer.echo("onechat chat — /exit to leave, /help for commands")
232
+ while True:
233
+ try:
234
+ prompt = input("you> ").strip()
235
+ except (EOFError, KeyboardInterrupt):
236
+ break
237
+ if not prompt:
238
+ continue
239
+ if prompt in SLASH_COMMANDS or prompt.split()[0] in SLASH_COMMANDS:
240
+ current_tier, current_executor, sess, last_executor, done = handle_slash(
241
+ client, sess, prompt, current_tier, current_executor, last_executor, workdir
242
+ )
243
+ if done:
244
+ break
245
+ continue
246
+ last_executor = run_chat_turn(
247
+ sess, prompt, current_tier, current_executor, capability, last_executor
248
+ )
249
+
250
+
251
+ if __name__ == "__main__":
252
+ app()