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.

fix(realtime): share evidence-aware turn routing

Ruben Lütke73341f6807b6
diff --git a/jarvis/brain/turn_planner.py b/jarvis/brain/turn_planner.py
new file mode 100644
index 0000000000..ab5edbc4aa
--- /dev/null
+++ b/jarvis/brain/turn_planner.py
@@ -0,0 +1,278 @@
+"""Shared local turn planner for Pipeline and Realtime.
+
+The realtime transport must not maintain a second, narrower vocabulary for
+deciding whether Jarvis needs private, local, current, or connected evidence.
+This module provides one deterministic decision that is safe to call on the
+voice hot path: no model call, disk access, or network access is performed.
+"""
+
+from __future__ import annotations
+
+import re
+import unicodedata
+from collections.abc import Iterable, Mapping, Sequence
+from dataclasses import dataclass
+from enum import StrEnum
+from typing import Any
+
+
+class TurnPath(StrEnum):
+ """Execution surface selected for one user turn."""
+
+ NATIVE_REALTIME = "native_realtime"
+ ORCHESTRATOR = "orchestrator"
+
+
+class TurnReason(StrEnum):
+ """Stable reasons why a turn needs the Jarvis orchestrator."""
+
+ ACTION = "action"
+ CAPABILITY = "capability"
+ CONNECTED_DATA = "connected_data"
+ CURRENT_DATA = "current_data"
+ LOCAL_STATE = "local_state"
+ MISSION = "mission"
+ PRIVATE_DATA = "private_data"
+ SKILL = "skill"
+ UNCERTAIN = "uncertain"
+
+
+@dataclass(frozen=True)
+class TurnPlan:
+ """Provider-neutral plan consumed by Pipeline and Realtime."""
+
+ path: TurnPath
+ reasons: frozenset[TurnReason] = frozenset()
+ required_capabilities: tuple[str, ...] = ()
+ requires_evidence: bool = False
+
+ @property
+ def requires_orchestrator(self) -> bool:
+ return self.path is TurnPath.ORCHESTRATOR
+
+
+_LOOKUP_SHAPE_RE = re.compile(
+ r"\b(?:what|when|where|which|who|how many|show|read|list|find|lookup|"
+ r"check|summarize|search|do i have|is there|are there|"
+ r"was|wann|wo|welch\w*|wer|wie viele|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|"
+ r"busca|revisa|resume|tengo|hay)\b" # i18n-allow: multilingual speech-input matching data
+)
+_DEFINITION_RE = re.compile(
+ r"\b(?:what is (?:a|an|the)?|what are|what does .{0,40} mean|explain|"
+ r"was ist (?:ein|eine|der|die|das)?|" # i18n-allow: speech input
+ r"was sind|was bedeutet|erklaer\w*|" # i18n-allow: speech input
+ r"que es|que son|explica)\b" # i18n-allow: multilingual speech-input matching data
+)
+_INSTRUCTIONAL_RE = re.compile(
+ r"\b(?:how (?:do|can|would) (?:i|you)|how to|"
+ r"wie (?:kann|koennte|wuerde) (?:ich|man)|" # i18n-allow: speech input
+ r"como (?:puedo|se puede)|como hacer)\b" # i18n-allow: multilingual speech-input matching data
+)
+_OWNERSHIP_RE = re.compile(
+ r"\b(?:my|mine|our|about me|remember me|"
+ r"mein\w*|unser\w*|mir|ueber mich|uber mich|erinner\w* mich|" # i18n-allow: speech input
+ r"mi|mis|mio|nuestr\w*|sobre mi|recuerd\w* de mi)\b" # i18n-allow: speech input
+)
+_CURRENT_RE = re.compile(
+ r"\b(?:current|currently|latest|today|tonight|tomorrow|now|recent|"
+ r"news|weather|status|available|online|"
+ r"aktuell\w*|neueste\w*|heute|morgen|jetzt|kuerzlich|nachrichten|"
+ r"wetter|status|verfuegbar|online|" # i18n-allow: speech input
+ r"actual\w*|ultimo\w*|hoy|manana|ahora|reciente\w*|noticias|"
+ r"clima|tiempo|estado|disponible)\b" # i18n-allow: multilingual speech-input matching data
+)
+_LOCAL_STATE_RE = re.compile(
+ r"\b(?:wiki|mcp\w*|cli\w*|tool\w*|plugin\w*|connector\w*|"
+ r"integration\w*|setting\w*|configuration\w*|api[\s-]?key\w*|"
+ r"jarvis|installed\w*|connected\w*|capabilit\w*|activity history|"
+ r"werkzeug\w*|einstellung\w*|konfiguration\w*|" # i18n-allow: speech input
+ r"installiert\w*|verbunden\w*|faehigkeit\w*|" # i18n-allow: speech input
+ r"aktivitaetsverlauf|" # i18n-allow: speech input
+ r"herramient\w*|ajuste\w*|configuracion\w*|integracion\w*|"
+ r"instalad\w*|conectad\w*|capacidad\w*)\b" # i18n-allow: speech input
+)
+_CONNECTED_DOMAIN_RE = re.compile(
+ r"\b(?:gmail|email|e-mail|mailbox|inbox|calendar|sap|salesforce|"
+ r"github|gitlab|drive|notion|slack|discord|telegram|whatsapp|"
+ r"repository|pull request|deployment|cloud billing|contact\w*|"
+ r"postfach|posteingang|kalender|termin\w*|kontakt\w*|abrechnung\w*|"
+ r"correo|bandeja|calendario|cita\w*|contacto\w*)\b" # i18n-allow: speech input
+)
+_MISSION_RE = re.compile(
+ r"\b(?:jarvis[\s-]?agent\w*|agent\w*|mission\w*|worker\w*|"
+ r"background task\w*|subagent\w*|sub-agent\w*|"
+ r"hintergrund\w*|agente\w*|mision\w*)\b" # i18n-allow: multilingual speech-input matching data
+)
+_SKILL_RE = re.compile(
+ r"\b(?:skill\w*|macro\w*|faehigkeit\w*|makro\w*|habilidad\w*)\b" # i18n-allow: speech input
+)
+_ACTION_FALLBACK_RE = re.compile(
+ r"\b(?:open|close|start|stop|create|write|save|add|change|set|restart|"
+ r"install|connect|delete|move|send|run|build|research|call|click|type|"
+ r"upload|download|book|buy|post|reply|"
+ r"oeffn\w*|schliess\w*|start\w*|stopp\w*|erstell\w*|schreib\w*|"
+ r"speicher\w*|aender\w*|installier\w*|verbind\w*|loesch\w*|"
+ r"verschieb\w*|schick\w*|send\w*|fuehr\w*|bau\w*|ruf\w*|klick\w*|"
+ r"tipp\w*|buch\w*|kauf\w*|antwort\w*|"
+ r"abre\w*|cierra\w*|inicia\w*|crea\w*|escrib\w*|guarda\w*|"
+ r"cambia\w*|instala\w*|conecta\w*|elimina\w*|envia\w*|"
+ r"ejecuta\w*|llama\w*|haz\w*)\b" # i18n-allow: multilingual speech-input matching data
+)
+
+
+def _normalize(text: str) -> str:
+ folded = unicodedata.normalize("NFKD", str(text or "").casefold())
+ return "".join(ch for ch in folded if not unicodedata.combining(ch))
+
+
+def _tokens_from_capability(capability: Any) -> set[str]:
+ tokens: set[str] = set()
+ for value in (
+ getattr(capability, "id", ""),
+ *tuple(getattr(capability, "objects", ()) or ()),
+ ):
+ normalized = _normalize(str(value)).replace("_", " ").replace("/", " ")
+ for token in re.split(r"[^a-z0-9-]+", normalized):
+ if len(token) >= 3:
+ tokens.add(token)
+ return tokens
+
+
+def _matched_capabilities(
+ text: str,
+ *,
+ capability_registry: Any | None,
+ tool_names: Iterable[str],
+) -> tuple[str, ...]:
+ matched: set[str] = set()
+ capabilities: Sequence[Any] = ()
+ if capability_registry is not None:
+ try:
+ resolved = capability_registry.resolve_intent(text)
+ if resolved is not None:
+ matched.add(str(getattr(resolved, "id", "")))
+ capabilities = capability_registry.all()
+ except Exception: # noqa: BLE001 - planner must fail safely
+ capabilities = ()
+
+ normalized = _normalize(text)
+ if _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("/", " ")
+ tokens = [
+ token
+ for token in re.split(r"[^a-z0-9-]+", normalized_name)
+ if len(token) >= 3
+ ]
+ if any(
+ re.search(r"\b" + re.escape(token) + r"\b", normalized)
+ for token in tokens
+ ):
+ matched.add(str(name))
+ return tuple(sorted(item for item in matched if item))
+
+
+def plan_turn(
+ text: str,
+ *,
+ capability_registry: Any | None = None,
+ tool_names: Iterable[str] = (),
+ evidence_domains: Mapping[str, Sequence[str]] | None = None,
+) -> TurnPlan:
+ """Return the conservative shared execution plan for ``text``.
+
+ Uncertainty is resolved toward the orchestrator because it can still
+ answer conversationally, while a native realtime model cannot recover
+ private or connected evidence it never received.
+ """
+ normalized = _normalize(text).strip()
+ if not normalized:
+ return TurnPlan(path=TurnPath.NATIVE_REALTIME)
+
+ reasons: set[TurnReason] = set()
+ definition = bool(_DEFINITION_RE.search(normalized))
+ instructional = bool(_INSTRUCTIONAL_RE.search(normalized))
+ required = () if definition or instructional else _matched_capabilities(
+ text,
+ capability_registry=capability_registry,
+ tool_names=tool_names,
+ )
+ if required:
+ reasons.add(TurnReason.CAPABILITY)
+
+ action_intent = bool(_ACTION_FALLBACK_RE.search(normalized))
+ if capability_registry is not None:
+ try:
+ action_intent = action_intent or bool(
+ capability_registry.has_action_intent(text)
+ )
+ except Exception: # noqa: BLE001,S110 - local fallback remains available
+ pass
+
+ lookup = bool(_LOOKUP_SHAPE_RE.search(normalized))
+ private = bool(_OWNERSHIP_RE.search(normalized))
+
+ if action_intent and not instructional:
+ reasons.add(TurnReason.ACTION)
+ if private and (lookup or action_intent):
+ reasons.add(TurnReason.PRIVATE_DATA)
+ if _LOCAL_STATE_RE.search(normalized) and not definition:
+ reasons.add(TurnReason.LOCAL_STATE)
+ if (
+ _CONNECTED_DOMAIN_RE.search(normalized)
+ and not definition
+ and (lookup or action_intent or private)
+ ):
+ reasons.add(TurnReason.CONNECTED_DATA)
+ if _CURRENT_RE.search(normalized) and (lookup or normalized.endswith("?")):
+ reasons.add(TurnReason.CURRENT_DATA)
+ if _MISSION_RE.search(normalized) and not definition:
+ reasons.add(TurnReason.MISSION)
+ if _SKILL_RE.search(normalized) and not definition:
+ reasons.add(TurnReason.SKILL)
+
+ if evidence_domains and lookup and not definition:
+ for keywords in evidence_domains.values():
+ if any(
+ re.search(r"\b" + re.escape(_normalize(keyword)) + r"\b", normalized)
+ for keyword in keywords
+ ):
+ reasons.add(TurnReason.CONNECTED_DATA)
+ break
+
+ # A lookup that names a live capability/tool but no stronger category is
+ # still connected evidence. This catches arbitrary future MCP objects.
+ if required and lookup and not definition:
+ reasons.add(TurnReason.CONNECTED_DATA)
+
+ # Questions that clearly request fresh or private evidence but are phrased
+ # outside the known lookup vocabulary fail toward the orchestrator.
+ if (private or _CURRENT_RE.search(normalized)) and normalized.endswith("?") and not definition:
+ reasons.add(TurnReason.UNCERTAIN)
+
+ if not reasons:
+ return TurnPlan(path=TurnPath.NATIVE_REALTIME)
+ return TurnPlan(
+ path=TurnPath.ORCHESTRATOR,
+ reasons=frozenset(reasons),
+ required_capabilities=required,
+ requires_evidence=bool(
+ reasons
+ & {
+ TurnReason.CAPABILITY,
+ TurnReason.CONNECTED_DATA,
+ TurnReason.CURRENT_DATA,
+ TurnReason.LOCAL_STATE,
+ TurnReason.PRIVATE_DATA,
+ }
+ ),
+ )
+
+
+__all__ = ["TurnPath", "TurnPlan", "TurnReason", "plan_turn"]
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index 14f77d6841..696054bf9f 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -9,13 +9,13 @@ status callbacks.
from __future__ import annotations
import asyncio
+import inspect
import logging
-import re
-import unicodedata
from dataclasses import dataclass, field
from typing import Any
from uuid import uuid4
+from jarvis.brain.turn_planner import TurnPlan, plan_turn
from jarvis.core.protocols import AudioChunk, BrainMessage
from jarvis.core.redact import safe_preview
from jarvis.core.turn_language import resolve_output_language
@@ -104,69 +104,9 @@ _DELEGATE_REQUIRED_DIRECTIVE = (
"for the trusted action result that the orchestrator will inject."
)
-# Speech-intent vocabulary only. These expressions decide when the live model
-# must cross the local evidence boundary instead of answering from its weights.
-_WIKI_REFERENCE_RE = re.compile(r"\bwiki(?:[\s-]?system)?\b")
-_PERSONAL_REFERENCE_RE = re.compile(
- r"\b(?:my|mine|about\s+me|remember\s+me|mein\w*|mir|u(?:e)?ber\s+mich|"
- r"mi|mis|sobre\s+mi)\b" # i18n-allow: multilingual speech-input vocabulary
-)
-_PERSONAL_KNOWLEDGE_RE = re.compile(
- r"\b(?:who|what|when|where|how|remember\w*|know\w*|favorite\w*|"
- r"birthday\w*|friend\w*|address\w*|name\w*|wer|was|wann|wo|wie|"
- r"erinner\w*|weiss\w*|liebling\w*|geburtstag\w*|freund\w*|adresse\w*|"
- r"quien|que|cuando|donde|como|recuerd\w*|sab\w*|favorit\w*|"
- r"cumplean\w*|amig\w*|nombre\w*)\b" # i18n-allow: multilingual speech-input vocabulary
-)
-_LOCAL_STATE_RE = re.compile(
- r"\b(?:mcp\w*|cli\w*|command[\s-]?line|tool\w*|werkzeug\w*|"
- r"integration\w*|connector\w*|plugin\w*|setting\w*|einstellung\w*|" # i18n-allow: German speech-input vocabulary
- r"configuration\w*|konfiguration\w*|config\w*|api[\s-]?key\w*|"
- r"system[\s-]?status|capabilit\w*|faehigkeit\w*|installed\w*|"
- r"installiert\w*|connected\w*|verbunden\w*|herramient\w*|ajuste\w*|" # i18n-allow: multilingual speech-input vocabulary
- r"configuracion\w*|integracion\w*|conectad\w*|instalad\w*|capacidad\w*|"
- r"clave\w*)\b" # i18n-allow: multilingual speech-input vocabulary
-)
-_ACTION_VERB_RE = re.compile(
- r"\b(?:open\w*|close\w*|start\w*|spawn\w*|create\w*|write\w*|save\w*|"
- r"add\w*|change\w*|set\w*|restart\w*|install\w*|connect\w*|delete\w*|"
- r"move\w*|send\w*|run\w*|build\w*|research\w*|o(?:e)?ffn\w*|schliess\w*|"
- r"erstell\w*|schreib\w*|speicher\w*|eintrag\w*|a(?:e)?nder\w*|stell\w*|" # i18n-allow: German speech-input vocabulary
- r"installier\w*|verbind\w*|lo(?:e)?sch\w*|verschieb\w*|schick\w*|fu(?:e)?hr\w*|"
- r"bau\w*|recherchier\w*|abre\w*|cierra\w*|inicia\w*|crea\w*|"
- r"escrib\w*|guarda\w*|cambia\w*|instala\w*|conecta\w*|elimina\w*|"
- r"envia\w*|ejecuta\w*)\b" # i18n-allow: multilingual speech-input vocabulary
-)
-_ACTION_TARGET_RE = re.compile(
- r"\b(?:app\w*|view\w*|window\w*|computer\w*|file\w*|folder\w*|"
- r"agent\w*|mission\w*|background\w*|transcript\w*|message\w*|that|this|it|"
- r"ansicht\w*|fenster\w*|datei\w*|ordner\w*|hintergrund\w*|"
- r"transkription\w*|nachricht\w*|das|dies\w*|es|aplicacion\w*|" # i18n-allow: multilingual speech-input vocabulary
- r"ventana\w*|archivo\w*|carpeta\w*|agente\w*|mision\w*|"
- r"transcripcion\w*|mensaje\w*|eso|esto)\b" # i18n-allow: multilingual speech-input vocabulary
-)
-
-
-def _normalize_delegate_text(text: str) -> str:
- folded = unicodedata.normalize("NFKD", str(text or "").casefold())
- return "".join(ch for ch in folded if not unicodedata.combining(ch))
-
-
def _requires_jarvis_action(text: str) -> bool:
- """Return whether this turn needs live local evidence or an action."""
- normalized = _normalize_delegate_text(text)
- if not normalized:
- return False
- if _WIKI_REFERENCE_RE.search(normalized) or _LOCAL_STATE_RE.search(normalized):
- return True
- if (
- _PERSONAL_REFERENCE_RE.search(normalized)
- and _PERSONAL_KNOWLEDGE_RE.search(normalized)
- ):
- return True
- return bool(
- _ACTION_VERB_RE.search(normalized) and _ACTION_TARGET_RE.search(normalized)
- )
+ """Compatibility wrapper around the shared Pipeline/Realtime planner."""
+ return plan_turn(text).requires_orchestrator
def _delegate_result_prompt(text: str, *, language: str, success: bool) -> str:
@@ -204,6 +144,8 @@ class _DelegateTurnState:
user_text: str = ""
result_payload: dict[str, Any] = field(default_factory=dict)
pending_tool_calls: list[tuple[str, str]] = field(default_factory=list)
+ seen_tool_call_ids: set[str] = field(default_factory=set)
+ dispatch_started: bool = False
input_boundary_ready: asyncio.Event = field(default_factory=asyncio.Event)
provider_ready: asyncio.Event = field(default_factory=asyncio.Event)
@@ -430,6 +372,39 @@ class RealtimeVoiceSession:
),
)
+ def _plan_turn(self, text: str) -> TurnPlan:
+ """Use the Brain's canonical plan, with a live-catalog local fallback."""
+ brain_planner = getattr(self._brain, "plan_turn", None)
+ if callable(brain_planner):
+ try:
+ planned = brain_planner(text)
+ if isinstance(planned, TurnPlan):
+ return planned
+ except Exception: # noqa: BLE001 - local planner remains available
+ log.debug("Realtime shared Brain planner failed", exc_info=True)
+
+ registry = None
+ try:
+ from jarvis.core.capabilities import get_registry
+
+ registry = get_registry()
+ except Exception: # noqa: BLE001 - planner has static safe fallbacks
+ log.debug("Realtime capability registry unavailable", exc_info=True)
+ tools = getattr(self._brain, "_tools", None)
+ tool_names = tuple(tools) if isinstance(tools, dict) else ()
+ evidence_cfg = getattr(
+ getattr(self._config, "brain", None), "evidence_domains", None
+ )
+ evidence_domains = getattr(evidence_cfg, "domains", None)
+ return plan_turn(
+ text,
+ capability_registry=registry,
+ tool_names=tool_names,
+ evidence_domains=(
+ evidence_domains if isinstance(evidence_domains, dict) else None
+ ),
+ )
+
async def handle_control(self, msg: dict[str, Any]) -> None:
kind = str(msg.get("type", ""))
if kind == "audio_start":
@@ -674,7 +649,9 @@ class RealtimeVoiceSession:
if self._delegate_enabled and self._last_user_text:
self._delegate_required_for_turn = (
self._delegate_required_for_turn
- or _requires_jarvis_action(self._last_user_text)
+ or self._plan_turn(
+ self._last_user_text
+ ).requires_orchestrator
)
refresh_tools = getattr(
self._tool_bridge, "refresh_from_source", None
@@ -901,6 +878,7 @@ class RealtimeVoiceSession:
self.session_id,
self._turn_id,
)
+ await self._coalesce_ready_delegate_result(delegate_state)
continue
self._cancel_release_task()
for chunk in self._gate.release_available():
@@ -1251,6 +1229,23 @@ class RealtimeVoiceSession:
for task in self._delegate_tasks_by_turn.get(turn_id, ())
)
+ @staticmethod
+ async def _coalesce_ready_delegate_result(
+ turn_state: _DelegateTurnState,
+ ) -> None:
+ """Let an already-ready Brain result settle without waiting on I/O.
+
+ Delegate work stays in a background task so provider audio cannot be
+ blocked by a slow model. A cached/local result may nevertheless need a
+ few scheduler hand-offs through ``asyncio.wait_for`` before it becomes
+ visible. This bounded zero-delay grace coalesces a provider function
+ call with that same dispatch; it never waits for remote work.
+ """
+ for _ in range(4):
+ if turn_state.result_complete:
+ return
+ await asyncio.sleep(0)
+
def _delegate_turn_is_active(
self, turn_id: str, turn_state: _DelegateTurnState
) -> bool:
@@ -1286,23 +1281,37 @@ class RealtimeVoiceSession:
and call_id
and wire_name == str(_DELEGATE_DECLARATION["name"])
):
- turn_state = self._delegate_turns.get(self._turn_id)
- if turn_state is not None and turn_state.deterministic:
- if turn_state.result_complete and turn_state.result_payload:
- self._drop_provider_output_until_new_response = False
- await self._session.send_tool_result(
- call_id,
- wire_name,
- turn_state.result_payload,
- )
- else:
- turn_state.pending_tool_calls.append((call_id, wire_name))
- turn_state.input_boundary_ready.set()
- turn_state.provider_ready.set()
+ turn_id = self._turn_id
+ turn_state = self._delegate_turns.setdefault(
+ turn_id,
+ _DelegateTurnState(),
+ )
+ if call_id in turn_state.seen_tool_call_ids:
+ log.debug(
+ "realtime[%s] ignored duplicate delegate call %s",
+ self.session_id,
+ call_id,
+ )
+ return
+ turn_state.seen_tool_call_ids.add(call_id)
+ turn_state.input_boundary_ready.set()
+ turn_state.provider_ready.set()
+ if turn_state.result_complete and turn_state.result_payload:
+ turn_state.delivery_started = True
+ self._drop_provider_output_until_new_response = False
+ await self._session.send_tool_result(
+ call_id,
+ wire_name,
+ turn_state.result_payload,
+ )
return
- # Routed HERE (not in the pump branch) so the untranscribed-call
- # guard and pending flush keep applying to delegate calls too.
- self._start_delegate(call_id, wire_name, arguments)
+ turn_state.pending_tool_calls.append((call_id, wire_name))
+ if not turn_state.user_text:
+ request = str(arguments.get("request", "") or "")
+ turn_state.user_text = self._last_user_text or request
+ if not turn_state.dispatch_started:
+ self._start_delegate(turn_id, turn_state)
+ await self._coalesce_ready_delegate_result(turn_state)
return
if not call_id or not wire_name or self._tool_bridge is None:
await self._session.send_tool_result(
@@ -1361,8 +1370,9 @@ class RealtimeVoiceSession:
)
turn_state.deterministic = True
turn_state.user_text = str(user_text or "").strip()
- if self._turn_has_pending_delegate(turn_id) or turn_state.result_complete:
+ if turn_state.dispatch_started or turn_state.result_complete:
return
+ turn_state.dispatch_started = True
log.info(
"realtime[%s] deterministic delegate: dispatching local-evidence turn",
self.session_id,
@@ -1528,33 +1538,26 @@ class RealtimeVoiceSession:
)
def _start_delegate(
- self, call_id: str, wire_name: str, arguments: dict[str, Any]
+ self,
+ turn_id: str,
+ turn_state: _DelegateTurnState,
) -> None:
- request = str(arguments.get("request", "") or "")
- # Dispatch the RAW final transcript: the model may paraphrase into
- # English, but the router's language resolver and intent matchers
- # need the user's own words. Snapshot NOW — turn state resets later.
- user_text = self._last_user_text or request
- turn_id = self._turn_id
- turn_state = self._delegate_turns.setdefault(
- turn_id,
- _DelegateTurnState(),
- )
+ """Start the single Brain dispatch owned by one realtime turn."""
+ if turn_state.dispatch_started or turn_state.result_complete:
+ return
+ turn_state.dispatch_started = True
log.info(
"realtime[%s] delegate call: dispatching user turn to the router brain",
self.session_id,
)
task = asyncio.create_task(
- self._run_delegate(call_id, wire_name, user_text, turn_id, turn_state),
+ self._run_delegate(turn_id, turn_state),
name=f"rt-delegate-{self.session_id}",
)
self._track_delegate_task(turn_id, task)
async def _run_delegate(
self,
- call_id: str,
- wire_name: str,
- user_text: str,
turn_id: str,
turn_state: _DelegateTurnState,
) -> None:
@@ -1562,7 +1565,7 @@ class RealtimeVoiceSession:
try:
reply = (
await asyncio.wait_for(
- self._dispatch_brain_turn(user_text),
+ self._dispatch_brain_turn(turn_state.user_text),
timeout=_DELEGATE_TIMEOUT_S,
)
or ""
@@ -1617,7 +1620,9 @@ class RealtimeVoiceSession:
turn_state.delivery_started = True
drop_before_delivery = self._drop_provider_output_until_new_response
self._drop_provider_output_until_new_response = False
- await self._session.send_tool_result(call_id, wire_name, result)
+ for call_id, wire_name in tuple(turn_state.pending_tool_calls):
+ await self._session.send_tool_result(call_id, wire_name, result)
+ turn_state.pending_tool_calls.clear()
except Exception: # noqa: BLE001 — late result on a torn-down wire
turn_state.delivery_started = False
self._drop_provider_output_until_new_response = drop_before_delivery
@@ -1631,50 +1636,50 @@ class RealtimeVoiceSession:
# allow_voice_confirm=True is load-bearing: without it an ask-tier
# tool blocks on a UI approval no voice user can give (the classic
# pipeline passes the same flag). prefer_tool_model routes the
- # delegated turn onto the Tool-Model pick. Compatibility degrade: an
- # older brain that rejects a newer kwarg must keep voice-confirm
- # rather than dropping straight to the bare call. Current managers
- # suppress their internal tool-result event so the realtime session
- # can publish the one response that was actually spoken.
+ # delegated turn onto the Tool-Model pick. Current managers suppress
+ # their internal tool-result event so the realtime session can publish
+ # the one response that was actually spoken.
generate = getattr(self._brain, "generate", None)
if callable(generate):
- isolated_context = {
+ desired_kwargs: dict[str, Any] = {
+ "allow_voice_confirm": True,
+ "prefer_tool_model": True,
+ "publish_response": False,
"use_history": False,
"history_override": tuple(self._delegate_history),
}
- for kwargs in (
- {
- "allow_voice_confirm": True,
- "prefer_tool_model": True,
- "publish_response": False,
- **isolated_context,
- },
- {
- "allow_voice_confirm": True,
- "publish_response": False,
- **isolated_context,
- },
- {
- "allow_voice_confirm": True,
- "prefer_tool_model": True,
- "publish_response": False,
- "use_history": False,
- },
- {
- "allow_voice_confirm": True,
- "publish_response": False,
- "use_history": False,
- },
- {
- "allow_voice_confirm": True,
- "prefer_tool_model": True,
- },
- {"allow_voice_confirm": True},
- ):
- try:
- return str(await generate(text, **kwargs) or "")
- except TypeError:
- continue
+ try:
+ signature = inspect.signature(generate)
+ except (TypeError, ValueError):
+ # Opaque callables cannot be probed safely: a TypeError may
+ # occur after a tool side effect. Invoke once with the oldest
+ # common contract instead of retrying the turn.
+ supported_kwargs: dict[str, Any] = {}
+ else:
+ parameters = signature.parameters.values()
+ accepts_arbitrary_kwargs = any(
+ parameter.kind is inspect.Parameter.VAR_KEYWORD
+ for parameter in parameters
+ )
+ keyword_names = {
+ parameter.name
+ for parameter in parameters
+ if parameter.kind
+ in {
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
+ inspect.Parameter.KEYWORD_ONLY,
+ }
+ }
+ supported_kwargs = (
+ desired_kwargs
+ if accepts_arbitrary_kwargs
+ else {
+ name: value
+ for name, value in desired_kwargs.items()
+ if name in keyword_names
+ }
+ )
+ return str(await generate(text, **supported_kwargs) or "")
return str(await self._brain(text) or "")
async def _finish_with_hangup(self) -> None:
diff --git a/tests/unit/brain/test_turn_planner.py b/tests/unit/brain/test_turn_planner.py
new file mode 100644
index 0000000000..8b322c0faf
--- /dev/null
+++ b/tests/unit/brain/test_turn_planner.py
@@ -0,0 +1,96 @@
+"""Parity guards for the shared Pipeline/Realtime turn planner."""
+
+from __future__ import annotations
+
+import pytest
+
+from jarvis.brain.turn_planner import TurnPath, TurnReason, plan_turn
+from jarvis.core.capabilities import Capability, CapabilityRegistry
+
+
+def registry() -> CapabilityRegistry:
+ value = CapabilityRegistry()
+ value.register(
+ Capability(
+ id="mcp.sap/customer_lookup",
+ source="mcp",
+ verbs=("lookup", "read"),
+ objects=("sap", "customer"),
+ description="Read one customer from SAP.",
+ risk_tier="safe",
+ requires_evidence=True,
+ )
+ )
+ value.register(
+ Capability(
+ id="mcp.gmail/list_messages",
+ source="mcp",
+ verbs=("list", "read"),
+ objects=("gmail", "inbox", "email"),
+ description="Read messages from Gmail.",
+ risk_tier="safe",
+ requires_evidence=True,
+ )
+ )
+ return value
+
+
+ "utterance",
+ [
+ "What is the capital of France?",
+ "Explain how DNS works.",
+ "What is SAP?",
+ "How do I open a file in Python?",
+ "Tell me a joke.",
+ ],
+)
+def test_timeless_or_instructional_turns_stay_native(
+ utterance: str, registry: CapabilityRegistry,
+) -> None:
+ assert plan_turn(utterance, capability_registry=registry).path is TurnPath.NATIVE_REALTIME
+
+
+ "utterance",
+ [
+ "What is in my Gmail inbox?",
+ "Read the SAP customer record.",
+ "Which pull requests are open today?",
+ "What is the latest Python release?",
+ "Who is my best friend?",
+ "Which MCPs are connected?",
+ "Use the morning routine skill.",
+ "Spawn a Jarvis-Agent for this research.",
+ "Call Anna.",
+ "Click Save in the browser.",
+ ],
+)
+def test_private_current_connected_and_action_turns_use_orchestrator(
+ utterance: str, registry: CapabilityRegistry,
+) -> None:
+ plan = plan_turn(utterance, capability_registry=registry)
+ assert plan.path is TurnPath.ORCHESTRATOR
+
+
+def test_read_only_dynamic_connector_matches_live_capability(
+ registry: CapabilityRegistry,
+) -> None:
+ plan = plan_turn("What customer is stored in SAP?", capability_registry=registry)
+ assert plan.required_capabilities == ("mcp.sap/customer_lookup",)
+ assert TurnReason.CONNECTED_DATA in plan.reasons
+ assert plan.requires_evidence is True
+
+
+def test_evidence_domain_routes_even_without_loaded_tool() -> None:
+ plan = plan_turn(
+ "Are there unread messages?",
+ evidence_domains={"email": ("messages", "unread")},
+ )
+ assert plan.path is TurnPath.ORCHESTRATOR
+ assert TurnReason.CONNECTED_DATA in plan.reasons
+
+
+def test_empty_turn_stays_native() -> None:
+ assert plan_turn(" ").path is TurnPath.NATIVE_REALTIME
diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.py
index 9004f93821..83461d8692 100644
--- a/tests/unit/realtime/test_session.py
+++ b/tests/unit/realtime/test_session.py
@@ -1285,11 +1285,19 @@ async def test_delegate_mode_declares_single_action_function():
"Who is my best friend?",
"Was weißt du über mich?", # i18n-allow: German speech-input fixture
"Which MCPs and CLIs are installed?",
+ "What is in my Gmail inbox?",
+ "Read the SAP customer record.",
+ "Which pull requests are open today?",
+ "What did I have open on my computer today?",
+ "Use the morning routine skill.",
+ "Call Anna.",
+ "Click Save in the browser.",
"¿Qué herramientas están conectadas?", # i18n-allow: Spanish speech-input fixture
"Write that to the wiki.",
"Write the last transcript to the wiki.",
- "Kannst du bitte mein Wiki-System eintragen, dass ich morgen nach " # i18n-allow: German speech-input fixture
- "San Francisco reisen will?", # i18n-allow: German speech-input fixture
+ "Kannst du bitte mein Wiki-System eintragen, " # i18n-allow: German speech-input fixture
+ "dass ich morgen nach San Francisco " # i18n-allow: German speech-input fixture
+ "reisen will?", # i18n-allow: German speech-input fixture
],
)
async def test_local_evidence_turns_run_deterministic_jarvis_action(utterance):
@@ -1313,12 +1321,21 @@ async def test_local_evidence_turns_run_deterministic_jarvis_action(utterance):
@pytest.mark.asyncio
-async def test_general_knowledge_turn_keeps_native_realtime_answering():
+ "utterance",
+ [
+ "What is the capital of France?",
+ "What is SAP?",
+ "How do I open a file in Python?",
+ "I sent you an email yesterday.",
+ ],
+)
+async def test_general_knowledge_turn_keeps_native_realtime_answering(utterance):
provider = FakeProvider(
[
RealtimeEvent(
type="input_transcript",
- text="What is the capital of France?",
+ text=utterance,
is_final=True,
)
]
@@ -1433,7 +1450,14 @@ async def test_multi_final_transcript_waits_for_provider_turn_boundary():
@pytest.mark.asyncio
async def test_barge_in_detaches_late_delegate_result_from_new_turn():
gate = asyncio.Event()
- brain = FakeBrain(replies=("Old Wiki action completed.",), gate=gate)
+ dispatch_started = asyncio.Event()
+
+ class _SignallingBrain(FakeBrain):
+ async def generate(self, text, **kwargs):
+ dispatch_started.set()
+ return await super().generate(text, **kwargs)
+
+ brain = _SignallingBrain(replies=("Old Wiki action completed.",), gate=gate)
class _BargeSession(FakeSession):
async def receive(self):
@@ -1442,8 +1466,7 @@ async def test_barge_in_detaches_late_delegate_result_from_new_turn():
text="Write this to my wiki.",
is_final=True,
)
- while not brain.calls:
- await asyncio.sleep(0.005)
+ await dispatch_started.wait()
yield RealtimeEvent(type="speech_started")
yield RealtimeEvent(
type="input_transcript",
@@ -1752,7 +1775,7 @@ async def test_direct_tool_turn_keeps_the_session_response_event():
@pytest.mark.asyncio
-async def test_multiple_delegate_calls_publish_one_response_for_the_turn():
+async def test_multiple_delegate_calls_coalesce_to_one_brain_turn():
bus = FakeBus()
brain = FakeBrain(replies=("First result.", "Second result."), bus=bus)
provider = ToolResultGatedProvider(
@@ -1784,9 +1807,12 @@ async def test_multiple_delegate_calls_publish_one_response_for_the_turn():
responses = [event for event in bus.events if isinstance(event, ResponseGenerated)]
assert [event.text for event in responses] == ["Both are done."]
- assert len(brain.calls) == 2
+ assert len(brain.calls) == 1
assert all(call[1]["publish_response"] is False for call in brain.calls)
assert len(provider.session.tool_results) == 2
+ assert {
+ result[2]["spoken_reply"] for result in provider.session.tool_results
+ } == {"First result."}
await sess.end(reason="test")
@@ -2110,8 +2136,7 @@ async def test_delegate_brain_exception_sends_safe_failure():
@pytest.mark.asyncio
async def test_delegate_degrades_kwargs_but_keeps_voice_confirm():
- """An older brain without the prefer_tool_model kwarg must still get
- allow_voice_confirm=True via the degrade step (exactly one real call)."""
+ """An older Brain receives only its supported confirmation keyword."""
class LegacyBrain:
def __init__(self):
@@ -2145,3 +2170,43 @@ async def test_delegate_degrades_kwargs_but_keeps_voice_confirm():
assert brain.calls == [("open it", True)]
assert provider.session.tool_results[0][2]["spoken_reply"] == "done legacy"
await sess.end(reason="test")
+
+
+async def test_delegate_does_not_retry_an_internal_type_error():
+ """A TypeError after dispatch may follow a side effect and is terminal."""
+
+ class TypeErrorBrain:
+ def __init__(self):
+ self.calls = 0
+
+ async def generate(self, text, **kwargs):
+ del text, kwargs
+ self.calls += 1
+ raise TypeError("simulated internal failure after dispatch")
+
+ async def __call__(self, text):
+ del text
+ raise AssertionError("fallback call must not retry the turn")
+
+ brain = TypeErrorBrain()
+ provider = FakeProvider(
+ [
+ RealtimeEvent(type="input_transcript", text="open it", is_final=True),
+ RealtimeEvent(
+ type="tool_call",
+ call_id="type-error-once",
+ tool_name="jarvis_action",
+ tool_args={"request": "open it"},
+ ),
+ ]
+ )
+ sess = _session(provider, brain=brain)
+
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ await sess.wait_finished()
+ await asyncio.sleep(0.02)
+
+ assert brain.calls == 1
+ assert provider.session.tool_results[0][2]["success"] is False
+ await sess.end(reason="test")