diff --git a/omniroute_offload/bin/claude-free b/omniroute_offload/bin/claude-free deleted file mode 100755 index ed1e45e..0000000 --- a/omniroute_offload/bin/claude-free +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/bash -# Claude Code with your full ~/.claude setup, but every model (main, subagents, -# background) is the free-best chain on the local OmniRoute gateway. Free providers log -# prompts, so it refuses to start outside public repos unless --force. -set -euo pipefail - -readonly GW="http://127.0.0.1:20128" -readonly MODEL="${CLAUDE_FREE_MODEL:-free-best}" -KEY="$(cat "${HOME}/.config/omniroute/api_key")" -readonly KEY - -if [[ "${1:-}" == --force ]]; then - shift -else - free-llm-check-dir . || { echo "claude-free: only public repos, /tmp, /var/log (or --force)" >&2; exit 2; } -fi - -curl -fsS -m 3 -o /dev/null "${GW}/v1/models" -H "Authorization: Bearer ${KEY}" || - { echo "claude-free: gateway down; run ~/src/omniroute-tetris-test/start.sh" >&2; exit 3; } - -export ANTHROPIC_BASE_URL="${GW}" ANTHROPIC_AUTH_TOKEN="${KEY}" ANTHROPIC_MODEL="${MODEL}" \ - ANTHROPIC_SMALL_FAST_MODEL="${MODEL}" ANTHROPIC_DEFAULT_OPUS_MODEL="${MODEL}" \ - ANTHROPIC_DEFAULT_SONNET_MODEL="${MODEL}" ANTHROPIC_DEFAULT_HAIKU_MODEL="${MODEL}" \ - CLAUDE_CODE_SUBAGENT_MODEL="${MODEL}" -exec claude --model "${MODEL}" "$@" diff --git a/omniroute_offload/omniroute_offload/_gw_api.py b/omniroute_offload/omniroute_offload/_gw_api.py index 1db65df..dcc66d8 100644 --- a/omniroute_offload/omniroute_offload/_gw_api.py +++ b/omniroute_offload/omniroute_offload/_gw_api.py @@ -69,13 +69,13 @@ def alive(cfg: Config) -> bool: return True -def chat(cfg: Config, key: str) -> str: - """One real completion through the combo; returns its text or raises ApiError.""" +def chat(cfg: Config, key: str, model: str = COMBO, max_tokens: int = 300) -> str: + """One real completion through the combo (or one model); its text, or ApiError.""" reply = call( f"{cfg.base_url}/v1/chat/completions", { - "model": COMBO, - "max_tokens": 300, + "model": model, + "max_tokens": max_tokens, "messages": [{"role": "user", "content": "Reply with exactly: OK"}], }, headers={"authorization": f"Bearer {key}"}, diff --git a/omniroute_offload/omniroute_offload/_gw_combo.py b/omniroute_offload/omniroute_offload/_gw_combo.py index d570b5b..8b134d5 100644 --- a/omniroute_offload/omniroute_offload/_gw_combo.py +++ b/omniroute_offload/omniroute_offload/_gw_combo.py @@ -5,15 +5,19 @@ the file's rank order (the combo is a priority chain), and drops every model of a provider whose connections are all inactive or logged out: OmniRoute hands such a member's 401 to the caller instead of the next model's answer (a kilo-gateway login expired on 2026-11-29 and failed a third of the board's free -turns). `keep_live` runs after each health tick and re-syncs the combo when that -set changes, so a reconnected provider comes back by itself. +turns). OmniRoute's own test revives such a login now and then, so one seen dead +is remembered (DEAD_FILE) until a real completion through it answers. `keep_live` +runs after each health tick and re-syncs the combo when that set changes, so a +reconnected provider comes back by itself. """ from __future__ import annotations import csv +import json import math import sys +from datetime import UTC, datetime from typing import TYPE_CHECKING, Any from omniroute_offload import _gw_api as api @@ -35,6 +39,9 @@ MIN_TETRIS = 0.85 MIN_CONTEXT = 32_000 # testStatus (or lastErrorType) of a login that is gone: kuhy reconnects it DEAD = frozenset({"expired", "unauthorized"}) +# state_dir file of logins seen dead; one stays out until a real request answers +DEAD_FILE = "dead_logins.json" +PROBE_TOKENS = 20 def _logged_out(conn: dict[str, Any]) -> bool: @@ -72,15 +79,64 @@ def dead_providers(conns: Iterable[dict[str, Any]]) -> set[str]: return {name for name, live in usable.items() if not live} +def _remembered(cfg: Config) -> dict[str, str]: + """Return the logins seen dead (provider -> first seen), kept across ticks.""" + try: + data = json.loads((cfg.state_dir / DEAD_FILE).read_text()) + except OSError, json.JSONDecodeError: + return {} + return {str(k): str(v) for k, v in data.items()} if isinstance(data, dict) else {} + + +def _remember(cfg: Config, dead: dict[str, str]) -> None: + cfg.state_dir.mkdir(parents=True, exist_ok=True) + (cfg.state_dir / DEAD_FILE).write_text(json.dumps(dead, sort_keys=True)) + + +def _answers(cfg: Config, model: str) -> bool: + """Say whether one real completion through `model` (not the combo) answers.""" + try: + api.chat(cfg, health.secret(cfg, "api_key"), model, PROBE_TOKENS) + except (api.ApiError, OSError) as err: + print(f"still out: {model}: {err}", file=sys.stderr) + return False + return True + + +def still_dead(cfg: Config, seen: set[str], order: Path) -> set[str]: + """Return providers to leave out: dead now, or seen dead and not yet answering. + + OmniRoute's own credential test passes a logged-out kilo-gateway every few + minutes (it marks it "active" and clears its last error), so a sync took it + back and the board's next free turn answered 401 (2026-11-29 12:56). A login + seen dead stays out until a real completion through one of its models answers. + """ + dead = _remembered(cfg) + now = datetime.now(UTC).isoformat() + for name in seen: + dead.setdefault(name, now) + for name in sorted(set(dead) - seen): + probe = next(iter(ranked_models(order, only=name)), None) + if probe is None: # no ranked model left: nothing of it can join the combo + del dead[name] + elif _answers(cfg, probe): + del dead[name] + print(f"back in: {name} answered a real request", file=sys.stderr) + _remember(cfg, dead) + return set(dead) + + def ranked_models( order: Path, dead: Iterable[str] = (), contexts: Mapping[str, int] | None = None, floor: int = MIN_PROMPT, + only: str | None = None, ) -> list[str]: """Return agent-capable models from order.tsv that pass the filters, best first. A model's input limit: the smaller of order.tsv's measured one and OmniRoute's. + `only` keeps one provider's models. """ gone, known = set(dead), contexts or {} with order.open(newline="") as handle: @@ -94,6 +150,7 @@ def ranked_models( and min(float(row.get("max_prompt") or 0), known.get(row["model"], math.inf)) >= floor and row["model"].split("/", 1)[0] not in gone + and only in (None, row["model"].split("/", 1)[0]) ] @@ -111,7 +168,8 @@ def _ranked(cfg: Config) -> bool: def _wanted(cfg: Config, admin: api.Admin) -> tuple[list[str], set[str]] | None: """Return the combo and the dead providers left out; None (logged) if all dead.""" - dead = dead_providers(admin.providers()) + order = cfg.conf_dir / "order.tsv" + dead = still_dead(cfg, dead_providers(admin.providers()), order) models = ranked_models( cfg.conf_dir / "order.tsv", dead, admin.contexts(), MIN_CONTEXT ) diff --git a/omniroute_offload/omniroute_offload/tests/test_gw_combo.py b/omniroute_offload/omniroute_offload/tests/test_gw_combo.py index d34dd1e..a07ad3f 100644 --- a/omniroute_offload/omniroute_offload/tests/test_gw_combo.py +++ b/omniroute_offload/omniroute_offload/tests/test_gw_combo.py @@ -241,6 +241,63 @@ def test_keep_live_brings_a_reconnected_provider_back( assert notices == ["free-best re-synced: every provider is back"] +@pytest.fixture +def probes(cfg: gwc.Config, monkeypatch: pytest.MonkeyPatch) -> dict[str, bool]: + """Model -> whether a real completion through it answers; records each probe.""" + (cfg.conf_dir / "api_key").write_text("k\n") + answers: dict[str, bool] = {} + + def chat(_cfg: gwc.Config, key: str, model: str = api.COMBO, _n: int = 0) -> str: + assert key == "k" + answers.setdefault(f"asked:{model}", True) + if not answers.get(model): + msg = "HTTP Error 401: Unauthorized" + raise api.ApiError(msg) + return "OK" + + monkeypatch.setattr(api, "chat", chat) + return answers + + +def test_keep_live_keeps_a_dead_login_out_when_omniroute_marks_it_active( + cfg: gwc.Config, + admins: list[FakeAdmin], + notices: list[str], + probes: dict[str, bool], +) -> None: + """OmniRoute's test revived a logged-out kilo-gateway; its next request was 401.""" + _write(cfg, HEADER + "nv/a\tyes\t1.0\t128000\nkilo/auto\tyes\t1.0\t128000\n") + CONNS.extend([_conn("nv"), _conn("kilo", "expired")]) + CURRENT.extend(["nv/a", "kilo/auto"]) + assert combo.keep_live(cfg) is True + CURRENT[:] = ["nv/a"] + CONNS[1] = _conn("kilo") # OmniRoute's credential test reset it to "active" + assert combo.keep_live(cfg) is False + assert probes == {"asked:kilo/auto": True} + assert admins[-1].upserts == [] + assert len(notices) == 1 + + +def test_keep_live_takes_a_dead_login_back_once_a_real_request_answers( + cfg: gwc.Config, + admins: list[FakeAdmin], + notices: list[str], + probes: dict[str, bool], + capsys: pytest.CaptureFixture[str], +) -> None: + _write(cfg, HEADER + "nv/a\tyes\t1.0\t128000\nkilo/auto\tyes\t1.0\t128000\n") + CONNS.extend([_conn("nv"), _conn("kilo", "expired")]) + CURRENT.extend(["nv/a", "kilo/auto"]) + assert combo.keep_live(cfg) is True + CURRENT[:] = ["nv/a"] + CONNS[1] = _conn("kilo") # kuhy reconnected it + probes["kilo/auto"] = True + assert combo.keep_live(cfg) is True + assert admins[-1].upserts == [(api.COMBO, ["nv/a", "kilo/auto"])] + assert "back in: kilo answered a real request" in capsys.readouterr().err + assert combo._remembered(cfg) == {} + + def test_keep_live_does_nothing_while_an_update_holds_the_lock( cfg: gwc.Config, admins: list[FakeAdmin] ) -> None: