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): stop Codex subscription self-dialogue

Ruben Lütkedc14e60d2e13
diff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.py
index 406288a312..94e5460688 100644
--- a/jarvis/plugins/realtime/codex_subscription.py
+++ b/jarvis/plugins/realtime/codex_subscription.py
@@ -63,6 +63,11 @@ _UNKNOWN_ITEM_LOG_MAX = 32
# adapter-side ceiling preserves a complete ordinary reply for one-shot STT.
_OUTPUT_TRANSCRIPT_RECOVERY_MAX_BYTES = _OUTPUT_RATE * 2 * 60
_OUTPUT_TRANSCRIPT_RECOVERY_TIMEOUT_S = 3.0
+# A provider copy of the real input transcript can lag the local recognizer a
+# little. Past this bound, a new server-side user caption with no local energy
+# inside an open response is not that duplicate: it is the silence/self-echo
+# turn that made ChatGPT-Live continue both sides of a conversation forever.
+_UNGROUNDED_RESPONSE_GRACE_S = 3.0
_HISTORY_MAX_ITEMS = 12
_HISTORY_MAX_CHARS = 12_000
# The experimental v1 protocol was shut off server-side with the ChatGPT-Live
@@ -105,7 +110,13 @@ _THREAD_BASE_INSTRUCTIONS = (
"commands, applications, plugins, skills, web search, MCP servers, or "
"other agents yourself, and never read or write the filesystem. When the "
"user asks for something to be DONE, request a handoff — the user's own "
- "supervisor performs it and reports back through you."
+ "supervisor performs it and reports back through you. Speak only the "
+ "assistant side: produce exactly one response to the latest actual user "
+ "audio, then stop and wait. Never invent, quote, role-play, or supply a "
+ "user reply, even if silence or speaker feedback looks like another turn. "
+ "Answer in the language spoken in the latest actual user audio unless "
+ "developer context explicitly pins another; never switch languages "
+ "because an English paraphrase, transcription, or example appears in context."
)
_THREAD_DEVELOPER_INSTRUCTIONS = (
"Execution boundary: do not call tools, shell commands, applications, "
@@ -131,6 +142,21 @@ _LANGUAGE_UPDATE_TEXT = {
"tools or perform an action."
),
}
+_UNGROUNDED_TURN_MESSAGES = {
+ "de": ( # i18n-allow: German runtime warning selected from the resolved turn language
+ "Die Realtime-Verbindung wird neu aufgebaut, " # i18n-allow: runtime warning
+ "weil eine Antwort ohne lokal bestätigte " # i18n-allow: runtime warning
+ "Spracheingabe erkannt wurde." # i18n-allow: runtime warning
+ ),
+ "en": (
+ "The realtime connection is being rebuilt because a response without "
+ "locally grounded microphone speech was detected."
+ ),
+ "es": (
+ "La conexión en tiempo real se está restableciendo porque se detectó "
+ "una respuesta sin voz confirmada localmente."
+ ),
+}
@dataclass(frozen=True, slots=True)
@@ -463,6 +489,7 @@ class _CodexSubscriptionRealtimeSession:
active_response_generation = 0
response_open = False
response_allowed = False
+ response_opened_at = 0.0
# Item types this session has already reported as unhandled. The v3 item
# vocabulary is only partly known, and silently swallowing the rest is
# why neither the real terminal-response item nor the never-observed
@@ -538,9 +565,11 @@ class _CodexSubscriptionRealtimeSession:
async def _begin_response(source: str) -> bool:
"""Authorize one response from fresh local input or trusted injection."""
nonlocal active_response_generation, response_allowed, response_open
+ nonlocal response_opened_at
if response_open:
return response_allowed
response_open = True
+ response_opened_at = asyncio.get_running_loop().time()
active_response_generation = 0
if self._input_transcriber is None:
response_allowed = True
@@ -563,7 +592,7 @@ class _CodexSubscriptionRealtimeSession:
def _finish_response() -> None:
nonlocal consumed_input_generation, active_response_generation
- nonlocal response_allowed, response_open
+ nonlocal response_allowed, response_open, response_opened_at
if response_allowed and active_response_generation:
consumed_input_generation = max(
consumed_input_generation, active_response_generation
@@ -571,6 +600,16 @@ class _CodexSubscriptionRealtimeSession:
active_response_generation = 0
response_allowed = False
response_open = False
+ response_opened_at = 0.0
+
+ def _ungrounded_caption_breaks_open_response() -> bool:
+ return bool(
+ response_open
+ and response_allowed
+ and response_opened_at > 0.0
+ and asyncio.get_running_loop().time() - response_opened_at
+ >= _UNGROUNDED_RESPONSE_GRACE_S
+ )
async def _recover_output_transcript() -> _ProviderEvent | None:
"""Recover text for provider audio whose transcript went missing."""
@@ -911,6 +950,30 @@ class _CodexSubscriptionRealtimeSession:
energy_plausible = self._server_user_transcript_is_plausible()
fresh_input = _fresh_local_input_exists()
if not energy_plausible or not fresh_input:
+ if _ungrounded_caption_breaks_open_response():
+ diagnostic = (
+ "Codex subscription detected an automatic "
+ "server turn without locally grounded "
+ "microphone speech; rebuilding the realtime "
+ "transport to stop a self-dialogue loop."
+ )
+ log.warning("%s Caption=%r", diagnostic, text[:80])
+ _cancel_completion()
+ completion_emitted = True
+ _reset_assistant_capture()
+ await self._interrupt_active_codex_turn()
+ _finish_response()
+ yield _ProviderEvent(
+ type="error",
+ error=_UNGROUNDED_TURN_MESSAGES.get(
+ self._language,
+ _UNGROUNDED_TURN_MESSAGES["en"],
+ ),
+ recoverable=True,
+ reconnect_advised=True,
+ )
+ yield _ProviderEvent(type="turn_complete")
+ return
log.info(
"Ignoring a server user transcript because %s (%r)",
(
@@ -1191,8 +1254,11 @@ class _CodexSubscriptionRealtimeSession:
# is delivered mid-call instead of being discarded.
await self._deliver_context(instructions)
normalized = str(language or "").strip().lower()
- if normalized not in _LANGUAGE_UPDATE_TEXT or normalized == self._language:
+ if normalized not in _LANGUAGE_UPDATE_TEXT:
return
+ # Reassert even when unchanged. The server can freeze an automatic
+ # response before the larger per-turn persona refresh takes effect;
+ # this compact final developer item is the authoritative turn pin.
await self._client.realtime_append_text(
self._thread_id,
_LANGUAGE_UPDATE_TEXT[normalized],
diff --git a/jarvis/realtime/scrub_gate.py b/jarvis/realtime/scrub_gate.py
index adea376d19..4f001f50a3 100644
--- a/jarvis/realtime/scrub_gate.py
+++ b/jarvis/realtime/scrub_gate.py
@@ -32,6 +32,7 @@ import time
from jarvis.brain.output_filter import FALLBACK_PHRASES, ScrubResult, scrub_for_voice
from jarvis.core.protocols import AudioChunk
+from jarvis.speech.hangup import END_CALL_SIGNAL
log = logging.getLogger(__name__)
@@ -88,6 +89,12 @@ class ScrubHoldGate:
self._hard_leak = False
self._transcript_seen = False
self._transcript_tail = ""
+ # A provider may split a control token across transcript deltas. The
+ # ordinary scrubber sees each delta independently for display, so a
+ # split token used to pass through unchanged even though the aggregate
+ # scrub correctly recognized it. Hold only a possible token prefix
+ # until the next delta decides it.
+ self._control_tail = ""
self._hard_leak_actions: tuple[str, ...] = ()
# Coverage budget (BUG-069): audio released so far vs. the estimated
# spoken duration of every transcript char the scrubber has vetted.
@@ -142,6 +149,11 @@ class ScrubHoldGate:
if self._hard_leak:
return self.fallback_phrase()
+ text = self._strip_stream_controls(str(text or ""))
+ if not text:
+ self._transcript_seen = True
+ return ""
+
self._transcript_tail = (
f"{self._transcript_tail}{text}"[-_TRANSCRIPT_TAIL_MAX_CHARS:]
)
@@ -190,6 +202,19 @@ class ScrubHoldGate:
return text
return _restore_edge_whitespace(text, result.cleaned)
+ def _strip_stream_controls(self, text: str) -> str:
+ """Remove complete or delta-split pipeline control tokens."""
+ combined = f"{self._control_tail}{text}"
+ self._control_tail = ""
+ combined = combined.replace(END_CALL_SIGNAL, "")
+ max_prefix = min(len(combined), len(END_CALL_SIGNAL) - 1)
+ for size in range(max_prefix, 0, -1):
+ if combined.endswith(END_CALL_SIGNAL[:size]):
+ self._control_tail = combined[-size:]
+ combined = combined[:-size]
+ break
+ return combined
+
async def push_audio(self, chunk: AudioChunk) -> list[AudioChunk]:
"""Buffer or release an audio delta. Returns chunks safe to play now.
@@ -329,6 +354,7 @@ class ScrubHoldGate:
self._hard_leak = False
self._transcript_seen = False
self._transcript_tail = ""
+ self._control_tail = ""
self._hard_leak_actions = ()
self._pending_since = None
self.last_hold_ms = 0.0
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index 06ff5c54fc..a30bdd1985 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -51,7 +51,7 @@ from jarvis.sessions.constants import (
SPOKEN_KIND_WITHHELD,
)
from jarvis.speech.echo_guard import SelfEchoGuard
-from jarvis.speech.hangup import HANGUP_RE
+from jarvis.speech.hangup import END_CALL_SIGNAL, HANGUP_RE
log = logging.getLogger(__name__)
@@ -650,6 +650,11 @@ _REALTIME_SAFETY_APPENDIX = (
"reply uses the same voice, gender, tone, and pace as your previous "
"replies. Never switch to a different voice, never imitate another "
"person or character, and never dramatize quoted or reported content. "
+ "Speak only the assistant side of the live conversation: produce exactly "
+ "one assistant response to the latest real user turn, then stop and wait. "
+ "Never supply the user's side, invent a user reply, or role-play dialogue, "
+ "and never perform dialogue examples from the persona. Never emit or speak pipeline "
+ "control markers; call lifetime is controlled outside the spoken reply. "
# 2026-07-21 11:32 live forensic: a tagged action result whose rendering
# was superseded by the surface TTS stayed in context as an un-honored
# order — three turns later a one-word user fragment made the model
@@ -661,6 +666,16 @@ _REALTIME_SAFETY_APPENDIX = (
)
_LANGUAGE_NAMES = {"de": "German", "en": "English", "es": "Spanish"}
+_REALTIME_ENDING_SECTION_RE = re.compile(
+ r"(?ms)^ENDING THE CALL[ \t]*\r?\n.*?(?=^CONTEXT[ \t]*(?:\r?\n|\Z)|\Z)"
+)
+
+
+def _realtime_persona(persona: str) -> str:
+ """Remove classic-pipeline controls from native realtime instructions."""
+ text = _REALTIME_ENDING_SECTION_RE.sub("", str(persona or ""))
+ return text.replace(END_CALL_SIGNAL, "").strip()
+
@dataclass(slots=True)
class _DelegateTurnState:
@@ -805,7 +820,7 @@ def _session_instructions(
) -> str:
from jarvis.brain.persona_loader import load_effective_persona_prompt
- persona = load_effective_persona_prompt().strip()
+ persona = _realtime_persona(load_effective_persona_prompt())
# The block is re-sent with every per-turn session update, so this stays
# current across long sessions. Without it the model must either
# hallucinate calendar answers or delegate a trivial "what day is
diff --git a/tests/unit/realtime/test_codex_subscription.py b/tests/unit/realtime/test_codex_subscription.py
index 090ad7f272..d0f9f19820 100644
--- a/tests/unit/realtime/test_codex_subscription.py
+++ b/tests/unit/realtime/test_codex_subscription.py
@@ -412,6 +412,30 @@ async def test_language_update_is_developer_context_and_speech_is_authoritative(
await session.close()
+async def test_same_language_is_reasserted_at_every_local_turn_boundary() -> None:
+ """Auto-response can start before a large persona refresh takes effect.
+
+ The concise language directive must therefore be the final developer item
+ on every grounded turn, even when the resolved language did not change.
+ """
+ client = _Client()
+ session = await _provider(client).open_session(
+ RealtimeSessionConfig(language="de", transport_offer_sdp="v=0\r\no=offer")
+ )
+
+ await session.update_session(language="de")
+
+ assert client.text_appends == [
+ (
+ "thread-1",
+ codex_subscription_mod._LANGUAGE_UPDATE_TEXT["de"],
+ "developer",
+ )
+ ]
+ await session.close()
+
+
@pytest.mark.asyncio
async def test_open_relies_on_authoritative_app_server_auth_without_pre_probe() -> None:
client = _UnauthenticatedClient()
@@ -1268,6 +1292,19 @@ class _ScriptedInputTranscriber(_StubEndpointer):
return await self._events.get()
+class _GroundedThenQuietTranscriber(_ScriptedInputTranscriber):
+ """Delivers one real local utterance, then reports a quiet microphone."""
+
+ def __init__(self) -> None:
+ super().__init__(
+ [
+ InputTranscriptEvent(kind="speech_started"),
+ InputTranscriptEvent(kind="transcript", text="What is up?", is_final=True),
+ ]
+ )
+ self._speaking = False
+
+
def _hallucination_client() -> _Client:
return _Client(
[
@@ -1440,6 +1477,107 @@ async def test_orphan_response_without_a_fresh_local_utterance_is_interrupted():
await session.close()
+async def test_ungrounded_server_turn_aborts_an_open_response_without_a_boundary(
+ monkeypatch,
+):
+ """A missing response boundary must not merge a self-dialogue forever.
+
+ Live Codex v3 evidence (2026-08-02) carried no terminal response item. The
+ legitimate answer therefore stayed open while silence produced a new
+ server-side user caption, and every automatic reply was accepted as more
+ of the original response. The first ungrounded final caption must close
+ the local turn and force a clean transport rebuild.
+ """
+ monkeypatch.setattr(codex_subscription_mod, "_UNGROUNDED_RESPONSE_GRACE_S", 0.0)
+ client = _Client()
+ client.subscription = _ScheduledSubscription(
+ [
+ (
+ 0.01,
+ _Notification(
+ "thread/realtime/transcript/done",
+ {"threadId": "thread-1", "role": "assistant", "text": "Hi."},
+ ),
+ ),
+ (
+ 0.01,
+ _Notification(
+ "thread/realtime/transcript/done",
+ {"threadId": "thread-1", "role": "user", "text": "Thanks."},
+ ),
+ ),
+ (
+ 0.0,
+ _Notification(
+ "thread/realtime/transcript/done",
+ {
+ "threadId": "thread-1",
+ "role": "assistant",
+ "text": "An invented second side of the conversation.",
+ },
+ ),
+ ),
+ ]
+ )
+ session = await _provider(
+ client,
+ input_transcriber_factory=_GroundedThenQuietTranscriber,
+ ).open_session(RealtimeSessionConfig())
+
+ events = [event async for event in session.receive()]
+
+ assert [event.text for event in events if event.type == "output_transcript_delta"] == [
+ "Hi."
+ ]
+ assert [event.type for event in events].count("turn_complete") == 1
+ errors = [event for event in events if event.type == "error"]
+ assert len(errors) == 1
+ assert errors[0].recoverable is True
+ assert errors[0].reconnect_advised is True
+ assert "locally grounded" in str(errors[0].error)
+ await session.close()
+
+
+async def test_ungrounded_turn_warning_uses_the_resolved_session_language(
+ monkeypatch,
+):
+ """A recovery warning must not switch the turn back to English."""
+ monkeypatch.setattr(codex_subscription_mod, "_UNGROUNDED_RESPONSE_GRACE_S", 0.0)
+ client = _Client()
+ client.subscription = _ScheduledSubscription(
+ [
+ (
+ 0.01,
+ _Notification(
+ "thread/realtime/transcript/done",
+ {"threadId": "thread-1", "role": "assistant", "text": "Hallo."},
+ ),
+ ),
+ (
+ 0.01,
+ _Notification(
+ "thread/realtime/transcript/done",
+ {"threadId": "thread-1", "role": "user", "text": "Danke."},
+ ),
+ ),
+ ]
+ )
+ session = await _provider(
+ client,
+ input_transcriber_factory=_GroundedThenQuietTranscriber,
+ ).open_session(RealtimeSessionConfig(language="de"))
+
+ events = [event async for event in session.receive()]
+
+ errors = [event for event in events if event.type == "error"]
+ assert [event.error for event in errors] == [
+ codex_subscription_mod._UNGROUNDED_TURN_MESSAGES["de"]
+ ]
+ await session.close()
+
+
@pytest.mark.asyncio
async def test_trusted_direct_speech_is_allowed_without_a_new_user_utterance():
"""Action readbacks intentionally create output outside a microphone turn."""
diff --git a/tests/unit/realtime/test_scrub_gate.py b/tests/unit/realtime/test_scrub_gate.py
index 1b61732bd7..8f922fd9ed 100644
--- a/tests/unit/realtime/test_scrub_gate.py
+++ b/tests/unit/realtime/test_scrub_gate.py
@@ -140,6 +140,19 @@ async def test_other_non_blocking_scrub_actions_do_not_raise_generic_error(
assert gate.hard_leak_pending() is False
+async def test_end_call_control_split_across_deltas_never_reaches_display():
+ """Streaming boundaries must not defeat control-token stripping."""
+ gate = ScrubHoldGate(language="de")
+
+ first = await gate.feed_transcript("Talk soon. [[END")
+ second = await gate.feed_transcript("_CALL]]Bis bald. [[END_CALL]]")
+
+ assert first + second == "Talk soon. Bis bald. "
+ assert END_CALL_SIGNAL not in first + second
+ assert gate.hard_leak_pending() is False
+
+
@pytest.mark.asyncio
async def test_streamed_jargon_prefix_can_complete_a_user_facing_compound():
"""A partial ``MCP-Server`` transcript must not abort a clean reply."""
diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.py
index 0b453532e6..1a42d7f7ee 100644
--- a/tests/unit/realtime/test_session.py
+++ b/tests/unit/realtime/test_session.py
@@ -4965,6 +4965,35 @@ def test_session_instructions_place_preferences_between_persona_and_directives(
)
+def test_session_instructions_never_teach_native_voice_pipeline_control_tokens(
+ monkeypatch,
+):
+ """The classic TTS sentinel is neither speakable nor valid in realtime."""
+ from jarvis.brain import persona_loader
+ from jarvis.realtime import session as session_mod
+ from jarvis.speech.hangup import END_CALL_SIGNAL
+
+ monkeypatch.setattr(
+ persona_loader,
+ "load_effective_persona_prompt",
+ lambda: (
+ "IDENTITY\n\n"
+ "ENDING THE CALL\n"
+ f"Say goodbye and append {END_CALL_SIGNAL}.\n\n"
+ "CONTEXT\nKeep the actual conversation context."
+ ),
+ )
+
+ text = session_mod._session_instructions("de")
+
+ assert "IDENTITY" in text
+ assert "Keep the actual conversation context" in text
+ assert "ENDING THE CALL" not in text
+ assert END_CALL_SIGNAL not in text
+ assert "exactly one assistant response" in text
+ assert "never supply the user's side" in text.lower()
+
+
def test_session_instructions_anchor_clock_and_stale_knowledge_guard(monkeypatch):
"""The per-turn instructions must carry today's date AND tell the model
its training knowledge is older than that date. Without the second half