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): give the subscription voice its identity, context and a clean signal

Ruben Lütke2fa9ee0a8e14
diff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.py
index 96473eb4b7..2701ee6a91 100644
--- a/jarvis/plugins/realtime/codex_subscription.py
+++ b/jarvis/plugins/realtime/codex_subscription.py
@@ -54,15 +54,29 @@ _V3_VOICES = frozenset(
)
_THREAD_BASE_INSTRUCTIONS = (
- "This ephemeral thread exists only to carry a realtime voice transport. "
- "Never use tools, inspect files, access the network, or perform actions. "
- "Never answer a realtime handoff as a Codex agent; the client-owned Jarvis "
- "supervisor handles every handoff."
+ # The thread used to be told it was a dumb pipe ("never perform actions"),
+ # which is why the voice had no identity, no project knowledge and no idea
+ # that actions exist. The SECURITY boundary is unchanged — the Codex agent
+ # itself still never touches tools or the filesystem — but the assistant
+ # is now allowed to be an assistant. Its real persona, capabilities and
+ # project context arrive as developer context at the start of every call.
+ "You are the live voice of the user's own assistant on an open call. "
+ "Speak naturally and conversationally, in short spoken sentences — never "
+ "read out lists, markup, or boilerplate. Your persona, your capabilities "
+ "and the current project context are delivered as developer context at "
+ "the start of this call: follow them as your own identity and knowledge. "
+ "Boundary: you are the VOICE, not the executor. Never run tools, shell "
+ "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."
)
_THREAD_DEVELOPER_INSTRUCTIONS = (
- "Transport-only boundary: do not call tools, shell commands, applications, "
- "plugins, skills, web search, MCP servers, or other agents. Do not read or "
- "write the filesystem. Yield all realtime handoffs to the client."
+ "Execution boundary: do not call tools, shell commands, applications, "
+ "plugins, skills, web search, MCP servers, or other agents, and do not "
+ "read or write the filesystem. Every action goes to the client through a "
+ "handoff. Conversation itself — answering, explaining, remembering what "
+ "was said, using the developer context you were given — is your job."
)
_LANGUAGE_UPDATE_TEXT = {
"de": (
@@ -269,6 +283,9 @@ class _CodexSubscriptionRealtimeSession:
self._language = str(language or "en").strip().lower()
self._active_codex_turn_id = ""
self._handoff_interrupt_pending = False
+ # Last persona/context text actually delivered, so a re-issued
+ # identical one is not sent again mid-call.
+ self._delivered_context = ""
async def _interrupt_active_codex_turn(self) -> None:
turn_id = self._active_codex_turn_id
@@ -706,11 +723,14 @@ class _CodexSubscriptionRealtimeSession:
language: str | None = None,
tools: tuple[dict[str, Any], ...] | None = None,
) -> None:
- # Dynamic tools/instructions are intentionally unsupported; the shared
- # Jarvis supervisor remains the only action boundary. The exact API
- # does support developer-role appendText, which is the safe per-turn
- # boundary for the canonical de/en/es resolver.
- del instructions, tools
+ # Tools stay unsupported by design: the Jarvis supervisor remains the
+ # only action boundary. INSTRUCTIONS, however, are the assistant's
+ # identity and project knowledge — dropping them was why the voice
+ # knew nothing about its own project. ChatGPT-Live accepts developer
+ # context (session.context.append), so a changed persona is delivered
+ # mid-call instead of being discarded.
+ del tools
+ await self._deliver_context(instructions)
normalized = str(language or "").strip().lower()
if normalized not in _LANGUAGE_UPDATE_TEXT or normalized == self._language:
return
@@ -721,6 +741,30 @@ class _CodexSubscriptionRealtimeSession:
)
self._language = normalized
+ async def _deliver_context(self, instructions: str | None) -> None:
+ """Give the model Jarvis's own persona, capabilities and context.
+
+ ChatGPT-Live has no session-instructions field a client may set, but
+ it does accept developer context — which is how the assistant learns
+ who it is and what this project is. Delivered once per distinct text
+ so a re-issued identical persona costs nothing.
+ """
+ text = str(instructions or "").strip()
+ if not text or text == self._delivered_context:
+ return
+ try:
+ await self._client.realtime_append_text(
+ self._thread_id, text, role="developer"
+ )
+ except Exception: # noqa: BLE001 - a mute persona must not kill the call
+ log.warning(
+ "Codex subscription realtime could not deliver its context; "
+ "the assistant continues without the persona",
+ exc_info=True,
+ )
+ return
+ self._delivered_context = text
+
async def request_response(self, *, required_tool: str | None = None) -> None:
# The upstream VAD creates responses automatically. A required tool
# stays with the Jarvis delegate rather than becoming a direct Codex
@@ -976,7 +1020,7 @@ class CodexSubscriptionRealtimeProvider:
# Fail here rather than mid-call: without a live media path the
# session would look connected and stay mute in both directions.
await audio_endpoint.wait_connected()
- return _CodexSubscriptionRealtimeSession(
+ session = _CodexSubscriptionRealtimeSession(
client=client,
subscription=subscription,
thread_id=thread_id,
@@ -984,6 +1028,10 @@ class CodexSubscriptionRealtimeProvider:
audio_endpoint=audio_endpoint,
language=str(getattr(cfg, "language", "en") or "en"),
)
+ # Identity FIRST: the model must know who it is and what this
+ # project is before the user's first word arrives.
+ await session._deliver_context(getattr(cfg, "instructions", ""))
+ return session
except BaseException:
try:
await _cleanup_remote_thread(client, thread_id)
diff --git a/jarvis/realtime/webrtc_transport.py b/jarvis/realtime/webrtc_transport.py
index 35c75e2916..7498e20f51 100644
--- a/jarvis/realtime/webrtc_transport.py
+++ b/jarvis/realtime/webrtc_transport.py
@@ -135,22 +135,46 @@ def _build_sender_track(base: Any) -> Any:
return _SenderTrack()
-def _upsample_to_wire(pcm: bytes, source_rate: int) -> bytes:
- """Convert mono int16 PCM to the 48 kHz wire rate."""
- import numpy as np # noqa: PLC0415
+class _MicResampler:
+ """Stateful mic resampler to the 48 kHz wire rate.
+
+ Statefulness is the point: resampling each 20 ms chunk INDEPENDENTLY
+ restarts the interpolation at every boundary, which stamps a periodic
+ discontinuity into the stream 50 times a second — audible as a robotic
+ buzz and, worse, degrading what the model's transcriber hears. One
+ resampler carried across chunks produces a continuous signal.
+ """
- if source_rate == _WIRE_RATE or not pcm:
- return pcm
- samples = np.frombuffer(pcm, dtype=np.int16)
- if samples.size == 0:
- return b""
- ratio = _WIRE_RATE / float(source_rate)
- target_len = max(1, int(round(samples.size * ratio)))
- # Linear interpolation: cheap, artifact-free enough for speech, and it
- # keeps this hot path free of a heavy resampler dependency.
- positions = np.linspace(0, samples.size - 1, target_len)
- resampled = np.interp(positions, np.arange(samples.size), samples)
- return resampled.astype(np.int16).tobytes()
+ def __init__(self) -> None:
+ self._resampler: Any = None
+ self._source_rate = 0
+ self._pts = 0
+
+ def convert(self, pcm: bytes, source_rate: int) -> bytes:
+ if not pcm:
+ return b""
+ if source_rate == _WIRE_RATE:
+ return pcm
+ import numpy as np # noqa: PLC0415
+ from av import AudioFrame # noqa: PLC0415
+ from av.audio.resampler import AudioResampler # noqa: PLC0415
+
+ if self._resampler is None or source_rate != self._source_rate:
+ self._resampler = AudioResampler(
+ format="s16", layout="mono", rate=_WIRE_RATE
+ )
+ self._source_rate = source_rate
+ self._pts = 0
+ samples = np.frombuffer(pcm, dtype=np.int16).reshape(1, -1)
+ frame = AudioFrame.from_ndarray(samples, format="s16", layout="mono")
+ frame.sample_rate = source_rate
+ frame.pts = self._pts
+ frame.time_base = fractions.Fraction(1, source_rate)
+ self._pts += samples.shape[1]
+ out = bytearray()
+ for resampled in self._resampler.resample(frame):
+ out += bytes(resampled.planes[0])[: resampled.samples * 2]
+ return bytes(out)
class RealtimeWebRtcAudioEndpoint:
@@ -180,6 +204,7 @@ class RealtimeWebRtcAudioEndpoint:
maxsize=_RECV_QUEUE_MAX
)
self._reader_task: asyncio.Task[None] | None = None
+ self._mic_resampler = _MicResampler()
self._closed = False
@self._pc.on("track")
@@ -272,7 +297,9 @@ class RealtimeWebRtcAudioEndpoint:
"""Queue one mono int16 PCM chunk for the outgoing media track."""
if self._closed or not pcm:
return
- payload = _upsample_to_wire(pcm, int(sample_rate or _JARVIS_RATE))
+ payload = self._mic_resampler.convert(pcm, int(sample_rate or _JARVIS_RATE))
+ if not payload:
+ return
try:
self._sender.queue.put_nowait(payload)
except asyncio.QueueFull:
diff --git a/tests/unit/realtime/test_codex_subscription.py b/tests/unit/realtime/test_codex_subscription.py
index 00b020da2d..1410dd862d 100644
--- a/tests/unit/realtime/test_codex_subscription.py
+++ b/tests/unit/realtime/test_codex_subscription.py
@@ -258,8 +258,23 @@ async def test_direct_sdp_open_uses_safe_experimental_transport_contract() -> No
thread_start = client.thread_starts[0]
assert thread_start["ephemeral"] is True
assert "extra" not in thread_start
- assert "transport" in thread_start["base_instructions"].lower()
- assert "tools" in thread_start["developer_instructions"].lower()
+ # The execution boundary is the security invariant: the Codex agent is
+ # the VOICE, never the executor — every action goes out as a handoff.
+ base = thread_start["base_instructions"].lower()
+ developer = thread_start["developer_instructions"].lower()
+ assert "never run tools" in base
+ assert "handoff" in base
+ assert "do not call tools" in developer
+ assert "filesystem" in developer
+ # …but it must no longer be told it is a dumb pipe: without an identity
+ # the voice knew nothing about its own project.
+ assert "persona" in base
+
+ # Jarvis's own persona/context reaches the model as developer context —
+ # ChatGPT-Live has no client-settable session-instructions field.
+ assert client.text_appends == [
+ ("thread-1", "Speak concise English.", "developer")
+ ]
_thread_id, start = client.realtime_starts[0]
assert start == {
"output_modality": "audio",