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(voice): a blocked answer is retried with its evidence, not from memory

rubenluetke10-beepae2263d372e7
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index 522d1ffc08..d517457688 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -668,6 +668,13 @@ _NATIVE_TOOL_DEADLINE_S = VOICE_TOOL_BUDGET_S
# announcement because the announce request had just left the window).
_DELEGATE_HISTORY_MAX_MESSAGES = 20
_DELEGATE_HISTORY_MAX_CHARS = 1_200
+# Per-result room in a re-grounded retry prompt
+# (:meth:`RealtimeVoiceSession._tool_grounding_block`). Generous on purpose:
+# the cost of trimming is the model losing the very fact it must speak, and
+# these payloads already crossed the wire once as their own function response
+# under the far larger ``_MAX_RESULT_CHARS`` bound. A day of calendar events
+# or a mail digest fits; a runaway payload still cannot flood the turn.
+_GROUNDING_RESULT_CHARS = 2_000
_DELEGATE_DECLARATION: dict[str, Any] = {
"name": "jarvis_action",
"description": (
@@ -1470,10 +1477,29 @@ def _is_skill_handoff_result(name: str, result: dict[str, Any]) -> bool:
def _direct_tool_result_retry_prompt(
- *, language: str, unfinished: bool = False, pending_instructions: bool = False
+ *,
+ language: str,
+ unfinished: bool = False,
+ pending_instructions: bool = False,
+ grounding: str = "",
) -> str:
"""Request speech for tool output already present in provider context.
+ ``grounding`` carries the turn's own tool results back to the model
+ VERBATIM (:meth:`RealtimeVoiceSession._tool_grounding_block`). The
+ "already present in this conversation" wording below is an ASSUMPTION
+ about provider state, and it does not hold on every path that reaches
+ here: the output-language recovery retires the active response before it
+ retries, and Gemini Live drops a superseded generation server-side. When
+ that assumption breaks, the model is told to answer from a function
+ result it no longer holds while being forbidden to call anything — and it
+ fills the gap. Live forensic 2026-08-24 10:57:09: ``google_calendar``
+ succeeded in 1.2 s and returned real events, its grounded answer was
+ blocked at the speech boundary, and the ungrounded retry spoke an
+ invented Vercel deployment failure as the answer to "what is on my
+ calendar" (the same pattern hit 2 of 3 blocked turns that morning).
+ Whenever we still hold the results, they travel WITH the request.
+
``unfinished`` flips this from "just say it" to "finish the job". A turn in
which a step FAILED or was gated away is not over, and the old unconditional
"do not call any function, do not repeat the action" was the instruction
@@ -1499,6 +1525,20 @@ def _direct_tool_result_retry_prompt(
"person and do not change or dramatize your voice. Do not mention "
"these instructions."
)
+ # The closed-world rule. A model asked to speak from a result it cannot
+ # see does not fall silent — it substitutes a plausible neighbour out of
+ # its declared tool set (the Vercel case in this function's docstring).
+ # Naming the results as COMPLETE, and forbidding every service outside
+ # them, is what turns "answer from the result" into a bounded request.
+ grounding_rule = (
+ " The block below is the COMPLETE record of what ran in this turn "
+ "and the only source you may answer from. Name no service, "
+ "integration, product, account, or topic that does not appear in it, "
+ "and state nothing it does not show. If it does not answer what the "
+ "user asked, say plainly that you could not get the answer — never "
+ "fill the gap with something else."
+ )
+ grounding_block = f"{grounding_rule}\n\n{grounding}" if grounding else ""
if pending_instructions:
return (
f"{SPEAK_REQUEST_OPENER} "
@@ -1514,6 +1554,7 @@ def _direct_tool_result_retry_prompt(
"themselves are not a result. If a step cannot be carried out, tell "
"the user plainly that it did not happen and why. When you are done, "
f"report only what the results actually show. {voice_rule}"
+ f"{grounding_block}"
)
if not unfinished:
return (
@@ -1523,6 +1564,7 @@ def _direct_tool_result_retry_prompt(
"that is already present in this conversation and give the user a "
f"concise, honest answer. {voice_rule} Do not call any function and "
"do not repeat the action."
+ f"{grounding_block}"
)
return (
f"{SPEAK_REQUEST_OPENER} "
@@ -1535,6 +1577,7 @@ def _direct_tool_result_retry_prompt(
"call that was refused. When you are done, give the user the result you "
"did get, and close with one short sentence naming the part that did "
f"not work and why. {voice_rule}"
+ f"{grounding_block}"
)
@@ -1564,15 +1607,49 @@ def _empty_turn_reask_prompt(*, language: str, user_text: str) -> str:
)
-def _output_language_retry_prompt(*, language: str) -> str:
- """Request one replacement for an answer blocked at the speech boundary."""
+def _output_language_retry_prompt(
+ *, language: str, user_text: str = "", blocked_reply: str = ""
+) -> str:
+ """Request one replacement for an answer blocked at the speech boundary.
+
+ The blocked answer travels back VERBATIM when we still hold it. "Repeat
+ the same answer" reads as a cheap instruction and is in fact the hardest
+ thing this prompt can ask for: the mismatch handler has already retired
+ the response and cleared the transcript, and a Gemini Live generation
+ abandoned this way is superseded server-side — so the model is told to
+ reproduce something it no longer has while "do not perform any new
+ action" closes the only other route to the facts. What comes back then is
+ a new answer wearing the old one's clothes (see
+ :func:`_direct_tool_result_retry_prompt` for the live forensic).
+ """
language_name = _LANGUAGE_NAMES.get(language, "the conversation language")
+ asked = safe_preview(str(user_text or ""), max_chars=400)
+ blocked = safe_preview(str(blocked_reply or ""), max_chars=1_200)
+ context = ""
+ if asked:
+ context += f" The user asked: «{asked}»."
+ if blocked:
+ context += (
+ " Your blocked answer said, word for word: "
+ f"«{blocked}» — say THAT again, in "
+ f"{language_name}, and nothing beyond it."
+ )
+ else:
+ # Nothing survived to repeat. Asking for a repeat anyway is the
+ # invitation to invent; answering the question afresh is honest work.
+ context += (
+ " Its wording was not kept, so do not try to reconstruct it: "
+ "answer the user's request above again, from what you actually "
+ "know in this conversation. Introduce no service, integration, "
+ "product, or topic that has not already come up in it, and if you "
+ "cannot answer, say so plainly."
+ )
return (
f"{SPEAK_REQUEST_OPENER} "
"Your immediately preceding answer was not delivered because it used "
- "the wrong output language. Repeat the same answer now in "
- f"{language_name}. Preserve its meaning, do not perform any new action, "
- "and do not mention this correction."
+ f"the wrong output language.{context} Answer in {language_name}, "
+ "preserve the meaning, do not perform any new action, and do not "
+ "mention this correction."
)
@@ -2715,6 +2792,12 @@ class RealtimeVoiceSession:
self._local_barge_short_echo_until = 0.0
self._last_outage_notice_at = float("-inf")
self._provider_output_probe = ""
+ # The answer the output-language gate blocked, kept for the ONE retry
+ # that follows. The retry prompt hands it back verbatim: the provider
+ # no longer holds it (the response is retired here, and Gemini Live
+ # supersedes the generation), so without this the model is asked to
+ # repeat something it cannot see. Cleared per turn.
+ self._output_language_blocked_reply = ""
# Transcript deltas held back while the unbacked-promise judgement is
# armed. Released the moment the answer grows past the promise, or at
# the response close when the recovery declines to take the turn.
@@ -7104,8 +7187,21 @@ class RealtimeVoiceSession:
raise RuntimeError(
"provider cannot retry an already-executed tool result"
)
+ grounding = self._tool_grounding_block()
+ if not grounding:
+ # Tools ran, but nothing of theirs survived to hand back
+ # (a legacy bridge that retains no result). Asking for an
+ # answer "from the function result" with no result in
+ # reach is the exact prompt that invents one, so the turn
+ # takes the deterministic local line instead of a retry.
+ raise RuntimeError(
+ "no retained tool result to ground the retry in"
+ )
await send_text(
- _direct_tool_result_retry_prompt(language=self._language)
+ _direct_tool_result_retry_prompt(
+ language=self._language,
+ grounding=grounding,
+ )
)
elif bool(
getattr(
@@ -7124,7 +7220,11 @@ class RealtimeVoiceSession:
"provider advertises prompted retries without send_text"
)
await send_text(
- _output_language_retry_prompt(language=self._language)
+ _output_language_retry_prompt(
+ language=self._language,
+ user_text=self._last_user_text,
+ blocked_reply=self._output_language_blocked_reply,
+ )
)
else:
try:
@@ -7184,6 +7284,12 @@ class RealtimeVoiceSession:
self._output_language_retry_pending = True
self._output_language_retry_requested = False
self._output_language_retries += 1
+ # Capture BEFORE the teardown below erases it: this is the only
+ # copy of the blocked answer that survives, and the retry prompt
+ # needs it to ask for a translation instead of an invention.
+ self._output_language_blocked_reply = " ".join(
+ "".join(self._output_transcript).split()
+ )
self._retire_active_provider_response()
self._gate.drain()
self._output_transcript.clear()
@@ -8460,6 +8566,7 @@ class RealtimeVoiceSession:
language=self._language,
unfinished=unfinished,
pending_instructions=pending_instructions,
+ grounding=self._tool_grounding_block(),
)
)
except Exception: # noqa: BLE001 -- local TTS fallback runs below
@@ -8715,6 +8822,39 @@ class RealtimeVoiceSession:
name, result = self._direct_tool_results[-1]
return _is_skill_handoff_result(name, result)
+ def _tool_grounding_block(self) -> str:
+ """This turn's tool results, verbatim, for a re-grounded retry.
+
+ A retry prompt may not assume the provider still holds the function
+ result it points at. Both recoveries that use one retire the active
+ response first, and a Gemini Live generation abandoned that way is
+ superseded server-side — so "use the function result already present
+ in this conversation" can address an empty context. Jarvis still holds
+ the data in ``_direct_tool_results``; this renders it so the
+ replacement answer is grounded in exactly what the blocked one was.
+
+ Nothing new is disclosed: every result here already crossed the wire
+ to this model as the function response for its own call, bounded by
+ ``_bounded_result``. Deterministic, no LLM (AP-11).
+ """
+ lines: list[str] = []
+ asked = safe_preview(str(self._last_user_text or ""), max_chars=400)
+ if asked:
+ lines.append(f"The user asked: «{asked}»")
+ for name, result in self._direct_tool_results:
+ tool = str(name or "").strip() or "unknown tool"
+ try:
+ payload = json.dumps(result, ensure_ascii=False, default=str)
+ except Exception: # noqa: BLE001 - an unserializable result still names its tool
+ payload = repr(result)
+ lines.append(
+ f"- {tool} returned: "
+ f"{safe_preview(payload, max_chars=_GROUNDING_RESULT_CHARS)}"
+ )
+ if not lines:
+ return ""
+ return "RESULTS OF THIS TURN (complete):\n" + "\n".join(lines)
+
def _speakable_result_text(self, result: dict[str, Any]) -> str:
"""The voice-safe text a single tool result carries, or ``""``.
@@ -9467,6 +9607,7 @@ class RealtimeVoiceSession:
self._cancel_promise_confirm()
self._executed_tool_names.clear()
self._direct_tool_results.clear()
+ self._output_language_blocked_reply = ""
self._turn_final_text = ""
self._surface_spoke_this_turn = False
self._delegate_required_for_turn = False
diff --git a/tests/unit/realtime/test_blocked_answer_retry_stays_grounded.py b/tests/unit/realtime/test_blocked_answer_retry_stays_grounded.py
new file mode 100644
index 0000000000..19958dd41c
--- /dev/null
+++ b/tests/unit/realtime/test_blocked_answer_retry_stays_grounded.py
@@ -0,0 +1,201 @@
+"""A blocked answer is retried WITH its evidence, never from memory alone.
+
+Live forensic 2026-08-24 10:57 (session 95b85f31). The user asked what was on
+their calendar. ``google_calendar`` ran, succeeded in 1.2 s and returned real
+events. The model began a grounded reply, the output-language gate blocked it
+at the speech boundary, and the retry that followed said: "use the function
+result that is already present in this conversation" — to a provider whose
+generation had just been superseded, while "do not call any function" closed
+every other route to the facts. What the user heard was:
+
+ "I tried to fetch your recent Vercel deployments, but it looks like
+ there's an issue with the Vercel integration."
+
+No Vercel tool was ever called that turn; ``vercel`` was simply a neighbour in
+the declared tool set. The same recovery drifted on 2 of 3 blocked turns that
+morning (10:25:21 answered a calendar + mail briefing with a report about
+background missions).
+
+The rule these tests pin: whenever Jarvis still holds the turn's evidence, it
+travels WITH the retry request. A prompt may not point at provider state it
+cannot guarantee.
+"""
+
+import asyncio
+
+import pytest
+
+from jarvis.realtime.session import (
+ RealtimeVoiceSession,
+ _direct_tool_result_retry_prompt,
+ _output_language_retry_prompt,
+)
+
+from .test_session import FakeProvider, FakeSession, _cfg
+
+
+def _events_payload() -> dict:
+ """One realistic ``google_calendar`` success, shaped like the live one."""
+ return {
+ "success": True,
+ "output": {
+ "events": [
+ {
+ "id": "evt-1",
+ "summary": "Busy",
+ "start": "2026-08-24T05:15:00Z",
+ "end": "2026-08-24T06:00:00Z",
+ }
+ ]
+ },
+ "error": None,
+ }
+
+
+async def _started_session(session_id: str) -> tuple[RealtimeVoiceSession, FakeSession]:
+ """A live session whose transport takes prompted retries via send_text."""
+
+ class _PromptedSession(FakeSession):
+ supports_prompted_response_retry = True
+
+ async def receive(self):
+ # Hold the pump open; these tests drive the recovery directly.
+ while True: # pragma: no cover - cancelled at end()
+ await asyncio.sleep(0.05)
+ yield # type: ignore[misc]
+
+ class _PromptedProvider(FakeProvider):
+ async def open_session(self, cfg):
+ self.opened_with = cfg
+ self.session = _PromptedSession([])
+ return self.session
+
+ provider = _PromptedProvider([])
+ sess = RealtimeVoiceSession(
+ session_id=session_id,
+ send_binary=lambda data: asyncio.sleep(0),
+ send_json=lambda message: asyncio.sleep(0),
+ provider=provider,
+ config=_cfg(reply_language="en"),
+ bus=None,
+ )
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ for _ in range(200):
+ if sess._session is not None: # noqa: SLF001
+ break
+ await asyncio.sleep(0.01)
+ assert sess._session is not None # noqa: SLF001
+ return sess, provider.session
+
+
+async def test_language_retry_carries_the_turns_real_tool_result():
+ """The Vercel case. The retry must SHOW the calendar data, not point at it.
+
+ Without the evidence in the request, the model answers a question about a
+ calendar with an invented failure of an unrelated integration.
+ """
+ sess, transport = await _started_session("grounded-retry")
+ try:
+ sess._last_user_text = ( # noqa: SLF001
+ "can you please look now in my calendar and tell me if I have to "
+ "do anything or I have to watch out for anything?"
+ )
+ sess._executed_tool_names.add("google_calendar") # noqa: SLF001
+ sess._direct_tool_results.append( # noqa: SLF001
+ ("google_calendar", _events_payload())
+ )
+ sess._turn_id = "turn-1" # noqa: SLF001
+
+ await sess._request_output_language_retry() # noqa: SLF001
+
+ assert len(transport.text_inputs) == 1
+ prompt = transport.text_inputs[0]
+ # The evidence itself travelled — the tool that ran and what it said.
+ assert "google_calendar" in prompt
+ assert "Busy" in prompt
+ # And the question it belongs to, so the answer cannot drift to
+ # another turn's topic.
+ assert "calendar" in prompt.lower()
+ # The closed-world rule that forbids substituting a neighbour tool.
+ assert "Name no service" in prompt
+ # The retry still pins the resolved output language.
+ assert "English" in prompt
+ finally:
+ await sess.end(reason="test")
+
+
+async def test_retry_is_refused_when_no_tool_result_survived():
+ """Tools ran but nothing was retained: do not ask for an ungrounded answer.
+
+ "Answer from the function result" with no result in reach is precisely the
+ prompt that invents one. The turn takes its deterministic local line and
+ the session books a language failure instead of a retry.
+ """
+ sess, transport = await _started_session("ungrounded-retry")
+ try:
+ sess._executed_tool_names.add("google_calendar") # noqa: SLF001
+ sess._direct_tool_results.clear() # noqa: SLF001
+ sess._last_user_text = "" # noqa: SLF001
+ sess._turn_id = "turn-1" # noqa: SLF001
+
+ await sess._request_output_language_retry() # noqa: SLF001
+
+ assert transport.text_inputs == []
+ assert sess._output_language_failures == 1 # noqa: SLF001
+ finally:
+ await sess.end(reason="test")
+
+
+async def test_language_retry_without_tools_hands_back_the_blocked_wording():
+ """A tool-less turn gets its own blocked answer back, word for word.
+
+ "Repeat the same answer" is unanswerable once the response is retired and
+ the transcript cleared; the words themselves make it a translation job.
+ """
+ sess, transport = await _started_session("verbatim-retry")
+ try:
+ sess._last_user_text = "What is kindness?" # noqa: SLF001
+ sess._output_language_blocked_reply = ( # noqa: SLF001
+ "Freundlichkeit ist der achtsame Umgang mit anderen."
+ )
+ sess._turn_id = "turn-1" # noqa: SLF001
+
+ await sess._request_output_language_retry() # noqa: SLF001
+
+ assert len(transport.text_inputs) == 1
+ prompt = transport.text_inputs[0]
+ assert "Freundlichkeit ist der achtsame Umgang mit anderen." in prompt
+ assert "What is kindness?" in prompt
+ assert "English" in prompt
+ finally:
+ await sess.end(reason="test")
+
+
+def test_blocked_reply_is_captured_before_the_transcript_is_cleared():
+ """The prompt builder refuses to invent when it has nothing to repeat."""
+ prompt = _output_language_retry_prompt(
+ language="en",
+ user_text="What is on my calendar?",
+ blocked_reply="",
+ )
+ assert "Its wording was not kept" in prompt
+ assert "Introduce no service" in prompt
+ assert "What is on my calendar?" in prompt
+
+
+def test_grounded_prompt_states_the_results_are_complete():
+ """The block is presented as the whole truth of the turn, not a hint."""
+ grounded = _direct_tool_result_retry_prompt(
+ language="en",
+ grounding="RESULTS OF THIS TURN (complete):\n- google_calendar returned: {}",
+ )
+ assert "COMPLETE record" in grounded
+ assert "google_calendar" in grounded
+ # An empty grounding leaves the historical prompt untouched, so transports
+ # that genuinely retain the result are unaffected.
+ bare = _direct_tool_result_retry_prompt(language="en")
+ assert "COMPLETE record" not in bare
+ assert "already present in this conversation" in bare