Skip to content

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.

feat(brain): tool-call recovery, scoped provider credentials, worker/critic updates

Ruben Lütke1e59b82f4e5c
diff --git a/jarvis/brain/ack_brain/spawn_announcement.py b/jarvis/brain/ack_brain/spawn_announcement.py
index 2114cfe6f4..49f03a2f13 100644
--- a/jarvis/brain/ack_brain/spawn_announcement.py
+++ b/jarvis/brain/ack_brain/spawn_announcement.py
@@ -23,11 +23,12 @@ as robotic and repetitive. Strategy, in preference order:
string, so the spawn confirmation always reaches TTS.
Validation chain for any candidate (brain or LLM): keep the longest
-leading sentence run within :data:`_MAX_WORDS`; the language must match
-the user's turn; ``scrub_for_voice`` in ack mode; no completion claims
-("ist erledigt" / "is done" — the worker has not even started, AD-OE1
-promises only the handover); no internal component names (the voice
-scrubber would shred them into gap-toothed sentences anyway).
+leading sentence run within :data:`_MAX_WORDS`; require the public
+``Jarvis-Agent`` label; the language must match the user's turn;
+``scrub_for_voice`` in ack mode; no completion claims ("ist erledigt" /
+"is done" — the worker has not even started, AD-OE1 promises only the
+handover); no internal component names (the voice scrubber would shred
+them into gap-toothed sentences anyway).
AD-OE2 note: the LLM call here is the same bounded flash-call category
as the established pre-thinking ack-brain — timeout-capped, breaker
@@ -90,16 +91,19 @@ _DEFAULT_TIMEOUT_MS = 1500
SPAWN_PERSONA_DE = """Du bist der persönliche Assistent des Nutzers. Die Anfrage des
-Nutzers wurde SOEBEN an einen Hintergrund-Helfer übergeben, das ist
+Nutzers wurde SOEBEN an einen Jarvis-Agent übergeben, das ist
bereits geschehen, du sagst es nur noch natürlich an.
DEINE AUFGABE, genau EINE kurze gesprochene Ansage (1-2 Sätze,
zusammen maximal 20 Wörter), die:
1. das KONKRETE Thema der Anfrage nennt (App, Datenobjekt, Ort,
Person, z.B. "dein Gmail", "der Kalender", "die Flüge"),
-2. natürlich vermittelt, dass das eine GRÖSSERE Sache ist, jetzt im
- Hintergrund läuft und deshalb einen Moment dauert,
-3. frisch für genau diese Anfrage formuliert ist.
+2. das exakte Produktwort "Jarvis-Agent" genau einmal enthält und
+ natürlich klarmacht, dass dieser Agent jetzt für die Aufgabe gestartet
+ oder hinzugezogen wurde,
+3. vermittelt, dass das eine GRÖSSERE Sache ist, jetzt im Hintergrund
+ läuft und deshalb einen Moment dauert,
+4. frisch für genau diese Anfrage formuliert ist.
TON: warm und zugewandt, wie ein hilfsbereiter Mensch im Gespräch,
nicht wie eine Statusmeldung. Du darfst die Mühe ruhig andeuten ("da
@@ -117,13 +121,14 @@ VERBOTEN:
- Vollzugsmeldungen ("ist erledigt", "fertig", "habe ich gemacht"),
die Arbeit beginnt gerade erst.
- Interne Bauteil-Namen: "OpenClaw", "Sub-Agent", "Subagent",
- "Mission", "Provider", "Subprocess", "Harness", "API".
+ "Mission", "Provider", "Subprocess", "Harness", "API". Der öffentliche
+ Produktname "Jarvis-Agent" ist dagegen PFLICHT.
- Anreden wie "Sir", "Jawohl", "Sehr wohl", "Boss".
- Rückfragen, Markdown, Anführungszeichen, mehr als zwei Sätze.
-ERLAUBT und erwünscht: natürliche Umschreibungen der Übergabe, z.B.
-"ich gebe das an meinen Helfer", "ich lasse das nebenher laufen",
-"ich hole mir kurz Unterstützung", "ein zweiter Kopf übernimmt das".
+Variiere frei, WO und WIE du "Jarvis-Agent" einbaust: starten,
+hinzuziehen, übernehmen lassen, mit der Recherche losschicken oder an die
+Aufgabe setzen. Verwende keine dieser Varianten als wiederkehrende Schablone.
Falls der Input eine Zeile "[Task: ...]" enthält, ist das die bereits
interpretierte Aufgabe, nutze sie als Themenquelle.
@@ -132,16 +137,18 @@ Output: NUR die Ansage, nichts anderes."""
SPAWN_PERSONA_EN = """You are the user's personal assistant. The user's request has
-JUST been handed to a background helper, that already happened; you
+JUST been handed to a Jarvis-Agent, that already happened; you
only announce it naturally.
YOUR JOB, exactly ONE short spoken announcement (1-2 sentences,
20 words max in total) that:
1. names the CONCRETE topic of the request (app, data object, place,
person, e.g. "your Gmail", "the calendar", "the flights"),
-2. naturally conveys that this is a BIGGER task, now runs in the
- background and therefore takes a moment,
-3. is phrased freshly for this exact request.
+2. contains the exact public product term "Jarvis-Agent" exactly once and
+ naturally makes clear that this agent was just started or brought in,
+3. conveys that this is a BIGGER task, now runs in the background and
+ therefore takes a moment,
+4. is phrased freshly for this exact request.
TONE: warm and human, like a helpful person in conversation, not a
status line. You may hint at the effort ("I'll take a proper look at
@@ -158,14 +165,15 @@ FORBIDDEN:
- Completion claims ("is done", "finished", "all set"), the work is
only starting now.
- Internal component names: "OpenClaw", "sub-agent", "subagent",
- "mission", "provider", "subprocess", "harness", "API".
+ "mission", "provider", "subprocess", "harness", "API". The public
+ product term "Jarvis-Agent" is REQUIRED.
- Honorifics like "Sir", "Boss", "Very well".
- Counter-questions, markdown, quotation marks, more than two
sentences.
-ALLOWED and encouraged: natural paraphrases of the handover, e.g.
-"I'm handing this to my helper", "I'll run this on the side",
-"I'm pulling in a second pair of hands".
+Freely vary WHERE and HOW you use "Jarvis-Agent": start one, bring one in,
+have one take over, send one researching, or put one on the task. Never use
+any of those variants as a recurring template.
If the input contains a "[Task: ...]" line, that is the already
interpreted task, use it as the topic source.
@@ -197,55 +205,58 @@ def get_spawn_persona(language: str) -> str:
_FALLBACK_SPAWN: dict[str, tuple[str, ...]] = {
"de": (
- "Mach ich. Grössere Sache, die nehme ich mir im Hintergrund vor und melde mich.",
- "Alles klar, das schaue ich mir in Ruhe an. Läuft jetzt nebenher, dauert einen Moment.",
- "Okay, da gehe ich gründlich ran. Ich lasse es im Hintergrund laufen und sage Bescheid.",
- "Übernehme ich. Das braucht etwas, ich kümmere mich nebenher und melde mich gleich.",
- "Geht klar. Das ist ein grösseres Stück Arbeit, ich nehme es mir im Hintergrund vor.",
- "Schon dabei. Das dauert einen Moment, ich will dir was Vernünftiges liefern.",
- "Hab ich. Das ist etwas umfangreicher, ich melde mich, sobald ich was Belastbares habe.",
- "Bin dran. Gib mir einen Moment, da steckt etwas mehr dahinter.",
+ "Mach ich. Dafür habe ich einen Jarvis-Agent gestartet; die grössere "
+ "Sache läuft jetzt im Hintergrund.",
+ "Alles klar, ein Jarvis-Agent schaut sich das in Ruhe an. Das dauert einen Moment.",
+ "Okay, da geht jetzt ein Jarvis-Agent gründlich ran und sagt dir danach Bescheid.",
+ "Ein Jarvis-Agent übernimmt das. Es braucht etwas, bis ein belastbares Ergebnis da ist.",
+ "Geht klar. Das grössere Stück Arbeit liegt jetzt bei einem Jarvis-Agent.",
+ "Schon angestossen: Ein Jarvis-Agent kümmert sich darum und braucht dafür einen Moment.",
+ "Hab ich. Ein Jarvis-Agent bearbeitet das umfangreichere Thema und "
+ "meldet sich mit Substanz.",
+ "Ein Jarvis-Agent ist jetzt dran. Gib ihm einen Moment, da steckt etwas mehr dahinter.",
),
"en": (
- "On it. This is a bigger one, so I'll work it in the background and report back.",
- "Got it. I'll take a proper look at this; it runs on the side and may take a moment.",
- "Okay, this needs some real digging. I'll handle it in the background and let you know.",
- "I'm taking this on. It's a meatier task, so give me a moment and I'll come back to you.",
- "Consider it picked up. A bit more involved, this one. I'll work it on the side for you.",
- "Sure. This one takes a little time. I'd rather get it right, so I'm digging in now.",
- "I'm on it. Slightly bigger job; I'll report back as soon as I have something solid.",
- "Working on it now. There's a bit more to this, so it'll take a short moment.",
+ "On it. I've started a Jarvis-Agent for this bigger task; it'll report back when ready.",
+ "Got it. A Jarvis-Agent is taking a proper look, which may take a moment.",
+ "Okay, this needs real digging. A Jarvis-Agent is handling it in the background now.",
+ "A Jarvis-Agent is taking this on. It's a meatier task, so give it a moment.",
+ "Consider it picked up. A Jarvis-Agent now has this more involved piece of work.",
+ "Sure. A Jarvis-Agent is digging in now; getting it right will take a little time.",
+ "I've put a Jarvis-Agent on the bigger job. It'll return with something solid.",
+ "A Jarvis-Agent is working on it now. There's more to this, so it'll take a short moment.",
),
"es": (
- "Voy con ello. Es algo más grande, así que lo trabajo en segundo plano y te aviso.",
- "Entendido. Le echo un buen vistazo; corre en segundo plano y puede tardar un momento.",
- "Vale, esto necesita mirarse a fondo. Lo dejo en segundo plano y te digo algo.",
- "Me encargo. Es una tarea con algo más de chicha, dame un momento y vuelvo contigo.",
- "Lo cojo. Esto lleva algo más de trabajo, lo voy haciendo en segundo plano.",
- "Claro. Esto necesita un poco de tiempo; prefiero hacerlo bien y me meto a fondo.",
- "Estoy en ello. Es un poco más grande; te aviso en cuanto tenga algo sólido.",
- "Trabajando en ello. Hay algo más detrás, así que tardará un momentito.",
+ "Voy con ello. He iniciado un Jarvis-Agent para esta tarea más grande; "
+ "te avisará al terminar.",
+ "Entendido. Un Jarvis-Agent le está echando un buen vistazo; puede tardar un momento.",
+ "Vale, esto necesita mirarse a fondo. Un Jarvis-Agent ya trabaja en segundo plano.",
+ "Un Jarvis-Agent se encarga. Es una tarea con más chicha, así que necesita un momento.",
+ "Lo tengo. Un Jarvis-Agent ha asumido este trabajo algo más amplio.",
+ "Claro. Un Jarvis-Agent ya está profundizando; hacerlo bien necesita un poco de tiempo.",
+ "He puesto un Jarvis-Agent con este tema más grande; volverá con algo sólido.",
+ "Un Jarvis-Agent ya trabaja en ello. Hay más detrás, así que tardará un momentito.",
),
}
_FALLBACK_ALREADY_RUNNING: dict[str, tuple[str, ...]] = {
"de": (
- "Bin schon dran, das läuft noch.",
- "Läuft bereits. Einen Moment noch, bitte.",
- "Schon in Arbeit, gleich gibt es etwas.",
- "Geduld, der Auftrag läuft schon.",
+ "Ein Jarvis-Agent ist schon dran, das läuft noch.",
+ "Der Jarvis-Agent arbeitet bereits. Einen Moment noch, bitte.",
+ "Schon beim Jarvis-Agent in Arbeit, gleich gibt es etwas.",
+ "Geduld, der Jarvis-Agent bearbeitet den Auftrag bereits.",
),
"en": (
- "Already on it, that one is still running.",
- "That job is already going, one moment.",
- "Still working on that one, almost there.",
- "Patience, that one is already in progress.",
+ "A Jarvis-Agent is already on it; that work is still running.",
+ "The Jarvis-Agent already has that job, one moment.",
+ "A Jarvis-Agent is still working on that one, almost there.",
+ "Patience, that task is already with a Jarvis-Agent.",
),
"es": (
- "Ya estoy con eso, sigue en marcha.",
- "Eso ya está en marcha, un momento.",
- "Sigo con ello, casi lo tengo.",
- "Paciencia, eso ya está en proceso.",
+ "Un Jarvis-Agent ya está con eso; sigue en marcha.",
+ "El Jarvis-Agent ya tiene esa tarea, un momento.",
+ "Un Jarvis-Agent sigue trabajando en ello, casi está.",
+ "Paciencia, esa tarea ya está con un Jarvis-Agent.",
),
}
@@ -311,6 +322,12 @@ _FORBIDDEN_VOCAB_RE = re.compile(
re.IGNORECASE,
)
+# Every fresh spawn announcement must name the public product surface so the
+# user can distinguish a delegated background task from ordinary thinking.
+# The old generic "sub-agent" spellings stay forbidden by
+# ``_FORBIDDEN_VOCAB_RE``; the repository's canonical singular name is exact.
+_JARVIS_AGENT_RE = re.compile(r"\bJarvis-Agent\b", re.IGNORECASE)
+
_SENTENCE_SPLIT_RE = re.compile(r"(?<=[.!?])\s+")
@@ -463,6 +480,8 @@ class SpawnAnnouncementComposer:
trimmed = _trim_to_sentences(text, _MAX_WORDS)
if trimmed is None:
return None
+ if len(_JARVIS_AGENT_RE.findall(trimmed)) != 1:
+ return None
if _COMPLETION_CLAIM_RE.search(trimmed):
return None
detected = _detect_language(trimmed)
diff --git a/jarvis/brain/app_control.py b/jarvis/brain/app_control.py
index 512dc52981..b9df71a0ac 100644
--- a/jarvis/brain/app_control.py
+++ b/jarvis/brain/app_control.py
@@ -88,11 +88,11 @@ AUTH_PROVIDER_ALIASES: dict[str, str] = {
"groq-api": "groq",
"gemini": "gemini",
"gemini-flash-tts": "gemini",
- "gemini-live": "gemini",
+ "gemini-live": "gemini-live",
"grok": "grok",
"grok-voice": "grok",
- "grok-realtime": "grok",
- "openai-realtime": "openai",
+ "grok-realtime": "grok-realtime",
+ "openai-realtime": "openai-realtime",
}
# Local providers that need no credential at all. Empty since v1.0.1: the only
@@ -596,13 +596,25 @@ async def _switch_subagent(
try:
from jarvis.codex_auth import CodexAuthService
- codex_connected = CodexAuthService().status().connected
+ codex_status = CodexAuthService().status()
+ codex_connected = codex_status.connected
except Exception: # noqa: BLE001 — codex CLI absent is just "not connected"
+ codex_status = None
codex_connected = False
has_key = bool(
- cfg_mod.get_secret("codex_openai_api_key")
- or cfg_mod.get_provider_secret("codex")
+ cfg_mod.get_secret(
+ "codex_openai_api_key", env_fallback="CODEX_OPENAI_API_KEY"
+ )
)
+ if codex_status is None or not codex_status.installed:
+ return {
+ "ok": False,
+ "error_kind": "subagent_unavailable",
+ "error": (
+ "Codex CLI is not installed. Install it or select the OpenAI "
+ "Jarvis-Agent provider for key-only execution."
+ ),
+ }
if not (codex_connected or has_key):
return {
"ok": False,
@@ -634,17 +646,22 @@ async def _switch_subagent(
try:
from jarvis.google_cli.auth_service import GoogleCliAuthService
- antigravity_connected = GoogleCliAuthService().status().connected
+ antigravity_status = GoogleCliAuthService().status()
+ antigravity_connected = (
+ antigravity_status.connected
+ and antigravity_status.mode == "oauth-personal"
+ )
except Exception: # noqa: BLE001 — Google CLI absent is just "not connected"
antigravity_connected = False
- if not antigravity_connected:
+ has_key = bool(cfg_mod.get_jarvis_agent_secret("gemini"))
+ if not (antigravity_connected or has_key):
return {
"ok": False,
"error_kind": "missing_credential",
"error": (
"Antigravity is not connected — sign in with Google "
- "(install agy or the Gemini CLI and log in), then switch "
- "the subagent."
+ "(install agy or the Gemini CLI and log in) or save a "
+ "Jarvis-Agent Gemini key, then switch the Agent."
),
}
persisted = (
@@ -683,13 +700,21 @@ async def _switch_subagent(
"error_kind": "unknown_provider",
"error": f"{provider!r} is not a subagent-capable provider. Available: {known}.",
}
- if not cfg_mod.get_provider_secret(canon):
+ has_credential = bool(cfg_mod.get_jarvis_agent_secret(canon))
+ if canon == "claude-api" and not has_credential:
+ try:
+ from jarvis.missions.isolation.env import read_live_claude_oauth_token
+
+ has_credential = bool(read_live_claude_oauth_token())
+ except Exception: # noqa: BLE001
+ has_credential = False
+ if not has_credential:
return {
"ok": False,
"error_kind": "missing_credential",
"error": (
- f"{canon} has no stored key. Set the key on the brain provider "
- "first, then switch the subagent."
+ f"{canon} has no Jarvis-Agent credential. Save a key on its "
+ "Jarvis-Agent card first, then switch the Agent."
),
}
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index 6e9f363f75..ab77f7ed0c 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -28,7 +28,7 @@ import json
import logging
import re
import time
-from collections.abc import AsyncIterator, Awaitable, Callable, Iterable
+from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Mapping
from contextvars import ContextVar
from typing import TYPE_CHECKING, Any, Literal
from uuid import UUID, uuid4
@@ -52,6 +52,7 @@ from jarvis.core.protocols import (
ImageBlock,
Tool,
)
+from jarvis.core.redact import safe_preview
from jarvis.core.turn_language import (
DEFAULT_LOCALE,
detect_text_language,
@@ -100,7 +101,8 @@ from .persona_loader import load_effective_persona_prompt
from .provider_registry import BrainProviderRegistry
from .rate_limit_tracker import RateLimitTracker
from .streaming import aggregate
-from .turn_planner import plan_turn
+from .tool_call_recovery import extract_leaked_tool_calls
+from .turn_planner import is_contextual_follow_up, plan_turn
from .voice_command_gate import match_voice_command
if TYPE_CHECKING:
@@ -120,6 +122,25 @@ _TURN_HISTORY_OVERRIDE: ContextVar[tuple[BrainMessage, ...] | None] = ContextVar
default=None,
)
+
+class _SkillTurnState:
+ """Task-local mutable state for one manager skill-routing turn."""
+
+ __slots__ = ("content", "injected_inline", "match", "owner", "source")
+
+ def __init__(self, owner: Any) -> None:
+ self.owner = owner
+ self.match: Any | None = None
+ self.content = ""
+ self.source = "match"
+ self.injected_inline = False
+
+
+_SKILL_TURN_STATE: ContextVar[_SkillTurnState | None] = ContextVar(
+ "jarvis.brain.manager.skill_turn_state",
+ default=None,
+)
+
#: Bounds for the conversation-context block appended to a Computer-Use goal.
#: The deterministic gate ships the RAW current utterance as the mission goal;
#: a correction / follow-up turn ("that is the wrong server", "do it with
@@ -1066,43 +1087,6 @@ def _is_conversational_coaching(user_text: str) -> bool:
return bool(_CONVERSATIONAL_COACHING_RE.search(user_text or ""))
-def _balanced_json_objects(text: str) -> list[str]:
- """Return every top-level balanced ``{...}`` substring of ``text``.
-
- String/escape-aware brace walk so a tool_use object can be recovered even
- when a provider wraps it in prose or markdown. Used by
- :func:`_extract_leaked_spawn_call` to find a tool_use block that a provider
- emitted as TEXT instead of executing.
- """
- objects: list[str] = []
- depth = 0
- start = -1
- in_str = False
- escape = False
- for i, ch in enumerate(text):
- if in_str:
- if escape:
- escape = False
- elif ch == "\\":
- escape = True
- elif ch == '"':
- in_str = False
- continue
- if ch == '"':
- in_str = True
- elif ch == "{":
- if depth == 0:
- start = i
- depth += 1
- elif ch == "}":
- if depth > 0:
- depth -= 1
- if depth == 0 and start >= 0:
- objects.append(text[start:i + 1])
- start = -1
- return objects
-
-
def _extract_leaked_spawn_call(text: str) -> dict[str, Any] | None:
"""Return the ``input`` dict of a leaked ``spawn_worker`` tool_use, else None.
@@ -1110,41 +1094,13 @@ def _extract_leaked_spawn_call(text: str) -> dict[str, Any] | None:
the response *text* instead of invoking the tool — the brain reply becomes
raw ``[{"type":"tool_use","name":"spawn_worker","input":{...}}]`` JSON,
which would otherwise be spoken (scrubbed to "Es trat ein Fehler auf") and
- the delegated sub-agent would never run. This detects that leak (bare
- object or list, with or without prose/markdown fences) and returns the
- tool ``input`` (possibly empty) so the caller can execute it deterministically.
+ the delegated Jarvis-Agent would never run. This accepts only a whole JSON
+ response (bare or strictly fenced); JSON quoted inside prose is never an
+ executable instruction.
"""
- if not text or "spawn_worker" not in text or "tool_use" not in text:
- return None
-
- candidates: list[Any] = []
- stripped = text.strip()
- # Drop a leading ```json / ``` fence if the whole reply is fenced.
- if stripped.startswith("```"):
- stripped = stripped.lstrip("`")
- if stripped[:4].lower() == "json":
- stripped = stripped[4:]
- stripped = stripped.strip().rstrip("`").strip()
- try:
- candidates.append(json.loads(stripped))
- except (json.JSONDecodeError, ValueError):
- # Embedded in prose — recover balanced {...} objects individually.
- for obj_str in _balanced_json_objects(text):
- try:
- candidates.append(json.loads(obj_str))
- except (json.JSONDecodeError, ValueError):
- continue
-
- for cand in candidates:
- blocks = cand if isinstance(cand, list) else [cand]
- for block in blocks:
- if (
- isinstance(block, dict)
- and block.get("type") == "tool_use"
- and block.get("name") == "spawn_worker"
- ):
- inp = block.get("input")
- return inp if isinstance(inp, dict) else {}
+ for call in extract_leaked_tool_calls(text):
+ if call.get("name") == "spawn_worker":
+ return dict(call.get("input") or {})
return None
@@ -1415,6 +1371,12 @@ def _unfulfilled_replacement(
return _evidence_unfulfilled_answer(lang=lang, domain=domain)
+def _safe_recovered_text(value: Any) -> str:
+ """Redact, cap, and reject tool-envelope text before it reaches speech."""
+ text = safe_preview(value, max_chars=600)[:600].strip()
+ return "" if _looks_like_tool_use_leak(text) else text
+
+
def _render_recovered_tool_output(output: Any) -> str:
"""Speakable plain-text rendering of a recovered tool's output.
@@ -1438,8 +1400,7 @@ def _render_recovered_tool_output(output: Any) -> str:
if output is None:
return ""
if isinstance(output, str):
- s = output.strip()
- return "" if _looks_like_tool_use_leak(s) else s
+ return _safe_recovered_text(output)
if isinstance(output, dict):
results = output.get("results")
if isinstance(results, list):
@@ -1447,34 +1408,75 @@ def _render_recovered_tool_output(output: Any) -> str:
for item in results:
if not isinstance(item, dict):
continue
- title = str(item.get("title") or "").strip()
- snippet = str(item.get("snippet") or "").strip()
+ title = _safe_recovered_text(item.get("title") or "")
+ snippet = _safe_recovered_text(item.get("snippet") or "")
if snippet and title and title.lower() not in snippet.lower():
parts.append(f"{title}: {snippet}")
else:
parts.append(snippet or title)
joined = " ".join(p for p in parts if p).strip()
- return joined[:600]
+ return _safe_recovered_text(joined)
# CLI tools (cli_<name>) return {exit_code, stdout, stderr, duration_ms}.
# This renderer is reached only after the caller verified success, so a
# non-empty stdout IS the answer — surface it instead of dead-ending in
# "" (which made the caller speak "Dazu habe ich nichts gefunden" even
# though gcloud returned real project data; live repro 2026-06-17).
if "exit_code" in output and ("stdout" in output or "stderr" in output):
- stdout = str(output.get("stdout") or "").strip()
- return stdout[:600] if stdout else ""
- # Other structured tools: surface the first human-readable text field,
- # never the dict repr.
- for key in ("text", "answer", "summary", "message", "content", "result"):
+ return _safe_recovered_text(output.get("stdout") or "")
+ # Connected tools use many result schemas. Preserve a bounded set of
+ # human-facing scalar fields while omitting technical identifiers,
+ # raw bodies, URLs, tokens, and headers. The normal ToolUseLoop gives
+ # structured results back to the model for synthesis; this branch is a
+ # defense-in-depth fallback when a provider leaked the call as text.
+ parts: list[str] = []
+ for key in (
+ "sender", "from", "subject", "title", "date", "time", "status",
+ "summary", "description",
+ ):
val = output.get(key)
if isinstance(val, str) and val.strip():
- return val.strip()[:600]
+ rendered = _safe_recovered_text(val)
+ if rendered:
+ parts.append(rendered)
+ elif isinstance(val, (list, tuple)):
+ rendered = _render_recovered_tool_output(val)
+ if rendered:
+ parts.append(rendered)
+ if parts:
+ return _safe_recovered_text(" — ".join(parts))
+ normalized_keys = {
+ re.sub(r"[^a-z0-9]", "", str(key).lower()) for key in output
+ }
+ has_private_or_technical_key = any(
+ key.endswith(("id", "token"))
+ or any(
+ marker in key
+ for marker in (
+ "body", "secret", "authorization", "header", "raw",
+ "html", "attachment", "payload", "apikey",
+ )
+ )
+ for key in normalized_keys
+ )
+ if not has_private_or_technical_key:
+ # Preserve the established fallback contract for compact explicit
+ # answer/status mappings. ``content`` remains excluded because
+ # connector schemas routinely use it for full private bodies.
+ for key in ("text", "answer", "message", "result"):
+ val = output.get(key)
+ if isinstance(val, str) and val.strip():
+ return _safe_recovered_text(val)
+ # Fail closed for unknown mappings. Connector schemas commonly store
+ # full private bodies under content/message/result and use camelCase
+ # identifiers/tokens, so a generic scalar fallback can disclose data.
return ""
if isinstance(output, (list, tuple)):
- joined = " ".join(str(x).strip() for x in output if str(x).strip()).strip()
- return "" if _looks_like_tool_use_leak(joined) else joined[:600]
- text = str(output).strip()
- return "" if _looks_like_tool_use_leak(text) else text
+ rendered_items = (
+ _render_recovered_tool_output(item).strip() for item in output
+ )
+ joined = " ".join(item for item in rendered_items if item).strip()
+ return _safe_recovered_text(joined)
+ return _safe_recovered_text(output)
def _extract_leaked_tool_call(text: str) -> tuple[str, dict[str, Any]] | None:
@@ -1488,31 +1490,10 @@ def _extract_leaked_tool_call(text: str) -> tuple[str, dict[str, Any]] | None:
the call so it can be executed deterministically (see
:meth:`BrainManager._recover_leaked_tool`).
"""
- if not text or "tool_use" not in text:
- return None
- candidates: list[Any] = []
- stripped = text.strip()
- if stripped.startswith("```"):
- stripped = stripped.lstrip("`")
- if stripped[:4].lower() == "json":
- stripped = stripped[4:]
- stripped = stripped.strip().rstrip("`").strip()
- try:
- candidates.append(json.loads(stripped))
- except (json.JSONDecodeError, ValueError):
- for obj_str in _balanced_json_objects(text):
- try:
- candidates.append(json.loads(obj_str))
- except (json.JSONDecodeError, ValueError):
- continue
- for cand in candidates:
- blocks = cand if isinstance(cand, list) else [cand]
- for block in blocks:
- if isinstance(block, dict) and block.get("type") == "tool_use":
- name = block.get("name")
- if isinstance(name, str) and name:
- inp = block.get("input")
- return name, (inp if isinstance(inp, dict) else {})
+ calls = extract_leaked_tool_calls(text)
+ if calls:
+ call = calls[0]
+ return str(call["name"]), dict(call.get("input") or {})
return None
@@ -4224,13 +4205,14 @@ class BrainManager:
# for the CURRENT turn, set early in generate() and overwritten on every
# turn. While set, force-spawn and the local-action fast path stand down
# and run-skill stays visible even on smalltalk turns.
- _skill_turn_match: Any | None = None
+ _skill_turn_match_fallback: Any | None = None
# Direct-trigger handoff (AD-S4): the speech pipeline / chat hook notes a
# trigger match here instead of macro-running it; generate() consumes it
# on the next call and injects the skill instructions into the turn.
_pending_forced_skill: tuple[str, str, str] | None = None
- _skill_turn_content: str = ""
- _skill_turn_source: str = "match"
+ _skill_turn_content_fallback: str = ""
+ _skill_turn_source_fallback: str = "match"
+ _skill_injected_inline_fallback: bool = False
# AD-S6: warn exactly once per manager lifetime when the AVAILABLE
# SKILLS section cannot be rendered (RC2 used to be silent).
_skills_omit_warned: bool = False
@@ -4252,6 +4234,82 @@ class BrainManager:
# at the start of every generate() turn; appended to the system prompt.
_self_control_directive: str = ""
+ def _local_skill_turn_state(self) -> _SkillTurnState | None:
+ state = _SKILL_TURN_STATE.get()
+ return state if state is not None and state.owner is self else None
+
+ @property
+ def _skill_turn_match(self) -> Any | None:
+ state = self._local_skill_turn_state()
+ if state is not None:
+ return state.match
+ return self.__dict__.get(
+ "_skill_turn_match_fallback",
+ type(self)._skill_turn_match_fallback,
+ )
+
+ @_skill_turn_match.setter
+ def _skill_turn_match(self, value: Any | None) -> None:
+ state = self._local_skill_turn_state()
+ if state is not None:
+ state.match = value
+ else:
+ self._skill_turn_match_fallback = value
+
+ @property
+ def _skill_turn_content(self) -> str:
+ state = self._local_skill_turn_state()
+ if state is not None:
+ return state.content
+ return self.__dict__.get(
+ "_skill_turn_content_fallback",
+ type(self)._skill_turn_content_fallback,
+ )
+
+ @_skill_turn_content.setter
+ def _skill_turn_content(self, value: str) -> None:
+ state = self._local_skill_turn_state()
+ if state is not None:
+ state.content = value
+ else:
+ self._skill_turn_content_fallback = value
+
+ @property
+ def _skill_turn_source(self) -> str:
+ state = self._local_skill_turn_state()
+ if state is not None:
+ return state.source
+ return self.__dict__.get(
+ "_skill_turn_source_fallback",
+ type(self)._skill_turn_source_fallback,
+ )
+
+ @_skill_turn_source.setter
+ def _skill_turn_source(self, value: str) -> None:
+ state = self._local_skill_turn_state()
+ if state is not None:
+ state.source = value
+ else:
+ self._skill_turn_source_fallback = value
+
+ @property
+ def _skill_injected_inline(self) -> bool:
+ state = self._local_skill_turn_state()
+ if state is not None:
+ return state.injected_inline
+ return self.__dict__.get(
+ "_skill_injected_inline_fallback",
+ type(self)._skill_injected_inline_fallback,
+ )
+
+ @_skill_injected_inline.setter
+ def _skill_injected_inline(self, value: bool) -> None:
+ state = self._local_skill_turn_state()
+ if state is not None:
+ state.injected_inline = bool(value)
+ else:
+ self._skill_injected_inline_fallback = bool(value)
+
def note_skill_trigger(
self, skill_name: str, *, content: str = "", source: str = "trigger"
) -> None:
@@ -4332,6 +4390,57 @@ class BrainManager:
except Exception: # noqa: BLE001
return None
+ def _previous_user_turn_text(self, *, use_history: bool) -> str:
+ """Return the latest bounded user message from this task's history."""
+ override = _TURN_HISTORY_OVERRIDE.get()
+ history = (
+ tuple(override)
+ if override is not None
+ else tuple(self._history if use_history else ())
+ )
+ for message in reversed(history):
+ if getattr(message, "role", None) != "user":
+ continue
+ content = getattr(message, "content", "")
+ if isinstance(content, str) and content.strip():
+ return content.strip()[-1_200:]
+ return ""
+
+ def _contextual_routing_state(
+ self, user_text: str, *, use_history: bool
+ ) -> tuple[str, tuple[str, ...]]:
+ """Return bounded context and live tools inherited by a follow-up.
+
+ The actual user message and tool arguments stay untouched. Only
+ deterministic skill/plugin/MCP selection sees the previous user turn,
+ and only when the shared planner identifies an explicit referential
+ follow-up. An unrelated request therefore cannot replay an old action.
+ """
+ previous = self._previous_user_turn_text(use_history=use_history)
+ if not previous:
+ return user_text, ()
+ if not is_contextual_follow_up(user_text, (previous,)):
+ return user_text, ()
+
+ try:
+ plan = plan_turn(
+ user_text,
+ tool_names=tuple((getattr(self, "_tools", None) or {}).keys()),
+ context=(previous,),
+ )
+ except Exception: # noqa: BLE001 - context must never break a turn
+ return user_text, ()
+ live_tools = tuple(
+ name
+ for name in plan.required_capabilities
+ if name in (getattr(self, "_tools", None) or {})
+ )
+ contextual = (
+ f"Previous user request: {previous}\n"
+ f"Current referential follow-up: {user_text}"
+ )
+ return contextual, live_tools
+
@staticmethod
def _skill_is_blocked(skill: Any) -> bool:
"""True for risk_policy block-tier skills — they must never capture a
@@ -4610,7 +4719,7 @@ class BrainManager:
if not _is_plain_knowledge_question(t):
return tools
# User explicitly named the vehicle → respect it, never hide (AD-S9).
- if self._get_force_spawn_pattern().search(t):
+ if self._is_explicit_heavy_request(t):
return tools
# A real desktop/action turn or an artifact-build request still needs
# the spawn tools — only a pure ANSWER question loses them.
@@ -4661,7 +4770,7 @@ class BrainManager:
if (
self._turn_has_action_intent(t)
or self._research_wants_artifact(t)
- or self._get_force_spawn_pattern().search(t)
+ or self._is_explicit_heavy_request(t)
):
return tools
# Hide computer_use/spawn AND the deterministic write/record tools so
@@ -4713,7 +4822,7 @@ class BrainManager:
return tools
# An explicit heavy-work vehicle or an artifact-build request still
# legitimately spawns — never hide the spawn vehicles there.
- if self._get_force_spawn_pattern().search(t) or self._research_wants_artifact(t):
+ if self._is_explicit_heavy_request(t) or self._research_wants_artifact(t):
return tools
from jarvis.marketplace.usage_cards.loader import load_usage_card
@@ -4875,7 +4984,7 @@ class BrainManager:
# combo like "Spawne einen Subagenten UND zeig mir die Socials" names the
# execution vehicle, so it must reach force-spawn rather than merely
# switch the sidebar section. Stand down and let the normal path spawn.
- if self._get_force_spawn_pattern().search(user_text):
+ if self._is_explicit_heavy_request(user_text):
log.info(
"navigation fast-path stands down — explicit heavy-work trigger "
"in the utterance wins (mission, not a sidebar switch)."
@@ -4903,6 +5012,18 @@ class BrainManager:
)
return f"Öffne {label}." if is_de else f"Opening {label}." # i18n-allow
+ def _is_explicit_heavy_request(self, user_text: str) -> bool:
+ """Return whether the user semantically requested a heavy worker."""
+ text = (user_text or "").strip()
+ if not text or _is_spawn_decline(text) or _is_spawn_feature_reference(text):
+ return False
+ trigger = self._get_force_spawn_pattern().search(text)
+ if trigger is None:
+ return False
+ if _trigger_names_vehicle(trigger.group(0)):
+ return True
+ return not _looks_like_pc_control(text)
+
def _should_force_spawn(
self, user_text: str, *, source_layer: str | None = None
) -> bool:
@@ -5037,11 +5158,9 @@ class BrainManager:
# decide. This reuses the existing pc-control detector — no new
# signal-word list, no widening of force_spawn_phrases.
_trigger = self._get_force_spawn_pattern().search(t)
+ if self._is_explicit_heavy_request(t):
+ return True
if _trigger is not None:
- if _trigger_names_vehicle(_trigger.group(0)):
- return True
- if not _looks_like_pc_control(t):
- return True # depth marker, no screen signal → heavy background work
log.info(
"force-spawn deferred to LLM: depth trigger %r + computer-use "
"request — router decides computer_use vs spawn",
@@ -6478,6 +6597,7 @@ class BrainManager:
*,
user_text: str,
trace_id: UUID,
+ allowed_tools: Mapping[str, Tool],
) -> str | None:
"""Execute a ``spawn_worker`` call a provider leaked as TEXT.
@@ -6496,7 +6616,7 @@ class BrainManager:
leaked = _extract_leaked_spawn_call(response_text)
if leaked is None:
return None
- tool = self._tools.get("spawn_worker")
+ tool = allowed_tools.get("spawn_worker")
if tool is None or self._tool_executor is None:
return None
@@ -6548,7 +6668,7 @@ class BrainManager:
reason_key="spawn_failed_reason",
lang=out_lang,
)
- return str(result.output or "")
+ return _safe_recovered_text(result.output or "")
async def _recover_leaked_tool(
self,
@@ -6556,6 +6676,7 @@ class BrainManager:
*,
user_text: str,
trace_id: UUID,
+ allowed_tools: Mapping[str, Tool],
) -> str | None:
"""Execute ANY tool a provider leaked as TEXT (generalises spawn-only).
@@ -6577,11 +6698,14 @@ class BrainManager:
name, inp = parsed
if name == "spawn_worker":
return await self._recover_leaked_spawn(
- response_text, user_text=user_text, trace_id=trace_id,
+ response_text,
+ user_text=user_text,
+ trace_id=trace_id,
+ allowed_tools=allowed_tools,
)
if self._tool_executor is None:
return None
- tool = self._tools.get(name)
+ tool = allowed_tools.get(name)
if tool is None:
return None
log.warning(
@@ -6596,8 +6720,12 @@ class BrainManager:
# it instead of the bare "exit N" error token (live repro
# 2026-06-17, gcloud billing budgets list -> exit 1).
if name.startswith(_CLI_TOOL_PREFIX):
- return _cli_failure_reason(
- result.output, result.error, german=_looks_german(user_text),
+ return _safe_recovered_text(
+ _cli_failure_reason(
+ result.output,
+ result.error,
+ german=_looks_german(user_text),
+ )
)
return await self._honest_failure_readback(
result,
@@ -6920,6 +7048,8 @@ class BrainManager:
history_token = _TURN_HISTORY_OVERRIDE.set(
tuple(history_override) if history_override is not None else None
)
+ skill_state = _SkillTurnState(self)
+ skill_token = _SKILL_TURN_STATE.set(skill_state)
try:
return await self._generate(
user_text,
@@ -6933,6 +7063,14 @@ class BrainManager:
emit_tool_ack=emit_tool_ack,
)
finally:
+ # Keep the last completed turn inspectable for diagnostics/tests,
+ # while active concurrent turns continue reading their own
+ # ContextVar-backed state.
+ self._skill_turn_match_fallback = skill_state.match
+ self._skill_turn_content_fallback = skill_state.content
+ self._skill_turn_source_fallback = skill_state.source
+ self._skill_injected_inline_fallback = skill_state.injected_inline
+ _SKILL_TURN_STATE.reset(skill_token)
_TURN_HISTORY_OVERRIDE.reset(history_token)
_PUBLISH_RESPONSE_EVENT.reset(token)
@@ -7110,6 +7248,10 @@ class BrainManager:
"set_mission_command_handlers() rufen."
)
+ routing_text, contextual_tool_names = self._contextual_routing_state(
+ user_text, use_history=use_history,
+ )
+
# Skill-aware routing guard (AD-S3): probe ONCE per turn, before any
# fast path can grab the utterance. "starte die Morgenroutine" is an
# is_open_app_intent hit AND a spawn-verb hit — without this early
@@ -7129,6 +7271,18 @@ class BrainManager:
# AD-S4: a trigger noted by the speech pipeline / chat hook takes
# precedence — it carries the captured content and the source label.
self._consume_pending_skill_trigger(user_text)
+ if self._skill_turn_match is None and routing_text != user_text:
+ # Match the prior utterance independently before trying the
+ # composite routing context. Whole-utterance (``^...$``) plugin
+ # skill triggers cannot match the wrapper by design, yet they
+ # still own an explicitly referential follow-up.
+ previous_text = self._previous_user_turn_text(use_history=use_history)
+ if previous_text:
+ self._skill_turn_match = self._match_skill_for_turn(previous_text)
+ if self._skill_turn_match is None:
+ self._skill_turn_match = self._match_skill_for_turn(routing_text)
+ if self._skill_turn_match is not None:
+ self._skill_turn_source = "continuation"
# AD-S9: an explicit heavy-work trigger ("Sub-Agent", "OpenClaw",
# "spawne", "deep dive", …) names the execution vehicle — the mission
# path owns such a turn, not the inline skill prompt. Live bug
@@ -7136,7 +7290,7 @@ class BrainManager:
# inline gmail-skill turn instead of a mission.
if (
self._skill_turn_match is not None
- and self._get_force_spawn_pattern().search(user_text)
+ and self._is_explicit_heavy_request(user_text)
):
log.info(
"Skill match %s stands down — explicit heavy-work trigger in "
@@ -7269,9 +7423,20 @@ class BrainManager:
# the LLM tool-use loop. Prevents spawn reflex on ambiguous smalltalk
# inputs (see docs/persona-research.md section 2 — 60% empty smalltalk
# outputs from the reflexive LLM spawn path).
- forced_spawn = await self._force_spawn_worker(
- user_text, trace_id=turn_trace_id, source_layer=source_layer,
- )
+ if (
+ contextual_tool_names
+ and not self._is_explicit_heavy_request(user_text)
+ and not self._research_wants_artifact(user_text)
+ ):
+ log.info(
+ "Force-spawn stood down for contextual live tool(s): %s",
+ ", ".join(contextual_tool_names),
+ )
+ forced_spawn = None
+ else:
+ forced_spawn = await self._force_spawn_worker(
+ user_text, trace_id=turn_trace_id, source_layer=source_layer,
+ )
if forced_spawn is not None:
# Bug fix 2026-04-30: history update also in the force-spawn path.
# Previously returned directly → main Jarvis had no memory on the
@@ -7649,7 +7814,7 @@ class BrainManager:
# utterance (progressive disclosure), then hide any plugin whose
# CLI counterpart is connected (req 4: CLI > plugin fallback).
else self._suppress_plugins_covered_by_cli(
- self._apply_plugin_relevance(user_text, self._tools)
+ self._apply_plugin_relevance(routing_text, self._tools)
)
)
# Skill inline-injected (AD-S4): drop run-skill so a weak model
@@ -7686,8 +7851,23 @@ class BrainManager:
# the spawn vehicles so the router uses the plugin tool DIRECTLY.
if isinstance(_turn_tools, dict):
_turn_tools = self._hide_spawn_when_plugin_tool_handles_turn(
- _turn_tools, user_text
+ _turn_tools, routing_text
)
+ # A referential follow-up that inherited a currently registered
+ # plugin/MCP tool remains inline even when that tool has no usage
+ # card. The explicit heavy-work and artifact requests above retain
+ # their normal mission path.
+ if (
+ isinstance(_turn_tools, dict)
+ and contextual_tool_names
+ and not self._is_explicit_heavy_request(user_text)
+ and not self._research_wants_artifact(user_text)
+ ):
+ _turn_tools = {
+ name: tool
+ for name, tool in _turn_tools.items()
+ if name not in _SPAWN_TOOL_NAMES
+ }
# PC-control run-skill hide (forensic 2026-07-02, voice 20:28): "ein
# Terminal öffnen, Cloud-Code öffnen, … ein Prompt geben" — an
# explicit desktop request — was hijacked by the semantically-similar
@@ -8019,14 +8199,11 @@ class BrainManager:
)
return await self._provider_down_reply(trace_uuid)
- # Robustness net (2026-05-24): a provider (notably Gemini) sometimes
- # emits a spawn_worker tool_use block as TEXT instead of executing
- # it — response_text becomes raw `[{"type":"tool_use",...}]` JSON.
- # Without this the JSON is spoken (scrubbed to "Es trat ein Fehler
- # auf") and the delegated Opus-4.7 sub-agent never runs. Detect the
- # leak and execute the spawn through the normal tool path so the
- # heavy-work delegation is robust against provider function-calling
- # flakiness.
+ # Text-serialized calls are recovered inside BrainDispatcher's shared
+ # ToolUseLoop, where the exact turn-scoped tool surface, deadline,
+ # safety guards, and exactly-once tracking remain authoritative. Never
+ # re-parse and execute here against the manager-global tool registry:
+ # that old fallback bypassed per-turn plugin/screen/deadline gates.
# Two-turn voice/chat confirmation (turn N): the tool-use loop deferred a
# consequential tool and produced a confirmation QUESTION as its text.
# Arm the pending state and return the question directly — the leaked-tool
@@ -8043,21 +8220,15 @@ class BrainManager:
)
return agg.text
- recovered = await self._recover_leaked_tool(
- response_text, user_text=user_text, trace_id=trace_uuid,
- )
- if recovered is not None:
- response_text = recovered
-
# Evidence-gate enforcement (live repro 2026-06-17, session 296abc82):
# the gate MANDATED a tool this turn, but neither the normal tool loop
# nor the leaked-tool recovery above actually ran it — so the model's
# answer is unverified, at worst a confabulation ("the gcloud tool
# blocked execution because it classified the request as an explanatory
# question"). Replace it with an honest non-data fallback; never speak an
- # answer a mandated read tool was supposed to ground. Runs AFTER recovery
- # so a leaked-but-recovered mandated tool (real data) is not pre-empted.
- if recovered is None and self._evidence_required_tool:
+ # answer a mandated read tool was supposed to ground. Shared-loop leak
+ # recovery has already populated ``_turn_executed`` when it succeeded.
+ if self._evidence_required_tool:
_replacement = _unfulfilled_replacement(
required_tool=self._evidence_required_tool,
executed=_turn_executed,
@@ -8080,8 +8251,6 @@ class BrainManager:
response_text = _replacement
execution_evidence = set(_turn_executed)
- if recovered is not None:
- execution_evidence.add("recovered_tool_call")
honest_response = replace_unbacked_action_claim(
response_text,
executed_tools=execution_evidence,
diff --git a/jarvis/brain/tool_call_recovery.py b/jarvis/brain/tool_call_recovery.py
new file mode 100644
index 0000000000..5743d8e277
--- /dev/null
+++ b/jarvis/brain/tool_call_recovery.py
@@ -0,0 +1,124 @@
+"""Provider-neutral recovery for function calls emitted as response text.
+
+Some model transports occasionally serialize a function call into the text
+stream instead of returning a structured tool-call delta. This module parses
+only explicit tool-call envelopes; arbitrary JSON is never treated as an
+action. Recovered calls still pass through ToolUseLoop and ToolExecutor.
+"""
+
+from __future__ import annotations
+
+import json
+from hashlib import sha256
+from typing import Any
+
+_CALL_MARKERS = ("tool_use", "function_call", "tool_calls", '"function"')
+_MISSING = object()
+
+
+def _strip_json_fence(text: str) -> str | None:
+ """Return an entire JSON response, optionally inside one strict fence."""
+ stripped = text.strip()
+ if not stripped.startswith("```"):
+ return stripped
+ lines = stripped.splitlines()
+ if len(lines) < 3 or lines[-1].strip() != "```":
+ return None
+ if lines[0].strip().lower() not in {"```", "```json"}:
+ return None
+ return "\n".join(lines[1:-1]).strip()
+
+
+def _decode_arguments(value: Any) -> dict[str, Any] | None:
+ if isinstance(value, dict):
+ return dict(value)
+ if isinstance(value, str):
+ try:
+ decoded = json.loads(value)
+ except (json.JSONDecodeError, ValueError):
+ return None
+ return dict(decoded) if isinstance(decoded, dict) else None
+ return None
+
+
+def _normalize_call(block: Any) -> dict[str, Any] | None:
+ if not isinstance(block, dict):
+ return None
+
+ call: Any = block
+ if isinstance(block.get("function_call"), dict):
+ call = block["function_call"]
+ elif isinstance(block.get("function"), dict):
+ call = block["function"]
+
+ if not isinstance(call, dict):
+ return None
+ call_type = str(block.get("type") or call.get("type") or "")
+ explicitly_wrapped = (
+ call is not block
+ or call_type in {"tool_use", "function_call", "function"}
+ )
+ if not explicitly_wrapped:
+ return None
+
+ name = call.get("name")
+ if not isinstance(name, str) or not name.strip():
+ return None
+ arguments = call.get("input", _MISSING)
+ if arguments is _MISSING:
+ arguments = call.get("arguments", call.get("args", _MISSING))
+ decoded_arguments = (
+ {} if arguments is _MISSING else _decode_arguments(arguments)
+ )
+ if decoded_arguments is None:
+ return None
+ fingerprint = json.dumps(
+ [name.strip(), decoded_arguments],
+ sort_keys=True,
+ separators=(",", ":"),
+ default=str,
+ ).encode("utf-8")
+ return {
+ "id": str(
+ block.get("id")
+ or call.get("id")
+ or f"leaked_{sha256(fingerprint).hexdigest()[:12]}"
+ ),
+ "name": name.strip(),
+ "input": decoded_arguments,
+ }
+
+
+def _calls_from_candidate(candidate: Any) -> list[dict[str, Any]]:
+ blocks = candidate if isinstance(candidate, list) else [candidate]
+ calls: list[dict[str, Any]] = []
+ for block in blocks:
+ if isinstance(block, dict) and isinstance(block.get("tool_calls"), list):
+ for nested in block["tool_calls"]:
+ normalized = _normalize_call(nested)
+ if normalized is not None:
+ calls.append(normalized)
+ continue
+ normalized = _normalize_call(block)
+ if normalized is not None:
+ calls.append(normalized)
+ return calls
+
+
+def extract_leaked_tool_calls(text: str) -> list[dict[str, Any]]:
+ """Parse explicit text-serialized tool calls into normal loop call records."""
+ if not text or not any(marker in text.lower() for marker in _CALL_MARKERS):
+ return []
+
+ stripped = _strip_json_fence(text)
+ if stripped is None:
+ return []
+ try:
+ candidate = json.loads(stripped)
+ except (json.JSONDecodeError, ValueError):
+ # Never execute quoted examples or JSON embedded in ordinary prose.
+ return []
+ return _calls_from_candidate(candidate)
+
+
+__all__ = ["extract_leaked_tool_calls"]
diff --git a/jarvis/brain/tool_use_loop.py b/jarvis/brain/tool_use_loop.py
index 133a29b086..6d0aeef444 100644
--- a/jarvis/brain/tool_use_loop.py
+++ b/jarvis/brain/tool_use_loop.py
@@ -26,6 +26,7 @@ from jarvis.safety.tool_executor import VOICE_CONFIRM_SENTINEL, ToolExecutor
from .iteration_budget import IterationBudget
from .streaming import StreamingAggregate, aggregate, aggregate_with_consumer
+from .tool_call_recovery import extract_leaked_tool_calls
# Central backstop for tool-output bloat: no tool result may exceed this many
# chars in the tool-role message fed back to the brain. Individual tools should
@@ -45,6 +46,15 @@ _DEADLINE_FINAL_DIRECTIVE = (
"not call any more tools."
)
+# A provider can repeat the exact same text-serialized call after receiving its
+# result. The action must remain exactly-once, but the turn must not end on an
+# empty ``tool_use`` round. Force one tool-less synthesis pass instead.
+_DUPLICATE_CALL_FINAL_DIRECTIVE = (
+ "[duplicate tool call suppressed] The exact requested tool call already "
+ "ran and its result is available above. Answer the user NOW from that "
+ "evidence. Do not call any more tools."
+)
+
def _cap_tool_result_json(serialized: str) -> str:
"""Truncate an over-long serialized tool result, leaving an honest marker so
@@ -58,6 +68,15 @@ def _cap_tool_result_json(serialized: str) -> str:
)
+def _tool_call_signature(call: dict[str, Any]) -> tuple[str, str]:
+ """Canonical name/arguments fingerprint for same-round duplicate calls."""
+ arguments = call.get("input", {})
+ return (
+ str(call.get("name") or ""),
+ json.dumps(arguments, sort_keys=True, separators=(",", ":"), default=str),
+ )
+
+
def _images_from_artifacts(artifacts: object) -> list[ImageBlock]:
"""Extract ImageBlocks from a tool's artifacts (Wave 2 on-demand vision).
@@ -507,6 +526,7 @@ class ToolUseLoop:
ack_attempted = False
loop_started = time.monotonic()
deadline_forced = False
+ seen_call_ids: set[str] = set()
def _progress() -> None:
# Stall-timeout heartbeat (see ``on_progress`` in the docstring).
@@ -542,6 +562,50 @@ class ToolUseLoop:
# execution + next round so a slow-but-working turn is not cut off.
_progress()
+ # Some providers occasionally serialize a function call into the
+ # response text instead of emitting a structured tool-call delta.
+ # Rehydrate only explicit call envelopes, then continue through the
+ # normal executor, risk, confirmation, telemetry, and synthesis
+ # path. This is shared by native, plugin, skill, and MCP tools.
+ if not deadline_forced and tools_payload:
+ recovered_calls = extract_leaked_tool_calls(agg.text)
+ if recovered_calls:
+ structured_signatures = {
+ _tool_call_signature(call) for call in agg.tool_calls
+ }
+ recovered_calls = [
+ call
+ for call in recovered_calls
+ if _tool_call_signature(call) not in structured_signatures
+ ]
+ log.warning(
+ "tool_use_loop: recovered %d text-serialized tool call(s): %s",
+ len(recovered_calls),
+ ", ".join(call["name"] for call in recovered_calls),
+ )
+ agg.tool_calls.extend(recovered_calls)
+ agg.text = ""
+ if agg.tool_calls:
+ agg.finish_reason = "tool_use"
+
+ duplicate_only_round = False
+ if agg.tool_calls:
+ had_tool_calls = True
+ unique_calls: list[dict[str, Any]] = []
+ for call in agg.tool_calls:
+ call_id = str(call.get("id") or "")
+ if call_id and call_id in seen_call_ids:
+ log.warning(
+ "tool_use_loop: skipped duplicate tool-call id %s",
+ call_id,
+ )
+ continue
+ if call_id:
+ seen_call_ids.add(call_id)
+ unique_calls.append(call)
+ agg.tool_calls = unique_calls
+ duplicate_only_round = had_tool_calls and not unique_calls
+
# Accumulate final text
if agg.text:
final_agg.text += agg.text
@@ -555,6 +619,22 @@ class ToolUseLoop:
tokens_out=agg.usage.get("output_tokens", 0),
)
+ # A repeated call was already executed in an earlier model round.
+ # Suppressing it is correct, but treating the now-empty call list
+ # as a completed answer would return silence. Give the provider one
+ # final tool-less round over the existing result instead.
+ if duplicate_only_round and not deadline_forced:
+ log.warning(
+ "tool_use_loop: duplicate-only round; forcing final "
+ "tool-less synthesis"
+ )
+ deadline_forced = True
+ tools_payload = []
+ current_messages.append(
+ BrainMessage(role="user", content=_DUPLICATE_CALL_FINAL_DIRECTIVE)
+ )
+ continue
+
# No tool calls → done
if not agg.tool_calls:
break
diff --git a/jarvis/brain/turn_planner.py b/jarvis/brain/turn_planner.py
index 5c32ec233c..f95599b542 100644
--- a/jarvis/brain/turn_planner.py
+++ b/jarvis/brain/turn_planner.py
@@ -52,9 +52,10 @@ class TurnPlan:
_LOOKUP_SHAPE_RE = re.compile(
- r"\b(?:what|when|where|which|who|how many|how is|show|read|list|find|"
+ r"\b(?:what|when|where|why|which|who|how many|how is|show|read|list|find|"
r"lookup|check|summarize|search|do i have|is there|are there|"
- r"was|wann|wo|welch\w*|wer|wie viele|wie ist|wie lautet|wie heisst|"
+ r"was|wann|wo|woran|warum|wieso|weshalb|welch\w*|wer|wie viele|"
+ r"wie ist|wie lautet|wie heisst|"
r"zeig\w*|lies|lese|list\w*|"
r"find\w*|such\w*|pruef\w*|fass\w*|habe ich|hab ich|gibt es|"
r"que|cuando|donde|cual\w*|quien|cuantos|muestra|lee|lista|"
@@ -172,6 +173,9 @@ _FOLLOW_UP_REFERENCE_RE = re.compile(
r"eso|esto|ahi|alli|dentro|que mas|resultados?|hallazgos?)\b|" # i18n-allow
r"\b(?:what\s+does\s+it|what(?:'s|\s+is)\s+in\s+it|in\s+it|"
r"what(?:'s|\s+is)\s+(?:it|this|that)\s+about|"
+ r"where\s+(?:is|did)\s+it|why\s+(?:did|does|is|was)\s+(?:it|this|that)|"
+ r"wo\s+(?:liegt|ist)\s+es|woran\s+liegt\s+es|" # i18n-allow: German speech-input matching data
+ r"(?:warum|wieso|weshalb).{0,30}\b(?:es|das)\b|" # i18n-allow: speech input
r"um\s+was\s+geht(?:\s+es|['’]?s)?|"
r"worum\s+geht(?:\s+es|['’]?s)?)\b" # i18n-allow
)
@@ -214,6 +218,8 @@ def _matched_capabilities(
*,
capability_registry: Any | None,
tool_names: Iterable[str],
+ require_lookup_shape: bool = True,
+ contextual_identity_only: bool = False,
) -> tuple[str, ...]:
matched: set[str] = set()
capabilities: Sequence[Any] = ()
@@ -227,13 +233,40 @@ def _matched_capabilities(
capabilities = ()
normalized = _normalize(text)
- if _LOOKUP_SHAPE_RE.search(normalized):
+ if not require_lookup_shape or _LOOKUP_SHAPE_RE.search(normalized):
for capability in capabilities:
tokens = _tokens_from_capability(capability)
if any(re.search(r"\b" + re.escape(token) + r"\b", normalized) for token in tokens):
matched.add(str(getattr(capability, "id", "")))
for name in tool_names:
normalized_name = _normalize(name).replace("_", " ").replace("/", " ")
+ if contextual_identity_only:
+ raw_name = _normalize(str(name)).replace("_", " ")
+ namespace, separator, _ = raw_name.partition("/")
+ identity = namespace if separator else raw_name
+ identity = re.sub(
+ r"^(?:(?:cli|mcp|plugin|server)[\s._-]+)+",
+ "",
+ identity,
+ )
+ identity = re.sub(
+ r"(?:[\s._-]+(?:cli|mcp|plugin|server))+$",
+ "",
+ identity,
+ )
+ identity_tokens = [
+ token
+ for token in re.split(r"[^a-z0-9]+", identity)
+ if len(token) >= 3 and token not in {"cli", "mcp", "plugin", "server"}
+ ]
+ if not identity_tokens:
+ continue
+ identity_pattern = r"\b" + r"\s+".join(
+ re.escape(token) for token in identity_tokens
+ ) + r"\b"
+ if re.search(identity_pattern, normalized):
+ matched.add(str(name))
+ continue
tokens = [
token
for token in re.split(r"[^a-z0-9-]+", normalized_name)
@@ -247,6 +280,20 @@ def _matched_capabilities(
return tuple(sorted(item for item in matched if item))
+def is_contextual_follow_up(text: str, context: Sequence[str]) -> bool:
+ """Return whether ``text`` explicitly refers to the bounded prior context."""
+ normalized = _normalize(text).strip()
+ context_text = " ".join(str(item or "") for item in context).strip()
+ if len(context_text) > _CONTEXT_MAX_CHARS:
+ context_text = context_text[-_CONTEXT_MAX_CHARS:]
+ return bool(
+ _normalize(context_text)
+ and _LOOKUP_SHAPE_RE.search(normalized)
+ and _FOLLOW_UP_REFERENCE_RE.search(normalized)
+ and not _INSTRUCTIONAL_RE.search(normalized)
+ )
+
+
def plan_turn(
text: str,
*,
@@ -333,12 +380,7 @@ def plan_turn(
if len(context_text) > _CONTEXT_MAX_CHARS:
context_text = context_text[-_CONTEXT_MAX_CHARS:]
context_normalized = _normalize(context_text)
- contextual_follow_up = bool(
- context_normalized
- and lookup
- and _FOLLOW_UP_REFERENCE_RE.search(normalized)
- and not instructional
- )
+ contextual_follow_up = is_contextual_follow_up(text, context)
if contextual_follow_up:
inherited = False
if _LOCAL_STATE_RE.search(context_normalized):
@@ -364,6 +406,8 @@ def plan_turn(
context_text,
capability_registry=capability_registry,
tool_names=tool_names,
+ require_lookup_shape=False,
+ contextual_identity_only=True,
)
if contextual_required:
required = tuple(sorted(set(required) | set(contextual_required)))
@@ -424,4 +468,10 @@ def plan_turn(
)
-__all__ = ["TurnPath", "TurnPlan", "TurnReason", "plan_turn"]
+__all__ = [
+ "TurnPath",
+ "TurnPlan",
+ "TurnReason",
+ "is_contextual_follow_up",
+ "plan_turn",
+]
diff --git a/jarvis/claude_auth.py b/jarvis/claude_auth.py
index b3e4b5c928..cab3c19e41 100644
--- a/jarvis/claude_auth.py
+++ b/jarvis/claude_auth.py
@@ -267,6 +267,16 @@ class ClaudeAuthService:
def status(self) -> ClaudeAuthStatus:
binary = self._resolve_binary()
if binary is None:
+ if self._api_key_present:
+ return ClaudeAuthStatus(
+ installed=False,
+ connected=True,
+ mode="api_key",
+ message="Connected via Anthropic API key; the Claude CLI is optional.",
+ account_label="Anthropic API key",
+ binary_path=self._binary_path,
+ api_key_present=True,
+ )
return ClaudeAuthStatus(
installed=False,
connected=False,
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index d477b559e0..f471b13bdd 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -18,9 +18,11 @@ import secrets
import sys
import threading
import tomllib
+from contextlib import contextmanager
+from contextvars import ContextVar
from dataclasses import dataclass
from pathlib import Path
-from typing import TYPE_CHECKING, Any, Literal
+from typing import TYPE_CHECKING, Any, Iterator, Literal, Mapping
import yaml
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, field_validator
@@ -149,8 +151,62 @@ PROVIDER_SECRET_CANDIDATES: dict[str, tuple[tuple[str, str], ...]] = {
("grok_api_key", "GROK_API_KEY"),
("xai_api_key", "XAI_API_KEY"),
),
+ # Realtime owns dedicated slots. The generic family slots remain trailing
+ # read-only compatibility fallbacks for upgraded installations; a key saved
+ # from the Realtime card is therefore never visible to Brain or Jarvis-Agent
+ # resolution.
+ "openai-realtime": (
+ ("realtime_openai_api_key", "JARVIS_REALTIME_OPENAI_API_KEY"),
+ ("openai_api_key", "OPENAI_API_KEY"),
+ ),
+ "gemini-live": (
+ ("realtime_gemini_api_key", "JARVIS_REALTIME_GEMINI_API_KEY"),
+ ("gemini_api_key", "GEMINI_API_KEY"),
+ ("google_aistudio_api_key", "GOOGLE_AIStudio_API_KEY"),
+ ("google_api_key", "GOOGLE_API_KEY"),
+ ),
+ "grok-realtime": (
+ ("realtime_grok_api_key", "JARVIS_REALTIME_GROK_API_KEY"),
+ ("grok_api_key", "GROK_API_KEY"),
+ ("xai_api_key", "XAI_API_KEY"),
+ ),
+}
+
+# Jarvis-Agent API credentials are independently replaceable from the Agent
+# tab. Generic provider slots remain a final compatibility fallback so existing
+# installations keep working, but scoped Agent keys always win and are never
+# consumed by Brain or Realtime.
+JARVIS_AGENT_SECRET_CANDIDATES: dict[str, tuple[tuple[str, str], ...]] = {
+ "claude-api": (
+ ("jarvis_agent_anthropic_api_key", "JARVIS_AGENT_ANTHROPIC_API_KEY"),
+ *PROVIDER_SECRET_CANDIDATES["claude-api"],
+ ),
+ "openai": (
+ ("jarvis_agent_openai_api_key", "JARVIS_AGENT_OPENAI_API_KEY"),
+ *PROVIDER_SECRET_CANDIDATES["openai"],
+ ),
+ "gemini": (
+ ("jarvis_agent_gemini_api_key", "JARVIS_AGENT_GEMINI_API_KEY"),
+ *PROVIDER_SECRET_CANDIDATES["gemini"],
+ ),
+ "openrouter": (
+ ("jarvis_agent_openrouter_api_key", "JARVIS_AGENT_OPENROUTER_API_KEY"),
+ *PROVIDER_SECRET_CANDIDATES["openrouter"],
+ ),
+ "grok": (
+ ("jarvis_agent_grok_api_key", "JARVIS_AGENT_GROK_API_KEY"),
+ *PROVIDER_SECRET_CANDIDATES["grok"],
+ ),
+ "nvidia": (
+ ("jarvis_agent_nvidia_api_key", "JARVIS_AGENT_NVIDIA_API_KEY"),
+ *PROVIDER_SECRET_CANDIDATES["nvidia"],
+ ),
}
+_PROVIDER_SECRET_OVERRIDES: ContextVar[Mapping[str, str | None] | None] = ContextVar(
+ "provider_secret_overrides", default=None
+)
+
# ----------------------------------------------------------------------
# Sub-configs (Pydantic models per layer)
@@ -954,12 +1010,13 @@ class SessionRollupConfig(BaseModel):
Outer ``asyncio.wait_for`` cap on the brain call.
``user_entity_slug``
- Slug of the user's own entity page. Empty by default so a fresh
- install carries no personal name; onboarding/profile resolves the
- real slug at runtime. When set (and the page exists), every session
- page links it in the ``## Related`` backbone footer, wiring each
- session into the graph through the shared user hub instead of
- floating as an island.
+ Slug of the user's own entity page. Empty or unsafe values resolve to
+ the neutral ``user`` slug in the conversation-memory pipeline, so a
+ fresh install uses ``entities/user.md`` and carries no personal name.
+ Onboarding may configure a safe slug later. When that page exists,
+ every session page links it in the ``## Related`` backbone footer,
+ wiring each session into the graph through the shared user hub instead
+ of floating as an island.
"""
model_config = ConfigDict(extra="allow")
@@ -1044,7 +1101,9 @@ class VoiceBridgeConfig(BaseModel):
model_config = ConfigDict(extra="allow")
aggressive_mode: bool = True
- min_user_chars: int = 30
+ # Keep this aligned with ExtractorConfig.min_user_chars. Stage 2 remains
+ # the quality gate; a 12-character ownership statement can be durable.
+ min_user_chars: int = 12
rate_limit_seconds: int = 0
@@ -1293,9 +1352,9 @@ class UIConfig(BaseModel):
# --dev; the fields here simply hold the parameters.
dev_mode: bool = False
vite_dev_url: str = "http://localhost:5173"
- # ENV variable that provides the session token for the WebView.
- # Default: JARVIS_UI_TOKEN. The token is freshly generated at startup
- # and pywebview injects it via evaluate_js into window.__JARVIS_TOKEN.
+ # ENV variable carrying the process-scoped UI bootstrap token. The native
+ # WebView exposes it once; AuthGate exchanges it for an unrelated HttpOnly
+ # session cookie and immediately clears the JavaScript value.
auth_token_env: str = "JARVIS_UI_TOKEN"
# On-screen overlay style: "jarvis_bar" (slim default), "mascot" (ghost
# orb), or "none". The mascot remains fully selectable.
@@ -1604,14 +1663,13 @@ class ComputerUseConfig(BaseModel):
model_config = {"extra": "allow"}
enabled: bool = False
- # Which Computer-Use engine runs (reversible switch). "v2" (default) = the
+ # Which Computer-Use engine runs. "v2" (default) = the
# rebuilt perceive->act->verify engine (jarvis/cu/engine.py): per-frame
# coordinate mapping, provider coordinate conventions, UI-idle capture,
- # effect-checked actions and the idempotency ledger. Legacy engines stay
- # available as fallbacks: "current" = the last maintained legacy loop,
- # "june13" / "stable" = frozen known-good snapshots. The harness reads
- # this per mission and logs which engine is live, so a flip applies on
- # the next mission with no restart. Roll back any time with "current".
+ # effect-checked actions and the idempotency ledger. The historical
+ # "current", "june13" and "stable" values remain accepted for read-time
+ # config compatibility but route to v2: their frozen loops lack current
+ # permission, topology and foreground-window action guards.
engine: Literal["v2", "current", "june13", "stable"] = "v2"
# Coordinate space the vision model's click coordinates are parsed in
# (CU v2 only). "auto" (default) resolves per provider: an explicit
@@ -2846,9 +2904,52 @@ def get_secret_any(candidates: tuple[tuple[str, str | None], ...]) -> str | None
def get_provider_secret(provider: str) -> str | None:
"""Return the API key for a Brain provider, including accepted aliases."""
+ overrides = _PROVIDER_SECRET_OVERRIDES.get()
+ if overrides is not None and provider in overrides:
+ return overrides[provider]
return get_secret_any(PROVIDER_SECRET_CANDIDATES.get(provider, ()))
+def get_jarvis_agent_secret(provider: str) -> str | None:
+ """Return the effective API key for one Jarvis-Agent provider.
+
+ A dedicated Agent slot wins. Generic provider credentials are read only as
+ an upgrade compatibility fallback; Realtime-only slots are never candidates.
+ OAuth-backed Agent providers keep resolving their login separately.
+ """
+ candidates = JARVIS_AGENT_SECRET_CANDIDATES.get(provider, ())
+ if not candidates:
+ return None
+ dedicated = get_secret_any((candidates[0],))
+ if dedicated:
+ return dedicated
+ return get_provider_secret(provider)
+
+
+def jarvis_agent_secret_slot(provider: str) -> tuple[str, str] | None:
+ """Return the dedicated ``(keyring slot, ENV name)`` for an Agent family."""
+ candidates = JARVIS_AGENT_SECRET_CANDIDATES.get(provider, ())
+ return candidates[0] if candidates else None
+
+
+@contextmanager
+def override_provider_secrets(
+ overrides: Mapping[str, str | None],
+) -> Iterator[None]:
+ """Task-local provider credentials for an in-process Agent or critic call.
+
+ ``ContextVar`` keeps concurrent workers isolated and avoids mutating process
+ environment variables. Normal Brain calls outside the scope are unchanged.
+ Team-proxy resolution also stays authoritative because it resolves before
+ :func:`get_provider_secret` is consulted.
+ """
+ token = _PROVIDER_SECRET_OVERRIDES.set(dict(overrides))
+ try:
+ yield
+ finally:
+ _PROVIDER_SECRET_OVERRIDES.reset(token)
+
+
@dataclass(frozen=True, slots=True)
class ResolvedEndpoint:
"""Effective endpoint + credential for a provider on this turn.
diff --git a/jarvis/google_cli/isolated_home.py b/jarvis/google_cli/isolated_home.py
index 85420a7df5..7a10378360 100644
--- a/jarvis/google_cli/isolated_home.py
+++ b/jarvis/google_cli/isolated_home.py
@@ -73,7 +73,8 @@ def _latest_login_mtime(real_dir: str) -> float | None:
def real_gemini_dir() -> str:
"""The user's real ~/.gemini dir — read-only source of the OAuth login."""
- return os.path.join(os.path.expanduser("~"), ".gemini")
+ override = os.environ.get("GEMINI_HOME")
+ return override if override else os.path.join(os.path.expanduser("~"), ".gemini")
def iso_home_root() -> str:
diff --git a/jarvis/missions/critic/runner.py b/jarvis/missions/critic/runner.py
index 1fd28456b0..6e23e24769 100644
--- a/jarvis/missions/critic/runner.py
+++ b/jarvis/missions/critic/runner.py
@@ -1782,13 +1782,19 @@ class CriticRunner:
"""
try:
from jarvis.brain.provider_registry import BrainProviderRegistry
+ from jarvis.core.config import (
+ get_jarvis_agent_secret,
+ override_provider_secrets,
+ )
from jarvis.core.protocols import BrainMessage, BrainRequest
cls = BrainProviderRegistry().get_class(provider)
- try:
- brain = cls(model) if model else cls() # type: ignore[call-arg]
- except TypeError:
- brain = cls() # type: ignore[call-arg]
+ worker_key = get_jarvis_agent_secret(provider)
+ with override_provider_secrets({provider: worker_key}):
+ try:
+ brain = cls(model) if model else cls() # type: ignore[call-arg]
+ except TypeError:
+ brain = cls() # type: ignore[call-arg]
req = BrainRequest(
messages=(BrainMessage(role="user", content=prompt),),
@@ -1802,10 +1808,11 @@ class CriticRunner:
)
parts: list[str] = []
async with asyncio.timeout(self._timeout):
- async for delta in brain.complete(req):
- chunk = getattr(delta, "content", None)
- if chunk:
- parts.append(chunk)
+ with override_provider_secrets({provider: worker_key}):
+ async for delta in brain.complete(req):
+ chunk = getattr(delta, "content", None)
+ if chunk:
+ parts.append(chunk)
return _parse_verdict_from_text(
"".join(parts), iteration=iteration, adversarial_reframe=adversarial_reframe,
)
diff --git a/jarvis/missions/init.py b/jarvis/missions/init.py
index e2d3fbd8ce..127e255da9 100644
--- a/jarvis/missions/init.py
+++ b/jarvis/missions/init.py
@@ -532,9 +532,9 @@ def _claude_cli_auth_viable() -> bool:
token = read_live_claude_oauth_token()
return not claude_auth_dead(current_fingerprint=credential_fingerprint(token))
try:
- from jarvis.core.config import get_secret
+ from jarvis.core.config import get_jarvis_agent_secret
- key = get_secret("anthropic_api_key", env_fallback="ANTHROPIC_API_KEY")
+ key = get_jarvis_agent_secret("claude-api")
except Exception: # noqa: BLE001 — unreadable secret store => not viable
return False
if not key or key.startswith("sk-ant-oat"):
@@ -557,9 +557,9 @@ def _api_key_family_viable(provider: str) -> bool:
worker already proved dead this session (fingerprinted) is skipped until
it changes.
"""
- from jarvis.core.config import get_provider_secret
+ from jarvis.core.config import get_jarvis_agent_secret
- key = get_provider_secret(provider)
+ key = get_jarvis_agent_secret(provider)
if not key:
return False
# A family a worker just proved quota-depleted / auth-dead is skipped
@@ -980,44 +980,40 @@ async def bootstrap_missions(
gemini_key: str | None = None
xai_key: str | None = None
openrouter_key: str | None = None
+ live_provider = _live_subagent_provider(sub_jarvis_provider)
try:
- from jarvis.core.config import get_secret
+ from jarvis.core.config import get_jarvis_agent_secret, get_secret
# Resolve the provider LIVE here too, so the injected key matches the
# worker the factory will actually pick (both read the same current
# persisted choice instead of the frozen boot snapshot).
- live_provider = _live_subagent_provider(sub_jarvis_provider)
-
- anthropic_key = get_secret("anthropic_api_key", env_fallback="ANTHROPIC_API_KEY")
+ if live_provider in {"claude", "claude-api"}:
+ anthropic_key = get_jarvis_agent_secret("claude-api")
# Codex-as-subagent API-key path: prefer the dedicated Codex key slot
# so OPENAI_API_KEY carries it (the OAuth path strips the key anyway —
# see CodexDirectWorker._build_codex_env). Other subagents use the
# general OpenAI key unchanged.
if live_provider in CODEX_SUBAGENT_SLUGS:
openai_key = get_secret(
- "codex_openai_api_key", env_fallback="OPENAI_API_KEY"
- ) or get_secret("openai_api_key", env_fallback="OPENAI_API_KEY")
- else:
- openai_key = get_secret("openai_api_key", env_fallback="OPENAI_API_KEY")
- # Antigravity (Google subscription) deliberately runs OAuth-only: a
- # configured Gemini API key must NOT be injected, or the CLI would
- # bill the key instead of the subscription login. Other subagents
- # keep the API-key path unchanged.
- if live_provider in ANTIGRAVITY_SUBAGENT_SLUGS:
- gemini_key = None
- else:
- gemini_key = get_secret(
- "gemini_api_key", env_fallback="GEMINI_API_KEY"
- ) or get_secret("google_api_key", env_fallback="GOOGLE_API_KEY")
+ "codex_openai_api_key", env_fallback="CODEX_OPENAI_API_KEY"
+ )
+ elif live_provider == "openai":
+ openai_key = get_jarvis_agent_secret("openai")
+ # GoogleCliWorker strips this key before the subscription/OAuth agy
+ # path, but needs it to cross to Gemini API billing when no OAuth
+ # login exists. Suppressing it here made key-only Antigravity look
+ # selectable and then fail at execution time.
+ if live_provider in {"gemini", "google", "antigravity"}:
+ gemini_key = get_jarvis_agent_secret("gemini")
# Grok / xAI: Jarvis stores under ``grok_api_key`` in the
# credential manager (ENV fallback ``GROK_API_KEY``); we set
# both XAI_API_KEY + GROK_API_KEY on the worker side so
# OpenClaw (XAI_API_KEY) and any legacy SDK (GROK_API_KEY)
# both find it.
- xai_key = get_secret("grok_api_key", env_fallback="GROK_API_KEY") or get_secret(
- "xai_api_key", env_fallback="XAI_API_KEY"
- )
- openrouter_key = get_secret("openrouter_api_key", env_fallback="OPENROUTER_API_KEY")
+ if live_provider in {"grok", "xai"}:
+ xai_key = get_jarvis_agent_secret("grok")
+ if live_provider == "openrouter":
+ openrouter_key = get_jarvis_agent_secret("openrouter")
except Exception as exc: # noqa: BLE001
logger.warning(
"missions: secret lookup failed (%s) — worker will hit authentication_failed",
@@ -1036,7 +1032,11 @@ async def bootstrap_missions(
# manager / .env; pinned to an isolated CLAUDE_CONFIG_DIR the env token is
# the only auth surface and a stale one 401s. A classic API key
# (sk-ant-api03) is used verbatim when there is no live OAuth login.
- live_oat = read_live_claude_oauth_token()
+ live_oat = (
+ read_live_claude_oauth_token()
+ if live_provider in {"claude", "claude-api"}
+ else None
+ )
if live_oat:
anthropic_key = live_oat
elif anthropic_key and anthropic_key.startswith("sk-ant-oat"):
@@ -1211,9 +1211,9 @@ async def bootstrap_missions(
# missing npm `gemini` CLI binary.
import shutil
- from jarvis.core.config import get_provider_secret
+ from jarvis.core.config import get_jarvis_agent_secret
- if not (shutil.which("gemini") or shutil.which("gemini.cmd")) and get_provider_secret(
+ if not (shutil.which("gemini") or shutil.which("gemini.cmd")) and get_jarvis_agent_secret(
"gemini"
):
logger.info(
diff --git a/jarvis/missions/worker_runtime/provider_map.py b/jarvis/missions/worker_runtime/provider_map.py
index 7da38e47ea..56ca49c33a 100644
--- a/jarvis/missions/worker_runtime/provider_map.py
+++ b/jarvis/missions/worker_runtime/provider_map.py
@@ -11,10 +11,10 @@ Bridge mechanics (summary for future readers):
5. env_vars_for() -> ENV vars that the worker harness reads at spawn time (primary +
fallback; both are set so that harness provider drift does not break auth).
-Why no dedicated per-provider API-key namespace (as originally assumed in AD-6)?
-The worker harness reads the standard provider ENV vars like any other
-Anthropic/OpenAI/Gemini client. Dual-maintenance in the wizard would be friction
-without benefit.
+Jarvis-Agent credentials use dedicated keyring slots. The supervisor resolves
+the scoped slot and translates it to the standard provider ENV name only at the
+worker boundary. Generic Brain credentials remain a compatibility fallback for
+upgraded installations; Realtime-only credentials are never candidates.
"""
from __future__ import annotations
diff --git a/jarvis/missions/workers/api_agent_worker.py b/jarvis/missions/workers/api_agent_worker.py
index a5953607a5..884a4fbd3a 100644
--- a/jarvis/missions/workers/api_agent_worker.py
+++ b/jarvis/missions/workers/api_agent_worker.py
@@ -323,7 +323,14 @@ class ApiAgentWorker:
try:
if self.provider not in _BRAIN_BY_PROVIDER:
raise RuntimeError(f"no API-agent worker for provider {self.provider!r}")
- brain = _build_brain(self.provider, resolved_model)
+ from jarvis.core.config import (
+ get_jarvis_agent_secret,
+ override_provider_secrets,
+ )
+
+ worker_key = get_jarvis_agent_secret(self.provider)
+ with override_provider_secrets({self.provider: worker_key}):
+ brain = _build_brain(self.provider, resolved_model)
except Exception as exc: # noqa: BLE001
res = ClaudeResult(
subtype="error_during_execution",
@@ -396,11 +403,15 @@ class ApiAgentWorker:
text_parts: list[str] = []
tool_calls: list[dict[str, Any]] = []
try:
- async for delta in brain.complete(req):
- if delta.content:
- text_parts.append(delta.content)
- if delta.tool_call:
- tool_calls.append(delta.tool_call)
+ # Override credential lookup only for this awaited provider
+ # call. ContextVar isolation keeps concurrent Brain and
+ # Jarvis-Agent tasks from observing one another's keys.
+ with override_provider_secrets({self.provider: worker_key}):
+ async for delta in brain.complete(req):
+ if delta.content:
+ text_parts.append(delta.content)
+ if delta.tool_call:
+ tool_calls.append(delta.tool_call)
except Exception as exc: # noqa: BLE001
# The capability pre-gate (above) catches a model the brain
# ALREADY knows is tool-incapable. Some providers (OpenRouter
@@ -553,9 +564,11 @@ class ApiAgentWorker:
fp: str | None = None
try:
- from jarvis.core.config import get_provider_secret
+ from jarvis.core.config import get_jarvis_agent_secret
- fp = credential_fingerprint(get_provider_secret(self.provider))
+ fp = credential_fingerprint(
+ get_jarvis_agent_secret(self.provider)
+ )
except Exception: # noqa: BLE001 — unreadable store => unbound cooldown
fp = None
mark_api_family_cooldown(self.provider, fingerprint=fp)
diff --git a/jarvis/missions/workers/google_cli_worker.py b/jarvis/missions/workers/google_cli_worker.py
index 9dd5fc52db..5ca6f337c9 100644
--- a/jarvis/missions/workers/google_cli_worker.py
+++ b/jarvis/missions/workers/google_cli_worker.py
@@ -234,7 +234,14 @@ class GoogleCliWorker:
session_id = resume_session_id or str(uuid.uuid4())
self.last_session_id = session_id
- if cli is None:
+ # API billing needs no Google CLI. Resolve it before the binary guard so
+ # a headless/API-key-only installation can use the in-process-compatible
+ # Gemini worker instead of failing on an absent ``agy`` executable.
+ use_api_billing = not _oauth_login_present(Path(real_gemini_dir())) and bool(
+ env.get("GEMINI_API_KEY") or env.get("GOOGLE_API_KEY")
+ )
+
+ if cli is None and not use_api_billing:
yield ClaudeSystemInit(
session_id=session_id,
model="antigravity/none",
@@ -258,17 +265,39 @@ class GoogleCliWorker:
# Gemini API key is available, bill per token via the proven Gemini API
# worker instead — same outcome the user asked for ("bill via the
# API"), on the tested path rather than coercing agy to use a key.
- use_api_billing = not _oauth_login_present(Path(real_gemini_dir())) and bool(
- env.get("GEMINI_API_KEY") or env.get("GOOGLE_API_KEY")
- )
- if cli.kind != "agy" or use_api_billing:
- # The Gemini CLI writes clean output to a pipe — reuse the proven worker.
+ if use_api_billing:
+ from .api_agent_worker import ApiAgentWorker
+
+ logger.info(
+ "GoogleCliWorker[%s] -> ApiAgentWorker(gemini) (API-key billing)",
+ worker_id,
+ )
+ api_worker = ApiAgentWorker(
+ "gemini", capability_inventory=self.capability_inventory
+ )
+ async for ev in api_worker.spawn(
+ prompt,
+ worktree=worktree,
+ env=env,
+ job=job,
+ worker_id=worker_id,
+ log_dir=log_dir,
+ model=model,
+ max_turns=max_turns,
+ resume_session_id=resume_session_id,
+ _broker_binding=broker_binding,
+ **_unused,
+ ):
+ yield ev
+ self.last_pid = api_worker.last_pid
+ self.last_session_id = api_worker.last_session_id
+ return
+
+ if cli is not None and cli.kind != "agy":
logger.info(
- "GoogleCliWorker[%s] -> GeminiWorker (%s)",
+ "GoogleCliWorker[%s] -> GeminiWorker (resolver kind=%s)",
worker_id,
- "API-key billing, no OAuth login"
- if use_api_billing
- else f"resolver kind={cli.kind}",
+ cli.kind,
)
async for ev in self._gemini_fallback.spawn(
prompt,
diff --git a/jarvis/plugins/brain/gemini.py b/jarvis/plugins/brain/gemini.py
index d047dbeb42..c12367d96d 100644
--- a/jarvis/plugins/brain/gemini.py
+++ b/jarvis/plugins/brain/gemini.py
@@ -718,6 +718,7 @@ class GeminiBrain:
contents=contents,
config=config_dict,
)
+ final_usage: dict[str, int] | None = None
async for chunk in stream:
# Text
text = getattr(chunk, "text", None)
@@ -754,13 +755,37 @@ class GeminiBrain:
usage = getattr(chunk, "usage_metadata", None)
if usage is not None:
yielded_delta = True
- yield BrainDelta(usage={
- "input_tokens": int(getattr(usage, "prompt_token_count", 0) or 0),
- "output_tokens": int(getattr(usage, "candidates_token_count", 0) or 0),
- "cache_read_input_tokens": int(
- getattr(usage, "cached_content_token_count", 0) or 0
- ),
- })
+ # Gemini reports cumulative snapshots, not per-chunk
+ # deltas. Emitting every snapshot makes the shared
+ # aggregator sum the same prompt repeatedly. Retain the
+ # latest snapshot and emit it once after the stream.
+ prompt_tokens = int(
+ getattr(usage, "prompt_token_count", 0) or 0
+ )
+ cache_hit_tokens = int(
+ getattr(usage, "cached_content_token_count", 0) or 0
+ )
+ candidate_tokens = int(
+ getattr(usage, "candidates_token_count", 0) or 0
+ )
+ thought_tokens = int(
+ getattr(usage, "thoughts_token_count", 0) or 0
+ )
+ tool_result_tokens = int(
+ getattr(usage, "tool_use_prompt_token_count", 0) or 0
+ )
+ final_usage = {
+ # The canonical cost contract stores non-cached
+ # input separately from discounted cache hits.
+ "input_tokens": max(
+ prompt_tokens - cache_hit_tokens,
+ 0,
+ ) + tool_result_tokens,
+ "output_tokens": candidate_tokens + thought_tokens,
+ "cache_hit_tokens": cache_hit_tokens,
+ }
+ if final_usage is not None:
+ yield BrainDelta(usage=final_usage)
return
except Exception as exc: # noqa: BLE001 — BUG-019 stale-cache recovery
if (
diff --git a/jarvis/plugins/tool/contact_upsert.py b/jarvis/plugins/tool/contact_upsert.py
index 3548058295..6ba3374630 100644
--- a/jarvis/plugins/tool/contact_upsert.py
+++ b/jarvis/plugins/tool/contact_upsert.py
@@ -108,7 +108,11 @@ class ContactUpsertTool:
continue
text = str(value).strip()
if text:
- fields[key] = text
+ # The voice/tool schema accepts the address as one natural
+ # language string, while ContactStore persists a structured
+ # address mapping. Preserve the complete phrase in the street
+ # field instead of passing an incompatible string to the store.
+ fields[key] = {"street": text} if key == "address" else text
if not fields:
return ToolResult(
@@ -132,10 +136,8 @@ class ContactUpsertTool:
),
)
- # Privacy: the field VALUES are logged at DEBUG only; INFO carries the
- # name + which fields changed, never the data itself.
+ # Contact values are personal data, so logs carry field names only.
log.info("contact-upsert: writing %r (fields=%s)", name, sorted(fields))
- log.debug("contact-upsert: %r fields=%r", name, fields)
try:
contact = store.upsert(name=name, **fields)
except Exception as exc: # noqa: BLE001 — a store error must not crash the turn
diff --git a/jarvis/plugins/tool/spawn_worker.py b/jarvis/plugins/tool/spawn_worker.py
index d2f23f7fcc..bea109b5a1 100644
--- a/jarvis/plugins/tool/spawn_worker.py
+++ b/jarvis/plugins/tool/spawn_worker.py
@@ -182,6 +182,26 @@ def _shares_content_word(a: str, b: str) -> bool:
return bool(wa & wb)
+_MAX_CONTEXT_HINTS = 8
+_MAX_CONTEXT_HINT_CHARS = 320
+
+
+def _bounded_context_hints(context_hints: list[str] | None) -> list[str]:
+ """Normalize and bound context copied into a worker mission prompt."""
+ hints: list[str] = []
+ for raw_hint in context_hints or []:
+ if not isinstance(raw_hint, str):
+ continue
+ hint = re.sub(r"[\x00-\x1f\x7f]+", " ", raw_hint)
+ hint = re.sub(r"\s{2,}", " ", hint).strip()
+ if not hint:
+ continue
+ hints.append(hint[:_MAX_CONTEXT_HINT_CHARS])
+ if len(hints) >= _MAX_CONTEXT_HINTS:
+ break
+ return hints
+
+
def _build_mission_prompt(
utterance: str,
action: str,
@@ -205,7 +225,9 @@ def _build_mission_prompt(
utterance = (utterance or "").strip()
action = (action or "").strip()
target = (target or "").strip()
- if not action or action == _GENERIC_ACTION_FALLBACK:
+ hints = _bounded_context_hints(context_hints)
+ no_interpretation = not action or action == _GENERIC_ACTION_FALLBACK
+ if no_interpretation:
# Force-spawn / no interpretation — the verbatim utterance is all we
# have. Strip any spawn/routing meta-clause ("spawn a sub-agent that …",
# "create and spawn a sub-agent …") so the worker receives the REAL task,
@@ -248,16 +270,18 @@ def _build_mission_prompt(
parts = [f"Aufgabe: {action}."]
if target:
parts.append(f"Zielort/Kontext: {target}.")
- hints = [
- h.strip()
- for h in (context_hints or [])
- if isinstance(h, str) and h.strip()
- ]
if hints:
parts.append("Hinweise: " + "; ".join(hints) + ".")
if utterance:
parts.append(f'Wortlaut des Nutzers: "{utterance}".')
body = "\n".join(parts)
+ if body and no_interpretation and hints:
+ context_block = "\n".join(f"- {hint}" for hint in hints)
+ body = (
+ f"{body}\n\nSupporting context from the recent conversation "
+ "(use only to resolve references; the underlying request remains "
+ f"authoritative):\n{context_block}"
+ )
if not body:
# Nothing to dispatch — keep the empty-in/empty-out contract so the
# caller's empty-utterance guard still short-circuits cleanly.
@@ -339,8 +363,12 @@ class SpawnWorkerTool:
"max) in the user's language, phrased freshly for THIS "
"exact request: name the concrete topic and naturally "
"convey that it runs on the side and may take a moment. "
+ "It MUST contain the exact public product term "
+ "'Jarvis-Agent' exactly once and make clear that one was "
+ "just started or brought in. Vary how and where that fact "
+ "is expressed; do not use a fixed sentence template. "
"NEVER a generic stock phrase, never claim the task is "
- "already done, no internal component names."
+ "already done, and never expose internal component names."
),
"default": "",
},
diff --git a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.model.test.tsx b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.model.test.tsx
index ef6c432f25..507d578e44 100644
--- a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.model.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.model.test.tsx
@@ -42,6 +42,24 @@ const MODELS = {
selects: "model",
};
+const OPENAI_AGENT_ROW = {
+ jarvis: "openai",
+ worker_slug: "openai",
+ env_var: "OPENAI_API_KEY",
+ env_fallback: null,
+ key_set: false,
+ api_key_set: false,
+ dedicated_key_set: false,
+ shared_key_set: false,
+ oauth_connected: false,
+ credential_source: "none",
+ secret_key: "jarvis_agent_openai_api_key",
+ dashboard_url: "https://platform.openai.com/api-keys",
+ credential_help: "Dedicated Jarvis-Agent key.",
+ is_active_brain: false,
+ billing: "api",
+};
+
function mockFetch() {
return vi.fn().mockImplementation(async (url: string) => {
const u = String(url);
@@ -100,4 +118,23 @@ describe("JarvisAgentSection — dedicated subagent LLM dropdown", () => {
);
});
});
+
+ it("renders a dedicated API-key input on the Jarvis-Agents card", async () => {
+ const status = { ...STATUS, mapping: [OPENAI_AGENT_ROW] };
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockImplementation(async (url: string) => {
+ if (String(url).includes("/api/jarvis-agent/status")) {
+ return { ok: true, json: async () => status };
+ }
+ return { ok: true, json: async () => ({}) };
+ }),
+ );
+
+ render(<JarvisAgentSection />);
+
+ expect(
+ await screen.findByLabelText("Enter jarvis_agent_openai_api_key"),
+ ).toBeTruthy();
+ });
});
diff --git a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx
index 21e7070bda..b91959e4d0 100644
--- a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx
+++ b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx
@@ -18,16 +18,16 @@ import {
type CodexStatus,
} from "@/hooks/useProviders";
import { BrainModelSelector } from "@/components/BrainModelSelector";
+import { ApiKeyForm } from "@/components/ApiKeyForm";
/**
* Subagent tier for the API-Keys view.
*
* Visually a sibling of the brain/tts/stt tiers in `ApiKeysView`: the same
* tier header + `card-outline` cards + identical `StatusBadge` styling. Each
- * provider card carries the same "Set active" radio as the API-key tiers, so
- * the user can switch the Heavy-Task subagent provider seamlessly instead of
- * being stuck on one. There is no key input — sub-agent workers reuse the
- * brain-provider keys entered above (`key_set` mirrors that state).
+ * provider card carries its own scoped API-key field and the same "Set active"
+ * radio as the other tiers. Legacy shared Brain credentials remain a visible
+ * compatibility fallback, never the only configuration path.
*
* Data source is `GET /api/jarvis-agent/status`; the switch posts to
* `POST /api/jarvis-agent/switch` (3-layer persist). This is its own section
@@ -43,6 +43,14 @@ interface SubagentMappingRow {
env_var: string;
env_fallback: string | null;
key_set: boolean;
+ api_key_set: boolean;
+ dedicated_key_set: boolean;
+ shared_key_set: boolean;
+ oauth_connected: boolean;
+ credential_source: string;
+ secret_key: string | null;
+ dashboard_url: string | null;
+ credential_help: string | null;
is_active_brain: boolean;
/** How this subagent is billed — "api" (per token) / "subscription" /
* "subscription_or_api". Drives the billing badge so the API-vs-subscription
@@ -221,17 +229,14 @@ export function JarvisAgentSection({
<BridgeStatusStrip status={bridge} />
- {/* The coupling is non-obvious: subagent providers have no key field of
- their own — they reuse the Brain-provider keys set above. A dim one-line
- hint instead of a loud banner: it informs without competing with the
- cards below. */}
+ {/* Scoped Agent keys are managed here. Older shared Brain keys remain a
+ compatibility fallback and are labelled honestly on the relevant card. */}
<p className="flex items-start gap-2 px-1 text-[11px] leading-relaxed text-muted-foreground">
<ArrowUp className="mt-0.5 h-3 w-3 shrink-0 text-primary" />
<span>
- Agents reuse the keys from the{" "}
- <strong className="text-foreground">Brain</strong> tab. Codex uses the
- ChatGPT login, Antigravity the Google login — connect there, then pick
- which provider runs heavy background tasks.
+ API-backed Agents can use a dedicated key set on this tab. Existing
+ Brain keys remain available as a compatibility fallback; Realtime keys
+ stay isolated to Realtime Voice.
</span>
</p>
@@ -395,8 +400,8 @@ function BridgeMeta({
* noise and is not surfaced.
*/
function BridgeStatusStrip({ status }: { status: SubagentStatus }) {
- const installed = Boolean(status.binary_detected);
- const live = status.enabled && installed;
+ const activeRow = status.mapping.find((row) => row.is_active_brain);
+ const live = Boolean(activeRow?.key_set);
const worker = PROVIDER_LABELS[status.brain_primary] ?? status.brain_primary;
const model = status.model_resolved ?? status.sub_model_override ?? null;
@@ -411,10 +416,10 @@ function BridgeStatusStrip({ status }: { status: SubagentStatus }) {
)}
/>
<span className="text-sm font-medium">
- {live ? "Agent bridge active" : "Agent bridge inactive"}
+ {live ? "Agent provider configured" : "Agent provider needs setup"}
</span>
<span className="text-[11px] text-muted-foreground">
- {installed ? "Engine installed" : "Engine not installed"}
+ {live ? "Credential or subscription available" : "Add a key or connect a login"}
{status.version_pin && (
<>
{" · pin "}
@@ -809,17 +814,40 @@ function CodexConnectionCard({
title="OpenAI Codex"
billing={row?.billing}
active={isActive}
- badge={<StatusPill state={isActive ? "active" : connected ? "ready" : "open"} />}
+ badge={
+ <StatusPill
+ state={
+ isActive
+ ? "active"
+ : connected || (installed && row?.api_key_set)
+ ? "ready"
+ : "open"
+ }
+ />
+ }
subtitle={detail}
warning={
- !installed && <CardHint icon={Terminal}>Install Codex before connecting.</CardHint>
+ <div className="space-y-2" data-agent-card-control>
+ {row?.secret_key && (
+ <ApiKeyForm
+ secretKey={row.secret_key}
+ dashboardUrl={row.dashboard_url}
+ configured={row.dedicated_key_set}
+ credentialHelp={row.credential_help}
+ onChanged={onChanged}
+ />
+ )}
+ {!installed && (
+ <CardHint icon={Terminal}>Install Codex before activating it.</CardHint>
+ )}
+ </div>
}
footer={
<>
{/* When connected, the same "Set active" control as the other
provider cards — so this subscription login is selectable right
here, not only via a duplicate card further down. */}
- {connected && row && (
+ {(connected || (installed && row?.api_key_set)) && row && (
<SubagentActiveControl
row={row}
activating={activating}
@@ -849,13 +877,17 @@ function AntigravityConnectionCard({
const pushToast = useEventStore((s) => s.pushToast);
const [pending, setPending] = useState(false);
const { activating, activate } = useSubagentActivate(row, onChanged);
- const connected = Boolean(status?.connected);
+ const connected = Boolean(status?.connected && status.mode === "oauth-personal");
const installed = status?.installed ?? false;
+ const apiKeyReady = Boolean(row?.api_key_set);
+ const usable = connected || apiKeyReady;
const isActive = Boolean(row?.is_active_brain);
const detail = connected
? status?.user_email
? `Connected as ${status.user_email}`
: status?.message || "Connected"
+ : apiKeyReady
+ ? "Gemini Jarvis-Agent API key ready (billed per token)"
: status?.message || "Google login not connected";
async function connect() {
@@ -896,10 +928,10 @@ function AntigravityConnectionCard({
title="Antigravity"
billing={row?.billing}
active={isActive}
- badge={<StatusPill state={isActive ? "active" : connected ? "ready" : "open"} />}
+ badge={<StatusPill state={isActive ? "active" : usable ? "ready" : "open"} />}
subtitle={detail}
warning={
- !installed && (
+ !installed && !apiKeyReady && (
<CardHint icon={Terminal}>
Install Antigravity or the Gemini CLI before connecting.
</CardHint>
@@ -907,7 +939,7 @@ function AntigravityConnectionCard({
}
footer={
<>
- {connected && row && (
+ {usable && row && (
<SubagentActiveControl
row={row}
activating={activating}
@@ -937,7 +969,7 @@ function ClaudeConnectionCard({
const pushToast = useEventStore((s) => s.pushToast);
const [pending, setPending] = useState(false);
const { activating, activate } = useSubagentActivate(row, onChanged);
- const connected = Boolean(status?.connected);
+ const connected = Boolean(status?.connected && status.mode === "subscription");
const installed = status?.installed ?? false;
// Claude has ONE subagent slug (claude-api) reached by EITHER the Claude Max
// OAuth login OR an Anthropic API key — split into two sibling cards (mirror
@@ -945,7 +977,7 @@ function ClaudeConnectionCard({
// when claude-api is the active worker AND it is running over the OAuth login
// (mode != "api_key"); the API key card owns the api_key mode. So exactly one
// of the two ever shows "active".
- const isActive = Boolean(row?.is_active_brain) && status?.mode !== "api_key";
+ const isActive = Boolean(row?.is_active_brain) && status?.mode === "subscription";
// A subscription login shows the signed-in account + tier ("Connected as
// ruben@… · Claude Max"); not connected shows how to sign in. The API-key
// alternative now lives on its own card below, not here.
@@ -1048,15 +1080,20 @@ function ClaudeApiCard({
onChanged: () => void | Promise<void>;
}) {
const { activating, activate } = useSubagentActivate(row, onChanged);
- // Mirror the other API cards: ready/locked tracks the stored brain key.
- const keySet = Boolean(row?.key_set);
+ // OAuth unlocks the subscription sibling only. This API card reflects an
+ // actual API key, so a Claude Max login cannot paint it falsely ready.
+ const keySet = Boolean(row?.api_key_set);
const isActive = Boolean(row?.is_active_brain) && status?.mode === "api_key";
// Click anywhere on the card activates — except the radio/label (own handler)
// so a single user click never fires activate() twice (mirror of the others).
function handleCardActivate(e: React.MouseEvent<HTMLDivElement>) {
const target = e.target as HTMLElement | null;
- if (target && (target.closest("input") || target.closest("label"))) {
+ if (
+ target?.closest(
+ "input, label, button, a, select, textarea, [data-agent-card-control]",
+ )
+ ) {
return;
}
void activate();
@@ -1071,23 +1108,32 @@ function ClaudeApiCard({
active={isActive}
interactive={keySet && !isActive}
onClick={handleCardActivate}
- onDoubleClick={handleCardActivate}
tooltip={
isActive
? "This Jarvis-Agent provider is active"
: keySet
? "Activate this Jarvis-Agent provider"
- : "Add the Claude API key in the Brain section first"
+ : "Save a dedicated Claude Jarvis-Agent key first"
}
badge={<StatusPill state={isActive ? "active" : keySet ? "ready" : "open"} />}
subtitle="API key · billed per token"
warning={
- !keySet && (
- <CardHint icon={Lock}>
- Locked &mdash; add the <strong>Claude (API-Key)</strong> key in the
- Brain tab to unlock it.
- </CardHint>
- )
+ <div className="space-y-2" data-agent-card-control>
+ {row?.secret_key && (
+ <ApiKeyForm
+ secretKey={row.secret_key}
+ dashboardUrl={row.dashboard_url}
+ configured={row.dedicated_key_set}
+ credentialHelp={row.credential_help}
+ onChanged={onChanged}
+ />
+ )}
+ {!keySet && (
+ <CardHint icon={Lock}>
+ Locked &mdash; save a dedicated <strong>Claude API key</strong> above.
+ </CardHint>
+ )}
+ </div>
}
footer={
row && (
@@ -1126,7 +1172,7 @@ function useSubagentActivate(
? `${label}: connect the ChatGPT login first.`
: row.jarvis === "antigravity"
? `${label}: connect the Google login first.`
- : `${label}: set the API key on the brain provider above first.`,
+ : `${label}: save a key on its Jarvis-Agent card first.`,
);
return;
}
@@ -1179,7 +1225,11 @@ function SubagentProviderCard({
// has its own handler) so a single user click never fires activate() twice.
function handleCardActivate(e: React.MouseEvent<HTMLDivElement>) {
const target = e.target as HTMLElement | null;
- if (target && (target.closest("input") || target.closest("label"))) {
+ if (
+ target?.closest(
+ "[data-agent-card-control], button, a, input, label, textarea, select",
+ )
+ ) {
return;
}
void activate();
@@ -1194,7 +1244,6 @@ function SubagentProviderCard({
active={row.is_active_brain}
interactive={row.key_set && !row.is_active_brain}
onClick={handleCardActivate}
- onDoubleClick={handleCardActivate}
tooltip={
row.is_active_brain
? "This Jarvis-Agent provider is active"
@@ -1207,28 +1256,30 @@ function SubagentProviderCard({
state={row.is_active_brain ? "active" : row.key_set ? "ready" : "open"}
/>
}
- subtitle="Reuses the matching key from the Brain tab"
+ subtitle={
+ row.dedicated_key_set
+ ? "Dedicated Jarvis-Agent key configured"
+ : row.shared_key_set
+ ? "Using the shared Brain key as a compatibility fallback"
+ : "Set a dedicated key for this Jarvis-Agent"
+ }
warning={
- !row.key_set && (
- <CardHint icon={Lock}>
- {row.jarvis === "openai-codex" ? (
- <>
- Locked &mdash; connect <strong>{label}</strong> with ChatGPT above
- to unlock it.
- </>
- ) : row.jarvis === "antigravity" ? (
- <>
- Locked &mdash; connect <strong>{label}</strong> with Google above
- to unlock it.
- </>
- ) : (
- <>
- Locked &mdash; add the <strong>{label}</strong> key in the Brain
- tab to unlock it.
- </>
- )}
- </CardHint>
- )
+ <div className="space-y-2" data-agent-card-control>
+ {row.secret_key && (
+ <ApiKeyForm
+ secretKey={row.secret_key}
+ dashboardUrl={row.dashboard_url}
+ configured={row.dedicated_key_set}
+ credentialHelp={row.credential_help}
+ onChanged={onSwitched}
+ />
+ )}
+ {!row.key_set && (
+ <CardHint icon={Lock}>
+ Locked &mdash; save a dedicated <strong>{label}</strong> key on this card.
+ </CardHint>
+ )}
+ </div>
}
footer={
<SubagentActiveControl
diff --git a/tests/integration/test_jarvis_agent_active_brain.py b/tests/integration/test_jarvis_agent_active_brain.py
index 21c5d3d06b..6830a7c66c 100644
--- a/tests/integration/test_jarvis_agent_active_brain.py
+++ b/tests/integration/test_jarvis_agent_active_brain.py
@@ -154,6 +154,75 @@ def test_subagent_switch_409_when_no_key(monkeypatch: pytest.MonkeyPatch) -> Non
assert persisted == [], "must not persist a provider that has no key"
+def test_realtime_only_key_does_not_unlock_jarvis_agent(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A key saved on Realtime must remain invisible to Jarvis-Agents."""
+ import jarvis.core.config as cfg_mod
+ import jarvis.core.config_writer as config_writer
+
+ monkeypatch.setattr(
+ cfg_mod,
+ "get_secret",
+ lambda key, *args, **kwargs: (
+ "realtime-only" if key == "realtime_openai_api_key" else None
+ ),
+ )
+ monkeypatch.setattr(config_writer, "set_worker_provider", lambda name: None)
+
+ cfg = load_config()
+ client = _client(cfg)
+ response = client.post(
+ "/api/jarvis-agent/switch",
+ json={"provider": "openai", "persist": True},
+ )
+
+ assert response.status_code == 409
+ row = next(
+ item
+ for item in client.get("/api/jarvis-agent/status").json()["mapping"]
+ if item["jarvis"] == "openai"
+ )
+ assert row["key_set"] is False
+ assert row["dedicated_key_set"] is False
+ assert row["credential_source"] == "none"
+
+
+def test_dedicated_jarvis_agent_key_unlocks_provider_without_brain_key(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import jarvis.core.config as cfg_mod
+ import jarvis.core.config_writer as config_writer
+
+ monkeypatch.setattr(
+ cfg_mod,
+ "get_secret",
+ lambda key, *args, **kwargs: (
+ "agent-only" if key == "jarvis_agent_openai_api_key" else None
+ ),
+ )
+ monkeypatch.setattr(config_writer, "set_worker_provider", lambda name: None)
+
+ cfg = load_config()
+ client = _client(cfg)
+ response = client.post(
+ "/api/jarvis-agent/switch",
+ json={"provider": "openai", "persist": True},
+ )
+
+ assert response.status_code == 200
+ row = next(
+ item
+ for item in client.get("/api/jarvis-agent/status").json()["mapping"]
+ if item["jarvis"] == "openai"
+ )
+ assert row["key_set"] is True
+ assert row["dedicated_key_set"] is True
+ assert row["shared_key_set"] is False
+ assert row["secret_key"] == "jarvis_agent_openai_api_key"
+ assert row["credential_source"] == "dedicated"
+
+
def test_subagent_switch_updates_status_endpoint(monkeypatch: pytest.MonkeyPatch) -> None:
"""After a switch, /api/jarvis-agent/status reflects the new active provider."""
import jarvis.core.config as cfg_mod
@@ -224,7 +293,11 @@ def test_subagent_switch_accepts_codex_oauth(monkeypatch: pytest.MonkeyPatch) ->
import jarvis.core.config as cfg_mod
import jarvis.core.config_writer as config_writer
- monkeypatch.setattr(cfg_mod, "get_provider_secret", lambda _p: None)
+ monkeypatch.setattr(
+ cfg_mod,
+ "get_provider_secret",
+ lambda provider: "AIza-fake" if provider == "gemini" else None,
+ )
monkeypatch.setattr(cfg_mod, "get_secret", lambda *_a, **_k: None)
_patch_codex(monkeypatch, connected=True)
calls: list[str] = []
diff --git a/tests/missions/workers/test_api_agent_worker.py b/tests/missions/workers/test_api_agent_worker.py
index c6481db10d..9f19f427b0 100644
--- a/tests/missions/workers/test_api_agent_worker.py
+++ b/tests/missions/workers/test_api_agent_worker.py
@@ -114,6 +114,52 @@ async def test_worker_writes_file_and_emits_critic_readable_stream(
assert "out.txt" in extract_write_targets(stream_text)
+async def test_worker_provider_call_uses_scoped_agent_key(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ from jarvis.core import config as cfg
+
+ observed: list[str | None] = []
+
+ class _CredentialReadingBrain:
+ def can_call_tools(self) -> bool:
+ return True
+
+ async def complete(self, req): # noqa: ANN001, ANN201
+ observed.append(cfg.get_provider_secret("openai"))
+ yield BrainDelta(content="done")
+
+ monkeypatch.setattr(
+ cfg,
+ "get_secret",
+ lambda key, *args, **kwargs: {
+ "jarvis_agent_openai_api_key": "agent-key",
+ "openai_api_key": "brain-key",
+ "realtime_openai_api_key": "realtime-key",
+ }.get(key),
+ )
+ monkeypatch.setattr(
+ "jarvis.missions.workers.api_agent_worker._build_brain",
+ lambda provider, model: _CredentialReadingBrain(),
+ )
+
+ events = await _drain(
+ ApiAgentWorker("openai"),
+ prompt="t",
+ worktree=tmp_path,
+ env={},
+ job=None,
+ worker_id="m::0",
+ log_dir=tmp_path / "_logs",
+ model="gpt-5.5",
+ )
+
+ assert events[-1].is_error is False
+ assert observed == ["agent-key"]
+ assert cfg.get_provider_secret("openai") == "brain-key"
+
+
@pytest.mark.asyncio
async def test_worker_run_command_is_async_and_mission_contained(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
diff --git a/tests/missions/workers/test_google_cli_worker.py b/tests/missions/workers/test_google_cli_worker.py
index 4ed934aca3..4ee3253de8 100644
--- a/tests/missions/workers/test_google_cli_worker.py
+++ b/tests/missions/workers/test_google_cli_worker.py
@@ -9,6 +9,7 @@ from __future__ import annotations
import pytest
+import jarvis.missions.workers.api_agent_worker as api_worker_mod
import jarvis.missions.workers.google_cli_worker as mod
from jarvis.google_cli.pty_runner import PtyRunResult
from jarvis.google_cli.resolver import GoogleCli
@@ -157,7 +158,7 @@ async def test_spawn_agy_with_gemini_key_but_no_oauth_bills_via_gemini(
) -> None:
"""Antigravity dual billing: agy is installed, but the user has NO Google
OAuth login and a Gemini API key IS set → bill per token via the proven
- GeminiWorker, NOT the agy PTY path (which would coerce OAuth)."""
+ API worker, not the agy PTY path (which would coerce OAuth)."""
monkeypatch.setattr(
mod, "resolve_google_cli", lambda: GoogleCli(kind="agy", argv_prefix=["agy.exe"])
)
@@ -169,7 +170,7 @@ async def test_spawn_agy_with_gemini_key_but_no_oauth_bills_via_gemini(
called["gemini"] = True
yield "GEMINI_EVENT"
- monkeypatch.setattr(mod.GeminiWorker, "spawn", _fake_gemini_spawn)
+ monkeypatch.setattr(api_worker_mod.ApiAgentWorker, "spawn", _fake_gemini_spawn)
# run_cli_over_pty must NOT be called on this path — make it explode if it is.
monkeypatch.setattr(
mod, "run_cli_over_pty",
diff --git a/tests/unit/brain/test_gemini_stale_cache_bug019.py b/tests/unit/brain/test_gemini_stale_cache_bug019.py
index ae9ee5c74a..62df00f867 100644
--- a/tests/unit/brain/test_gemini_stale_cache_bug019.py
+++ b/tests/unit/brain/test_gemini_stale_cache_bug019.py
@@ -294,3 +294,51 @@ async def test_automatic_function_calling_is_disabled() -> None:
"automatic_function_calling not set — Gemini will run its own tool loop"
)
assert getattr(afc, "disable", None) is True
+
+
+class _CumulativeUsageClient:
+ """Gemini repeats cumulative usage snapshots on multiple stream chunks."""
+
+ def __init__(self) -> None:
+ self.aio = SimpleNamespace(models=self)
+
+ async def generate_content_stream(
+ self,
+ *,
+ model: str,
+ contents: list[Any],
+ config: dict[str, Any],
+ ) -> AsyncIterator[Any]:
+ async def _stream() -> AsyncIterator[Any]:
+ for text, output_tokens in (("One", 1), (" two", 2), (" three", 3)):
+ yield SimpleNamespace(
+ text=text,
+ candidates=[],
+ usage_metadata=SimpleNamespace(
+ prompt_token_count=100,
+ candidates_token_count=output_tokens,
+ cached_content_token_count=40,
+ thoughts_token_count=7,
+ tool_use_prompt_token_count=5,
+ ),
+ )
+
+ return _stream()
+
+
+async def test_cumulative_stream_usage_is_emitted_once_from_final_snapshot() -> None:
+ provider = GeminiBrain(model="gemini-3-flash-preview")
+ provider._client = _CumulativeUsageClient() # type: ignore[assignment]
+ req = BrainRequest(messages=(BrainMessage(role="user", content="ping"),))
+
+ deltas = await _drain(provider.complete(req))
+ usage = [delta.usage for delta in deltas if delta.usage]
+
+ assert usage == [
+ {
+ "input_tokens": 65,
+ "output_tokens": 10,
+ "cache_hit_tokens": 40,
+ }
+ ]
diff --git a/tests/unit/brain/test_leaked_spawn_recovery.py b/tests/unit/brain/test_leaked_spawn_recovery.py
index e029d9e0fb..0860fe0f55 100644
--- a/tests/unit/brain/test_leaked_spawn_recovery.py
+++ b/tests/unit/brain/test_leaked_spawn_recovery.py
@@ -46,11 +46,11 @@ def test_extract_detects_leaked_spawn_variants() -> None:
'```json\n[{"type":"tool_use","name":"spawn_worker",'
'"input":{"action":"y"}}]\n```'
) == {"action": "y"}
- # Prose-wrapped.
+ # Quoted/example JSON inside prose is not an executable provider envelope.
assert _extract_leaked_spawn_call(
'Klar! {"type":"tool_use","name":"spawn_worker",'
'"input":{"target":"z"}} erledige ich.'
- ) == {"target": "z"}
+ ) is None
def test_extract_ignores_normal_text_and_other_tools() -> None:
@@ -98,6 +98,7 @@ async def test_recover_executes_leaked_spawn_and_returns_ack() -> None:
leaked,
user_text="erstelle mir eine Datei test-opus.md",
trace_id=uuid4(),
+ allowed_tools=mgr._tools,
)
assert out == "Mach ich, ich kümmere mich im Hintergrund darum." # i18n-allow
# The leaked utterance is forwarded to the spawn tool.
@@ -113,6 +114,7 @@ async def test_recover_returns_none_for_normal_response() -> None:
"Alles erledigt, ich habe das im Hintergrund übernommen.", # i18n-allow
user_text="erstelle mir eine Datei",
trace_id=uuid4(),
+ allowed_tools=mgr._tools,
)
assert out is None
assert "args" not in captured # executor never called
@@ -191,6 +193,68 @@ def test_render_recovered_tool_output_never_emits_brace_prefixed_repr() -> None:
assert not _looks_like_tool_use_leak(rendered)
+def test_render_recovered_tool_output_preserves_safe_message_fields() -> None:
+ """A successful connector result must not collapse into "nothing found"."""
+ rendered = _render_recovered_tool_output(
+ {
+ "id": "message-id-must-not-be-spoken",
+ "threadId": "thread-id-must-not-be-spoken",
+ "from": "[email protected]",
+ "subject": "Important account notice",
+ "date": "2026-07-15 10:45",
+ "snippet": "Please review the attached account notice.",
+ "body": "A very long private body that is intentionally omitted.",
+ }
+ )
+
+ assert "[email protected]" in rendered
+ assert "Important account notice" in rendered
+ assert "2026-07-15" in rendered
+ assert "Please review" not in rendered
+ assert "message-id-must-not-be-spoken" not in rendered
+ assert "very long private body" not in rendered
+ assert not _looks_like_tool_use_leak(rendered)
+
+
+def test_render_recovered_tool_output_fails_closed_for_unknown_private_fields() -> None:
+ rendered = _render_recovered_tool_output(
+ {
+ "messageId": "opaque-message-id",
+ "nextPageToken": "opaque-page-token",
+ "content": "FULL PRIVATE MESSAGE BODY",
+ "resultSizeEstimate": 201,
+ }
+ )
+
+ assert rendered == ""
+ assert _render_recovered_tool_output(
+ {"content": "FULL PRIVATE MESSAGE BODY"}
+ ) == ""
+
+
[email protected]("key", ["text", "answer", "message", "result"])
+def test_render_recovered_tool_output_keeps_compact_answer_fields(key: str) -> None:
+ assert _render_recovered_tool_output({key: "Connected tool answer."}) == (
+ "Connected tool answer."
+ )
+
+
+def test_render_recovered_output_redacts_credentials_and_caps_every_branch() -> None:
+ secret = "sk-" + "A" * 32
+
+ for output in (
+ f"answer {secret}",
+ {"subject": f"notice {secret}"},
+ {"results": [{"title": "Result", "snippet": f"value {secret}"}]},
+ {"exit_code": 0, "stdout": f"value {secret}" + "x" * 1_000},
+ {"answer": f"value {secret}"},
+ ):
+ rendered = _render_recovered_tool_output(output)
+ assert secret not in rendered
+ assert "<redacted:" in rendered
+ assert len(rendered) <= 600
+
+
@pytest.mark.asyncio
async def test_recover_leaked_search_web_speaks_answer_not_failure_phrase() -> None:
captured: dict = {}
@@ -201,6 +265,7 @@ async def test_recover_leaked_search_web_speaks_answer_not_failure_phrase() -> N
)
out = await mgr._recover_leaked_tool(
leaked, user_text="Was hältst du von exp.com?", trace_id=uuid4(), # i18n-allow
+ allowed_tools=mgr._tools,
)
# The search actually ran with the leaked query.
assert captured["args"]["query"] == "exp.com"
@@ -220,6 +285,7 @@ async def test_recover_leaked_search_web_empty_results_is_spoken_fallback() -> N
leaked = '{"type":"tool_use","name":"search_web","input":{"query":"zzz"}}'
out = await mgr._recover_leaked_tool(
leaked, user_text="Was hältst du von zzz?", trace_id=uuid4(), # i18n-allow
+ allowed_tools=mgr._tools,
)
assert out is not None
assert not any(frag in out.lower() for frag in _FAILURE_FRAGMENTS)
@@ -227,6 +293,26 @@ async def test_recover_leaked_search_web_empty_results_is_spoken_fallback() -> N
assert out.strip() # a real spoken sentence, never silence
+async def test_legacy_recovery_cannot_escape_turn_scoped_tool_surface() -> None:
+ captured: dict = {}
+ mgr = _manager_with_fake_tool(captured, name="search_web", output=_SEARCH_OUTPUT)
+ leaked = (
+ '{"type":"tool_use","name":"search_web",'
+ '"input":{"query":"exp.com"}}'
+ )
+
+ out = await mgr._recover_leaked_tool(
+ leaked,
+ user_text="Read the result.",
+ trace_id=uuid4(),
+ allowed_tools={},
+ )
+
+ assert out is None
+ assert "args" not in captured
+
+
# ---------------------------------------------------------------------------
# Leaked CLI-tool (cli_<name>) recovery (live repro 2026-06-17).
#
@@ -312,6 +398,7 @@ async def test_recover_leaked_cli_success_speaks_stdout_not_nothing_found() -> N
)
out = await mgr._recover_leaked_tool(
leaked, user_text="nutze die Google Cloud CLI", trace_id=uuid4(),
+ allowed_tools=mgr._tools,
)
assert out is not None
assert "n8n-wf-demo-611441" in out
@@ -339,6 +426,7 @@ async def test_recover_leaked_cli_failure_speaks_stderr_cause_not_bare_exit() ->
)
out = await mgr._recover_leaked_tool(
leaked, user_text="wie viel Geld habe ich noch", trace_id=uuid4(),
+ allowed_tools=mgr._tools,
)
assert out is not None
# Honest cause from stderr is surfaced (the API-disabled / permission line).
diff --git a/tests/unit/brain/test_output_filter.py b/tests/unit/brain/test_output_filter.py
index 43c7883afd..711ff95ce6 100644
--- a/tests/unit/brain/test_output_filter.py
+++ b/tests/unit/brain/test_output_filter.py
@@ -446,6 +446,14 @@ def test_sub_agent_jargon_is_removed() -> None:
assert "removed_engineering_jargon" in result.actions
+def test_official_jarvis_agent_label_is_preserved() -> None:
+ """The public product label is not the retired generic engineering term."""
+ text = "Ein Jarvis-Agent prüft das gründlich und meldet sich."
+ result = scrub_for_voice(text, language="de", ack_mode=True)
+ assert result.cleaned == text
+ assert "removed_engineering_jargon" not in result.actions
+
+
def test_supervisor_agent_jargon_is_removed() -> None:
"""'Supervisor-Agent' as an engineering reveal is removed — probe drift 13."""
text = "Dein persoenlicher Supervisor-Agent erledigt das." # i18n-allow
diff --git a/tests/unit/brain/test_skill_routing_guard.py b/tests/unit/brain/test_skill_routing_guard.py
index d4882d3d02..c066b4a778 100644
--- a/tests/unit/brain/test_skill_routing_guard.py
+++ b/tests/unit/brain/test_skill_routing_guard.py
@@ -19,7 +19,7 @@ import pytest
from jarvis.brain.manager import BrainManager
from jarvis.core.bus import EventBus
from jarvis.core.config import JarvisConfig
-from jarvis.core.protocols import ToolResult
+from jarvis.core.protocols import BrainMessage, ToolResult
from jarvis.skills.registry import SkillRegistry
from jarvis.skills.skill_context import SkillContext, set_skill_context
@@ -39,6 +39,12 @@ class _FakeScreenshotTool:
schema: dict[str, Any] = {}
+class _FakeStreamlineTool:
+ name = "streamline/query"
+ description = "Read the latest Streamline item."
+ schema: dict[str, Any] = {}
+
+
class _RecordingExecutor:
def __init__(self) -> None:
self.calls: list[tuple[Any, dict[str, Any], str]] = []
@@ -270,9 +276,14 @@ class _SpawnPathProbeManager(BrainManager):
) -> str | None:
return None
+ def _check_unsupported_intent(self, user_text: str) -> str | None:
+ return None
+
async def _force_spawn_worker(
self, user_text: str, *, trace_id: Any = None, source_layer: Any = None
) -> str | None:
+ if not self._should_force_spawn(user_text, source_layer=source_layer):
+ return None
self.spawn_calls.append(user_text)
return "SPAWN_SENTINEL"
@@ -280,6 +291,26 @@ class _SpawnPathProbeManager(BrainManager):
return [] # force the provider-down exit — no LLM in unit tests
+class _ConcurrentSkillProbeManager(_SpawnPathProbeManager):
+ """Pause two skill turns after matching to expose cross-task state leaks."""
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ super().__init__(*args, **kwargs)
+ self._arrived = 0
+ self._both_arrived = asyncio.Event()
+
+ async def _maybe_dispatch_skill_mission(
+ self, user_text: str, *, trace_id: Any = None
+ ) -> str | None:
+ self._arrived += 1
+ if self._arrived >= 2:
+ self._both_arrived.set()
+ await self._both_arrived.wait()
+ skill = self._skill_turn_match
+ assert skill is not None
+ return f"{skill.name}:{self._skill_turn_source}"
+
+
async def test_generate_drops_skill_match_on_explicit_spawn_trigger(
tmp_path: Path,
) -> None:
@@ -306,6 +337,241 @@ async def test_generate_drops_skill_match_on_explicit_spawn_trigger(
assert len(m.spawn_calls) == 1
+async def test_realtime_history_keeps_plugin_skill_on_referential_follow_up(
+ tmp_path: Path,
+) -> None:
+ """The exact forensic follow-up remains on the connected Gmail surface."""
+ _write_skill(tmp_path, "plugin-gmail", "(gmail)")
+ registry = SkillRegistry(root=tmp_path)
+ registry.reload_sync()
+ set_skill_context(
+ SkillContext(registry=registry, runner=_StubRunner()) # type: ignore[arg-type]
+ )
+ executor = _RecordingExecutor()
+ manager = _SpawnPathProbeManager(
+ config=JarvisConfig(),
+ bus=EventBus(),
+ tools={"spawn_worker": _FakeSpawnTool(), "run-skill": _FakeRunSkillTool()},
+ tool_executor=executor, # type: ignore[arg-type]
+ )
+ history = (
+ BrainMessage(
+ role="user",
+ content=(
+ "Kannst du bitte mein Gmail Plugin benutzen und sagen, welche "
+ "wichtigen Mails anstehen?" # i18n-allow: German forensic speech-input fixture
+ ),
+ ),
+ BrainMessage(role="assistant", content="I did not find anything."),
+ )
+
+ follow_up = "Wo liegt es? Ich habe es auch als Plugin installiert." # i18n-allow
+ reply = await manager.generate(
+ follow_up,
+ use_history=False,
+ history_override=history,
+ )
+
+ assert reply != "SPAWN_SENTINEL"
+ assert manager.spawn_calls == []
+ assert manager._skill_turn_match is not None
+ assert manager._skill_turn_match.name == "plugin-gmail"
+ assert manager._skill_turn_source == "continuation"
+
+
+async def test_realtime_follow_up_preserves_anchored_plugin_skill(
+ tmp_path: Path,
+) -> None:
+ """An exact trigger remains authoritative for a referential next turn."""
+ _write_skill(tmp_path, "plugin-gmail", "^check gmail$")
+ registry = SkillRegistry(root=tmp_path)
+ registry.reload_sync()
+ set_skill_context(
+ SkillContext(registry=registry, runner=_StubRunner()) # type: ignore[arg-type]
+ )
+ manager = _SpawnPathProbeManager(
+ config=JarvisConfig(),
+ bus=EventBus(),
+ tools={"spawn_worker": _FakeSpawnTool(), "run-skill": _FakeRunSkillTool()},
+ tool_executor=_RecordingExecutor(), # type: ignore[arg-type]
+ )
+ history = (
+ BrainMessage(role="user", content="check gmail"),
+ BrainMessage(role="assistant", content="The lookup did not finish."),
+ )
+
+ reply = await manager.generate(
+ "Where is it? I installed it as a plugin.",
+ use_history=False,
+ history_override=history,
+ )
+
+ assert reply != "SPAWN_SENTINEL"
+ assert manager.spawn_calls == []
+ assert manager._skill_turn_match is not None
+ assert manager._skill_turn_match.name == "plugin-gmail"
+ assert manager._skill_turn_source == "continuation"
+
+
+ "follow_up",
+ [
+ "Don't spawn a worker; where is it? It is installed as a plugin.",
+ "Where is it, and why did auto-spawn run for this plugin?",
+ ],
+)
+async def test_spawn_decline_or_feature_discussion_keeps_contextual_skill(
+ tmp_path: Path,
+ follow_up: str,
+) -> None:
+ _seed_plugin_skill(tmp_path, "plugin-gmail", "(gmail)")
+ manager = _SpawnPathProbeManager(
+ config=JarvisConfig(),
+ bus=EventBus(),
+ tools={"spawn_worker": _FakeSpawnTool(), "run-skill": _FakeRunSkillTool()},
+ tool_executor=_RecordingExecutor(), # type: ignore[arg-type]
+ )
+ history = (
+ BrainMessage(role="user", content="Please check my Gmail plugin."),
+ BrainMessage(role="assistant", content="The lookup did not finish."),
+ )
+
+ reply = await manager.generate(
+ follow_up,
+ use_history=False,
+ history_override=history,
+ )
+
+ assert reply != "SPAWN_SENTINEL"
+ assert manager.spawn_calls == []
+ assert manager._skill_turn_match is not None
+ assert manager._skill_turn_match.name == "plugin-gmail"
+
+
+async def test_explicit_spawn_still_overrides_contextual_skill(tmp_path: Path) -> None:
+ _seed_plugin_skill(tmp_path, "plugin-gmail", "(gmail)")
+ manager = _SpawnPathProbeManager(
+ config=JarvisConfig(),
+ bus=EventBus(),
+ tools={"spawn_worker": _FakeSpawnTool(), "run-skill": _FakeRunSkillTool()},
+ tool_executor=_RecordingExecutor(), # type: ignore[arg-type]
+ )
+ history = (
+ BrainMessage(role="user", content="Please check my Gmail plugin."),
+ BrainMessage(role="assistant", content="The lookup did not finish."),
+ )
+ follow_up = "Spawn a worker to investigate it; where is it?"
+
+ reply = await manager.generate(
+ follow_up,
+ use_history=False,
+ history_override=history,
+ )
+
+ assert reply == "SPAWN_SENTINEL"
+ assert manager._skill_turn_match is None
+ assert manager.spawn_calls == [follow_up]
+
+
+async def test_concurrent_realtime_turns_keep_skill_state_task_local(
+ tmp_path: Path,
+) -> None:
+ _write_skill(tmp_path, "plugin-gmail", "(gmail)")
+ _write_skill(tmp_path, "plugin-streamline", "(streamline)")
+ registry = SkillRegistry(root=tmp_path)
+ registry.reload_sync()
+ set_skill_context(
+ SkillContext(registry=registry, runner=_StubRunner()) # type: ignore[arg-type]
+ )
+ manager = _ConcurrentSkillProbeManager(
+ config=JarvisConfig(),
+ bus=EventBus(),
+ tools={"spawn_worker": _FakeSpawnTool(), "run-skill": _FakeRunSkillTool()},
+ tool_executor=_RecordingExecutor(), # type: ignore[arg-type]
+ )
+ gmail_history = (
+ BrainMessage(role="user", content="Please check my Gmail plugin."),
+ BrainMessage(role="assistant", content="The lookup did not finish."),
+ )
+
+ gmail_result, streamline_result = await asyncio.gather(
+ manager.generate(
+ "Where is it? I installed it as a plugin.",
+ use_history=False,
+ history_override=gmail_history,
+ ),
+ manager.generate("Run Streamline.", use_history=False),
+ )
+
+ assert gmail_result == "plugin-gmail:continuation"
+ assert streamline_result == "plugin-streamline:match"
+
+
+async def test_realtime_history_keeps_cardless_namespaced_tool_inline() -> None:
+ """A cardless plugin/MCP remains visible and cannot be replaced by a mission."""
+ config = JarvisConfig()
+ config.brain.routing.force_spawn_mode = "permissive"
+ executor = _RecordingExecutor()
+ manager = _SpawnPathProbeManager(
+ config=config,
+ bus=EventBus(),
+ tools={
+ "spawn_worker": _FakeSpawnTool(),
+ "run-skill": _FakeRunSkillTool(),
+ "streamline/query": _FakeStreamlineTool(),
+ },
+ tool_executor=executor, # type: ignore[arg-type]
+ )
+ history = (
+ BrainMessage(
+ role="user",
+ content="Use Streamline to create a ticket for the incident.",
+ ),
+ BrainMessage(role="assistant", content="The lookup did not finish."),
+ )
+ manager._history = list(history)
+ follow_up = "Where is it? Please check it again; it is installed as a plugin."
+
+ routing_text, live_tools = manager._contextual_routing_state(
+ follow_up, use_history=True,
+ )
+ assert live_tools == ("streamline/query",)
+ relevant_tools = manager._apply_plugin_relevance(routing_text, manager._tools)
+ assert "streamline/query" in relevant_tools
+
+ reply = await manager.generate(
+ follow_up,
+ use_history=False,
+ history_override=history,
+ )
+
+ assert reply != "SPAWN_SENTINEL"
+ assert manager.spawn_calls == []
+
+
+def test_unrelated_current_question_does_not_replay_prior_plugin_skill(
+ tmp_path: Path,
+) -> None:
+ _seed_plugin_skill(tmp_path, "plugin-gmail", "(gmail)")
+ manager = _make_manager()
+ manager._history = [
+ BrainMessage(
+ role="user",
+ content="Please list the important messages in my Gmail inbox.",
+ ),
+ BrainMessage(role="assistant", content="The Gmail lookup finished."),
+ ]
+ current = "What's my current weather?"
+
+ routing_text, live_tools = manager._contextual_routing_state(
+ current, use_history=True,
+ )
+
+ assert routing_text == current
+ assert live_tools == ()
+ assert manager._match_skill_for_turn(routing_text) is None
+
+
# ----------------------------------------------------------------------
# AD-S3 ordering: a skill match must bypass the local-action fast path
# (is_open_app_intent grabs "starte die Morgenroutine" otherwise)
diff --git a/tests/unit/brain/test_spawn_announcement.py b/tests/unit/brain/test_spawn_announcement.py
index a66add49f1..1cfafe7f2c 100644
--- a/tests/unit/brain/test_spawn_announcement.py
+++ b/tests/unit/brain/test_spawn_announcement.py
@@ -8,8 +8,9 @@ with a dedicated delegation persona) and only then falls back to a small
bilingual no-repeat pool. Guarantees under test:
* never raises, never returns an empty string (AD-OE6 zero silent drops)
-* candidate/LLM output is validated: short, right language, no completion
- claims, no internal component names, voice-scrubbed
+* candidate/LLM output is validated: short, right language, the public
+ ``Jarvis-Agent`` label is explicit, no completion claims, no internal
+ component names, voice-scrubbed
* de + en both work; the language follows the user's turn
* the fallback pool never repeats the same phrase back-to-back
"""
@@ -182,6 +183,18 @@ def test_pool_phrases_pass_own_validation_and_ban_old_template() -> None:
assert "vom User beschriebenen Workflow" not in phrase
+def test_agent_status_pools_name_jarvis_agent_exactly_once() -> None:
+ """Spawn and duplicate-status fallbacks must identify the delegated actor.
+
+ The phrasing may rotate freely, but it must never leave the user guessing
+ whether Jarvis is merely thinking or has started a background agent.
+ """
+ for pool_by_language in (_FALLBACK_SPAWN, _FALLBACK_ALREADY_RUNNING):
+ for pool in pool_by_language.values():
+ for phrase in pool:
+ assert phrase.lower().count("jarvis-agent") == 1, phrase
+
+
def test_es_pools_survive_voice_scrubbing() -> None:
"""The Spanish pools are returned deterministically (never through
``_validate`` — ``_detect_language`` only knows de/en/unknown), so guard the
@@ -229,7 +242,7 @@ _SUBSTANCE_CUES: dict[str, tuple[str, ...]] = {
),
"es": (
"más grande", "momento", "chicha", "más de trabajo", "poco de tiempo",
- "a fondo", "algo más", "momentito", "buen vistazo", "sólido",
+ "a fondo", "algo más", "más amplio", "momentito", "buen vistazo", "sólido",
),
}
@@ -267,7 +280,7 @@ def test_still_running_phrases_cover_all_languages() -> None:
@pytest.mark.asyncio
async def test_provider_text_is_used_when_valid() -> None:
provider = _FakeProvider(
- reply="Ich schaue gleich in dein Gmail und sage dir Bescheid."
+ reply="Ein Jarvis-Agent schaut gleich in dein Gmail und sagt dir Bescheid."
)
composer = _composer(provider)
out = await composer.compose(
@@ -281,7 +294,7 @@ async def test_provider_text_is_used_when_valid() -> None:
@pytest.mark.asyncio
async def test_provider_gets_de_persona_for_german_turn() -> None:
"""Language unset → composer detects German from the utterance."""
- provider = _FakeProvider(reply="Ich schaue gleich in dein Gmail rein.")
+ provider = _FakeProvider(reply="Ein Jarvis-Agent schaut gleich in dein Gmail rein.")
composer = _composer(provider)
await composer.compose(
utterance="Schau bitte nach, ob die Rechnung schon da ist und was drinsteht."
@@ -291,7 +304,9 @@ async def test_provider_gets_de_persona_for_german_turn() -> None:
@pytest.mark.asyncio
async def test_provider_gets_en_persona_for_english_turn() -> None:
- provider = _FakeProvider(reply="Checking your Gmail in the background now.")
+ provider = _FakeProvider(
+ reply="A Jarvis-Agent is checking your Gmail in the background now."
+ )
composer = _composer(provider)
await composer.compose(
utterance="Check my Gmail for new mail.", language="en"
@@ -301,7 +316,9 @@ async def test_provider_gets_en_persona_for_english_turn() -> None:
@pytest.mark.asyncio
async def test_provider_content_includes_interpreted_action() -> None:
- provider = _FakeProvider(reply="Ich prüfe gleich deine Gmail-Inbox.")
+ provider = _FakeProvider(
+ reply="Ein Jarvis-Agent prüft gleich deine Gmail-Inbox."
+ )
composer = _composer(provider)
await composer.compose(
utterance="Schau da bitte mal rein.",
@@ -349,13 +366,13 @@ async def test_overlong_reply_is_trimmed_to_leading_sentences() -> None:
"""Two sentences, the second pushing past the word cap: keep sentence 1."""
long_tail = " ".join(["und"] * 30)
provider = _FakeProvider(
- reply=f"Ich schaue kurz in dein Gmail. Danach {long_tail}."
+ reply=f"Ein Jarvis-Agent schaut kurz in dein Gmail. Danach {long_tail}."
)
composer = _composer(provider)
out = await composer.compose(
utterance="Schau in mein Gmail.", language="de"
)
- assert out == "Ich schaue kurz in dein Gmail."
+ assert out == "Ein Jarvis-Agent schaut kurz in dein Gmail."
@pytest.mark.asyncio
@@ -457,7 +474,7 @@ async def test_fallback_provider_used_when_primary_exhausted() -> None:
announcement to a generic stock line."""
primary = _FakeProvider(reply=None)
fallback = _FakeProvider(
- reply="Ich gebe das Thema Gmail gerade an meinen Helfer weiter."
+ reply="Ein Jarvis-Agent übernimmt gerade das Thema Gmail."
)
composer = _composer_with_fallback(primary, fallback)
out = await composer.compose(
@@ -472,35 +489,41 @@ async def test_fallback_provider_used_when_primary_exhausted() -> None:
@pytest.mark.asyncio
async def test_fallback_provider_used_when_primary_errors() -> None:
primary = _FakeProvider(raises=True)
- fallback = _FakeProvider(reply="Ich kümmere mich gleich um dein Gmail.")
+ fallback = _FakeProvider(
+ reply="Ein Jarvis-Agent kümmert sich gleich um dein Gmail."
+ )
composer = _composer_with_fallback(primary, fallback)
out = await composer.compose(
utterance="Schau in mein Gmail.", language="de"
)
- assert out == "Ich kümmere mich gleich um dein Gmail."
+ assert out == "Ein Jarvis-Agent kümmert sich gleich um dein Gmail."
assert len(fallback.calls) == 1
@pytest.mark.asyncio
async def test_fallback_provider_used_when_primary_times_out() -> None:
primary = _FakeProvider(reply="Ich schaue in dein Gmail.", delay_s=0.5)
- fallback = _FakeProvider(reply="Ich nehme mir dein Gmail gleich vor.")
+ fallback = _FakeProvider(
+ reply="Ein Jarvis-Agent nimmt sich dein Gmail gleich vor."
+ )
composer = _composer_with_fallback(primary, fallback, timeout_ms=100)
out = await composer.compose(
utterance="Schau in mein Gmail.", language="de"
)
- assert out == "Ich nehme mir dein Gmail gleich vor."
+ assert out == "Ein Jarvis-Agent nimmt sich dein Gmail gleich vor."
@pytest.mark.asyncio
async def test_primary_success_skips_fallback() -> None:
- primary = _FakeProvider(reply="Ich schaue gleich in dein Gmail.")
+ primary = _FakeProvider(
+ reply="Ein Jarvis-Agent schaut gleich in dein Gmail."
+ )
fallback = _FakeProvider(reply="should never be reached")
composer = _composer_with_fallback(primary, fallback)
out = await composer.compose(
utterance="Schau in mein Gmail.", language="de"
)
- assert out == "Ich schaue gleich in dein Gmail."
+ assert out == "Ein Jarvis-Agent schaut gleich in dein Gmail."
assert fallback.calls == []
@@ -522,7 +545,9 @@ async def test_open_primary_breaker_still_consults_fallback() -> None:
"""An open primary breaker (dead provider already tripped it) must not kill
the context-aware path — the failover is still consulted before the pool."""
primary = _FakeProvider(reply="primary text")
- fallback = _FakeProvider(reply="Ich nehme mir dein Gmail gleich vor.")
+ fallback = _FakeProvider(
+ reply="Ein Jarvis-Agent nimmt sich dein Gmail gleich vor."
+ )
primary_breaker = CircuitBreaker(threshold=1, cooldown_s=60)
await primary_breaker.record_failure() # opens immediately at threshold=1
composer = _composer_with_fallback(
@@ -532,7 +557,7 @@ async def test_open_primary_breaker_still_consults_fallback() -> None:
utterance="Schau in mein Gmail.", language="de"
)
assert primary.calls == [] # primary skipped (breaker open)
- assert out == "Ich nehme mir dein Gmail gleich vor."
+ assert out == "Ein Jarvis-Agent nimmt sich dein Gmail gleich vor."
assert len(fallback.calls) == 1
@@ -548,7 +573,7 @@ async def test_valid_candidate_short_circuits_llm() -> None:
out = await composer.compose(
utterance="Schau in mein Gmail.",
language="de",
- candidate="Ich gehe gleich durch dein Gmail und melde mich.",
+ candidate="Ein Jarvis-Agent geht gleich durch dein Gmail und meldet sich.",
)
assert "Gmail" in out
assert provider.calls == []
@@ -556,14 +581,34 @@ async def test_valid_candidate_short_circuits_llm() -> None:
@pytest.mark.asyncio
async def test_invalid_candidate_falls_through_to_llm() -> None:
- provider = _FakeProvider(reply="Ich schaue gleich in dein Gmail rein.")
+ provider = _FakeProvider(
+ reply="Ein Jarvis-Agent schaut gleich in dein Gmail rein."
+ )
composer = _composer(provider)
out = await composer.compose(
utterance="Schau in mein Gmail.",
language="de",
candidate="Erledigt.", # completion claim — must be rejected
)
- assert out == "Ich schaue gleich in dein Gmail rein."
+ assert out == "Ein Jarvis-Agent schaut gleich in dein Gmail rein."
+ assert len(provider.calls) == 1
+
+
+async def test_candidate_without_public_agent_label_is_rejected() -> None:
+ """Natural but ambiguous background wording must not bypass the contract."""
+ provider = _FakeProvider(
+ reply="Ein Jarvis-Agent schaut gründlich in dein Gmail."
+ )
+ composer = _composer(provider)
+
+ out = await composer.compose(
+ utterance="Schau in mein Gmail.",
+ language="de",
+ candidate="Ich kümmere mich im Hintergrund darum und melde mich.",
+ )
+
+ assert out == "Ein Jarvis-Agent schaut gründlich in dein Gmail."
assert len(provider.calls) == 1
diff --git a/tests/unit/brain/test_tool_use_loop.py b/tests/unit/brain/test_tool_use_loop.py
index d2a1605e92..365d6d6286 100644
--- a/tests/unit/brain/test_tool_use_loop.py
+++ b/tests/unit/brain/test_tool_use_loop.py
@@ -5,6 +5,7 @@ from typing import Any
import pytest
+from jarvis.brain.tool_call_recovery import extract_leaked_tool_calls
from jarvis.brain.tool_use_loop import _MAX_TOOL_RESULT_CHARS, ToolUseLoop
from jarvis.core.protocols import BrainDelta, BrainRequest, ToolResult
@@ -128,6 +129,257 @@ class _GmailTool:
schema: dict[str, Any] = {}
+class _NamedReadTool:
+ schema: dict[str, Any] = {}
+
+ def __init__(self, name: str) -> None:
+ self.name = name
+
+
+ "serialized",
+ [
+ (
+ "For example, a provider might emit "
+ '{"type":"tool_use","name":"gmail","input":{}} in prose.'
+ ),
+ '{"type":"tool_use","name":"gmail","input":"{bad json"}',
+ '{"type":"tool_use","name":"gmail","input":["not","an","object"]}',
+ "```json\n{\"type\":\"tool_use\",\"name\":\"gmail\",\"input\":{}}",
+ ],
+)
+def test_leaked_call_recovery_rejects_untrusted_or_malformed_input(
+ serialized: str,
+) -> None:
+ assert extract_leaked_tool_calls(serialized) == []
+
+
+def test_leaked_call_recovery_accepts_one_strict_fenced_envelope() -> None:
+ calls = extract_leaked_tool_calls(
+ "```json\n"
+ '{"type":"tool_use","name":"gmail","input":{"action":"list"}}'
+ "\n```"
+ )
+
+ assert len(calls) == 1
+ assert calls[0]["name"] == "gmail"
+ assert calls[0]["input"] == {"action": "list"}
+
+
+class _ExecStructuredRead:
+ def __init__(self) -> None:
+ self.calls: list[tuple[Any, dict[str, Any]]] = []
+
+ async def execute(
+ self, tool: Any, args: dict[str, Any], **_: Any,
+ ) -> ToolResult:
+ self.calls.append((tool, args))
+ return ToolResult(
+ success=True,
+ output={
+ "from": "[email protected]",
+ "subject": "Account notice",
+ "snippet": "A grounded result from the connected service.",
+ },
+ )
+
+
+class _LeakedReadThenAnswerBrain:
+ """A provider emits a function call as text before normal synthesis."""
+
+ def __init__(self, tool_name: str) -> None:
+ self._tool_name = tool_name
+ self.requests: list[BrainRequest] = []
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ self.requests.append(req)
+ if len(self.requests) == 1:
+ yield BrainDelta(
+ content=(
+ '[{"type":"tool_use","name":"'
+ f'{self._tool_name}","input":{{"item_id":"m1"}}}}]'
+ )
+ )
+ yield BrainDelta(finish_reason="stop")
+ return
+ yield BrainDelta(content="The connected service returned a grounded result.")
+ yield BrainDelta(finish_reason="stop")
+
+
+ "tool_name",
+ [
+ "gmail",
+ "streamline/query",
+ "mcp.notebook/search",
+ ],
+)
+async def test_text_leaked_read_call_rejoins_normal_tool_loop(
+ tool_name: str,
+) -> None:
+ """Native, plugin, and MCP calls share exactly-once leak recovery."""
+ brain = _LeakedReadThenAnswerBrain(tool_name)
+ executor = _ExecStructuredRead()
+ loop = ToolUseLoop(
+ brain,
+ {tool_name: _NamedReadTool(tool_name)},
+ executor, # type: ignore[arg-type]
+ )
+
+ result = await loop.run(
+ [],
+ user_utterance="Read the latest connected item.",
+ )
+
+ assert len(executor.calls) == 1
+ assert executor.calls[0][1] == {"item_id": "m1"}
+ assert result.executed_tool_names == {tool_name}
+ assert result.text == "The connected service returned a grounded result."
+ assert len(brain.requests) == 2
+ assert any(message.role == "tool" for message in brain.requests[1].messages)
+
+
+class _StructuredThenLeakedGmailBrain:
+ """Exact incident shape: list call, leaked detail call, final answer."""
+
+ def __init__(self) -> None:
+ self.requests: list[BrainRequest] = []
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ self.requests.append(req)
+ if len(self.requests) == 1:
+ yield BrainDelta(
+ tool_call={
+ "id": "list-call",
+ "name": "gmail",
+ "input": {"action": "list_messages", "max_results": 10},
+ }
+ )
+ yield BrainDelta(finish_reason="tool_use")
+ return
+ if len(self.requests) == 2:
+ yield BrainDelta(
+ content=(
+ '[{"type":"tool_use","name":"gmail","input":'
+ '{"action":"get_message","message_id":"m1"}}]'
+ )
+ )
+ yield BrainDelta(finish_reason="stop")
+ return
+ yield BrainDelta(
+ content="The newest unread message is an important account notice."
+ )
+ yield BrainDelta(finish_reason="stop")
+
+
+async def test_structured_list_then_leaked_detail_call_synthesizes_once() -> None:
+ brain = _StructuredThenLeakedGmailBrain()
+ executor = _ExecStructuredRead()
+ loop = ToolUseLoop(
+ brain,
+ {"gmail": _NamedReadTool("gmail")},
+ executor, # type: ignore[arg-type]
+ )
+
+ result = await loop.run([], user_utterance="Check my important Gmail messages.")
+
+ assert [args["action"] for _, args in executor.calls] == [
+ "list_messages",
+ "get_message",
+ ]
+ assert result.executed_tool_names == {"gmail"}
+ assert result.text == (
+ "The newest unread message is an important account notice."
+ )
+ assert len(brain.requests) == 3
+
+
+class _DuplicateEnvelopeBrain:
+ def __init__(self, *, with_structured_call: bool) -> None:
+ self._with_structured_call = with_structured_call
+ self.requests: list[BrainRequest] = []
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ self.requests.append(req)
+ if len(self.requests) == 1:
+ leaked = (
+ '{"type":"tool_use","name":"gmail",'
+ '"input":{"action":"get_message","message_id":"m1"}}'
+ )
+ yield BrainDelta(content=f"[{leaked},{leaked}]")
+ if self._with_structured_call:
+ yield BrainDelta(
+ tool_call={
+ "id": "structured-call",
+ "name": "gmail",
+ "input": {"action": "get_message", "message_id": "m1"},
+ }
+ )
+ yield BrainDelta(finish_reason="tool_use")
+ return
+ yield BrainDelta(content="One grounded answer.")
+ yield BrainDelta(finish_reason="stop")
+
+
[email protected]("with_structured_call", [False, True])
+async def test_duplicate_leaked_envelopes_execute_exactly_once(
+ with_structured_call: bool,
+) -> None:
+ brain = _DuplicateEnvelopeBrain(with_structured_call=with_structured_call)
+ executor = _ExecStructuredRead()
+ loop = ToolUseLoop(
+ brain,
+ {"gmail": _NamedReadTool("gmail")},
+ executor, # type: ignore[arg-type]
+ )
+
+ result = await loop.run([], user_utterance="Read message m1.")
+
+ assert len(executor.calls) == 1
+ assert result.text == "One grounded answer."
+ assert "tool_use" not in result.text
+
+
+class _RepeatedLeakAcrossRoundsBrain:
+ def __init__(self) -> None:
+ self.requests: list[BrainRequest] = []
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ self.requests.append(req)
+ if len(self.requests) <= 2:
+ yield BrainDelta(
+ content=(
+ '[{"type":"tool_use","name":"gmail","input":'
+ '{"action":"get_message","message_id":"m1"}}]'
+ )
+ )
+ yield BrainDelta(finish_reason="tool_use")
+ return
+ yield BrainDelta(content="The result is available and grounded.")
+ yield BrainDelta(finish_reason="stop")
+
+
+async def test_duplicate_leak_across_rounds_executes_once_then_synthesizes() -> None:
+ brain = _RepeatedLeakAcrossRoundsBrain()
+ executor = _ExecStructuredRead()
+ loop = ToolUseLoop(
+ brain,
+ {"gmail": _NamedReadTool("gmail")},
+ executor, # type: ignore[arg-type]
+ )
+
+ result = await loop.run([], user_utterance="Read message m1.")
+
+ assert len(executor.calls) == 1
+ assert len(brain.requests) == 3
+ assert brain.requests[-1].tools == ()
+ assert result.text == "The result is available and grounded."
+
+
class _ExecOK:
def __init__(self) -> None:
self.calls: list[tuple[Any, dict[str, Any]]] = []
diff --git a/tests/unit/brain/test_turn_planner.py b/tests/unit/brain/test_turn_planner.py
index 874d96dc92..bcb0150ac6 100644
--- a/tests/unit/brain/test_turn_planner.py
+++ b/tests/unit/brain/test_turn_planner.py
@@ -131,6 +131,77 @@ def test_elliptical_follow_up_inherits_evidence_domain(
assert plan.requires_evidence is True
+def test_plugin_location_follow_up_inherits_named_live_tool() -> None:
+ previous = (
+ "Please use my Gmail plugin and tell me which messages need attention.",
+ )
+
+ follow_up = "Wo liegt es? Ich habe es auch als Plugin installiert." # i18n-allow
+ plan = plan_turn(
+ follow_up,
+ context=previous,
+ tool_names=("gmail", "streamline/query"),
+ )
+
+ assert plan.required_capabilities == ("gmail",)
+ assert TurnReason.CONNECTED_DATA in plan.reasons
+ assert TurnReason.UNCERTAIN in plan.reasons
+
+
+def test_plugin_action_follow_up_inherits_named_live_tool() -> None:
+ plan = plan_turn(
+ "Where is it? I installed it as a plugin.",
+ context=("Use Streamline to create a ticket for the incident.",),
+ tool_names=(
+ "jira/create_ticket",
+ "notion/create_page",
+ "streamline/query",
+ ),
+ )
+
+ assert plan.required_capabilities == ("streamline/query",)
+ assert TurnReason.UNCERTAIN in plan.reasons
+
+
+ "follow_up",
+ [
+ "Woran liegt es? Ich habe es als Plugin installiert.", # i18n-allow
+ "Warum ist es fehlgeschlagen?", # i18n-allow
+ ],
+)
+def test_german_reason_follow_up_inherits_named_live_tool(follow_up: str) -> None:
+ plan = plan_turn(
+ follow_up,
+ context=("Please use my Gmail plugin and read the latest message.",),
+ tool_names=("gmail", "streamline/query"),
+ )
+
+ assert plan.required_capabilities == ("gmail",)
+ assert TurnReason.UNCERTAIN in plan.reasons
+
+
+ ("tool_name", "previous"),
+ [
+ ("google-calendar/list_events", "Use Google Calendar to find the event."),
+ ("plugin-streamline/query", "Use Streamline to create a ticket."),
+ ("mcp.notebook/search", "Use Notebook to find the note."),
+ ],
+)
+def test_context_matches_hyphenated_or_prefixed_namespace_identity(
+ tool_name: str,
+ previous: str,
+) -> None:
+ plan = plan_turn(
+ "Where is it? I installed it as a plugin.",
+ context=(previous,),
+ tool_names=(tool_name, "jira/create_ticket"),
+ )
+
+ assert plan.required_capabilities == (tool_name,)
+
+
def test_unrelated_lookup_does_not_inherit_old_evidence_domain() -> None:
context = ("The previous turn asked about the user's private Wiki.",)
diff --git a/tests/unit/core/test_scoped_provider_credentials.py b/tests/unit/core/test_scoped_provider_credentials.py
new file mode 100644
index 0000000000..ddf56d57c3
--- /dev/null
+++ b/tests/unit/core/test_scoped_provider_credentials.py
@@ -0,0 +1,124 @@
+"""Credential-scope guards for Realtime Voice and Jarvis-Agents."""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from jarvis.core import config as cfg
+
+
+def _secret_reader(values: dict[str, str]):
+ def read(key: str, env_fallback: str | None = None) -> str | None:
+ return values.get(key)
+
+ return read
+
+
+ ("provider", "agent_slot", "realtime_provider", "realtime_slot"),
+ [
+ ("openai", "jarvis_agent_openai_api_key", "openai-realtime", "realtime_openai_api_key"),
+ ("gemini", "jarvis_agent_gemini_api_key", "gemini-live", "realtime_gemini_api_key"),
+ ("grok", "jarvis_agent_grok_api_key", "grok-realtime", "realtime_grok_api_key"),
+ ],
+)
+def test_scoped_keys_do_not_cross_between_agent_realtime_and_brain(
+ monkeypatch: pytest.MonkeyPatch,
+ provider: str,
+ agent_slot: str,
+ realtime_provider: str,
+ realtime_slot: str,
+) -> None:
+ monkeypatch.setattr(
+ cfg,
+ "get_secret",
+ _secret_reader({agent_slot: "agent-key", realtime_slot: "realtime-key"}),
+ )
+
+ assert cfg.get_jarvis_agent_secret(provider) == "agent-key"
+ assert cfg.get_provider_secret(realtime_provider) == "realtime-key"
+ assert cfg.get_provider_secret(provider) is None
+
+
+def test_agent_and_realtime_keep_generic_keys_as_upgrade_fallback(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ cfg,
+ "get_secret",
+ _secret_reader({"openai_api_key": "legacy-key"}),
+ )
+
+ assert cfg.get_jarvis_agent_secret("openai") == "legacy-key"
+ assert cfg.get_provider_secret("openai-realtime") == "legacy-key"
+
+
+def test_dedicated_agent_key_wins_over_generic_fallback(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ cfg,
+ "get_secret",
+ _secret_reader(
+ {
+ "jarvis_agent_openai_api_key": "agent-key",
+ "openai_api_key": "generic-key",
+ }
+ ),
+ )
+
+ assert cfg.get_jarvis_agent_secret("openai") == "agent-key"
+ assert cfg.get_provider_secret("openai") == "generic-key"
+
+
+async def test_provider_overrides_are_task_local_and_reset(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ cfg,
+ "get_secret",
+ _secret_reader({"openai_api_key": "generic-key"}),
+ )
+ both_inside = asyncio.Event()
+ release = asyncio.Event()
+ entered = 0
+
+ async def read_scoped(value: str) -> str | None:
+ nonlocal entered
+ with cfg.override_provider_secrets({"openai": value}):
+ entered += 1
+ if entered == 2:
+ both_inside.set()
+ await both_inside.wait()
+ observed = cfg.get_provider_secret("openai")
+ if value == "worker-a":
+ release.set()
+ else:
+ await release.wait()
+ return observed
+
+ assert await asyncio.gather(read_scoped("worker-a"), read_scoped("worker-b")) == [
+ "worker-a",
+ "worker-b",
+ ]
+ assert cfg.get_provider_secret("openai") == "generic-key"
+
+
+def test_provider_override_restores_after_exception(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ cfg,
+ "get_secret",
+ _secret_reader({"openai_api_key": "generic-key"}),
+ )
+
+ with pytest.raises(RuntimeError):
+ with cfg.override_provider_secrets({"openai": "worker-key"}):
+ assert cfg.get_provider_secret("openai") == "worker-key"
+ raise RuntimeError("stop")
+
+ assert cfg.get_provider_secret("openai") == "generic-key"
diff --git a/tests/unit/missions/test_api_critic.py b/tests/unit/missions/test_api_critic.py
index d82ae2e3fc..379d13f5a9 100644
--- a/tests/unit/missions/test_api_critic.py
+++ b/tests/unit/missions/test_api_critic.py
@@ -10,6 +10,7 @@ from pathlib import Path
import pytest
import jarvis.core.config as cfg_mod
+from jarvis.core.protocols import BrainDelta
from jarvis.missions.critic.runner import (
REQUIRED_AXES,
CriticAxis,
@@ -27,7 +28,7 @@ def _valid_verdict_json() -> str:
issues=[],
correction_instruction="",
summary="Looks good.",
- summary_de="Sieht gut aus.",
+ summary_de="Looks good.",
confidence=0.9,
suggested_next_action="accept",
)
@@ -90,6 +91,46 @@ def test_api_critic_resolver_can_exclude_a_failed_family(monkeypatch):
assert provider == "gemini"
+async def test_api_critic_uses_scoped_jarvis_agent_key(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ observed: list[str | None] = []
+
+ class _Brain:
+ def __init__(self, model=None): # noqa: ANN001
+ pass
+
+ async def complete(self, req): # noqa: ANN001, ANN201
+ observed.append(cfg_mod.get_provider_secret("openai"))
+ yield BrainDelta(content=_valid_verdict_json())
+
+ monkeypatch.setattr(
+ cfg_mod,
+ "get_secret",
+ lambda key, *args, **kwargs: {
+ "jarvis_agent_openai_api_key": "agent-key",
+ "openai_api_key": "brain-key",
+ }.get(key),
+ )
+ monkeypatch.setattr(
+ "jarvis.brain.provider_registry.BrainProviderRegistry.get_class",
+ lambda self, provider: _Brain,
+ )
+
+ verdict = await CriticRunner()._invoke_via_api_critic(
+ prompt="Review it.",
+ model="gpt-test",
+ provider="openai",
+ iteration=0,
+ adversarial_reframe=False,
+ )
+
+ assert verdict is not None and verdict.verdict == "approve"
+ assert observed == ["agent-key"]
+ assert cfg_mod.get_provider_secret("openai") == "brain-key"
+
+
@pytest.mark.asyncio
async def test_critic_walks_to_next_api_family_after_invalid_verdict(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/plugins/tool/test_contact_upsert.py b/tests/unit/plugins/tool/test_contact_upsert.py
index e9e40750ff..9e5ad0d8d9 100644
--- a/tests/unit/plugins/tool/test_contact_upsert.py
+++ b/tests/unit/plugins/tool/test_contact_upsert.py
@@ -103,7 +103,7 @@ async def test_upsert_passes_optional_fields_through() -> None:
)
call = store.upserts[0]
assert call["email"] == "[email protected]"
- assert call["address"] == "Hauptstr. 1, Berlin"
+ assert call["address"] == {"street": "Hauptstr. 1, Berlin"}
assert call["note"] == "colleague from work"
diff --git a/tests/unit/plugins/tool/test_spawn_worker_ack.py b/tests/unit/plugins/tool/test_spawn_worker_ack.py
index 8fabbc33b6..7f6a256182 100644
--- a/tests/unit/plugins/tool/test_spawn_worker_ack.py
+++ b/tests/unit/plugins/tool/test_spawn_worker_ack.py
@@ -420,3 +420,4 @@ def test_schema_offers_spoken_ack_and_language() -> None:
assert SpawnWorkerTool.schema["required"] == ["utterance", "action"]
description = props["spoken_ack"]["description"]
assert "stock phrase" in description
+ assert "'Jarvis-Agent' exactly once" in description
diff --git a/tests/unit/plugins/tool/test_spawn_worker_mission_prompt.py b/tests/unit/plugins/tool/test_spawn_worker_mission_prompt.py
index 7f9e9199ac..ecd1c2a890 100644
--- a/tests/unit/plugins/tool/test_spawn_worker_mission_prompt.py
+++ b/tests/unit/plugins/tool/test_spawn_worker_mission_prompt.py
@@ -80,6 +80,35 @@ def test_no_action_falls_back_to_raw_utterance() -> None:
assert "Aufgabe:" not in prompt # no interpretation enrichment
+def test_no_action_keeps_bounded_recent_context_for_references() -> None:
+ """A forced follow-up must not reach a stateless worker without its topic."""
+ long_hint = "bounded-marker " + ("x" * 1_000)
+ prompt = _build_mission_prompt(
+ utterance="Where is it? I also installed it as a plugin.",
+ action="",
+ context_hints=[
+ "Conversation context (recent turns, newest last):",
+ (
+ "Earlier turn — User: 'Please inspect my Gmail plugin.' | "
+ "Assistant: 'The lookup did not finish.'"
+ ),
+ long_hint,
+ ],
+ )
+
+ assert "Please inspect my Gmail plugin" in prompt
+ assert "The lookup did not finish" in prompt
+ assert "Supporting context from the recent conversation" in prompt
+ assert "bounded-marker" in prompt
+ assert long_hint not in prompt
+
+
+def test_empty_no_action_stays_empty_even_when_context_exists() -> None:
+ assert _build_mission_prompt(
+ utterance="", action="", context_hints=["old context"],
+ ) == ""
+
+
def test_generic_default_action_is_not_treated_as_interpretation() -> None:
"""The generic ACK filler ('einer komplexen Aufgabe nachgeht') is NOT a
real interpretation — it must not become the worker's task; fall back to