#!/usr/bin/env python3 import argparse import concurrent.futures import json import os import re import statistics import subprocess import sys import time import urllib.error import urllib.request DEFAULT_MODEL = "nvidia/nemotron-3-ultra-550b-a55b:free" FALLBACK_POOL_ACCOUNTS = [ "LaserPix42025", "Higginsoft", "FactoryRat003", "FactoryRat004", "FactoryRat005", "FactoryAgent002", "FactoryAgent003", ] CHEW_PROMPT = """Analyze this short Swift 6 snippet without modifying anything: ```swift @MainActor struct AccountBadge { let email: String func renderAsync() async -> String { email } } nonisolated func buildBadges(_ items: [AccountBadge]) async -> [String] { var labels: [String] = [] for item in items { labels.append(await item.renderAsync()) } return labels } ``` Tasks: 1. Briefly explain why `await item.renderAsync()` hops to `@MainActor` per iteration and how to make it zero-hop (`nonisolated` or `Sendable` synchronous helper). 2. Count the exact number of lines inside the Swift code fence above (`swift_line_count`). 3. Return a short explanation followed by a single JSON object containing keys: `"hop_actor"`, `"fix"`, `"swift_line_count"`, and `"status"` (set `"status"` to `"ok"`).""" def discover_pool_accounts(): try: res = subprocess.run( ["/usr/bin/defaults", "read", "com.higginsoft.ZooKeeper", "OpenRouterAccountNames"], capture_output=True, text=True, timeout=5, ) if res.returncode == 0 and res.stdout.strip(): # defaults read prints plist array: (\n LaserPix42025,\n ...\n) parsed = [ item.strip().strip('",') for item in res.stdout.splitlines() if item.strip() not in ("(", ")") and item.strip().strip('",') ] parsed = [a for a in parsed if a and a != "default"] if parsed: return parsed except Exception: pass try: res = subprocess.run( ["/usr/bin/security", "dump-keychain"], capture_output=True, text=True, timeout=8, ) if res.returncode == 0: blocks = res.stdout.split("keychain:") found = [] for block in blocks: if '"svce"="OpenRouter"' in block: m = re.search(r'"acct"="([^"]+)"', block) if m: acct = m.group(1) if acct != "default" and acct not in found: found.append(acct) if found: return found except Exception: pass return list(FALLBACK_POOL_ACCOUNTS) def read_keychain_token(account): try: res = subprocess.run( ["/usr/bin/security", "find-generic-password", "-s", "OpenRouter", "-a", account, "-w"], capture_output=True, text=True, timeout=5, ) if res.returncode != 0: return None, (res.stderr.strip() or f"Keychain exit {res.returncode}") token = res.stdout.strip() if not token: return None, "Empty Keychain token" return token, None except Exception as exc: return None, str(exc) def extract_error_detail(raw_body): if not raw_body: return "" try: obj = json.loads(raw_body) if isinstance(obj, dict): err = obj.get("error") if isinstance(obj.get("error"), dict) else obj msg = err.get("message") or "" meta = err.get("metadata") if isinstance(err.get("metadata"), dict) else {} raw = meta.get("raw") if isinstance(raw, str) and raw.strip(): try: raw_obj = json.loads(raw) inner = raw_obj.get("error", raw_obj) if isinstance(raw_obj, dict) else {} inner_msg = inner.get("message") if isinstance(inner, dict) else None if inner_msg: return f"{msg} ({inner_msg})".strip() except Exception: return f"{msg} ({raw[:140]})".strip() if msg: return str(msg).strip() except Exception: pass return " ".join(raw_body.split())[:180] def probe_account(account, model, timeout_seconds): token, key_err = read_keychain_token(account) if not token: return { "account": account, "status": "NO KEY", "ttft": None, "total": 0.0, "reasoning_chars": 0, "content_chars": 0, "keepalives": 0, "detail": key_err or "Missing Keychain entry", } payload = { "model": model, "stream": True, "max_tokens": 3000, "messages": [ {"role": "system", "content": "Be concise, accurate, and follow all requested output fields."}, {"role": "user", "content": CHEW_PROMPT}, ], } req = urllib.request.Request( "https://openrouter.ai/api/v1/chat/completions", data=json.dumps(payload).encode("utf-8"), method="POST", headers={ "Content-Type": "application/json", "Authorization": f"Bearer {token}", "X-Title": "Sidecar-HealthProbe", }, ) started = time.monotonic() ttft = None reasoning_chars = 0 content_chars = 0 keepalives = 0 finish_reason = None try: with urllib.request.urlopen(req, timeout=timeout_seconds) as resp: if resp.status < 200 or resp.status >= 300: body = resp.read(2048).decode("utf-8", errors="replace") return { "account": account, "status": f"HTTP {resp.status}", "ttft": None, "total": time.monotonic() - started, "reasoning_chars": 0, "content_chars": 0, "keepalives": 0, "detail": extract_error_detail(body), } while True: if time.monotonic() - started > timeout_seconds: elapsed = time.monotonic() - started return { "account": account, "status": "TIMEOUT", "ttft": ttft, "total": elapsed, "reasoning_chars": reasoning_chars, "content_chars": content_chars, "keepalives": keepalives, "detail": f"Exceeded {timeout_seconds:.0f}s wall-clock limit (keepalives={keepalives})", } raw_line = resp.readline() if not raw_line: break line = raw_line.decode("utf-8", errors="replace").rstrip("\r\n") if not line: continue if line.startswith(":"): keepalives += 1 continue if not line.startswith("data: "): continue data_str = line[6:].strip() if data_str == "[DONE]": break try: chunk = json.loads(data_str) except Exception: continue if isinstance(chunk, dict) and chunk.get("error"): err_obj = chunk["error"] code = err_obj.get("code") if isinstance(err_obj, dict) else None detail = extract_error_detail(json.dumps(chunk)) return { "account": account, "status": f"SSE {code}" if code else "SSE ERR", "ttft": ttft, "total": time.monotonic() - started, "reasoning_chars": reasoning_chars, "content_chars": content_chars, "keepalives": keepalives, "detail": detail, } for choice in chunk.get("choices") or []: delta = choice.get("delta") or {} r_text = delta.get("reasoning") or "" c_text = delta.get("content") or "" if r_text: if ttft is None: ttft = time.monotonic() - started reasoning_chars += len(r_text) if c_text: if ttft is None: ttft = time.monotonic() - started content_chars += len(c_text) if choice.get("finish_reason"): finish_reason = choice.get("finish_reason") elapsed = time.monotonic() - started if reasoning_chars == 0 and content_chars == 0: return { "account": account, "status": "EMPTY", "ttft": None, "total": elapsed, "reasoning_chars": 0, "content_chars": 0, "keepalives": keepalives, "detail": f"Stream ended with 0 output chars (finish_reason={finish_reason})", } if finish_reason == "error" and content_chars == 0: return { "account": account, "status": "SSE ERR", "ttft": ttft, "total": elapsed, "reasoning_chars": reasoning_chars, "content_chars": content_chars, "keepalives": keepalives, "detail": "Stream terminated with finish_reason=error", } return { "account": account, "status": "PASS", "ttft": ttft, "total": elapsed, "reasoning_chars": reasoning_chars, "content_chars": content_chars, "keepalives": keepalives, "detail": f"finish={finish_reason or 'ok'}", } except urllib.error.HTTPError as exc: body = "" try: body = exc.read(2048).decode("utf-8", errors="replace") except Exception: pass return { "account": account, "status": f"HTTP {exc.code}", "ttft": ttft, "total": time.monotonic() - started, "reasoning_chars": reasoning_chars, "content_chars": content_chars, "keepalives": keepalives, "detail": extract_error_detail(body) or str(exc.reason), } except TimeoutError: return { "account": account, "status": "TIMEOUT", "ttft": ttft, "total": time.monotonic() - started, "reasoning_chars": reasoning_chars, "content_chars": content_chars, "keepalives": keepalives, "detail": f"Socket timed out after {timeout_seconds:.0f}s", } except Exception as exc: return { "account": account, "status": "ERROR", "ttft": ttft, "total": time.monotonic() - started, "reasoning_chars": reasoning_chars, "content_chars": content_chars, "keepalives": keepalives, "detail": " ".join(str(exc).split())[:180], } def main(): parser = argparse.ArgumentParser(description="OpenRouter Non-Destructive Health Probe") parser.add_argument("--model", default=DEFAULT_MODEL, nargs="?") parser.add_argument("--scope", default="pool", nargs="?") parser.add_argument("--timeout_seconds", default="45", nargs="?") args, _ = parser.parse_known_args() model = (args.model or DEFAULT_MODEL).strip() or DEFAULT_MODEL scope = (args.scope or "pool").strip().lower() if scope not in ("pool", "primary"): scope = "pool" try: timeout_seconds = max(5.0, float(str(args.timeout_seconds or "45").strip())) except ValueError: timeout_seconds = 45.0 accounts = ["default"] if scope == "primary" else discover_pool_accounts() print("=== OpenRouter SSE Chew Probe ===") print(f"Model: {model} | Scope: {scope} ({len(accounts)} account(s)) | Cap: {timeout_seconds:.0f}s\n") results = [] if len(accounts) == 1: results.append(probe_account(accounts[0], model, timeout_seconds)) else: with concurrent.futures.ThreadPoolExecutor(max_workers=min(4, len(accounts))) as executor: futures = [executor.submit(probe_account, acct, model, timeout_seconds) for acct in accounts] results = [f.result() for f in futures] # Preserve input account order order = {acct: idx for idx, acct in enumerate(accounts)} results.sort(key=lambda r: order.get(r["account"], 999)) print(f"{'Account':<16} {'Status':<9} {'TTFT':>7} {'Total':>7} {'Reas':>6} {'Out':>6} {'KA':>4} Detail") print("-" * 88) passed = [] for r in results: ttft_s = f"{r['ttft']:.1f}s" if r["ttft"] is not None else "—" tot_s = f"{r['total']:.1f}s" print( f"{r['account']:<16} {r['status']:<9} {ttft_s:>7} {tot_s:>7} " f"{r['reasoning_chars']:>6} {r['content_chars']:>6} {r['keepalives']:>4} {r['detail']}" ) if r["status"] == "PASS": passed.append(r) total_count = len(results) pass_count = len(passed) if pass_count == total_count: verdict = "HEALTHY" elif pass_count > 0: verdict = "DEGRADED" else: verdict = "DOWN" print("\n--- Summary ---") print(f"Verdict: {verdict} ({pass_count}/{total_count} passed)") if passed: ttfts = [r["ttft"] for r in passed if r["ttft"] is not None] totals = [r["total"] for r in passed] med_ttft = f"{statistics.median(ttfts):.2f}s" if ttfts else "—" med_tot = f"{statistics.median(totals):.2f}s" print(f"Median TTFT: {med_ttft} | Median Total: {med_tot}") if __name__ == "__main__": main()