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(realtime): delegate tool mode — one jarvis_action function routes to the router brain

Ruben Lütked8f9344aa3f7
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index 2004a72590..c52ff93348 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -1930,6 +1930,13 @@ class VoiceConfig(BaseModel):
# (browser, OpenAI Realtime; opt-in). Read once per voice session; a live
# change lands on the next session.
mode: str = "pipeline"
+ # Realtime tool exposure. "delegate" (default) declares ONE action function
+ # (jarvis_action) that hands the user's spoken request to the classic
+ # router brain — full ToolExecutor safety path, two-turn voice confirm,
+ # spawn-worker escalation for heavy missions. "direct" declares every
+ # router tool individually via RealtimeToolBridge. Read once per session;
+ # unknown values fall back to "delegate".
+ realtime_tool_mode: str = "delegate"
# Per-gap budget after which a stale pending fragment is silently
# discarded (user-mandated 2026-05-26 — was: flushed/spoken). NOT a total
# budget — every continuation resets the timer. Bumped from 8 s to 15 s
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index 65dad5ad00..b082197734 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -43,6 +43,47 @@ _END_CALL_DECLARATION: dict[str, Any] = {
),
"parameters": {"type": "object", "properties": {}},
}
+# Delegate mode: the realtime model gets ONE action function instead of the
+# full router-tool set. The handler runs a complete classic router-brain turn
+# (ToolExecutor risk tiers, two-turn voice confirm, spawn-worker escalation)
+# and returns the spoken reply for the realtime voice to deliver. Hard budget:
+# the router turn itself offloads heavy work to background missions, so a
+# turn that exceeds this is stuck, not busy.
+_DELEGATE_TIMEOUT_S = 90.0
+_DELEGATE_DECLARATION: dict[str, Any] = {
+ "name": "jarvis_action",
+ "description": (
+ "Execute an action for the user through the Jarvis action system: "
+ "open apps or views, change settings, control the computer, manage "
+ "files, start background research or coding missions, and any other "
+ "operation on the user's system. Also call this to relay the user's "
+ "answer to a pending confirmation question."
+ ),
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "request": {
+ "type": "string",
+ "description": "The user's request in their own words.",
+ }
+ },
+ "required": ["request"],
+ },
+}
+_DELEGATE_ROLE_DIRECTIVE = (
+ "You have ONE action function: jarvis_action. It hands the user's spoken "
+ "request to the Jarvis action system, which can open apps and views, "
+ "change settings, control the computer, manage files and windows, and "
+ "start background research or coding missions. Whenever the user asks "
+ "you to DO something on their computer or in the Jarvis app, call "
+ "jarvis_action — never claim you cannot act, and never invent an "
+ "outcome. The function returns spoken_reply: deliver that content to the "
+ "user in your own voice, in the conversation language, without reading "
+ "JSON. If spoken_reply asks a confirmation question, ask the user and "
+ "call jarvis_action again with their answer. Answer pure knowledge and "
+ "chat questions yourself, without the function. Use end_call only when "
+ "the user says goodbye."
+)
_REALTIME_SAFETY_APPENDIX = (
"This is a realtime spoken conversation. Never read tool JSON, function-call "
"arguments, source code, stack traces, file paths, base64, or raw URLs aloud. "
@@ -69,7 +110,7 @@ def _session_instructions(
provider: str = "",
model: str = "",
language_is_pinned: bool = True,
- has_action_tools: bool = False,
+ tool_directive: str = "",
) -> str:
from jarvis.brain.persona_loader import load_effective_persona_prompt
@@ -85,7 +126,7 @@ def _session_instructions(
)
parts = [
persona,
- _TOOL_ROLE_DIRECTIVE if has_action_tools else "",
+ tool_directive,
_REALTIME_SAFETY_APPENDIX,
(
"Runtime identity: this voice session is using the Realtime engine"
@@ -153,7 +194,22 @@ class RealtimeVoiceSession:
getattr(self._config, "stt", None), "language", "unknown"
)
self._language = self._resolve_lang(text="")
- if tool_bridge is None and brain is not None:
+ self._brain = brain
+ mode = str(
+ getattr(
+ getattr(self._config, "voice", None), "realtime_tool_mode", "delegate"
+ )
+ or "delegate"
+ ).strip().lower()
+ if mode not in {"delegate", "direct"}:
+ mode = "delegate"
+ # Delegate mode needs only a callable brain (the boot proxy and the
+ # real BrainManager both qualify); an explicitly injected bridge
+ # always wins so existing callers/tests keep today's behavior.
+ self._delegate_enabled = (
+ mode == "delegate" and tool_bridge is None and callable(brain)
+ )
+ if tool_bridge is None and brain is not None and not self._delegate_enabled:
try:
from jarvis.realtime.tools import RealtimeToolBridge
@@ -163,10 +219,17 @@ class RealtimeVoiceSession:
except Exception: # noqa: BLE001 — conversation still works without tools
log.warning("Realtime tool bridge is unavailable", exc_info=True)
self._tool_bridge = tool_bridge
+ self._delegate_tasks: set[asyncio.Task[None]] = set()
# from_brain returns None SILENTLY when the brain object carries no
# _tools/_tool_executor_ref (e.g. a bare callback was passed) — say so,
# or a tool-less session is indistinguishable from a healthy one.
- if tool_bridge is not None:
+ if self._delegate_enabled:
+ log.info(
+ "realtime[%s] tool mode: delegate — one action function "
+ "backed by the router brain",
+ session_id,
+ )
+ elif tool_bridge is not None:
log.info(
"realtime[%s] tool bridge active: %d tools",
session_id,
@@ -272,7 +335,7 @@ class RealtimeVoiceSession:
provider=str(getattr(provider, "name", "") or ""),
model=model,
language_is_pinned=self._language_is_pinned,
- has_action_tools=self._tool_bridge is not None,
+ tool_directive=self._tool_directive(),
),
language=self._language,
language_is_pinned=self._language_is_pinned,
@@ -281,14 +344,7 @@ class RealtimeVoiceSession:
input_sample_rate=input_rate,
output_sample_rate=output_rate,
modalities=("audio",),
- tools=(
- *(
- self._tool_bridge.declarations
- if self._tool_bridge is not None
- else ()
- ),
- _END_CALL_DECLARATION,
- ),
+ tools=self._declared_tools(),
)
try:
session = await provider.open_session(session_config)
@@ -372,7 +428,7 @@ class RealtimeVoiceSession:
provider=self.active_provider,
model=self._active_model,
language_is_pinned=True,
- has_action_tools=self._tool_bridge is not None,
+ tool_directive=self._tool_directive(),
),
language=new_language,
)
@@ -690,6 +746,20 @@ class RealtimeVoiceSession:
self._output_transcript.clear()
self._executed_tool_names.clear()
+ def _declared_tools(self) -> tuple[dict[str, Any], ...]:
+ if self._delegate_enabled:
+ return (_DELEGATE_DECLARATION, _END_CALL_DECLARATION)
+ if self._tool_bridge is not None:
+ return (*self._tool_bridge.declarations, _END_CALL_DECLARATION)
+ return (_END_CALL_DECLARATION,)
+
+ def _tool_directive(self) -> str:
+ if self._delegate_enabled:
+ return _DELEGATE_ROLE_DIRECTIVE
+ if self._tool_bridge is not None:
+ return _TOOL_ROLE_DIRECTIVE
+ return ""
+
async def _handle_tool_call(self, event: Any) -> None:
if self._session is None:
return
@@ -698,6 +768,15 @@ class RealtimeVoiceSession:
arguments = getattr(event, "tool_args", None)
if not isinstance(arguments, dict):
arguments = {}
+ if (
+ self._delegate_enabled
+ and call_id
+ and wire_name == str(_DELEGATE_DECLARATION["name"])
+ ):
+ # 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)
+ return
if not call_id or not wire_name or self._tool_bridge is None:
await self._session.send_tool_result(
call_id,
@@ -743,6 +822,93 @@ class RealtimeVoiceSession:
name=f"rt-end-call-{self.session_id}",
)
+ def _start_delegate(
+ self, call_id: str, wire_name: str, arguments: dict[str, Any]
+ ) -> 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
+ 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),
+ name=f"rt-delegate-{self.session_id}",
+ )
+ self._delegate_tasks.add(task)
+ task.add_done_callback(self._delegate_tasks.discard)
+
+ async def _run_delegate(
+ self, call_id: str, wire_name: str, user_text: str
+ ) -> None:
+ try:
+ reply = (
+ await asyncio.wait_for(
+ self._dispatch_brain_turn(user_text),
+ timeout=_DELEGATE_TIMEOUT_S,
+ )
+ or ""
+ ).strip()
+ if reply:
+ result: dict[str, Any] = {"success": True, "spoken_reply": reply}
+ else:
+ result = {
+ "success": True,
+ "spoken_reply": "",
+ "note": (
+ "The action completed without a spoken reply; "
+ "briefly confirm it to the user."
+ ),
+ }
+ self._executed_tool_names.add(str(_DELEGATE_DECLARATION["name"]))
+ except TimeoutError:
+ result = {
+ "success": False,
+ "error": (
+ "The action did not finish in time. Tell the user it may "
+ "still be running and offer to check later."
+ ),
+ }
+ except asyncio.CancelledError:
+ raise
+ except Exception: # noqa: BLE001 — a failed delegation must not kill audio
+ log.warning(
+ "realtime[%s] delegate turn failed", self.session_id, exc_info=True
+ )
+ await self._publish_error(
+ "RealtimeDelegateError", "Delegated brain turn failed", recoverable=True
+ )
+ result = {
+ "success": False,
+ "error": "The action failed safely and was not completed.",
+ }
+ if self._ended or self._session is None:
+ return
+ try:
+ await self._session.send_tool_result(call_id, wire_name, result)
+ except Exception: # noqa: BLE001 — late result on a torn-down wire
+ log.debug(
+ "realtime[%s] delegate result send failed",
+ self.session_id,
+ exc_info=True,
+ )
+
+ async def _dispatch_brain_turn(self, text: str) -> str:
+ # 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).
+ generate = getattr(self._brain, "generate", None)
+ if callable(generate):
+ try:
+ return str(await generate(text, allow_voice_confirm=True) or "")
+ except TypeError:
+ # Bare callables / older brains without the kwarg.
+ pass
+ return str(await self._brain(text) or "")
+
async def _finish_with_hangup(self) -> None:
"""Mark this session as ended by voice and notify the surface.
@@ -853,6 +1019,10 @@ class RealtimeVoiceSession:
if self._end_call_timer is not None and not self._end_call_timer.done():
self._end_call_timer.cancel()
self._end_call_timer = None
+ for task in tuple(self._delegate_tasks):
+ if not task.done():
+ task.cancel()
+ self._delegate_tasks.clear()
if self._pump_task is not None and not self._pump_task.done():
self._pump_task.cancel()
try:
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 6e0079e08e..5dbd46cd90 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -1135,6 +1135,18 @@ class DesktopApp:
brain = brain_holder["brain"]
return str(getattr(brain, "conversation_language", "")) if brain else ""
+ # Realtime direct mode builds its tool bridge from these two
+ # attributes at session construction; delegate through to the
+ # real brain so a session opened after boot sees the full tool
+ # set (None during early boot → bridge cleanly degrades).
+ @property
+ def _tools(self) -> Any:
+ return getattr(brain_holder["brain"], "_tools", None)
+
+ @property
+ def _tool_executor_ref(self) -> Any:
+ return getattr(brain_holder["brain"], "_tool_executor_ref", None)
+
def _brain_unavailable_message(self) -> str:
detail = brain_holder["error"] or "BrainManager not initialized"
return f"Brain unavailable: {detail}"
diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.py
index 8afa9cd2ff..1258c42f0e 100644
--- a/tests/unit/realtime/test_session.py
+++ b/tests/unit/realtime/test_session.py
@@ -868,3 +868,331 @@ async def test_instructions_omit_tool_role_without_bridge():
await sess.end(reason="test")
assert "call the matching function" not in provider.opened_with.instructions
+
+
+# --- Delegate tool mode (jarvis_action -> classic router-brain turn) --------
+
+
+class FakeBrain:
+ """Recording callable brain with a generate(text, **kwargs) contract."""
+
+ def __init__(self, replies=("done",), error=None, gate=None):
+ self.calls = []
+ self._replies = list(replies)
+ self._error = error
+ self._gate = gate
+
+ async def generate(self, text, **kwargs):
+ self.calls.append((text, kwargs))
+ if self._gate is not None:
+ await self._gate.wait()
+ if self._error is not None:
+ raise self._error
+ return self._replies.pop(0) if self._replies else "done"
+
+ async def __call__(self, text):
+ return await self.generate(text)
+
+
+class _StubTool:
+ name = "open_app"
+ description = "Open an application."
+ risk_tier = "monitor"
+ schema = {"type": "object", "properties": {}}
+
+
+def _delegate_cfg(tool_mode=None):
+ cfg = _cfg()
+ if tool_mode is not None:
+ cfg.voice.realtime_tool_mode = tool_mode
+ return cfg
+
+
+def _tool_names(opened_cfg):
+ return [d["name"] for d in opened_cfg.tools]
+
+
+def _session(provider, *, brain=None, tool_bridge=None, tool_mode=None, jsons=None):
+ return RealtimeVoiceSession(
+ session_id="delegate-test",
+ send_binary=lambda _data: asyncio.sleep(0),
+ send_json=(
+ (lambda m: jsons.append(m) or asyncio.sleep(0))
+ if jsons is not None
+ else (lambda _m: asyncio.sleep(0))
+ ),
+ provider=provider,
+ config=_delegate_cfg(tool_mode),
+ bus=None,
+ brain=brain,
+ tool_bridge=tool_bridge,
+ )
+
+
+async def test_delegate_mode_declares_single_action_function():
+ provider = FakeProvider([RealtimeEvent(type="turn_complete")])
+ sess = _session(provider, brain=FakeBrain())
+
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ await sess.wait_finished()
+ await sess.end(reason="test")
+
+ assert _tool_names(provider.opened_with) == ["jarvis_action", "end_call"]
+ assert "jarvis_action" in provider.opened_with.instructions
+
+
+async def test_direct_mode_builds_bridge_from_brain():
+ brain = FakeBrain()
+ brain._tools = {"open_app": _StubTool()}
+ brain._tool_executor_ref = object()
+ provider = FakeProvider([RealtimeEvent(type="turn_complete")])
+ sess = _session(provider, brain=brain, tool_mode="direct")
+
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ await sess.wait_finished()
+ await sess.end(reason="test")
+
+ names = _tool_names(provider.opened_with)
+ assert "open_app" in names
+ assert "end_call" in names
+ assert "jarvis_action" not in names
+
+
+async def test_explicit_bridge_wins_over_delegate_mode():
+ provider = FakeProvider([RealtimeEvent(type="turn_complete")])
+ sess = _session(provider, brain=FakeBrain(), tool_bridge=FakeToolBridge())
+
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ await sess.wait_finished()
+ await sess.end(reason="test")
+
+ names = _tool_names(provider.opened_with)
+ assert "open_app" in names
+ assert "jarvis_action" not in names
+
+
+async def test_delegate_call_dispatches_raw_transcript_with_voice_confirm():
+ brain = FakeBrain(replies=("Settings are open.",))
+ provider = FakeProvider(
+ [
+ RealtimeEvent(
+ type="input_transcript",
+ text="please open the settings view",
+ is_final=True,
+ ),
+ RealtimeEvent(
+ type="tool_call",
+ call_id="c-1",
+ tool_name="jarvis_action",
+ tool_args={"request": "Open settings"},
+ ),
+ RealtimeEvent(type="turn_complete"),
+ ]
+ )
+ 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 == [
+ ("please open the settings view", {"allow_voice_confirm": True})
+ ]
+ assert provider.session.tool_results == [
+ (
+ "c-1",
+ "jarvis_action",
+ {"success": True, "spoken_reply": "Settings are open."},
+ )
+ ]
+ await sess.end(reason="test")
+
+
+async def test_delegate_does_not_block_pump():
+ gate = asyncio.Event()
+ brain = FakeBrain(replies=("Done.",), gate=gate)
+ jsons = []
+ provider = FakeProvider(
+ [
+ RealtimeEvent(type="input_transcript", text="do the thing", is_final=True),
+ RealtimeEvent(
+ type="tool_call",
+ call_id="c-2",
+ tool_name="jarvis_action",
+ tool_args={"request": "do the thing"},
+ ),
+ RealtimeEvent(type="output_transcript_delta", text="Working on it."),
+ ]
+ )
+ sess = _session(provider, brain=brain, jsons=jsons)
+
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ await sess.wait_finished()
+
+ # The pump processed the later transcript while the brain turn still hangs.
+ assert any(
+ m.get("type") == "transcript" and m.get("role") == "assistant" for m in jsons
+ )
+ assert provider.session.tool_results == []
+
+ gate.set()
+ await asyncio.sleep(0.02)
+ assert provider.session.tool_results
+ assert provider.session.tool_results[0][2]["spoken_reply"] == "Done."
+ await sess.end(reason="test")
+
+
+async def test_delegate_timeout_sends_honest_failure(monkeypatch):
+ monkeypatch.setattr("jarvis.realtime.session._DELEGATE_TIMEOUT_S", 0.05)
+ gate = asyncio.Event() # never set -- the brain turn hangs
+ brain = FakeBrain(gate=gate)
+ provider = FakeProvider(
+ [
+ RealtimeEvent(type="input_transcript", text="slow task", is_final=True),
+ RealtimeEvent(
+ type="tool_call",
+ call_id="c-3",
+ tool_name="jarvis_action",
+ tool_args={"request": "slow task"},
+ ),
+ ]
+ )
+ sess = _session(provider, brain=brain)
+
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ await sess.wait_finished()
+ await asyncio.sleep(0.15)
+
+ result = provider.session.tool_results[0][2]
+ assert result["success"] is False
+ assert "did not finish" in result["error"]
+ await sess.end(reason="test")
+
+
+async def test_delegate_confirm_roundtrip():
+ brain = FakeBrain(
+ replies=("Should I really restart the app?", "Restarted."),
+ )
+ provider = FakeProvider(
+ [
+ RealtimeEvent(
+ type="input_transcript",
+ text="starte die app neu", # i18n-allow: German confirm fixture
+ is_final=True,
+ ),
+ RealtimeEvent(
+ type="tool_call",
+ call_id="c-4",
+ tool_name="jarvis_action",
+ tool_args={"request": "restart the app"},
+ ),
+ RealtimeEvent(type="turn_complete"),
+ RealtimeEvent(
+ type="input_transcript",
+ text="ja bitte", # i18n-allow: German confirm fixture
+ is_final=True,
+ ),
+ RealtimeEvent(
+ type="tool_call",
+ call_id="c-5",
+ tool_name="jarvis_action",
+ tool_args={"request": "yes"},
+ ),
+ RealtimeEvent(type="turn_complete"),
+ ]
+ )
+ 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)
+
+ replies = [r[2]["spoken_reply"] for r in provider.session.tool_results]
+ assert replies == ["Should I really restart the app?", "Restarted."]
+ # The confirmation answer went through in the user's own words.
+ assert brain.calls[1][0] == "ja bitte" # i18n-allow: German confirm fixture
+ await sess.end(reason="test")
+
+
+async def test_delegate_untranscribed_tool_call_rejected(monkeypatch):
+ monkeypatch.setattr("jarvis.realtime.session._TOOL_TRANSCRIPT_WAIT_S", 0.01)
+ brain = FakeBrain()
+ provider = FakeProvider(
+ [
+ RealtimeEvent(
+ type="tool_call",
+ call_id="c-6",
+ tool_name="jarvis_action",
+ tool_args={"request": "mystery action"},
+ ),
+ ]
+ )
+ sess = _session(provider, brain=brain)
+
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ await sess.wait_finished()
+ await asyncio.sleep(0.05)
+
+ assert brain.calls == []
+ assert provider.session.tool_results[0][2]["success"] is False
+ await sess.end(reason="test")
+
+
+async def test_delegate_tasks_cancelled_on_end():
+ gate = asyncio.Event() # never set
+ brain = FakeBrain(gate=gate)
+ provider = FakeProvider(
+ [
+ RealtimeEvent(type="input_transcript", text="long task", is_final=True),
+ RealtimeEvent(
+ type="tool_call",
+ call_id="c-7",
+ tool_name="jarvis_action",
+ tool_args={"request": "long task"},
+ ),
+ ]
+ )
+ sess = _session(provider, brain=brain)
+
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ await sess.wait_finished()
+ await sess.end(reason="test")
+ await asyncio.sleep(0.02)
+
+ assert provider.session.tool_results == []
+ assert sess._delegate_tasks == set()
+
+
+async def test_delegate_brain_exception_sends_safe_failure():
+ brain = FakeBrain(error=RuntimeError("boom"))
+ provider = FakeProvider(
+ [
+ RealtimeEvent(type="input_transcript", text="do it", is_final=True),
+ RealtimeEvent(
+ type="tool_call",
+ call_id="c-8",
+ tool_name="jarvis_action",
+ tool_args={"request": "do 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)
+
+ result = provider.session.tool_results[0][2]
+ assert result["success"] is False
+ assert "failed safely" in result["error"]
+ await sess.end(reason="test")