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
feat(brain): resolve a connected subscription for output-is-the-product callers
Ruben Lütke43b1a194747d
diff --git a/jarvis/brain/model_catalog.py b/jarvis/brain/model_catalog.pyindex a03d9a5f3d..7143d78d38 100644--- a/jarvis/brain/model_catalog.py+++ b/jarvis/brain/model_catalog.py@@ -661,6 +661,26 @@ def _build_provider_catalog() -> dict[str, CatalogSpec]:),live=False,)+ # Claude CLI — the Anthropic-subscription writer (``claude -p``); no+ # /v1/models over a plan login, so curated only. The aliases are what the CLI+ # itself accepts, not dated API ids: they keep pointing at the plan's current+ # model as Anthropic rotates it, which is exactly right for a subscription+ # path where the account's plan decides what is reachable anyway. Leaving the+ # model unset is also valid and means "whatever this plan defaults to".+ cat["claude-cli"] = CatalogSpec(+ "brain",+ "model",+ tuple(+ _curated(+ [+ ("sonnet", "Claude Sonnet (plan default tier)"),+ ("opus", "Claude Opus (deepest, slowest)"),+ ("haiku", "Claude Haiku (fastest)"),+ ]+ )+ ),+ live=False,+ )for p, (selects, opts) in TTS_CATALOG.items():cat[p] = CatalogSpec("tts", selects, tuple(opts), live=False)for p, opts in STT_CATALOG.items():diff --git a/jarvis/brain/resolver.py b/jarvis/brain/resolver.pyindex 4058197b1f..98d165c570 100644--- a/jarvis/brain/resolver.py+++ b/jarvis/brain/resolver.py@@ -31,7 +31,7 @@ Cache strategy: singleton cache, invalidated on ``ConfigReloaded`` eventfrom __future__ import annotationsimport logging-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Anyfrom jarvis.brain.manager import TIER_DEFAULTS_BY_PROVIDERfrom jarvis.brain.provider_registry import BrainProviderRegistry@@ -232,6 +232,122 @@ def resolve_quality_brain(return None+def _subscription_connected(provider: str) -> bool:+ """Whether ``provider``'s subscription login is usable right now.++ Asks the provider CLASS through the registry rather than importing an auth+ service per family here, so a subscription brain added later answers for+ itself with no edit to this module (AP-21). A provider that offers no probe+ is treated as connected: the instantiation that follows is the real gate, a+ false "yes" costs one wasted candidate, and a false "no" would hide a+ working subscription the user is paying for. The drift guard in+ ``tests/unit/brain/test_resolve_subscription_brain.py`` is what keeps that+ lenient default from quietly becoming the normal case.+ """+ try:+ brain_cls = _get_registry().get_class(provider)+ except Exception: # noqa: BLE001 - an unloadable plugin is simply not usable+ return False+ probe = getattr(brain_cls, "subscription_connected", None)+ if probe is None:+ return True+ try:+ return bool(probe())+ except Exception: # noqa: BLE001 - a probe must never break a turn+ log.info("resolve_subscription_brain: %s probe failed", provider, exc_info=True)+ return False+++def _subscription_candidates(config: JarvisConfig) -> list[str]:+ """Registered brain providers billed against a subscription, in card order.++ Membership comes from the provider cards' billing mode — never a name list,+ so a fourth coding CLI joins the chain by shipping a card (AP-21/AP-22).+ ``config`` is accepted for signature symmetry with the other helpers here.+ """+ from jarvis.ui.web.provider_spec import PROVIDERS, provider_billing++ available = set(_get_registry().available())+ return [+ spec.id+ for spec in PROVIDERS+ if spec.tier == "brain"+ and spec.id in available+ and provider_billing(spec).startswith("subscription")+ ]+++def resolve_subscription_brain(+ config: JarvisConfig,+ *,+ bus: EventBus | None = None,+ cli_timeout_s: float | None = None,+) -> Brain | None:+ """A Brain billed against a connected subscription, or None.++ For callers whose output IS the product and who are already waiting seconds+ — the Agentic IDE's prompt composer and work splitter. It exists so those+ callers can spend a plan the user already pays for instead of a per-token+ key, and so a downloader whose ONLY credential is a coding subscription+ stops falling through to the deterministic prompt on every instruction.++ Never raises: None means "no subscription can do this", and the caller falls+ through to the API-billed resolver and finally to its own plain layer.++ **A candidate that cannot honour ``structured_prompts`` is SKIPPED, never+ used conversationally.** A CLI brain in conversational mode replaces the+ caller's contract with "answer in one to three short sentences" and returns+ three fluent sentences that read like a valid brief. That is strictly worse+ than returning None, because the caller's own fallback is at least honest+ about being plain.++ Deliberately does NOT populate ``_cache``: its key is ``(provider, model)``+ and is shared with the voice-tier resolvers, so a cached structured instance+ would later be handed to a spoken turn built to expect the conversational+ wrapper.+ """+ _ensure_bus_subscription(bus)+ try:+ candidates = _subscription_candidates(config)+ except Exception: # noqa: BLE001 - a spec problem must not kill the caller+ log.info("resolve_subscription_brain: candidates unavailable", exc_info=True)+ return None++ for provider in candidates:+ if not _subscription_connected(provider):+ log.debug("resolve_subscription_brain: %s not signed in", provider)+ continue+ kwargs: dict[str, Any] = {"structured_prompts": True}+ model = _deep_model_for(config, provider)+ if model:+ kwargs["model"] = model+ if cli_timeout_s and cli_timeout_s > 0:+ kwargs["cli_timeout_s"] = float(cli_timeout_s)+ try:+ brain = _get_registry().instantiate(provider, **kwargs)+ except TypeError:+ # Signature probe, not a name check (AP-21): no structured mode+ # means no brief, so skip rather than degrade invisibly.+ log.info(+ "resolve_subscription_brain: %s cannot forward a system "+ "contract — skipping rather than answering conversationally",+ provider,+ )+ continue+ except Exception as exc: # noqa: BLE001+ log.info(+ "resolve_subscription_brain: %s not instantiable (%s)",+ provider,+ type(exc).__name__,+ )+ continue+ log.info("resolve_subscription_brain: writing on %s", provider)+ return brain++ log.info("resolve_subscription_brain: no connected subscription reachable")+ return None++# ----------------------------------------------------------------------# Internal — Chain-Building# ----------------------------------------------------------------------diff --git a/jarvis/plugins/brain/antigravity.py b/jarvis/plugins/brain/antigravity.pyindex c89052043d..d0654eb128 100644--- a/jarvis/plugins/brain/antigravity.py+++ b/jarvis/plugins/brain/antigravity.py@@ -190,6 +190,27 @@ class AntigravityBrain:budget = 0.0self._cli_timeout_s = budget if budget > 0 else _CLI_TIMEOUT_S+ @staticmethod+ def subscription_connected() -> bool:+ """Whether this provider's Google subscription login is usable now.++ The subscription resolver asks the provider class rather than importing+ an auth service per family, so each brain answers for itself. Only a+ personal OAuth login counts: an API key configured for this family bills+ per token, which is precisely what a subscription caller is avoiding.+ Never raises — a failed probe means "not connected", never a broken turn.+ """+ try:+ from jarvis.google_cli.auth_service import GoogleCliAuthService++ status = GoogleCliAuthService().status()+ return bool(+ getattr(status, "connected", False)+ and getattr(status, "mode", "") == "oauth-personal"+ )+ except Exception: # noqa: BLE001 - a probe degrades, never raises+ return False+def can_call_tools(self) -> bool:"""Runtime tool-calling capability (NOT the static ``supports_tools``).diff --git a/jarvis/plugins/brain/codex.py b/jarvis/plugins/brain/codex.pyindex 6a85a31624..9bfb0e9e59 100644--- a/jarvis/plugins/brain/codex.py+++ b/jarvis/plugins/brain/codex.py@@ -166,6 +166,16 @@ class CodexBrain:# Only the API-key path can see images (see the supports_vision note).self.supports_vision = bool(self._api_key())+ @staticmethod+ def subscription_connected() -> bool:+ """Whether this provider's ChatGPT subscription login is usable now.++ The subscription resolver asks the provider class rather than importing+ an auth service per family, so each brain answers for itself. Never+ raises — a failed probe means "not connected", never a broken turn.+ """+ return _codex_oauth_connected()+def can_call_tools(self) -> bool:"""Runtime tool-calling capability (NOT the static ``supports_tools``).diff --git a/tests/unit/brain/test_resolve_subscription_brain.py b/tests/unit/brain/test_resolve_subscription_brain.pynew file mode 100644index 0000000000..4d229de5a9--- /dev/null+++ b/tests/unit/brain/test_resolve_subscription_brain.py@@ -0,0 +1,161 @@+"""resolve_subscription_brain — spec-driven, capability-gated, never name-gated.++The guard that matters here is the SKIP: a CLI brain that cannot forward the+caller's system contract answers conversationally, and three fluent sentences+read exactly like a valid brief. Choosing such a provider is worse than choosing+none, because the caller's own deterministic layer is at least honest about what+it is.+"""+from __future__ import annotations++from typing import Any++from jarvis.brain import resolver+from jarvis.core.config import JarvisConfig+++class _FakeRegistry:+ """Records how each provider was instantiated."""++ def __init__(+ self,+ available: list[str],+ accepts_structured: tuple[str, ...] = (),+ fail: tuple[str, ...] = (),+ ) -> None:+ self._available = list(available)+ self._accepts = set(accepts_structured)+ self._fail = set(fail)+ self.calls: list[tuple[str, dict[str, Any]]] = []++ def available(self) -> list[str]:+ return list(self._available)++ def instantiate(self, name: str, **kwargs: Any) -> Any:+ self.calls.append((name, dict(kwargs)))+ if name in self._fail:+ raise RuntimeError("not instantiable")+ if "structured_prompts" in kwargs and name not in self._accepts:+ raise TypeError("unexpected keyword argument 'structured_prompts'")+ return f"brain:{name}"+++def _cfg() -> JarvisConfig:+ return JarvisConfig()+++def test_only_subscription_providers_are_considered(monkeypatch) -> None:+ """API-key families never appear here — that is resolve_quality_brain's job."""+ registry = _FakeRegistry(+ available=["codex", "claude-cli", "antigravity", "gemini", "openai"],+ accepts_structured=("codex", "claude-cli", "antigravity"),+ )+ monkeypatch.setattr(resolver, "_get_registry", lambda: registry)+ monkeypatch.setattr(resolver, "_subscription_connected", lambda name: True)++ assert resolver.resolve_subscription_brain(_cfg()) is not None+ picked = [name for name, _ in registry.calls]+ assert "gemini" not in picked+ assert "openai" not in picked+++def test_a_provider_that_cannot_take_structured_prompts_is_skipped(monkeypatch) -> None:+ """The load-bearing guard against invisible degradation."""+ registry = _FakeRegistry(+ available=["codex", "claude-cli"], accepts_structured=("claude-cli",)+ )+ monkeypatch.setattr(resolver, "_get_registry", lambda: registry)+ monkeypatch.setattr(resolver, "_subscription_connected", lambda name: True)++ assert resolver.resolve_subscription_brain(_cfg()) == "brain:claude-cli"+++def test_disconnected_subscriptions_are_not_offered(monkeypatch) -> None:+ """A CLI that is installed but not logged in must not be chosen."""+ registry = _FakeRegistry(available=["codex"], accepts_structured=("codex",))+ monkeypatch.setattr(resolver, "_get_registry", lambda: registry)+ monkeypatch.setattr(resolver, "_subscription_connected", lambda name: False)++ assert resolver.resolve_subscription_brain(_cfg()) is None+++def test_returns_none_instead_of_raising_when_nothing_is_reachable(monkeypatch) -> None:+ """None is the answer, not an error — the caller degrades openly."""+ registry = _FakeRegistry(+ available=["codex"], accepts_structured=("codex",), fail=("codex",)+ )+ monkeypatch.setattr(resolver, "_get_registry", lambda: registry)+ monkeypatch.setattr(resolver, "_subscription_connected", lambda name: True)++ assert resolver.resolve_subscription_brain(_cfg()) is None+++def test_cli_timeout_is_forwarded(monkeypatch) -> None:+ """A caller waiting 90 s must not be killed by a provider's own voice cap."""+ registry = _FakeRegistry(available=["codex"], accepts_structured=("codex",))+ monkeypatch.setattr(resolver, "_get_registry", lambda: registry)+ monkeypatch.setattr(resolver, "_subscription_connected", lambda name: True)++ resolver.resolve_subscription_brain(_cfg(), cli_timeout_s=300.0)+ assert registry.calls[0][1]["cli_timeout_s"] == 300.0+++def test_structured_prompts_is_always_requested(monkeypatch) -> None:+ """Every candidate is asked for the verbatim contract, never the chat wrapper."""+ registry = _FakeRegistry(available=["codex"], accepts_structured=("codex",))+ monkeypatch.setattr(resolver, "_get_registry", lambda: registry)+ monkeypatch.setattr(resolver, "_subscription_connected", lambda name: True)++ resolver.resolve_subscription_brain(_cfg())+ assert registry.calls[0][1]["structured_prompts"] is True+++def test_the_result_is_not_cached_under_the_shared_key(monkeypatch) -> None:+ """The module cache is keyed (provider, model) and shared with the voice-tier+ resolvers. Caching a structured instance there would later hand a spoken turn+ a brain built to ignore its conversational wrapper."""+ registry = _FakeRegistry(available=["codex"], accepts_structured=("codex",))+ monkeypatch.setattr(resolver, "_get_registry", lambda: registry)+ monkeypatch.setattr(resolver, "_subscription_connected", lambda name: True)++ before = dict(resolver._cache)+ resolver.resolve_subscription_brain(_cfg())+ assert dict(resolver._cache) == before+++def test_membership_is_spec_driven_not_a_name_list() -> None:+ """Adding a subscription card must extend the chain with no resolver edit."""+ from jarvis.ui.web import provider_spec++ ids = {+ spec.id+ for spec in provider_spec.PROVIDERS+ if spec.tier == "brain"+ and provider_spec.provider_billing(spec).startswith("subscription")+ }+ assert {"codex", "antigravity", "claude-cli"} <= ids+++def test_every_subscription_card_can_answer_the_connection_probe() -> None:+ """A card whose class has no probe would be assumed connected forever.++ This is the drift guard: someone adds a fourth subscription brain, forgets+ the probe, and the resolver starts choosing a provider nobody is signed in+ to — which fails at call time, several seconds into a turn.+ """+ from jarvis.brain.provider_registry import BrainProviderRegistry+ from jarvis.ui.web import provider_spec++ registry = BrainProviderRegistry()+ available = set(registry.available())+ for spec in provider_spec.PROVIDERS:+ if spec.tier != "brain" or not provider_spec.provider_billing(+ spec+ ).startswith("subscription"):+ continue+ if spec.id not in available:+ continue+ brain_cls = registry.get_class(spec.id)+ assert callable(+ getattr(brain_cls, "subscription_connected", None)+ ), f"{spec.id} has no subscription_connected probe"