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): vendor the local server's create_response patch with checksum-guarded apply

rubenluetke10-beep46793dfec783
diff --git a/jarvis/realtime/local_server/__init__.py b/jarvis/realtime/local_server/__init__.py
new file mode 100644
index 0000000000..93f8fc1c55
--- /dev/null
+++ b/jarvis/realtime/local_server/__init__.py
@@ -0,0 +1,21 @@
+"""Managed local realtime server: install, patch, and readiness machinery.
+
+The self-hosted speech-to-speech server behind the ``local-realtime``
+provider graduates here from a hand-built experiment to a Jarvis-managed
+runtime (docs/plans/local-realtime-one-click-install-plan.md). The package
+owns everything a non-maintainer install needs: the vendored upstream patch
+(:mod:`.patching`), and — in later chunks — preflight, tier selection, the
+install engine, and fail-closed readiness reporting.
+"""
+
+from jarvis.realtime.local_server.patching import (
+ PatchDriftError,
+ apply_create_response_patch,
+ patch_state,
+)
+
+__all__ = [
+ "PatchDriftError",
+ "apply_create_response_patch",
+ "patch_state",
+]
diff --git a/jarvis/realtime/local_server/patches/service_create_response_0.2.12.patch b/jarvis/realtime/local_server/patches/service_create_response_0.2.12.patch
new file mode 100644
index 0000000000..3e08019793
--- /dev/null
+++ b/jarvis/realtime/local_server/patches/service_create_response_0.2.12.patch
@@ -0,0 +1,38 @@
+--- a/speech_to_speech/api/openai_realtime/service.py
++++ b/speech_to_speech/api/openai_realtime/service.py
+@@ -417,6 +417,24 @@
+
+ # ── STT → LM bridge ────────────────────────────
+
++ def _client_wants_auto_response(self, cfg) -> bool:
++ """Whether the session's turn_detection asks for automatic responses.
++
++ LOCAL PATCH (pending upstream, speech-to-speech 0.2.12): the OpenAI
++ Realtime protocol's manual-response mode (``turn_detection.
++ create_response: false``) was ignored — every final transcription
++ triggered a full LLM generation plus TTS that a manual-mode client
++ then had to cancel as unsolicited. That doubled LLM load and burned
++ seconds of TTS per turn for nothing. Default stays True: only an
++ explicit ``create_response: false`` disables the auto response.
++ """
++ session = getattr(cfg, "session", None)
++ audio = getattr(session, "audio", None)
++ audio_input = getattr(audio, "input", None)
++ turn_detection = getattr(audio_input, "turn_detection", None)
++ create_response = getattr(turn_detection, "create_response", None)
++ return True if create_response is None else bool(create_response)
++
+ def _on_transcription_completed(self, conn_id: str, event: TranscriptionCompletedEvent) -> list[ServerEvent]:
+ """Handle a final STT transcription: emit protocol event, append to chat, trigger LM."""
+ st = self._state(conn_id)
+@@ -453,7 +471,9 @@
+ st.speculative_user_speech_stopped_at_s = event.speech_stopped_at_s
+
+ queue = self.text_prompt_queue
+- if queue and transcript:
++ # LOCAL PATCH: honor manual-response mode (create_response: false) —
++ # the client requests its responses explicitly via response.create.
++ if queue and transcript and self._client_wants_auto_response(cfg):
+ st.response_pending = True
+ queue.put(
+ GenerateResponseRequest(
diff --git a/jarvis/realtime/local_server/patching.py b/jarvis/realtime/local_server/patching.py
new file mode 100644
index 0000000000..9bb24fc378
--- /dev/null
+++ b/jarvis/realtime/local_server/patching.py
@@ -0,0 +1,139 @@
+"""Checksum-guarded application of the vendored local-realtime server patch.
+
+The managed install pins ``speech-to-speech==0.2.12`` whose realtime API
+ignores the OpenAI protocol's manual-response mode (``turn_detection.
+create_response: false``): every final transcription triggered an LLM
+generation plus TTS that a manual-mode client then cancelled as unsolicited,
+doubling LLM load per turn. The fix lives as a unified diff next to this
+module (``patches/service_create_response_0.2.12.patch``, upstream
+candidate) and is applied after every install.
+
+Fail-closed by design (AD-3): the diff is only ever applied to the
+byte-exact pristine 0.2.12 file, verified by SHA-256 before and after. Any
+drift — a different upstream version, a hand-edited file, a partially
+written install — raises :class:`PatchDriftError` instead of guessing, so a
+pin bump can never silently ship the unpatched double-generation behavior.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+from pathlib import Path
+
+log = logging.getLogger(__name__)
+
+#: The upstream version this patch targets. A pin bump MUST regenerate the
+#: diff and both hashes together (guarded by tests + the install smoke).
+PATCH_TARGET_VERSION = "0.2.12"
+
+#: sha256 of the pristine service.py inside the 0.2.12 wheel from PyPI.
+PRISTINE_SHA256 = "31b622c287c946a9604abd56e3531a898084cbd9ab7f53292db9d7146c63a7c2"
+
+#: sha256 of service.py after this patch applied — the only accepted result.
+PATCHED_SHA256 = "17aa3f65b5ae434a5b33e149ab0994e98a5f372128763bcf2a54d180b3144d4c"
+
+#: Path of the patched file relative to a venv's site-packages directory.
+SERVICE_RELPATH = Path("speech_to_speech") / "api" / "openai_realtime" / "service.py"
+
+_PATCH_FILE = (
+ Path(__file__).parent / "patches" / f"service_create_response_{PATCH_TARGET_VERSION}.patch"
+)
+
+
+class PatchDriftError(RuntimeError):
+ """The target file matches neither the pristine nor the patched hash."""
+
+
+def _sha256(data: bytes) -> str:
+ return hashlib.sha256(data).hexdigest()
+
+
+def _apply_unified_diff(original: str, diff_text: str) -> str:
+ """Apply a single-file unified diff to ``original`` and return the result.
+
+ Deliberately minimal: no fuzz, no offsets — a context mismatch raises.
+ That strictness is safe here because the caller only ever reaches this
+ function after the SHA-256 gate proved the input is the byte-exact file
+ the diff was generated from.
+ """
+ src = original.splitlines(keepends=True)
+ out: list[str] = []
+ cursor = 0
+ for raw_line in diff_text.splitlines(keepends=True):
+ if raw_line.startswith(("--- ", "+++ ")):
+ continue
+ if raw_line.startswith("@@"):
+ header = raw_line.split("@@")[1].strip()
+ old_start = int(header.split(" ")[0].lstrip("-").split(",")[0])
+ hunk_start = old_start - 1
+ out.extend(src[cursor:hunk_start])
+ cursor = hunk_start
+ continue
+ body = raw_line[1:]
+ if raw_line.startswith("+"):
+ out.append(body)
+ elif raw_line.startswith("-"):
+ if src[cursor].rstrip("\r\n") != body.rstrip("\r\n"):
+ raise PatchDriftError("hunk context mismatch on a removed line")
+ cursor += 1
+ elif raw_line.startswith((" ", "\n")):
+ if src[cursor].rstrip("\r\n") != body.rstrip("\r\n"):
+ raise PatchDriftError("hunk context mismatch on a context line")
+ out.append(src[cursor])
+ cursor += 1
+ # Anything else ("\\ No newline at end of file", index lines) is
+ # metadata this single-file diff does not contain; ignore defensively.
+ out.extend(src[cursor:])
+ return "".join(out)
+
+
+def patch_state(site_packages: Path) -> str:
+ """Report the patch state of an installed server, without touching it.
+
+ Returns ``"pristine"``, ``"patched"``, ``"missing"`` or ``"drifted"``.
+ Read-only and network-free, so status probes may call it freely.
+ """
+ target = site_packages / SERVICE_RELPATH
+ try:
+ digest = _sha256(target.read_bytes())
+ except OSError:
+ return "missing"
+ if digest == PRISTINE_SHA256:
+ return "pristine"
+ if digest == PATCHED_SHA256:
+ return "patched"
+ return "drifted"
+
+
+def apply_create_response_patch(site_packages: Path) -> str:
+ """Apply the vendored patch to a freshly installed server.
+
+ Returns ``"applied"`` or ``"already-applied"``. Raises
+ :class:`PatchDriftError` for a missing or drifted target and never
+ writes anything in that case.
+ """
+ target = site_packages / SERVICE_RELPATH
+ state = patch_state(site_packages)
+ if state == "patched":
+ return "already-applied"
+ if state != "pristine":
+ raise PatchDriftError(
+ f"{target} is {state}: expected the pristine speech-to-speech "
+ f"{PATCH_TARGET_VERSION} file (sha256 {PRISTINE_SHA256[:12]}…). "
+ "A pin bump must regenerate the vendored patch and hashes "
+ "together; refusing to modify an unknown file."
+ )
+ # Bytes in, bytes out: text-mode IO would translate line endings and
+ # silently break the byte-exact result hash below.
+ original = target.read_bytes().decode("utf-8")
+ diff_text = _PATCH_FILE.read_bytes().decode("utf-8")
+ patched = _apply_unified_diff(original, diff_text)
+ if _sha256(patched.encode("utf-8")) != PATCHED_SHA256:
+ raise PatchDriftError(
+ "patch application produced an unexpected result hash; the "
+ "vendored diff and its recorded hashes are out of sync"
+ )
+ target.write_bytes(patched.encode("utf-8"))
+ log.info("local-realtime: applied create_response patch to %s", target)
+ return "applied"
diff --git a/pyproject.toml b/pyproject.toml
index 42306e7b1e..6bc2276fa8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -789,6 +789,9 @@ jarvis = [
# In-repo C source for the macOS stub launcher, compiled at install time
# by jarvis/setup/macos_app_bundle.py (BUG-060 stable TCC identity).
"setup/*.c",
+ # Vendored upstream patch for the managed local-realtime server install
+ # (realtime/local_server/patching.py reads it via Path(__file__)).
+ "realtime/local_server/patches/*.patch",
]
[tool.setuptools.data-files]
diff --git a/tests/unit/realtime/local_server/__init__.py b/tests/unit/realtime/local_server/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/unit/realtime/local_server/test_patching.py b/tests/unit/realtime/local_server/test_patching.py
new file mode 100644
index 0000000000..e00b7567aa
--- /dev/null
+++ b/tests/unit/realtime/local_server/test_patching.py
@@ -0,0 +1,71 @@
+"""Checksum-guarded patch machinery for the managed local-realtime server.
+
+The full pristine→patched round trip is exercised by the install engine's
+smoke test against the real wheel; these tests pin the fail-closed contract
+with synthetic files — the paths a drifted upstream or broken install must
+never sneak through.
+"""
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.realtime.local_server import patching
+
+
+def _write_service(site: Path, data: bytes) -> Path:
+ target = site / patching.SERVICE_RELPATH
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(data)
+ return target
+
+
+class TestPatchState:
+ def test_missing_file_reports_missing(self, tmp_path: Path) -> None:
+ assert patching.patch_state(tmp_path) == "missing"
+
+ def test_unknown_content_reports_drifted(self, tmp_path: Path) -> None:
+ _write_service(tmp_path, b"def something_else(): ...\n")
+ assert patching.patch_state(tmp_path) == "drifted"
+
+
+class TestApplyFailClosed:
+ def test_missing_target_raises_and_writes_nothing(self, tmp_path: Path) -> None:
+ with pytest.raises(patching.PatchDriftError):
+ patching.apply_create_response_patch(tmp_path)
+ assert not (tmp_path / patching.SERVICE_RELPATH).exists()
+
+ def test_drifted_target_raises_and_stays_untouched(self, tmp_path: Path) -> None:
+ drifted = b"# some other upstream version\n"
+ target = _write_service(tmp_path, drifted)
+ with pytest.raises(patching.PatchDriftError):
+ patching.apply_create_response_patch(tmp_path)
+ assert target.read_bytes() == drifted
+
+
+class TestUnifiedDiffApplier:
+ def test_applies_insert_and_replace_hunks(self) -> None:
+ original = "one\ntwo\nthree\nfour\n"
+ diff = "--- a/f\n+++ b/f\n@@ -1,4 +1,5 @@\n one\n+inserted\n two\n-three\n+THREE\n four\n"
+ assert patching._apply_unified_diff(original, diff) == "one\ninserted\ntwo\nTHREE\nfour\n"
+
+ def test_context_mismatch_raises(self) -> None:
+ diff = "--- a/f\n+++ b/f\n@@ -1,1 +1,1 @@\n-not there\n+x\n"
+ with pytest.raises(patching.PatchDriftError):
+ patching._apply_unified_diff("actual line\n", diff)
+
+
+class TestVendoredArtifacts:
+ def test_vendored_patch_file_ships_and_parses(self) -> None:
+ raw = patching._PATCH_FILE.read_bytes().decode("utf-8")
+ assert raw.startswith("--- a/speech_to_speech/")
+ assert "create_response" in raw
+ # The vendored diff must stay a single-file patch (one +++ header);
+ # a multi-file diff would silently confuse the minimal applier.
+ assert raw.count("+++ ") == 1
+
+ def test_hashes_are_wired_to_the_pinned_version(self) -> None:
+ assert patching.PATCH_TARGET_VERSION in patching._PATCH_FILE.name
+ assert len(patching.PRISTINE_SHA256) == 64
+ assert len(patching.PATCHED_SHA256) == 64
+ assert patching.PRISTINE_SHA256 != patching.PATCHED_SHA256