Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
chore: auto-save WIP via Claude stop-hook safety net (2026-06-30 18:16)
Ruben Lütke9c23cd2b4205
diff --git a/jarvis/harness/screenshot_only_loop.py b/jarvis/harness/screenshot_only_loop.pyindex d4c42ca53d..44bda3ad4c 100644--- a/jarvis/harness/screenshot_only_loop.py+++ b/jarvis/harness/screenshot_only_loop.py@@ -92,6 +92,23 @@ class CULoopError(RuntimeError):"""Structural error in the screenshot-only loop."""+class CUNoCapableProviderError(CULoopError):+ """No screen-capable (vision) brain was reachable for Computer-Use.++ Raised when the whole provider chain is exhausted because every candidate+ was keyless / out-of-credit (402) / rate-limited (429) / unreachable /+ no-vision — i.e. an account/credential fact the user can fix in-app, NOT the+ model returning an unparseable response. Subclasses :class:`CULoopError` so+ existing ``except CULoopError`` paths keep catching it, while callers that+ care (the exit-code mapper) can tell it apart and report it honestly (exit 3,+ a "check your keys/credit" readback) instead of the generic parse phrase.+ Live forensic 2026-06-30: a Spotify screen action failed because Gemini's+ credits were depleted, Claude returned 502, OpenAI had no key, and the+ OpenRouter model had no vision — yet the user heard the misleading "couldn't+ get a valid screen-control response" (exit 2).+ """++_VALID_ACTIONS: frozenset[str] = frozenset({"click", "click_element", "type", "key", "scroll", "drag","open_app", "switch_window", "wait", "done", "fail"}diff --git a/jarvis/memory/wiki/provider_chain.py b/jarvis/memory/wiki/provider_chain.pynew file mode 100644index 0000000000..a337ff2e94--- /dev/null+++ b/jarvis/memory/wiki/provider_chain.py@@ -0,0 +1,118 @@+"""Key-aware provider fallback for wiki-tier LLM calls (extractor + curator).++Why this exists+---------------+The main ``BrainManager`` survives a dead / throttled / keyless provider by+looping over a key-aware fallback CHAIN (``manager._build_fallback_chain``): it+tries the next provider on any failure and only gives up when none is reachable.+The wiki extractor (stage 1) and curator (stage 2) did NOT — each resolved to a+SINGLE provider (``cfg.provider`` or ``brain.primary``) and, on any error,+returned an empty list with only a WARNING.++Live forensic 2026-06-30: the user's openrouter key was over its total limit+(403), gemini was out of prepaid credit (429) AND claude-api auth was rejected+(401) at various moments. Whenever the wiki's single resolved provider was the+one erroring, the whole pipeline silently no-op'd — nothing journaled, nothing+written — even though the main voice brain limped along via its own fallback+chain and a working provider existed. The wiki looked dead while the user had+credit. This module gives the wiki the SAME resilience, plus an HONEST signal+when the whole chain is exhausted (AP-22 single-provider brick / AP-23+maintainer-config coupling).+"""+from __future__ import annotations++import asyncio+import logging+from collections.abc import Callable+from typing import Any++from jarvis.memory.wiki import telemetry++log = logging.getLogger(__name__)++# Cross-family fallback order, mirroring manager._build_fallback_chain step 3: a+# separate-quota family first (claude-api), then the gateways. Each is tried+# ONLY if registered (registry.available()); a keyless / throttled one fails+# fast and the loop crosses to the next FAMILY — never a same-family dead-end.+_CROSS_FAMILY_ORDER: tuple[str, ...] = ("claude-api", "gemini", "openrouter", "openai")+++def build_wiki_provider_chain(+ *,+ primary: str,+ model_override: str,+ available: set[str] | frozenset[str],+) -> list[tuple[str, str | None]]:+ """Ordered, de-duplicated ``(provider, model)`` attempts for a wiki LLM call.++ ``primary`` (``cfg.provider`` or ``brain.primary``) leads, then the+ cross-family order. Only providers in ``available`` survive. An explicit+ ``model_override`` (``cfg.model``) applies ONLY to ``primary`` — a fallback+ provider gets its OWN cheap router-tier model, never the primary's model id+ (sending a gemini model id to claude-api would 404).+ """+ from jarvis.memory.wiki.curator_llm import _cheap_model_for++ chain: list[tuple[str, str | None]] = []+ seen: set[str] = set()+ override = (model_override or "").strip()+ for name in (primary, *_CROSS_FAMILY_ORDER):+ if not name or name in seen or name not in available:+ continue+ seen.add(name)+ model = override if (name == primary and override) else _cheap_model_for(name)+ chain.append((name, model or None))+ return chain+++async def complete_with_fallback(+ *,+ registry: Any,+ chain: list[tuple[str, str | None]],+ request: Any,+ timeout_s: float,+ label: str,+ aggregate: Callable[[Any], Any],+) -> tuple[Any, str] | None:+ """Try each ``(provider, model)`` until one returns an aggregated response.++ Returns ``(agg, provider_name)`` on the first success, or ``None`` when the+ WHOLE chain failed. A single provider failure is a WARNING (visible, not+ fatal); an exhausted chain is an ERROR plus a ``wiki_all_providers_failed``+ telemetry bump — the HONEST signal that the wiki could reach NO provider,+ instead of the old silent empty return.+ """+ from jarvis.memory.wiki.curator_llm import instantiate_curator_brain++ for provider, model in chain:+ try:+ brain = instantiate_curator_brain(registry, provider, model)+ except Exception as exc: # noqa: BLE001 — a bad provider must not abort the chain+ log.warning("%s: could not instantiate %s (%s) — trying next provider", label, provider, exc)+ continue+ if brain is None:+ continue+ try:+ agg = await asyncio.wait_for(aggregate(brain.complete(request)), timeout=timeout_s)+ return agg, provider+ except TimeoutError:+ log.warning("%s: provider %s timed out after %.1fs — trying next provider", label, provider, timeout_s)+ continue+ except Exception as exc: # noqa: BLE001 — try the next family, never dead-end on one+ log.warning("%s: provider %s failed (%s) — trying next provider", label, provider, exc)+ continue++ log.error(+ "%s: ALL %d wiki provider(s) failed — no LLM reachable this round; nothing "+ "was written. Check API keys / quota in the API-Keys section.",+ label,+ len(chain),+ )+ try:+ telemetry.inc("wiki_all_providers_failed")+ except Exception: # noqa: BLE001 — telemetry must never break the pipeline+ pass+ return None+++__all__ = ["build_wiki_provider_chain", "complete_with_fallback"]diff --git a/tests/unit/harness/test_cu_loop_robustness.py b/tests/unit/harness/test_cu_loop_robustness.pyindex 3175e77f13..f8bc3dfc39 100644--- a/tests/unit/harness/test_cu_loop_robustness.py+++ b/tests/unit/harness/test_cu_loop_robustness.py@@ -32,7 +32,11 @@ from jarvis.core.protocols import (from jarvis.harness.computer_use_context import ComputerUseContextfrom jarvis.harness.screenshot_only_loop import (CULoopError,+ CUNoCapableProviderError,+ _NO_PROVIDER_EXIT_CODE,+ _PARSE_EXIT_CODE,_call_brain,+ _llm_failure_exit_code,_run_screenshot_loop,)@@ -343,6 +347,59 @@ async def test_repeated_model_failures_end_mission_cleanly() -> None:assert len(brain.requests) == 3+# ---------------------------------------------------------------------------+# Honest exit code when the vision-provider chain is EXHAUSTED (exit 3, not the+# overloaded parse/"confused" exit 2). Live forensic 2026-06-30: every CU vision+# provider was dead (Gemini credits depleted, Claude 502, OpenAI no key,+# OpenRouter model no-vision), so _call_brain raised the provider-chain error 3×+# — but the loop reported exit 2 and the user heard "couldn't get a valid+# screen-control response" instead of an honest "no screen-capable model; check+# your keys/credit". An exhausted chain is an account/credential fact, not model+# confusion, so it gets its own exit code.+# ---------------------------------------------------------------------------+++def test_llm_failure_exit_code_distinguishes_dead_chain_from_parse() -> None:+ # An exhausted vision-provider chain → the honest "no capable provider" code.+ assert _llm_failure_exit_code(+ CUNoCapableProviderError("provider chain failed: no vision-capable provider")+ ) == _NO_PROVIDER_EXIT_CODE+ # A generic brain failure / parse error stays the parse/confused code.+ assert _llm_failure_exit_code(CULoopError("bad parse")) == _PARSE_EXIT_CODE+ assert _llm_failure_exit_code(RuntimeError("provider hiccup")) == _PARSE_EXIT_CODE+ # The honest code must be distinct from the parse code (no overloading).+ assert _NO_PROVIDER_EXIT_CODE != _PARSE_EXIT_CODE+++async def test_exhausted_vision_chain_exits_with_no_provider_code() -> None:+ class _DeadChainManager:+ """Every provider in the chain is dead (the 2026-06-30 reality)."""++ active_provider = "primary"++ def __init__(self) -> None:+ self.brain = _StreamingBrain(+ exc=RuntimeError("429 prepayment credits depleted"),+ supports_vision=True,+ )++ def _build_fallback_chain(self, level: str) -> list[tuple[str, str | None]]:+ return [("primary", "vision-model")]++ def _get_brain(self, name: str, model: str | None = None) -> "_StreamingBrain":+ return self.brain++ ctx = make_ctx(_DeadChainManager())+ chunks = await run_loop(ctx, "öffne mein spotify und spiel das lied")++ final = chunks[-1]+ assert final.is_final+ assert final.exit_code == _NO_PROVIDER_EXIT_CODE, (+ f"exhausted vision chain must exit {_NO_PROVIDER_EXIT_CODE} (honest), "+ f"got {final.exit_code}: {final.stderr!r}"+ )++# ---------------------------------------------------------------------------# Wave A4 — _call_brain must raise on an unusable manager, never return None# ---------------------------------------------------------------------------diff --git a/tests/unit/marketplace/test_connect_helpers.py b/tests/unit/marketplace/test_connect_helpers.pyindex 208188709b..56977ae72e 100644--- a/tests/unit/marketplace/test_connect_helpers.py+++ b/tests/unit/marketplace/test_connect_helpers.py@@ -201,13 +201,60 @@ def test_resolve_pkce_client_google_prefers_secret(assert csec == "GOCSPX-x"-def test_resolve_pkce_client_non_google_passthrough(+def test_resolve_pkce_client_unmapped_passthrough(monkeypatch: pytest.MonkeyPatch,) -> None:+ # A PKCE plugin with no own-client family mapping returns the catalog values+ # unchanged and never reads a secret (defensive: no accidental hijack).monkeypatch.setattr("jarvis.core.config.get_secret",lambda key, env_fallback=None: "should-not-be-used",)- cid, csec = resolve_pkce_client("slack", "slack.id", "slack.secret")- assert cid == "slack.id"- assert csec == "slack.secret"+ cid, csec = resolve_pkce_client("some_future_pkce", "cat.id", "cat.secret")+ assert cid == "cat.id"+ assert csec == "cat.secret"+++def test_resolve_pkce_client_slack_prefers_secret(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # Slack now supports a bring-your-own OAuth client via the slack_oauth_client_*+ # secrets, exactly like the Google family — so a downloader can run their own+ # production Slack app instead of the maintainer's catalog client.+ monkeypatch.setattr(+ "jarvis.core.config.get_secret",+ lambda key, env_fallback=None: {+ "slack_oauth_client_id": "111.222",+ "slack_oauth_client_secret": "slack-sec",+ }.get(key),+ )+ cid, csec = resolve_pkce_client("slack", "catalog.id", "catalog.secret")+ assert cid == "111.222"+ assert csec == "slack-sec"+++def test_resolve_pkce_client_asana_prefers_secret(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ "jarvis.core.config.get_secret",+ lambda key, env_fallback=None: {+ "asana_oauth_client_id": "asana-rid",+ "asana_oauth_client_secret": "asana-sec",+ }.get(key),+ )+ cid, csec = resolve_pkce_client("asana", "catalog.id", "catalog.secret")+ assert cid == "asana-rid"+ assert csec == "asana-sec"+++def test_resolve_pkce_client_slack_falls_back_to_catalog_when_no_secret(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # No slack_oauth secret set -> the real catalog client_id is used unchanged.+ monkeypatch.setattr(+ "jarvis.core.config.get_secret", lambda key, env_fallback=None: None+ )+ cid, csec = resolve_pkce_client("slack", "slack.real.id", "slack.real.secret")+ assert cid == "slack.real.id"+ assert csec == "slack.real.secret"diff --git a/tests/unit/memory/wiki/test_provider_chain.py b/tests/unit/memory/wiki/test_provider_chain.pynew file mode 100644index 0000000000..fe05b70057--- /dev/null+++ b/tests/unit/memory/wiki/test_provider_chain.py@@ -0,0 +1,118 @@+"""Wiki provider fallback chain — the fix for the silent single-provider brick.++Live 2026-06-30: openrouter 403 (key over total limit), gemini 429 (credit+depleted) and claude-api 401 (auth) all hit at various moments. The wiki was+pinned to ONE provider with no fallback, so whenever that one erred it silently+journaled/wrote nothing — while the main brain limped on via its chain. These+tests pin the new resilience: cross to a working FAMILY, give up honestly only+when ALL fail.+"""+from __future__ import annotations++from typing import Any++from jarvis.memory.wiki.provider_chain import (+ build_wiki_provider_chain,+ complete_with_fallback,+)++_ALL = {"openrouter", "gemini", "claude-api", "openai"}+++# --- chain shape (pure) ------------------------------------------------------+++def test_chain_leads_with_primary_then_crosses_families():+ chain = build_wiki_provider_chain(primary="openrouter", model_override="", available=_ALL)+ providers = [p for p, _ in chain]+ assert providers[0] == "openrouter" # configured/primary first+ assert "claude-api" in providers # then a different family+ assert "gemini" in providers+ assert providers.count("openrouter") == 1 # primary not duplicated+++def test_chain_keeps_only_available_providers():+ chain = build_wiki_provider_chain(primary="gemini", model_override="", available={"gemini"})+ assert [p for p, _ in chain] == ["gemini"] # nothing to cross to+++def test_model_override_applies_only_to_primary():+ chain = build_wiki_provider_chain(+ primary="gemini", model_override="gemini-custom-x", available={"gemini", "claude-api"}+ )+ by = dict(chain)+ assert by["gemini"] == "gemini-custom-x" # explicit model honored for primary+ assert by["claude-api"] != "gemini-custom-x" # fallback gets its OWN cheap model+++# --- the fallback loop -------------------------------------------------------+++class _FakeBrain:+ def __init__(self, *, fail: bool) -> None:+ self._fail = fail++ def complete(self, request: Any):+ async def _gen():+ if self._fail:+ raise RuntimeError("provider down")+ yield "chunk"++ return _gen()+++class _FakeRegistry:+ def __init__(self, fail_providers: set[str]) -> None:+ self._fail = set(fail_providers)+ self.tried: list[str] = []++ def available(self) -> set[str]:+ return set(_ALL)++ def instantiate(self, name: str, **kwargs: Any) -> Any:+ self.tried.append(name)+ return _FakeBrain(fail=name in self._fail)+++async def _aggregate(stream: Any) -> Any:+ chunks = []+ async for c in stream:+ chunks.append(c)+ return type("Agg", (), {"text": "".join(chunks), "finish_reason": "stop"})()+++async def test_falls_over_to_first_working_provider():+ reg = _FakeRegistry(fail_providers={"openrouter", "gemini"})+ chain = build_wiki_provider_chain(primary="openrouter", model_override="", available=reg.available())+ result = await complete_with_fallback(+ registry=reg, chain=chain, request=object(), timeout_s=5.0,+ label="test", aggregate=_aggregate,+ )+ assert result is not None+ agg, provider = result+ assert provider == "claude-api" # crossed past the two dead ones+ assert reg.tried == ["openrouter", "claude-api"]+ assert agg.text == "chunk"+++async def test_returns_none_only_when_every_provider_fails():+ reg = _FakeRegistry(fail_providers=set(_ALL))+ chain = build_wiki_provider_chain(primary="openrouter", model_override="", available=reg.available())+ result = await complete_with_fallback(+ registry=reg, chain=chain, request=object(), timeout_s=5.0,+ label="test", aggregate=_aggregate,+ )+ assert result is None # honest give-up, not a crash+ assert set(reg.tried) == _ALL # it really tried all families+++async def test_first_provider_success_does_not_try_others():+ reg = _FakeRegistry(fail_providers=set())+ chain = build_wiki_provider_chain(primary="gemini", model_override="", available=reg.available())+ result = await complete_with_fallback(+ registry=reg, chain=chain, request=object(), timeout_s=5.0,+ label="test", aggregate=_aggregate,+ )+ assert result is not None+ assert result[1] == "gemini"+ assert reg.tried == ["gemini"] # no needless fallback calls