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): let the paid Codex/Antigravity subscriptions genuinely power the wiki tier
Ruben Lütke0a080a7c268e
diff --git a/jarvis/memory/wiki/curator_llm.py b/jarvis/memory/wiki/curator_llm.pyindex 21637adc11..c0e4dd9635 100644--- a/jarvis/memory/wiki/curator_llm.py+++ b/jarvis/memory/wiki/curator_llm.py@@ -165,10 +165,17 @@ def instantiate_curator_brain(kwargs: dict[str, Any] = {"model": model}if provider == "gemini" and "pro" not in (model or "").lower():kwargs["thinking_budget"] = 0- try:- return registry.instantiate(provider, **kwargs)- except TypeError:- return registry.instantiate(provider)+ # Subscription-CLI brains (codex, antigravity) flatten voice turns into a+ # conversational plain-text prompt by design — which silently destroys the+ # curator tier's JSON contract. Providers whose constructor accepts+ # ``structured_prompts`` forward the contract verbatim instead; the probe+ # is signature acceptance (capability, never a provider name — AP-21).+ for attempt in ({**kwargs, "structured_prompts": True}, kwargs):+ try:+ return registry.instantiate(provider, **attempt)+ except TypeError:+ continue+ return registry.instantiate(provider)def _extract_json_array(text: str) -> Any:diff --git a/jarvis/plugins/brain/antigravity.py b/jarvis/plugins/brain/antigravity.pyindex 8ad3b58f06..7bf1acdbf5 100644--- a/jarvis/plugins/brain/antigravity.py+++ b/jarvis/plugins/brain/antigravity.py@@ -45,6 +45,7 @@ from jarvis.google_cli.resolver import GoogleCli, resolve_google_clifrom .cli_prompt_context import (extract_reply_language_directive,render_cli_standing_instructions,+ render_structured_prompt,)log = logging.getLogger(__name__)@@ -167,8 +168,16 @@ class AntigravityBrain:supports_tools: bool = True # ignored on the CLI path (mirrors CodexBrain)supports_vision: bool = False- def __init__(self, model: str | None = None) -> None:+ def __init__(+ self, model: str | None = None, structured_prompts: bool = False,+ ) -> None:self._model = model or DEFAULT_MODEL+ # Background/structured callers (the wiki curator tier) set this so+ # their JSON contract reaches the CLI model verbatim instead of the+ # conversational "answer in 1-3 plain-text sentences" wrapper — which+ # made structured output impossible by instruction (live 2026-07-18:+ # every wiki extraction died with "no JSON array found in response").+ self._structured_prompts = bool(structured_prompts)def can_call_tools(self) -> bool:"""Runtime tool-calling capability (NOT the static ``supports_tools``).@@ -180,6 +189,12 @@ class AntigravityBrain:tool-capable provider instead of letting the CLI silently no-op."""return False+ def _render_prompt(self, req: BrainRequest) -> str:+ """Conversational flattening for voice turns; verbatim for structured."""+ if self._structured_prompts:+ return render_structured_prompt(req)+ return _build_cli_prompt(req)+async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:cli = resolve_google_cli()if cli is None:@@ -188,7 +203,7 @@ class AntigravityBrain:"CLI and sign in with Google.")- prompt = _build_cli_prompt(req)+ prompt = self._render_prompt(req)argv = _build_argv(cli, prompt, self._model)# agy is a TUI tool: over a plain pipe it emits 0 bytes (the brain then# sees "no answer"). It must be driven over a real pseudo-terminal. Thediff --git a/jarvis/plugins/brain/cli_prompt_context.py b/jarvis/plugins/brain/cli_prompt_context.pyindex 3a2c1768bd..3aca567414 100644--- a/jarvis/plugins/brain/cli_prompt_context.py+++ b/jarvis/plugins/brain/cli_prompt_context.py@@ -58,6 +58,34 @@ def extract_reply_language_directive(system_prompt: str | None) -> str:return system_prompt[idx:].strip()+def render_structured_prompt(req: object) -> str:+ """Render a background/structured request verbatim for a CLI agent.++ Voice turns are flattened into a light conversational prompt on purpose,+ but background curation (the wiki extractor and Stage-2 judge) carries its+ own binding contract in ``req.system`` ("Return ONLY a JSON array ...").+ Replacing that contract with the conversational wrapper ("answer in one to+ three short sentences, plain text only") makes structured output+ impossible BY INSTRUCTION — the subscription CLI then looks permanently+ broken to the wiki provider chain (live 2026-07-18: every antigravity+ extraction died with "no JSON array found in response"). Structured mode+ forwards the system contract and the user payload verbatim instead.+ """+ parts: list[str] = []+ system = str(getattr(req, "system", "") or "").strip()+ if system:+ parts.append(system)+ for message in getattr(req, "messages", ()) or ():+ content = getattr(message, "content", None)+ if (+ getattr(message, "role", "") in ("system", "user")+ and isinstance(content, str)+ and content.strip()+ ):+ parts.append(content.strip())+ return "\n\n".join(parts)++def render_cli_standing_instructions(system_prompt: str | None) -> str:"""Render a compact system-like block for flattened CLI prompts."""block = extract_standing_instructions_block(system_prompt)diff --git a/jarvis/plugins/brain/codex.py b/jarvis/plugins/brain/codex.pyindex e7b11d4ed4..ddc0446344 100644--- a/jarvis/plugins/brain/codex.py+++ b/jarvis/plugins/brain/codex.py@@ -39,6 +39,7 @@ from ._openai_base import stream_completefrom .cli_prompt_context import (extract_reply_language_directive,render_cli_standing_instructions,+ render_structured_prompt,)log = logging.getLogger(__name__)@@ -139,9 +140,16 @@ class CodexBrain:# True only when an API key (→ the vision-capable API path) is configured.supports_vision: bool = False- def __init__(self, model: str | None = None) -> None:+ def __init__(+ self, model: str | None = None, structured_prompts: bool = False,+ ) -> None:self._model = model or DEFAULT_MODELself._client: Any = None+ # Background/structured callers (the wiki curator tier) set this so the+ # CLI path forwards their JSON contract verbatim instead of the+ # conversational "answer in 1-3 plain-text sentences" wrapper — which+ # made structured output impossible by instruction.+ self._structured_prompts = bool(structured_prompts)# Only the API-key path can see images (see the supports_vision note).self.supports_vision = bool(self._api_key())@@ -172,6 +180,12 @@ class CodexBrain:# ---- CLI (ChatGPT-OAuth) path ------------------------------------+ def _render_prompt(self, req: BrainRequest) -> str:+ """Conversational flattening for voice turns; verbatim for structured."""+ if self._structured_prompts:+ return render_structured_prompt(req)+ return _build_cli_prompt(req)+async def _complete_via_cli(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:"""Drive ``codex exec`` over the ChatGPT login and stream its answer.@@ -190,7 +204,7 @@ class CodexBrain:"Codex CLI not found — run 'npm i -g @openai/codex' and 'codex login'.")- prompt = _build_cli_prompt(req)+ prompt = self._render_prompt(req)workdir = tempfile.mkdtemp(prefix="jarvis-codex-brain-")# OAuth env: drop OPENAI_API_KEY (so the subscription token wins) and# CODEX_HOME (a custom home breaks the global ~/.codex auth lookup).@@ -351,7 +365,34 @@ class CodexBrain:if api_key:log.info("CodexBrain.complete: API-key path (model=%s)", self._model)client = self._ensure_client(api_key)- async for delta in stream_complete(client, self._model, req):+ emitted = False+ try:+ async for delta in stream_complete(client, self._model, req):+ if delta.content or getattr(delta, "tool_calls", None):+ emitted = True+ yield delta+ return+ except Exception as exc: # noqa: BLE001 — classified below, re-raised when not recoverable+ status = getattr(exc, "status_code", None)+ if status is None:+ status = getattr(+ getattr(exc, "response", None), "status_code", None+ )+ # A throttled/dead API KEY must not brick the provider while+ # the user's paid ChatGPT subscription sits idle next to it+ # (live 2026-07-18: every wiki call died on a 429ing key).+ # Only account-level failures cross over, and only when the+ # stream produced nothing a listener could have consumed.+ if emitted or status not in (401, 402, 403, 429):+ raise+ if not _codex_oauth_connected():+ raise+ log.warning(+ "CodexBrain: API-key path failed (HTTP %s) — falling back "+ "to the ChatGPT-subscription CLI",+ status,+ )+ async for delta in self._complete_via_cli(req):yield deltareturnoauth = _codex_oauth_connected()diff --git a/tests/unit/memory/wiki/test_curator_brain_instantiation.py b/tests/unit/memory/wiki/test_curator_brain_instantiation.pyindex 327b9c279f..1f78b63a69 100644--- a/tests/unit/memory/wiki/test_curator_brain_instantiation.py+++ b/tests/unit/memory/wiki/test_curator_brain_instantiation.py@@ -64,3 +64,31 @@ def test_none_model_is_passed_through() -> None:instantiate_curator_brain(registry, "grok", None)_name, kwargs = registry.calls[0]assert kwargs.get("model") is None+++def test_structured_prompts_probe_reaches_supporting_providers() -> None:+ """Subscription-CLI brains (codex/antigravity) must receive the curator's+ structured-prompt flag so the JSON contract survives the CLI flattening."""+ registry = FakeRegistry()+ instantiate_curator_brain(registry, "codex", None)+ _name, kwargs = registry.calls[0]+ assert kwargs.get("structured_prompts") is True+++class _NoStructuredRegistry(FakeRegistry):+ def instantiate(self, name: str, **kwargs: Any) -> Any:+ if "structured_prompts" in kwargs:+ self.calls.append((name, dict(kwargs)))+ raise TypeError("unexpected keyword argument 'structured_prompts'")+ return super().instantiate(name, **kwargs)+++def test_structured_prompts_probe_degrades_without_losing_the_model() -> None:+ """A provider without the flag keeps model + thinking kwargs on the retry —+ the probe must never demote it to a bare default instantiation."""+ registry = _NoStructuredRegistry()+ instantiate_curator_brain(registry, "gemini", "gemini-3-flash-preview")+ _name, kwargs = registry.calls[-1]+ assert "structured_prompts" not in kwargs+ assert kwargs["model"] == "gemini-3-flash-preview"+ assert kwargs["thinking_budget"] == 0diff --git a/tests/unit/plugins/brain/test_antigravity_brain.py b/tests/unit/plugins/brain/test_antigravity_brain.pyindex 148830bec7..5d63ad5672 100644--- a/tests/unit/plugins/brain/test_antigravity_brain.py+++ b/tests/unit/plugins/brain/test_antigravity_brain.py@@ -56,6 +56,32 @@ def _system_with_empty_standing_instructions() -> str:)+def _wiki_request() -> BrainRequest:+ return BrainRequest(+ messages=(BrainMessage(role="user", content="Source content here."),),+ system="Return ONLY a single JSON array. No prose before or after.",+ )+++def test_structured_mode_forwards_the_json_contract_verbatim():+ """Wiki-tier callers need their JSON contract to reach the CLI model —+ the conversational wrapper made structured output impossible by+ instruction (live 2026-07-18: every extraction died with 'no JSON array+ found in response')."""+ brain = AntigravityBrain(structured_prompts=True)+ prompt = brain._render_prompt(_wiki_request())+ assert "Return ONLY a single JSON array" in prompt+ assert "Source content here." in prompt+ assert "one to three short sentences" not in prompt+++def test_voice_mode_keeps_the_conversational_flattening():+ brain = AntigravityBrain()+ prompt = brain._render_prompt(_wiki_request())+ assert "one to three short sentences" in prompt+ assert "Return ONLY a single JSON array" not in prompt++def test_cli_prompt_includes_standing_instructions_without_heavy_router_prompt():req = BrainRequest(messages=(BrainMessage(role="user", content="Was ist das wertvollste Unternehmen?"),), # i18n-allow: simulated German user utterance, content under testdiff --git a/tests/unit/plugins/brain/test_cli_prompt_context.py b/tests/unit/plugins/brain/test_cli_prompt_context.pyindex fd4810edda..e2152ab96d 100644--- a/tests/unit/plugins/brain/test_cli_prompt_context.py+++ b/tests/unit/plugins/brain/test_cli_prompt_context.py@@ -42,6 +42,25 @@ def _empty_state_block() -> str:)+def test_render_structured_prompt_keeps_system_and_user_verbatim() -> None:+ from types import SimpleNamespace++ from jarvis.plugins.brain.cli_prompt_context import render_structured_prompt++ req = SimpleNamespace(+ system="Return ONLY a single JSON array.",+ messages=(+ SimpleNamespace(role="user", content="Source content."),+ SimpleNamespace(role="assistant", content="never included"),+ SimpleNamespace(role="user", content=None),+ ),+ )+ prompt = render_structured_prompt(req)+ assert prompt.startswith("Return ONLY a single JSON array.")+ assert "Source content." in prompt+ assert "never included" not in prompt # assistant turns are not payload++def test_extracts_trailing_mandatory_directive() -> None:assert extract_reply_language_directive(_system_with_directive()) == _MANDATORYdiff --git a/tests/unit/plugins/brain/test_codex_brain.py b/tests/unit/plugins/brain/test_codex_brain.pynew file mode 100644index 0000000000..12e1787fc0--- /dev/null+++ b/tests/unit/plugins/brain/test_codex_brain.py@@ -0,0 +1,123 @@+"""CodexBrain: structured-prompt mode + API-key -> ChatGPT-CLI crossover.++Live 2026-07-18: the maintainer pays for the ChatGPT subscription, yet every+wiki extraction died on the SEPARATE, throttled OpenAI API key (RateLimitError+HTTP 429) — the subscription CLI was never tried because the API key existed.+And even when the CLI ran, the conversational prompt wrapper ("answer in one+to three short sentences, plain text only") made the wiki's JSON contract+unfulfillable by instruction. These tests pin both fixes.+"""+from __future__ import annotations++from collections.abc import AsyncIterator+from typing import Any++import pytest++from jarvis.core.protocols import BrainDelta, BrainMessage, BrainRequest+from jarvis.plugins.brain import codex as codex_module+from jarvis.plugins.brain.codex import CodexBrain+++def _wiki_request() -> BrainRequest:+ return BrainRequest(+ messages=(BrainMessage(role="user", content="Source content here."),),+ system="Return ONLY a single JSON array. No prose before or after.",+ max_tokens=900,+ temperature=0.2,+ stream=True,+ )+++def test_structured_mode_forwards_the_json_contract_verbatim() -> None:+ brain = CodexBrain(structured_prompts=True)+ prompt = brain._render_prompt(_wiki_request())+ assert "Return ONLY a single JSON array" in prompt+ assert "Source content here." in prompt+ assert "one to three short sentences" not in prompt+++def test_voice_mode_keeps_the_conversational_flattening() -> None:+ brain = CodexBrain()+ prompt = brain._render_prompt(_wiki_request())+ assert "one to three short sentences" in prompt+ # The heavy system contract stays out of conversational CLI turns.+ assert "Return ONLY a single JSON array" not in prompt+++class _StatusError(RuntimeError):+ def __init__(self, status: int) -> None:+ super().__init__(f"HTTP {status}")+ self.status_code = status+++async def _collect(stream: AsyncIterator[BrainDelta]) -> str:+ chunks: list[str] = []+ async for delta in stream:+ if delta.content:+ chunks.append(delta.content)+ return "".join(chunks)+++def _arm_api_and_oauth(+ monkeypatch: pytest.MonkeyPatch, brain: CodexBrain, *, status: int,+) -> list[str]:+ """API path raises ``status``; OAuth is connected; CLI yields 'cli-answer'."""+ monkeypatch.setattr(CodexBrain, "_api_key", lambda self: "sk-test")+ monkeypatch.setattr(CodexBrain, "_ensure_client", lambda self, key: object())+ monkeypatch.setattr(codex_module, "_codex_oauth_connected", lambda: True)++ async def _failing_stream(client: Any, model: str, req: BrainRequest):+ raise _StatusError(status)+ yield # pragma: no cover — makes this an async generator++ monkeypatch.setattr(codex_module, "stream_complete", _failing_stream)++ calls: list[str] = []++ async def _fake_cli(self: CodexBrain, req: BrainRequest):+ calls.append("cli")+ yield BrainDelta(content="cli-answer")+ yield BrainDelta(finish_reason="stop")++ monkeypatch.setattr(CodexBrain, "_complete_via_cli", _fake_cli)+ return calls++[email protected]("status", [401, 402, 403, 429])+async def test_throttled_api_key_crosses_over_to_the_subscription_cli(+ monkeypatch: pytest.MonkeyPatch, status: int,+) -> None:+ brain = CodexBrain()+ calls = _arm_api_and_oauth(monkeypatch, brain, status=status)++ answer = await _collect(brain.complete(_wiki_request()))++ assert answer == "cli-answer"+ assert calls == ["cli"]+++async def test_non_account_errors_still_raise(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ brain = CodexBrain()+ calls = _arm_api_and_oauth(monkeypatch, brain, status=500)++ with pytest.raises(_StatusError):+ await _collect(brain.complete(_wiki_request()))+ assert calls == [] # a server error is not an account problem — no crossover+++async def test_no_oauth_means_the_account_error_is_surfaced(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ brain = CodexBrain()+ calls = _arm_api_and_oauth(monkeypatch, brain, status=429)+ monkeypatch.setattr(codex_module, "_codex_oauth_connected", lambda: False)++ with pytest.raises(_StatusError):+ await _collect(brain.complete(_wiki_request()))+ assert calls == []